carlos / platform Public

Merge origin/main 0374ac2e into config-receipts-1 (#522 plan 1)

One conflict, the root-read chain manifest: main's audit-aws-timeouts
overlay first, config-receipts-1 last, re-sealed with census-propose
on top of it. The overlay file is byte-identical to c5d5a930 (unit
rows and envelope pins unchanged); only its chain seal and the card's
seal line move.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 8e229fdb62be5a3dd451e14f4f6f5b77700a0e47 parent c5d5a93parent 0374ac2
17 files changed, +1,650 −24
  • docs/superpowers/notes/census-proposal-audit-aws-timeouts.md +24 −0
  • docs/superpowers/notes/census-proposal-config-receipts-1.md +1 −1
  • docs/superpowers/reviews/CHECK-BRIEF-audit-aws-timeouts-R2-fix.md +34 −0
  • docs/superpowers/reviews/FINDINGS-audit-aws-timeouts-R1.md +63 −0
  • docs/superpowers/reviews/FINDINGS-audit-aws-timeouts-R2.md +74 −0
  • docs/superpowers/reviews/REVIEW-BRIEF-audit-aws-timeouts-R2.md +99 −0
  • docs/superpowers/reviews/REVIEW-BRIEF-audit-aws-timeouts.md +77 −0
  • internal/host/movescut.go +6 −2
  • internal/host/movescut_leaserelease_test.go +63 −0
  • internal/host/movesstore.go +32 −16
  • internal/host/movesstore_stall_test.go +35 −0
  • internal/provision/testdata/plan14-root-reads-audit-aws-timeouts.tsv +11 −0
  • internal/provision/testdata/plan14-root-reads-chain.tsv +2 −1
  • internal/rootaws/config.go +17 −4
  • internal/rootaws/guard_test.go +250 −0
  • internal/rootaws/stall.go +362 −0
  • internal/rootaws/stall_test.go +500 −0

CI passed — run details

diff --git a/docs/superpowers/notes/census-proposal-audit-aws-timeouts.md b/docs/superpowers/notes/census-proposal-audit-aws-timeouts.md
new file mode 100644
index 000000000..945e43e1d
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-audit-aws-timeouts.md
@@ -0,0 +1,24 @@
+# Census approval: audit-aws-timeouts
+
+Ruling `census-ruling-audit-aws-timeouts`. The independent reviewer approves or rejects every change below, 2 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+| unit | change | read sites | what changed |
+|---|---|---|---|
+| `internal/host/movesstore.go` `probeStore` | body | unchanged (1) | body: builds the same T4 probe client via probeStoreOptions (same delivered credentials, region, endpoint, checksums) with HTTPClient rootaws.BoundedHTTPClient(); operations and reads unchanged, no new root read |
+
+Envelopes re-pinned: `internal/host`, `internal/rootaws`.
+
+Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner.
+
+Recorded dispositions, which each change must still satisfy:
+
+- `internal/host/movesstore.go` `probeStore`: legacy, task accepted-legacy. Basis: accepted-legacy;rev3=J4;basis=root-input
+
+New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff:
+
+- new `internal/rootaws/stall.go:idleBody.Read`: reads +file:Read ×2; written legacy, accepted-legacy, frozen
+- new `internal/rootaws/stall.go:progressConn.Read`: reads +file:Read ×2; written legacy, accepted-legacy, frozen
+
+Seal: `d4d3f367ca135da40d2c392d22b51669281d2d8268c0a5aa22ebf738cbe65080` → `c3e74a3069651a7ae638b2ecba5e38c4dbaec2831865318a52f254b5a041160f`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-audit-aws-timeouts.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/notes/census-proposal-config-receipts-1.md b/docs/superpowers/notes/census-proposal-config-receipts-1.md
index d6ed2deb6..ff4c59358 100644
--- a/docs/superpowers/notes/census-proposal-config-receipts-1.md
+++ b/docs/superpowers/notes/census-proposal-config-receipts-1.md
@@ -18,6 +18,6 @@ New dispositions, which census-propose wrote and the reviewer checks against the
- new `appconfig_cli.go:envDigest`: reads +file:ReadFile; written legacy, accepted-legacy, frozen
-Seal: `d4d3f367ca135da40d2c392d22b51669281d2d8268c0a5aa22ebf738cbe65080` → `02727e76acd7a3df06a0ba0801edf131c5cb718859e5d2b511bf7142068f8c92`.
+Seal: `c3e74a3069651a7ae638b2ecba5e38c4dbaec2831865318a52f254b5a041160f` → `4abde13ec40d53a479684b7f1e2079fbedb6c40cb1a28819c97853cdab768b2f`.
Overlay: `internal/provision/testdata/plan14-root-reads-config-receipts-1.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/reviews/CHECK-BRIEF-audit-aws-timeouts-R2-fix.md b/docs/superpowers/reviews/CHECK-BRIEF-audit-aws-timeouts-R2-fix.md
new file mode 100644
index 000000000..faa954b13
--- /dev/null
+++ b/docs/superpowers/reviews/CHECK-BRIEF-audit-aws-timeouts-R2-fix.md
@@ -0,0 +1,34 @@
+# Scoped check: audit-aws-timeouts, after round 2 (not a review round)
+
+Repo carlos/platform, branch `audit-aws-timeouts`, commit 0f6a4993ef058677b4cedf9ba0d332f94b500cb0.
+
+Round 2 (`docs/superpowers/reviews/FINDINGS-audit-aws-timeouts-R2.md`)
+ended READY AFTER FIXES with three P2s in one fault family (root-worker
+liveness). Stopping rule 2 applied; Paul chose central enforcement. The
+fix is commit b409dee1 (then 55fdf6a2 merges main, 0f6a4993 re-proposes
+the census). AGENTS.md "Stopping rules" rule 1: the review does not
+reopen, but two checks apply to the fix's diff: the census, and review of
+the newly changed production-storage behaviour. This is that check.
+
+Scope: `git show b409dee1` and the census card
+`docs/superpowers/notes/census-proposal-audit-aws-timeouts.md`. Nothing
+else.
+
+Check:
+1. Do the three round-2 P2s close? (a) a non-legacy AWS_DEFAULTS_MODE
+ keeps the body bound; (b) the bounded transport never speaks HTTP/2,
+ including ALPN; (c) a 307/308 redirect body drain is bounded.
+2. Does the fix break anything the bound clients did before: AWS_CA_BUNDLE,
+ s3compat endpoints, IMDS/STS/SSO credential loading, caller-supplied
+ WithHTTPClient (the implementer restored "a caller's own client wins";
+ the guard test keeps such overrides out of root-binary production
+ code), the SDK's redirect policy, connection reuse?
+3. The guard test `TestAWSClientsAreBounded` and its allowlist: does it
+ actually catch an unbounded client in the root binary's graph, and is
+ each allowlist entry justified?
+4. Census: a verdict for every unit and envelope on the card at this tip.
+
+Answer each item: OK, or a finding with file:line, failure scenario and
+fix, marked P1 (unsafe or broken) or P2. End with exactly one line:
+CHECK PASSED, or CHECK FAILED with the P1s. Do not edit files, do not
+spawn reviewers or agents, do not run full test suites.
diff --git a/docs/superpowers/reviews/FINDINGS-audit-aws-timeouts-R1.md b/docs/superpowers/reviews/FINDINGS-audit-aws-timeouts-R1.md
new file mode 100644
index 000000000..0db62a974
--- /dev/null
+++ b/docs/superpowers/reviews/FINDINGS-audit-aws-timeouts-R1.md
@@ -0,0 +1,63 @@
+Reviewed `91e6d5b54af585128265effb56108ff920b1d530`, round **1 of 3**, against merge base `15b1ee6b6a65a52b82075003d8d6c2bcbb100ca5`. The pinned tip adds only the brief to the implementation commit named there.
+
+Found **one P1 and two P2s**.
+
+1. **P1 — The body timer can abort a transfer that is making progress.**
+
+ **Evidence:** [stall.go:125](/home/paulca/amadan.net/carlos/platform-audit-aws-timeouts/internal/rootaws/stall.go:125) starts a timer around the entire underlying `Read`; [stall.go:141](/home/paulca/amadan.net/carlos/platform-audit-aws-timeouts/internal/rootaws/stall.go:141) closes the body when it expires. But Go’s HTTP/1 [chunked reader:97](/home/paulca/.local/go-dist/src/net/http/internal/chunked.go:97) can perform successive underlying reads within one chunk before returning. Its early-return checks concern chunk boundaries; within a chunk, lines 131–146 continue filling the supplied buffer.
+
+ **Failure scenario:** An S3-compatible endpoint sends a large HTTP chunk incrementally. A consumer requests 32 KiB, while the server delivers 128 bytes each second. Data arrives throughout the 120-second interval, but the chunked reader has not filled the buffer or finished the chunk. The timer closes this healthy transfer and returns `bodyStallError`. Larger buffers used during downloads make this relevant beyond unusually small transfer rates.
+
+ The existing [trickle test:218](/home/paulca/amadan.net/carlos/platform-audit-aws-timeouts/internal/rootaws/stall_test.go:218) writes and flushes complete 16 KiB chunks. It does not exercise incremental delivery *within* a chunk.
+
+ **Fix:** Measure progress below HTTP chunk decoding, while retaining request-scoped cancellation and the exemption for pauses between consumer reads. Avoid connection-wide deadlines that could terminate unrelated HTTP/2 streams. Add a regression test that delivers one chunk in smaller fragments, with every fragment arriving within the idle limit but the enclosing `Read` taking longer.
+
+ **Fault family:** Transfer progress — receiving bytes must prevent an idle timeout. This is a source-verified failure scenario; execution was blocked by the sandbox.
+
+2. **P2 — Move storage probes remain an unbounded root-side gap.**
+
+ **Evidence:** [movesstore.go:48](/home/paulca/amadan.net/carlos/platform-audit-aws-timeouts/internal/host/movesstore.go:48) constructs an S3 client directly, without either new bound. Its list, put, get and delete operations use the incoming context unchanged. [movesreport.go:549](/home/paulca/amadan.net/carlos/platform-audit-aws-timeouts/internal/host/movesreport.go:549) supplies that context without a deadline. The instances loop creates it from `context.Background()` at [agent.go:4663](/home/paulca/amadan.net/carlos/platform-audit-aws-timeouts/internal/host/agent.go:4663), then calls `runMovesPass` at line 4699. The pass holds `w.pass` throughout, starting at [movespass.go:1096](/home/paulca/amadan.net/carlos/platform-audit-aws-timeouts/internal/host/movespass.go:1096).
+
+ **Failure scenario:** During a move’s target storage check, a configured object store accepts the request and stops answering. The instances loop remains blocked, holding the moves-pass mutex; another pass cannot progress either. This retains the root-agent failure the audit is addressing.
+
+ **Fix:** Give these small probe operations explicit request deadlines covering response-body consumption, or apply the corrected shared stall policy to this directly constructed client. Preserve its delivered static credentials, endpoint and checksum settings.
+
+ **Fault family:** Root-worker liveness — an external storage probe must not indefinitely occupy the shared worker.
+
+3. **P2 — The stated six-minute worst-case duration is incorrect.**
+
+ **Evidence:** [stall.go:26](/home/paulca/amadan.net/carlos/platform-audit-aws-timeouts/internal/rootaws/stall.go:26) claims approximately six minutes “at worst.” The header and body timers are independent.
+
+ **Failure scenario:** Each attempt receives headers just before 120 seconds, then stalls while the SDK decodes the body for another 120 seconds. Three attempts take nearly twelve minutes, plus connection establishment and retry delays. Successful body progress before the eventual stall can extend elapsed time further; upload time is also deliberately unbounded by these timers.
+
+ **Fix:** Describe these as per-phase inactivity limits. Restrict the six-minute estimate to three attempts each encountering one immediate 120-second stall, excluding other elapsed time. Keep whole-request and whole-pass deadlines as separate guarantees.
+
+ **Fault family:** Timeout contract — operational duration claims must match the implemented bounds.
+
+No P3 findings.
+
+The remaining checks produced these conclusions:
+
+- **Configuration compatibility:** Keeping the client buildable preserves CA-bundle handling and defaults-mode dial/TLS adjustments. `s3compat` still applies its endpoint and middleware settings. Caller `WithHTTPClient` options can deliberately replace the header-bound client; ordinary `WithAPIOptions` calls append in this installed SDK and retain the body middleware. Arbitrary caller options can still replace the API-options slice. These are caller-controlled extension points, not newly granted tenant authority.
+- **Connection pooling:** Sharing depends on defaults mode. Legacy mode can retain the shared buildable client; supported non-legacy modes clone it during service-client construction, as shown in [the SDK’s client resolver:554](/home/paulca/go/pkg/mod/github.com/aws/aws-sdk-go-v2/service/s3@v1.105.0/api_client.go:554). Existing transport limits remain intact. I found no correctness issue from pooling.
+- **Retries:** The timeout interfaces make errors returned during SDK deserialization retryable. A streamed `GetObject` body failure occurs after the SDK operation returns, so the SDK does **not** automatically retry that read. For example, [S3Store.Get:935](/home/paulca/amadan.net/carlos/platform-audit-aws-timeouts/internal/release/store.go:935) returns the subsequent `io.ReadAll` error directly. All new integration tests configure one attempt, so they do not demonstrate retries.
+- **Timer lifecycle:** Serial reads reuse one timer, stopped after each read. Ordinary consumer pauses leave it disarmed. I found no additional persistent timer/goroutine leak or wrapper-field race with concurrent `Close` for the default HTTP bodies. There is an expiry/completion boundary race, as the implementation comments acknowledge.
+- **Values and streaming:** The three cited existing limits are indeed 120 seconds. They support retaining that conservative value, but do not establish that every shorter value would be safe. Multipart request-body upload time and presigning are not capped by these response timers. Event-stream decoding passes through the body wrapper and is subject to finding 1.
+- **Lease cleanup:** Both error paths release immediately, preserve the original construction error and clear `c.release`, preventing a second release from the outer defer. `Held.Release` still stops the renewer before releasing remotely. No cut-state or ordering regression found.
+- **Other exclusions:** `grouprollaws` has its own bounds; the host-fence loop supplies a two-minute pass deadline; `NewStagingMirrorAt` has no production callers. The mail sender, non-group SSM loader and diagnostic `moveprobe` are reasonable follow-up scope. The move storage probe is the exception described above.
+
+The tests provide useful regression coverage, with limits. Loader assertions and the lease-release deadline assertion would detect the old behavior. The stall tests would hang without the bounds; their ten-second elapsed-time assertion is checked only after return and is not itself a watchdog. CA-bundle, trickle and pausing-reader tests protect compatibility and need not fail against the old implementation. The trickle test’s 50 ms sleeps against a 300 ms timeout can flake if a loaded runner delays the server sufficiently.
+
+**Census verdicts for this tip:**
+
+| Unit or envelope | Verdict | Evidence and basis |
+|---|---|---|
+| `internal/rootaws/stall.go:idleBody.Read` | **Approve `legacy` / `accepted-legacy`** | [stall.go:95](/home/paulca/amadan.net/carlos/platform-audit-aws-timeouts/internal/rootaws/stall.go:95) supplies an existing HTTP response body; lines 121–143 read and close it. No filesystem path, executable or additional root authority is introduced. |
+| `internal/rootaws` envelope | **Approve** | Reviewed [config.go:39](/home/paulca/amadan.net/carlos/platform-audit-aws-timeouts/internal/rootaws/config.go:39), the complete new `stall.go`, and loader/middleware dependencies. Root credential refusals and shared-file suppression remain enforced. The functional timeout defect above does not widen root’s read authority. |
+| `internal/host` envelope | **Approve** | Reviewed [movescut.go:889](/home/paulca/amadan.net/carlos/platform-audit-aws-timeouts/internal/host/movescut.go:889) through `releaseLease`, its `Held.Release` dependency and the added test. The change bounds an existing release; it introduces no new target, read authority or weakened guard. |
+
+These are census authority verdicts, not approval of the branch’s functional behavior.
+
+`git diff --check` passed. Targeted tests could not start because Go could not create its build directory in the read-only sandbox. No test execution or census-test pass is claimed. No files were edited, no subagents were spawned, and no full suites were run.
+
+**NOT READY**
\ No newline at end of file
diff --git a/docs/superpowers/reviews/FINDINGS-audit-aws-timeouts-R2.md b/docs/superpowers/reviews/FINDINGS-audit-aws-timeouts-R2.md
new file mode 100644
index 000000000..add738ff2
--- /dev/null
+++ b/docs/superpowers/reviews/FINDINGS-audit-aws-timeouts-R2.md
@@ -0,0 +1,74 @@
+Reviewed `1325f6ec6d49bdd004ea5a637d7133d901bc50a1`, round **2 of 3**, against merge base `15b1ee6b6a65a52b82075003d8d6c2bcbb100ca5`. The requested tip adds only review documents after the implementation tip named in the brief.
+
+- **R1 P1, healthy chunked transfers aborted: resolved.** Progress is now measured below chunk decoding; the new single-chunk regression test exercises the original failure.
+- **R1 P2, unbounded move-probe client: resolved.** `probeStoreOptions` installs both shared bounds while preserving the delivered credentials, endpoint and checksum settings.
+- **R1 P2, incorrect worst-case duration: resolved.** The implementation comment now distinguishes independent phase limits from whole-call deadlines.
+
+Found **no P1s and three P2s**. These are remaining coverage gaps, with source-verified failure paths; test execution was blocked by the sandbox.
+
+1. **P2 — Non-legacy defaults modes silently disable body-stall protection.**
+
+ **Evidence:** [stall.go:179](/home/paulca/amadan.net/carlos/platform-audit-aws-timeouts/internal/rootaws/stall.go:179) returns the unwrapped response whenever the connection lacks `progressConn`. The installed S3 SDK calls `WithDialerOptions` for supported non-legacy modes at [api_client.go:567](/home/paulca/go/pkg/mod/github.com/aws/aws-sdk-go-v2/service/s3@v1.105.0/api_client.go:567), which replaces the wrapped `DialContext` at [client.go:145](/home/paulca/go/pkg/mod/github.com/aws/aws-sdk-go-v2@v1.44.0/aws/transport/http/client.go:145).
+
+ **Failure scenario:** With `AWS_DEFAULTS_MODE=standard`, a root worker receives response headers and then waits indefinitely for the body. The header timer has finished, and no body timer is installed. This affects ordinary configurations without an explicit custom HTTP client.
+
+ **Fix:** Preserve progress instrumentation through defaults-mode service-client construction, including credential clients. Alternatively, explicitly refuse unsupported modes before starting work. Add an integration test that constructs the actual service client under a non-legacy mode and verifies a stalled body times out.
+
+ **Fault family:** Root-worker liveness — ordinary configuration must not silently remove the protection against an indefinitely blocked storage call.
+
+ I do **not** accept this as an implicit opt-out. An explicitly supplied custom HTTP client is a reasonable caller-controlled override; selecting AWS defaults mode is not an explicit request to disable body protection.
+
+2. **P2 — Unrelated HTTP/2 traffic can keep a stalled response alive indefinitely.**
+
+ **Evidence:** [progressConn.Read:121](/home/paulca/amadan.net/carlos/platform-audit-aws-timeouts/internal/rootaws/stall.go:121) records every received connection byte. [idleBody.check:257](/home/paulca/amadan.net/carlos/platform-audit-aws-timeouts/internal/rootaws/stall.go:257) treats that timestamp as progress for every response using the connection. HTTP/2 remains enabled by the SDK’s [default transport:217](/home/paulca/go/pkg/mod/github.com/aws/aws-sdk-go-v2@v1.44.0/aws/transport/http/client.go:217).
+
+ **Failure scenario:** An HTTP/2-compatible storage endpoint sends headers for request A, then never sends its remaining body. Request B continues receiving data on the same connection, or the endpoint sends periodic PING frames. Every timer check for A observes recent connection traffic and rearms forever. No additional application request is necessary in the PING case.
+
+ The comment that other streams “can only delay a timeout” understates this: the delay can be unlimited.
+
+ **Fix:** Measure HTTP/2 progress per response stream, retaining connection-level measurement for HTTP/1 chunk decoding. If that cannot be supported in this slice, explicitly restrict the bounded transport to HTTP/1 where compatible. Add a two-stream regression test proving that activity on one stream cannot preserve another stalled stream.
+
+ **Fault family:** Root-worker liveness — unrelated traffic must not satisfy a blocked operation’s progress requirement.
+
+3. **P2 — Redirect-body reads occur before the body timer is installed.**
+
+ **Evidence:** [stall.go:174](/home/paulca/amadan.net/carlos/platform-audit-aws-timeouts/internal/rootaws/stall.go:174) waits for the downstream HTTP call to return before wrapping its response body at line 186. The SDK permits 307/308 redirects at [client.go:325](/home/paulca/go/pkg/mod/github.com/aws/aws-sdk-go-v2@v1.44.0/aws/transport/http/client.go:325). Before following one, Go drains small or unknown-length response bodies using `io.CopyN` at [net/http/client.go:713](/home/paulca/.local/go-dist/src/net/http/client.go:713).
+
+ **Failure scenario:** An endpoint returns `307`, a valid `Location`, and `Content-Length: 100`, then sends no body. `http.Client.Do` blocks draining those bytes. The header timeout has completed, and the middleware has not yet received the response, so neither bound ends the wait. This also affects the newly bounded move probe under legacy defaults and HTTP/1.
+
+ **Fix:** Apply body protection at the response transport boundary, before the HTTP client performs redirect-body reads. Preserve the existing redirect policy. Add a regression test with a stalled 307/308 body and an independent test deadline.
+
+ **Fault family:** Root-worker liveness — every response-body read performed for a storage call must receive the bound, including reads inside the HTTP client.
+
+No P3 findings.
+
+The other requested checks produced these conclusions:
+
+- **Healthy transfers and consumer pauses:** The new connection timestamp fixes the original slow-chunk failure. Reads start their own idle interval, so time spent between consumer reads is excluded. Multipart upload duration and presigning are not capped by these response timers. Streamed responses remain subject to the coverage gaps above.
+- **Timer lifecycle:** Serial reads reuse one timer and stop it after returning. Callback state is mutex-protected; connection timestamps are atomic. I found no additional persistent timer/goroutine leak or wrapper-state race with concurrent `Close` for the standard HTTP bodies. Expiry can still race with arriving data at the timeout boundary.
+- **Configuration:** CA-bundle loading preserves the transport options. `s3compat` retains its endpoint, checksum and middleware behavior. Caller `WithHTTPClient` options intentionally win; ordinary `WithAPIOptions` calls append in the installed SDK. Root shared-profile refusals and credential-file restrictions remain intact.
+- **Connection pooling:** Legacy-mode service clients can share the configured client and pool. Non-legacy modes clone it. Existing pool limits remain unchanged. HTTP/2 sharing matters because of finding 2.
+- **Retries:** `bodyStallError` implements the timeout interfaces recognized by the SDK. Errors during SDK deserialization are retryable. A streamed `GetObject` body fails after the operation returns, so the SDK does not automatically retry that read; `S3Store.Get` propagates its `io.ReadAll` error.
+- **Values:** The three cited existing whole-request limits are 120 seconds. Keeping that conservative value is consistent with them. They do not prove a shorter limit safe. Three attempts can approach twelve minutes plus connection establishment and backoff when both phase limits are consumed, and progress before stalling can extend this.
+- **Lease cleanup:** Both construction-error paths now use the existing ten-second release context, preserve the original error and clear the release handle. `Held.Release` still stops the renewer before remote release. I found no cut-state or ordering regression.
+- **Excluded clients:** `grouprollaws` has separate bounds; the host-fence loop supplies a two-minute pass deadline. The other listed exclusions remain reasonable follow-up scope; the direct move probe was the root-worker gap requiring inclusion here.
+
+The tests cover the original regressions, but do not establish the remaining cases. Loader and release-deadline assertions detect the old behavior; the new fragmented-chunk test targets the round-one P1. Compatibility tests need not fail against the original implementation. Progress tests now allow substantially more scheduling slack, though their wall-clock sleeps can still flake after a sufficiently long scheduling delay. Stall tests use one attempt, so they do not demonstrate retries. Their elapsed-time assertion runs only after return and is not an independent watchdog.
+
+**Census verdicts at the requested tip:**
+
+| Unit or envelope | Verdict | Evidence and basis |
+|---|---|---|
+| `internal/host/movesstore.go:probeStore` | **Approve existing `legacy` / `accepted-legacy` disposition** | Reviewed [probeStore:46](/home/paulca/amadan.net/carlos/platform-audit-aws-timeouts/internal/host/movesstore.go:46) and `probeStoreOptions`, lines 81–99. Same credentials, destinations, operations and bounded body consumption; no additional root read authority. |
+| `internal/rootaws/stall.go:idleBody.Read` | **Approve new `legacy` / `accepted-legacy` disposition** | Reviewed [Read:220](/home/paulca/amadan.net/carlos/platform-audit-aws-timeouts/internal/rootaws/stall.go:220), `check` and `Close`, through line 268. Reads the existing HTTP response body; introduces no filesystem path or executable input. |
+| `internal/rootaws/stall.go:progressConn.Read` | **Approve new `legacy` / `accepted-legacy` disposition** | Reviewed [Read:121](/home/paulca/amadan.net/carlos/platform-audit-aws-timeouts/internal/rootaws/stall.go:121) and its construction at lines 96–108. Reads the connection already dialed for the request and records timing; adds no destination-selection authority. |
+| `internal/rootaws` envelope | **Approve** | Reviewed all of `stall.go`, [config.go:39](/home/paulca/amadan.net/carlos/platform-audit-aws-timeouts/internal/rootaws/config.go:39) through both loaders and their credential restrictions, plus the changed tests and SDK dependencies. No root credential guard or validation is weakened. |
+| `internal/host` envelope | **Approve** | Reviewed the complete changed probe path and [movescut.go:889](/home/paulca/amadan.net/carlos/platform-audit-aws-timeouts/internal/host/movescut.go:889) through `releaseLease`, their dependencies and added tests. Existing operations gain timeout handling; no additional root authority is granted. |
+
+These census approvals concern authority, not functional completeness.
+
+`git diff --check` passed. Targeted tests could not start: Go could not create its work directory in the read-only sandbox. No test or census-test pass is claimed. No files were edited, no subagents were spawned, and no full suites were run.
+
+This is the first round without P1s, so the review stops here. Root-worker liveness has findings in both rounds; stopping rule 2 applies. The implementation should choose explicit refusal of unsupported cases, cut unsupported transport behavior, or enforce the invariant centrally with guard tests. I recommend central enforcement before HTTP-client body consumption. The resulting production-storage changes and census still require the scoped checks specified by rule 1, without reopening the full review.
+
+**READY AFTER FIXES**
\ No newline at end of file
diff --git a/docs/superpowers/reviews/REVIEW-BRIEF-audit-aws-timeouts-R2.md b/docs/superpowers/reviews/REVIEW-BRIEF-audit-aws-timeouts-R2.md
new file mode 100644
index 000000000..11befdb14
--- /dev/null
+++ b/docs/superpowers/reviews/REVIEW-BRIEF-audit-aws-timeouts-R2.md
@@ -0,0 +1,99 @@
+# Review brief: branch audit-aws-timeouts, round 2 of 3
+
+Repo carlos/platform, branch `audit-aws-timeouts`, commit 43f121edd3496fdec7f0b0c6d02aa1c4fd416015.
+Under review: the diff `origin/main...43f121edd3496fdec7f0b0c6d02aa1c4fd416015` (base 15b1ee6b).
+Authorities: AGENTS.md on main ("The census", "Stopping rules"). Context:
+amadan discussion #1123 (Go audit backlog, first batch item 1).
+
+You are an independent reviewer. Read the diff, then the code it touches,
+and check every claim in the commit messages against that code. This
+branch changes **production storage** behaviour: every AWS client the
+platform builds through internal/rootaws, including the root host agent's.
+
+You are also the census reviewer: the card is
+`docs/superpowers/notes/census-proposal-audit-aws-timeouts.md`. Give a
+verdict for every unit and envelope it lists, citing the lines you read,
+per AGENTS.md "Getting a change approved" step 4.
+
+## What to check
+
+1. `internal/rootaws/stall.go`: ResponseHeaderTimeout 120 s and a
+ body-idle timeout 120 s that runs only while a Read is waiting. Can it
+ ever cut a transfer that is making progress, or a caller that pauses
+ between reads (streamed GetObject handed to a slow consumer, multipart
+ or manager uploads, S3 Select/streaming APIs, presigned flows)? Does the
+ timer leak (goroutine or timer per body) or race with Close? Is the
+ error surfaced so the SDK retries it sensibly?
+2. Installing one HTTP client per loaded config: any loss of an existing
+ option (AWS_CA_BUNDLE, custom endpoints via s3compat, defaults modes,
+ caller-supplied HTTP clients overriding ours or being overridden)?
+ Ordering: bounds are added ahead of caller options; can a caller
+ option silently remove them, and is that acceptable?
+3. Shared connection pool across service clients from one config: any
+ effect on behaviour or limits?
+4. Values: 120 s each, so a stalled call with 3 SDK attempts fails in
+ about 6.5 min at worst. Is that consistent with the per-request limits
+ already in the tree (hostbox.RequestLimit, lease stagingRequestTimeout,
+ generationRequestLimit)? Would a shorter value break anything you can
+ name?
+5. `internal/host/movescut.go`: error-path lease releases now go through
+ `releaseLease` (10 s) and log a failure instead of dropping it. Any
+ ordering change against the renewer stop or the cut's state?
+6. The implementer's list of sites NOT covered (grouprollaws, hostfence,
+ mail/sessend, hostenv SSM non-root path, movesstore, NewStagingMirrorAt,
+ cmd/moveprobe): is any root-side one a real gap that should be covered
+ in this branch rather than a follow-up?
+7. Tests: would each fail against the old code? Any wall-clock sleeps that
+ could flake on a loaded runner?
+
+## Round 2
+
+Earlier rounds: round 1, Astra, `docs/superpowers/reviews/FINDINGS-audit-aws-timeouts-R1.md`
+(NOT READY: one P1, two P2s; census approved at 91e6d5b5).
+
+First give one line per P1 and P2 from round 1: resolved, partly, or not.
+Carry every unresolved or partly resolved finding forward at its current
+severity, then add new findings. The verdict covers everything
+outstanding, earlier rounds included.
+
+Fixes since round 1: 93be380b (progress measured on the connection below
+TLS and chunk decoding, via a wrapped DialContext and an httptrace GotConn
+lookup; comment on per-phase limits), 6bf4d1e8 (move storage probe gets
+the shared bounds via rootaws.StallHTTPClient / StallAPIOptions), 43f121ed
+(census overlay re-run). The implementer notes one accepted gap: a
+connection the wrapper did not dial (another HTTP client, or a
+non-legacy AWS_DEFAULTS_MODE swapping DialContext) gets only the header
+bound, by choice, so a healthy transfer is never cut. Judge whether that
+is acceptable. The census card has changed (new unit progressConn.Read,
+changed unit host probeStore): give fresh verdicts for every unit and
+envelope at this tip.
+
+## Severity
+
+- **P1**: unsafe, would not compile, a test fails, or it would not work.
+ Blocks merge.
+- **P2**: wrong or missing. Fixed without reopening this review. (The
+ census, and review of any newly changed security, root, termination
+ or production-storage behaviour, still check the fix; see AGENTS.md,
+ "Stopping rules".)
+- **P3**: clarity or polish. Goes on a follow-up list; never a reason for
+ another round.
+
+A P1 states its failure scenario and the evidence (file:line). Do not
+raise a P2 to P1 to keep the review open.
+
+## Output
+
+Findings ranked P1, P2, P3. Each gives the section or task, the problem,
+the evidence (file:line, verified), the failure scenario, a concrete
+fix and the invariant or trust boundary it breaks (that is its fault
+family). Then the census verdict per unit and envelope. End with exactly
+one verdict:
+
+- **READY**: no P1 and no P2.
+- **READY AFTER FIXES**: no P1. The listed P2s are fixed without another
+ round.
+- **NOT READY**: one or more P1s, listed.
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents of
+your own. Do not run the full test suites.
diff --git a/docs/superpowers/reviews/REVIEW-BRIEF-audit-aws-timeouts.md b/docs/superpowers/reviews/REVIEW-BRIEF-audit-aws-timeouts.md
new file mode 100644
index 000000000..08ead4cc2
--- /dev/null
+++ b/docs/superpowers/reviews/REVIEW-BRIEF-audit-aws-timeouts.md
@@ -0,0 +1,77 @@
+# Review brief: branch audit-aws-timeouts, round 1 of 3
+
+Repo carlos/platform, branch `audit-aws-timeouts`, commit bfe0e558be1d07011d84cba795b8ed786d718926.
+Under review: the diff `origin/main...bfe0e558be1d07011d84cba795b8ed786d718926` (base 15b1ee6b).
+Authorities: AGENTS.md on main ("The census", "Stopping rules"). Context:
+amadan discussion #1123 (Go audit backlog, first batch item 1).
+
+You are an independent reviewer. Read the diff, then the code it touches,
+and check every claim in the commit messages against that code. This
+branch changes **production storage** behaviour: every AWS client the
+platform builds through internal/rootaws, including the root host agent's.
+
+You are also the census reviewer: the card is
+`docs/superpowers/notes/census-proposal-audit-aws-timeouts.md`. Give a
+verdict for every unit and envelope it lists, citing the lines you read,
+per AGENTS.md "Getting a change approved" step 4.
+
+## What to check
+
+1. `internal/rootaws/stall.go`: ResponseHeaderTimeout 120 s and a
+ body-idle timeout 120 s that runs only while a Read is waiting. Can it
+ ever cut a transfer that is making progress, or a caller that pauses
+ between reads (streamed GetObject handed to a slow consumer, multipart
+ or manager uploads, S3 Select/streaming APIs, presigned flows)? Does the
+ timer leak (goroutine or timer per body) or race with Close? Is the
+ error surfaced so the SDK retries it sensibly?
+2. Installing one HTTP client per loaded config: any loss of an existing
+ option (AWS_CA_BUNDLE, custom endpoints via s3compat, defaults modes,
+ caller-supplied HTTP clients overriding ours or being overridden)?
+ Ordering: bounds are added ahead of caller options; can a caller
+ option silently remove them, and is that acceptable?
+3. Shared connection pool across service clients from one config: any
+ effect on behaviour or limits?
+4. Values: 120 s each, so a stalled call with 3 SDK attempts fails in
+ about 6.5 min at worst. Is that consistent with the per-request limits
+ already in the tree (hostbox.RequestLimit, lease stagingRequestTimeout,
+ generationRequestLimit)? Would a shorter value break anything you can
+ name?
+5. `internal/host/movescut.go`: error-path lease releases now go through
+ `releaseLease` (10 s) and log a failure instead of dropping it. Any
+ ordering change against the renewer stop or the cut's state?
+6. The implementer's list of sites NOT covered (grouprollaws, hostfence,
+ mail/sessend, hostenv SSM non-root path, movesstore, NewStagingMirrorAt,
+ cmd/moveprobe): is any root-side one a real gap that should be covered
+ in this branch rather than a follow-up?
+7. Tests: would each fail against the old code? Any wall-clock sleeps that
+ could flake on a loaded runner?
+
+## Severity
+
+- **P1**: unsafe, would not compile, a test fails, or it would not work.
+ Blocks merge.
+- **P2**: wrong or missing. Fixed without reopening this review. (The
+ census, and review of any newly changed security, root, termination
+ or production-storage behaviour, still check the fix; see AGENTS.md,
+ "Stopping rules".)
+- **P3**: clarity or polish. Goes on a follow-up list; never a reason for
+ another round.
+
+A P1 states its failure scenario and the evidence (file:line). Do not
+raise a P2 to P1 to keep the review open.
+
+## Output
+
+Findings ranked P1, P2, P3. Each gives the section or task, the problem,
+the evidence (file:line, verified), the failure scenario, a concrete
+fix and the invariant or trust boundary it breaks (that is its fault
+family). Then the census verdict per unit and envelope. End with exactly
+one verdict:
+
+- **READY**: no P1 and no P2.
+- **READY AFTER FIXES**: no P1. The listed P2s are fixed without another
+ round.
+- **NOT READY**: one or more P1s, listed.
+
+Do not edit files. Do not spawn Anthropic-model reviewers or subagents of
+your own. Do not run the full test suites.
diff --git a/internal/host/movescut.go b/internal/host/movescut.go
index 815bffc28..2a2a4836d 100644
--- a/internal/host/movescut.go
+++ b/internal/host/movescut.go
@@ -907,14 +907,18 @@ func (c *cutRun) lease(ctx context.Context) (waiting bool, err error) {
}
return false, fmt.Errorf("staging lease: %w", err)
}
+ // The error paths release through releaseLease, with its bound: a store
+ // that hangs at this moment must not hang the cut's goroutine.
stg, err := c.w.staging(ctx, tgt.DataBucketRegion)
if err != nil {
- rel(context.Background())
+ c.release = rel
+ c.releaseLease()
return false, err
}
own, err := c.w.mirror(ctx, tgt.DataBucketRegion)
if err != nil {
- rel(context.Background())
+ c.release = rel
+ c.releaseLease()
return false, err
}
c.gm = &guardedMirror{w: stg, g: moves.Guarded{Lease: held, Now: cfg.Now}, dst: tgt.DataBucket, own: own}
diff --git a/internal/host/movescut_leaserelease_test.go b/internal/host/movescut_leaserelease_test.go
new file mode 100644
index 000000000..f23881f82
--- /dev/null
+++ b/internal/host/movescut_leaserelease_test.go
@@ -0,0 +1,63 @@
+package host
+
+import (
+ "context"
+ "errors"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/lease"
+ "github.com/carlosframework/platform/internal/moves"
+ "github.com/carlosframework/platform/internal/provision"
+)
+
+// The cut's staging lease is released with a bounded context on every
+// path: when the staging writer or the mirror cannot be built right after
+// the lease is taken, as on the normal release (releaseLease's 10 s).
+func TestCutReleasesStagingLeaseBoundedOnError(t *testing.T) {
+ for _, fail := range []string{"staging", "mirror"} {
+ t.Run(fail, func(t *testing.T) {
+ h := newCutHarness(t)
+ h.ready(t)
+ // Stopped, with execution given up: the next pass is the final
+ // round, which takes the cut's own lease (cutRun.lease). The
+ // requested phase's source round has a lease of its own.
+ h.crashAt = "after-exec-none"
+ h.cut(t)
+ h.crashPass(t)
+ if m := h.move(t); m.CutPhase != provision.CutStopped {
+ t.Fatalf("the fixture did not stop: %+v", m)
+ }
+ var released []time.Duration
+ h.cfg.StagingLease = func(context.Context, string, string) (moves.SafeUntilGuard, func(context.Context) error, error) {
+ return h.lease, func(ctx context.Context) error {
+ d, ok := ctx.Deadline()
+ if !ok {
+ released = append(released, -1)
+ return nil
+ }
+ released = append(released, time.Until(d))
+ return nil
+ }, nil
+ }
+ broken := errors.New("injected " + fail + " failure")
+ switch fail {
+ case "staging":
+ h.cfg.Staging = func(context.Context, string) (lease.StagingWriter, error) { return nil, broken }
+ case "mirror":
+ h.cfg.Mirror = func(context.Context, string) (lease.MirrorStore, error) { return nil, broken }
+ }
+ h.freshWorker() // the worker memoizes its staging writer and mirrors
+ _ = movesPass(context.Background(), h.s, h.w())
+ if m := h.move(t); m.CutPhase != provision.CutStopped {
+ t.Fatalf("the failed final round moved the cut on: %+v", m)
+ }
+ if len(released) != 1 {
+ t.Fatalf("the lease was released %d times, want once", len(released))
+ }
+ if d := released[0]; d <= 0 || d > 10*time.Second {
+ t.Fatalf("released with deadline %v away, want a bound of at most 10s", d)
+ }
+ })
+ }
+}
diff --git a/internal/host/movesstore.go b/internal/host/movesstore.go
index 7d1b1e9e1..63999245f 100644
--- a/internal/host/movesstore.go
+++ b/internal/host/movesstore.go
@@ -16,6 +16,7 @@ import (
"github.com/carlosframework/platform/internal/lease"
"github.com/carlosframework/platform/internal/moves"
"github.com/carlosframework/platform/internal/objstore"
+ "github.com/carlosframework/platform/internal/rootaws"
)
// The storage probes of the target's report: T4's probe of every store
@@ -31,6 +32,9 @@ import (
// credentials, the delivered region, and the endpoint path-style when one
// is delivered.
func probeStores(ctx context.Context, env map[string]string, id string) (string, error) {
+ // The caller's context has no deadline (the instances loop's pass), and
+ // the pass holds the moves worker's mutex throughout, so the probe
+ // client carries the shared stall bounds (probeStoreOptions).
for _, p := range storePrefixes(env) {
if err := probeStore(ctx, env, p, id); err != nil {
return p, err
@@ -40,22 +44,8 @@ func probeStores(ctx context.Context, env map[string]string, id string) (string,
}
func probeStore(ctx context.Context, env map[string]string, prefix, id string) error {
- bn, rn, en, ak, sk := objstore.EnvNames(prefix)
- region := env[rn]
- if region == "" {
- region = "us-east-1"
- }
- opts := awss3.Options{
- Region: region,
- Credentials: credentials.NewStaticCredentialsProvider(env[ak], env[sk], ""),
- RequestChecksumCalculation: aws.RequestChecksumCalculationWhenRequired,
- ResponseChecksumValidation: aws.ResponseChecksumValidationWhenRequired,
- }
- if ep := env[en]; ep != "" {
- opts.BaseEndpoint = aws.String(ep)
- opts.UsePathStyle = true
- }
- c := awss3.New(opts)
+ bn, _, _, _, _ := objstore.EnvNames(prefix)
+ c := awss3.New(probeStoreOptions(env, prefix))
bucket := aws.String(env[bn])
key := aws.String(".carlos-move-probe/" + id)
body := []byte("carlos move probe " + id)
@@ -83,6 +73,32 @@ func probeStore(ctx context.Context, env map[string]string, prefix, id string) e
return nil
}
+// 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 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]
+ if region == "" {
+ region = "us-east-1"
+ }
+ opts := awss3.Options{
+ Region: region,
+ Credentials: credentials.NewStaticCredentialsProvider(env[ak], env[sk], ""),
+ RequestChecksumCalculation: aws.RequestChecksumCalculationWhenRequired,
+ ResponseChecksumValidation: aws.ResponseChecksumValidationWhenRequired,
+ HTTPClient: rootaws.BoundedHTTPClient(),
+ }
+ if ep := env[en]; ep != "" {
+ opts.BaseEndpoint = aws.String(ep)
+ opts.UsePathStyle = true
+ }
+ return opts
+}
+
// laneProbe is T10 in production: put-if-absent then delete-by-version of
// moves/_lane/<id> in the source's bucket. A probe object left by an earlier
// pass whose delete failed is removed by version and the check fails this
diff --git a/internal/host/movesstore_stall_test.go b/internal/host/movesstore_stall_test.go
new file mode 100644
index 000000000..a15a7994f
--- /dev/null
+++ b/internal/host/movesstore_stall_test.go
@@ -0,0 +1,35 @@
+package host
+
+import (
+ "context"
+ "testing"
+
+ "github.com/aws/aws-sdk-go-v2/aws"
+
+ "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 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")
+
+ 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())
+ if err != nil || creds.AccessKeyID != "AK" || creds.SecretAccessKey != "SK" {
+ t.Fatalf("credentials changed: %+v %v", creds, err)
+ }
+ if o.Region != "eu-west-2" || o.BaseEndpoint == nil || *o.BaseEndpoint != "https://store.example.com" || !o.UsePathStyle {
+ t.Fatalf("region or endpoint changed: %s %v %v", o.Region, o.BaseEndpoint, o.UsePathStyle)
+ }
+ if o.RequestChecksumCalculation != aws.RequestChecksumCalculationWhenRequired || o.ResponseChecksumValidation != aws.ResponseChecksumValidationWhenRequired {
+ t.Fatalf("checksum settings changed: %v %v", o.RequestChecksumCalculation, o.ResponseChecksumValidation)
+ }
+}
diff --git a/internal/provision/testdata/plan14-root-reads-audit-aws-timeouts.tsv b/internal/provision/testdata/plan14-root-reads-audit-aws-timeouts.tsv
new file mode 100644
index 000000000..972c7ee96
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-audit-aws-timeouts.tsv
@@ -0,0 +1,11 @@
+# Census overlay audit-aws-timeouts, written by census-propose (#369). census-ruling-audit-aws-timeouts, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-audit-aws-timeouts.md.
+# 1 body, 0 sites, 2 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+# 2 new dispositions: 0 reads re-frozen at their disposition with the claim, 2 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other.
+@legacy 5a5fd7c128bbf3e2380f430c919630c3af17f72b053bfcaf79ed50f813c4f428 internal/host/movesstore.go probeStore legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-audit-aws-timeouts;basis=body: builds the same T4 probe client via probeStoreOptions (same delivered credentials, region, endpoint, checksums) with HTTPClient rootaws.BoundedHTTPClient(); operations and reads unchanged, no new root read file:ReadAll@766 ec7acc9388fcf8b65fe9f09e79d86e956853bcfdd0b315c7a3b20931dd6a4ed8
+@legacy d5a06eb3b127a364da3c08534f75ce1572ab37902b51345dfa8493251497cfc1 internal/rootaws/stall.go idleBody.Read legacy accepted-legacy accepted-legacy;rev3=census-ruling-audit-aws-timeouts;basis=new: wraps an AWS HTTP response body inside boundedTransport.RoundTrip; reads only that body (b.rc.Read) under an inactivity timer that consults the connection's last-received time; no file opened, run or named; no new root read file:Read@19,file:Read@315 203ac8d3fef1cee3c2cb99246612b58492d793ec3013d431d93c3a3a66e17348
+@legacy 420b1db0f553c8ae30f9af10e1aa847d9317904ea8580281cf8a3264989e31fb internal/rootaws/stall.go progressConn.Read legacy accepted-legacy accepted-legacy;rev3=census-ruling-audit-aws-timeouts;basis=new: net.Conn wrapper the bounded AWS transport dials; Read reads the network connection (c.Conn.Read) and records the time of the last bytes; no file opened, run or named; no new root read file:Read@23,file:Read@64 bb23c1f4d3b4bc1004bc648e0089b0a062596c9296b0387cf19e66040bbb5d81
+internal/host/movesstore.go probeStore legacy accepted-legacy accepted-legacy;rev3=J4;basis=root-input;rev3=census-ruling-audit-aws-timeouts;basis=body: builds the same T4 probe client via probeStoreOptions (same delivered credentials, region, endpoint, checksums) with HTTPClient rootaws.BoundedHTTPClient(); operations and reads unchanged, no new root read file:ReadAll@766 ec7acc9388fcf8b65fe9f09e79d86e956853bcfdd0b315c7a3b20931dd6a4ed8
+internal/rootaws/stall.go idleBody.Read legacy accepted-legacy accepted-legacy;rev3=census-ruling-audit-aws-timeouts;basis=new: wraps an AWS HTTP response body inside boundedTransport.RoundTrip; reads only that body (b.rc.Read) under an inactivity timer that consults the connection's last-received time; no file opened, run or named; no new root read file:Read@19,file:Read@315 203ac8d3fef1cee3c2cb99246612b58492d793ec3013d431d93c3a3a66e17348
+internal/rootaws/stall.go progressConn.Read legacy accepted-legacy accepted-legacy;rev3=census-ruling-audit-aws-timeouts;basis=new: net.Conn wrapper the bounded AWS transport dials; Read reads the network connection (c.Conn.Read) and records the time of the last bytes; no file opened, run or named; no new root read file:Read@23,file:Read@64 bb23c1f4d3b4bc1004bc648e0089b0a062596c9296b0387cf19e66040bbb5d81
+@coverage internal/host b0e285d662931ee8b52e23b24251a60ccbd7d4cfcccdb882f6769d7a85e16ec8
+@coverage internal/rootaws cd629ab0ddaaf55009225a8ac4de6c256a33a2942c3da5d37988ab8d9f756beb
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index 7e2d6476a..4d0d769ad 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -236,4 +236,5 @@ plan14-root-reads-sec-edge-redirect-linklocal.tsv 4eda67fee53800e2cfa4177b954c7f
plan14-root-reads-sec-unit-app-demobuild.tsv fea6bec1f00dace47aa6006bf8606602efda4cecfa4fe3c3890136c0fb27720c
plan14-root-reads-audit-request-path.tsv 3f7dc37d114377b168c6bc1ae48e7bf815dbc1f5a569274af642e00e7d08ca2a
plan14-root-reads-audit-gate-vet-staticcheck.tsv d4d3f367ca135da40d2c392d22b51669281d2d8268c0a5aa22ebf738cbe65080
-plan14-root-reads-config-receipts-1.tsv 02727e76acd7a3df06a0ba0801edf131c5cb718859e5d2b511bf7142068f8c92
+plan14-root-reads-audit-aws-timeouts.tsv c3e74a3069651a7ae638b2ecba5e38c4dbaec2831865318a52f254b5a041160f
+plan14-root-reads-config-receipts-1.tsv 4abde13ec40d53a479684b7f1e2079fbedb6c40cb1a28819c97853cdab768b2f
diff --git a/internal/rootaws/config.go b/internal/rootaws/config.go
index f24e49766..07cdecea7 100644
--- a/internal/rootaws/config.go
+++ b/internal/rootaws/config.go
@@ -35,11 +35,20 @@ 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)
+ 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) {
@@ -52,7 +61,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 {
@@ -61,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
new file mode 100644
index 000000000..394d5123e
--- /dev/null
+++ b/internal/rootaws/stall.go
@@ -0,0 +1,362 @@
+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"
+)
+
+// 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.
+//
+// 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
+// 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 its headers, or gets no bytes at all for this long, is stalled,
+// not slow, and no call that fits those whole-request bounds today can be cut
+// by these per-phase ones. How long a stalled call takes to fail depends on
+// where it stalls: one attempt that stalls at once on the headers ends in
+// 120 s, and with the SDK's three attempts in about six minutes plus dial
+// time and backoff. The timers are independent, so an attempt whose headers
+// come just inside 120 s and whose decoded body then stalls takes up to
+// 240 s, about twelve minutes over three attempts, and body progress before
+// a stall extends that further.
+const (
+ // ResponseHeaderTimeout bounds the wait for a response's headers once
+ // the request, body included, has been written.
+ ResponseHeaderTimeout = 120 * time.Second
+ // BodyIdleTimeout bounds how long a body read may wait while the
+ // 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 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...)
+}
+
+// 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)
+ })
+}
+
+// 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 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" })
+ }
+}
+
+// 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
+}
+
+// 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
+ }
+ })
+}
+
+// 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 = 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. 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
+}
+
+func (c *progressConn) Read(p []byte) (int, error) {
+ n, err := c.Conn.Read(p)
+ if n > 0 {
+ c.last.Store(time.Now().UnixNano())
+ }
+ return n, err
+}
+
+// connProgress finds the progressConn under the connection a request got:
+// net/http hands GotConn the TLS connection over it for https.
+func connProgress(c net.Conn) *progressConn {
+ for i := 0; i < 4 && c != nil; i++ {
+ if pc, ok := c.(*progressConn); ok {
+ return pc
+ }
+ u, ok := c.(interface{ NetConn() net.Conn })
+ if !ok {
+ return nil
+ }
+ c = u.NetConn()
+ }
+ return 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.
+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 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 // nil: each Read measured on its own
+
+ mu sync.Mutex // guards the fields below; never held across I/O
+ timer *time.Timer
+ reading bool
+ readStart int64 // UnixNano
+ stalled bool
+}
+
+func (b *idleBody) Read(p []byte) (int, error) {
+ b.mu.Lock()
+ if b.stalled {
+ b.mu.Unlock()
+ return 0, bodyStallError{b.idle}
+ }
+ b.reading, b.readStart = true, time.Now().UnixNano()
+ if b.timer == nil {
+ b.timer = time.AfterFunc(b.idle, b.check)
+ } else {
+ b.timer.Reset(b.idle)
+ }
+ b.mu.Unlock()
+
+ n, err := b.rc.Read(p)
+
+ b.mu.Lock()
+ b.reading = false
+ b.timer.Stop()
+ stalled := b.stalled
+ b.mu.Unlock()
+ if stalled {
+ return n, bodyStallError{b.idle}
+ }
+ return n, err
+}
+
+// check runs when the timer fires: a stall if the connection has been quiet
+// for idle since the Read began, otherwise the timer waits out the rest. A
+// check that fires after its Read returned finds reading false (or a newer
+// Read's start) and does nothing harmful.
+func (b *idleBody) check() {
+ b.mu.Lock()
+ if !b.reading || b.stalled {
+ b.mu.Unlock()
+ return
+ }
+ 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()
+ return
+ }
+ b.stalled = true
+ b.mu.Unlock()
+ b.rc.Close() // unblocks the pending Read
+}
+
+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
new file mode 100644
index 000000000..efaacf73a
--- /dev/null
+++ b/internal/rootaws/stall_test.go
@@ -0,0 +1,500 @@
+package rootaws
+
+import (
+ "bufio"
+ "bytes"
+ "context"
+ "crypto/tls"
+ "encoding/pem"
+ "errors"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/aws/aws-sdk-go-v2/aws"
+ 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"
+)
+
+// bounds reads back what a client will apply.
+func bounds(t *testing.T, c aws.HTTPClient) (header, idle time.Duration) {
+ t.Helper()
+ if !IsBounded(c) {
+ t.Fatalf("HTTP client is %T, not the bounded client", c)
+ }
+ bt := c.(*http.Client).Transport.(*boundedTransport)
+ return bt.header, bt.idle
+}
+
+// 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) {
+ 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")
+ },
+ // 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)...)
+ if err != nil {
+ return cfg, err
+ }
+ return boundConfig(cfg, BodyIdleTimeout)
+ },
+ }
+ 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 := bounds(t, cfg.HTTPClient)
+ if header != ResponseHeaderTimeout || idle != BodyIdleTimeout {
+ t.Fatalf("bounds %s/%s, want %s/%s", header, idle, ResponseHeaderTimeout, BodyIdleTimeout)
+ }
+ })
+ }
+}
+
+// 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) {
+ 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 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 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())
+ defer srv.Close()
+ t.Setenv("AWS_CA_BUNDLE", caBundle(t, srv))
+ cfg, err := LoadStaticConfig(context.Background(), "ACCESS", "SECRET")
+ if err != nil {
+ t.Fatalf("a CA bundle no longer loads: %v", err)
+ }
+ if header, _ := bounds(t, cfg.HTTPClient); header != ResponseHeaderTimeout {
+ t.Fatalf("the CA bundle dropped the header timeout: %s", header)
+ }
+}
+
+func caBundle(t *testing.T, srv *httptest.Server) string {
+ t.Helper()
+ 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)
+ }
+ return bundle
+}
+
+const (
+ // The stall tests' bounds: a stall must fail, so short is fine.
+ testHeaderTimeout = 300 * time.Millisecond
+ testIdleTimeout = 300 * time.Millisecond
+ // The progress tests' bound, with the server's gaps a twentieth of it
+ // (progressGap): a loaded runner would have to delay one write by
+ // nearly a second to fail them falsely.
+ progressIdle = time.Second
+ progressGap = progressIdle / 20
+ // 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 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()
+ 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),
+ 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
+ })
+}
+
+// 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()
+ isolatedAWSEnv(t)
+ 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:
+ }
+}
+
+// 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()
+ 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(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
+ }
+ return out.Body, nil
+}
+
+func get(c *awss3.Client) ([]byte, error) {
+ body, err := getObject(c)
+ if err != nil {
+ return nil, err
+ }
+ defer body.Close()
+ 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) })
+ stalls(t, getErr(stallClient(t, url, testIdleTimeout)))
+}
+
+func stallAfterSome(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)
+}
+
+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)
+ 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) 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{})
+ srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { stallAfterSome(w, r, done) }))
+ t.Cleanup(srv.Close)
+ t.Cleanup(func() { close(done) })
+ t.Setenv("AWS_CA_BUNDLE", caBundle(t, srv))
+ 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)
+ }
+}
+
+// (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)
+ })
+ 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
+// long but taking several times the bound overall, arrives whole.
+func TestTrickleBodySucceeds(t *testing.T) {
+ const chunks, size = 60, 4 << 10 // 60 gaps of progressIdle/20: 3x the bound
+ 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(progressGap)
+ }
+ })
+ start := time.Now()
+ 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)
+ }
+ if len(body) != chunks*size {
+ t.Fatalf("got %d bytes, want %d", len(body), chunks*size)
+ }
+}
+
+// (c) One HTTP chunk delivered in small fragments, each well inside the
+// bound, read with a buffer larger than the chunk: net/http's chunked reader
+// keeps filling that buffer until the chunk ends, so a single Read spans
+// every fragment and lasts longer than the bound while bytes keep arriving
+// (Astra round 1, P1). It must not be cut.
+func TestOneSlowChunkInOneReadSucceeds(t *testing.T) {
+ isolatedAWSEnv(t)
+ const fragments, fragment = 60, 64 // 60 gaps of progressIdle/20: 3x the bound
+ want := bytes.Repeat([]byte("z"), fragments*fragment)
+ url := rawServer(t, func(c net.Conn) {
+ fmt.Fprintf(c, "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\nContent-Type: application/octet-stream\r\n\r\n%x\r\n", len(want))
+ for i := 0; i < fragments; i++ {
+ if _, err := c.Write(want[i*fragment : (i+1)*fragment]); err != nil {
+ return
+ }
+ time.Sleep(progressGap)
+ }
+ io.WriteString(c, "\r\n0\r\n\r\n")
+ })
+ body, err := getObject(stallClient(t, url, progressIdle))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer body.Close()
+ buf := make([]byte, 2*len(want))
+ start := time.Now()
+ n, err := body.Read(buf)
+ took := time.Since(start)
+ if err != nil && err != io.EOF {
+ t.Fatalf("a chunk arriving steadily was cut off after %s: %v", took, err)
+ }
+ if took < progressIdle {
+ t.Fatalf("the Read took %s, shorter than the bound: the test proves nothing", took)
+ }
+ rest, err := io.ReadAll(body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got := append(buf[:n], rest...); !bytes.Equal(got, want) {
+ t.Fatalf("got %d bytes, want %d", len(got), len(want))
+ }
+}
+
+// rawServer answers each request on a connection with respond, writing the
+// response bytes itself; it closes its listener and connections at cleanup.
+func rawServer(t *testing.T, respond func(net.Conn)) string {
+ t.Helper()
+ ln, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var mu sync.Mutex
+ var conns []net.Conn
+ t.Cleanup(func() {
+ ln.Close()
+ mu.Lock()
+ defer mu.Unlock()
+ for _, c := range conns {
+ c.Close()
+ }
+ })
+ go func() {
+ for {
+ c, err := ln.Accept()
+ if err != nil {
+ return
+ }
+ mu.Lock()
+ conns = append(conns, c)
+ mu.Unlock()
+ go func() {
+ defer c.Close()
+ if _, err := http.ReadRequest(bufio.NewReader(c)); err != nil {
+ return
+ }
+ respond(c)
+ }()
+ }
+ }()
+ return "http://" + ln.Addr().String()
+}
+
+// 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)
+ })
+ body, err := getObject(stallClient(t, url, testIdleTimeout))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer body.Close()
+ head := make([]byte, 10)
+ if _, err := io.ReadFull(body, head); err != nil {
+ t.Fatal(err)
+ }
+ time.Sleep(3 * testIdleTimeout)
+ rest, err := io.ReadAll(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")
+ }
+}