rootaws: bound credential exchanges; keep caller clients; tighter guard
The #1143 follow-ups to the AWS stall bounds (0374ac2): - STS (web identity, assume-role), SSO and SSO OIDC credential clients and container credentials get the body bound; login-session credentials are refused (no way to bound their sign-in client). - Whether the HTTP client is ours is decided by identity before the SDK resolves: an explicit BuildableClient stays the caller's. - The fence writer and non-group host-env now use bounded clients; their allowlist entries are gone. - TestAWSClientsAreBounded reads the root binary with type information: HTTPClient set on any SDK struct and zero configs or Options are caught; the allowlist names each construction. - Credential tests dial loopback only. Reviewed by Astra (round 1, READY AFTER FIXES; P2s fixed in e140ec55), scoped check passed. Census approved on #280. P3 follow-ups on #1143. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Squashed from aws-followups-1143 into main.
14 files changed,
+1,388
−157
docs/superpowers/notes/census-proposal-aws-followups-1143.md+19 −0docs/superpowers/reviews/CHECK-BRIEF-aws-followups-1143-R1-fix.md+32 −0docs/superpowers/reviews/CHECK-aws-followups-1143-R1-fix.md+48 −0docs/superpowers/reviews/FINDINGS-aws-followups-1143-R1.md+73 −0docs/superpowers/reviews/REVIEW-BRIEF-aws-followups-1143.md+52 −0internal/hostenv/awsssm.go+4 −5internal/hostfence/writer.go+6 −1internal/provision/testdata/plan14-root-reads-aws-followups-1143.tsv+6 −0internal/provision/testdata/plan14-root-reads-chain.tsv+1 −0internal/rootaws/config.go+11 −4internal/rootaws/guard_test.go+483 −118internal/rootaws/stall.go+217 −20internal/rootaws/stall_credentials_test.go+339 −0internal/rootaws/stall_test.go+97 −9
CI passed — run details
diff --git a/docs/superpowers/notes/census-proposal-aws-followups-1143.md b/docs/superpowers/notes/census-proposal-aws-followups-1143.md| new file mode 100644 |
| index 000000000..1395a3866 |
| --- /dev/null |
| +++ b/docs/superpowers/notes/census-proposal-aws-followups-1143.md |
| @@ -0,0 +1,19 @@ |
| +# Census approval: aws-followups-1143 |
| + |
| +Ruling `census-ruling-aws-followups-1143`. The independent reviewer approves or rejects every change below, 0 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26). |
| + |
| +| unit | change | read sites | what changed | |
| +|---|---|---|---| |
| +| `internal/hostfence/writer.go` `OpenRootFenceStore` | body | unchanged (1) | the literal config now carries rootaws.BoundedHTTPClient(), so the STS AssumeRole exchange (which the credentials cache runs with the deadline removed) and the S3 client have header and body stall bounds; credentials file reads, mode checks, receipt check and credential selection unchanged; no read added | |
| + |
| +Envelopes re-pinned: `internal/hostenv`, `internal/hostfence`, `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/hostfence/writer.go` `OpenRootFenceStore`: authority, task F,J4. Basis: rev3=PROPOSED-activation-tools;identity=root fence service and explicit installer uid 0;basis=dedicated root fence credentials retain 0400 compatibility; 0600 needs a matching protected installation receipt; absent explicit installation keeps prior refusal |
| + |
| +Seal: `33e5eaaa9b2d80f6f8f5de8d04e908e39ecfc820c5fe7b44c870e671565e1063` → `33e5eaaa9b2d80f6f8f5de8d04e908e39ecfc820c5fe7b44c870e671565e1063`. |
| + |
| +Overlay: `internal/provision/testdata/plan14-root-reads-aws-followups-1143.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
diff --git a/docs/superpowers/reviews/CHECK-BRIEF-aws-followups-1143-R1-fix.md b/docs/superpowers/reviews/CHECK-BRIEF-aws-followups-1143-R1-fix.md| new file mode 100644 |
| index 000000000..a700aec9a |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/CHECK-BRIEF-aws-followups-1143-R1-fix.md |
| @@ -0,0 +1,32 @@ |
| +# Scoped check: aws-followups-1143, after round 1 (not a review round) |
| + |
| +Repo carlos/platform, branch `aws-followups-1143` (tip in the prompt). |
| +Round 1 (`docs/superpowers/reviews/FINDINGS-aws-followups-1143-R1.md`) |
| +ended READY AFTER FIXES with three P2s. The fix is commit e140ec55, census |
| +6ed4d208. AGENTS.md rule 1: no new round; production storage, root |
| +behaviour and the census are checked. Scope: `git show e140ec55` and the |
| +card `docs/superpowers/notes/census-proposal-aws-followups-1143.md`. |
| + |
| +Check: |
| +1. Each round-1 P2: resolved, partly, not. |
| +2. Container credentials bounded through EndpointCredentialOptions (only |
| + when the client is rootaws's own; caller hooks still win). Login-session |
| + credentials refused at load with errLoginSession. Does refusing |
| + login-session break any real platform path (who uses it)? |
| +3. **Root read change:** host-env without --group now always loads through |
| + rootaws.LoadDefaultConfig, so as root it gains rootaws's |
| + /etc/carlos/credentials fallback (as the --group path already had). |
| + As census reviewer: does root now read a file or credential it did |
| + not before, and can a tenant, app or box agent write or name it? The |
| + card lists internal/hostenv as envelope-only; judge whether that is |
| + right or a unit claim is owed. |
| +4. hostfence OpenRootFenceStore: literal config carries the bounded |
| + client; credential selection, mode checks, receipt check unchanged? |
| +5. Test isolation: loopback-only dialer, no proxy, ignore-endpoints off. |
| + Any remaining route to real AWS? The test-only withoutWriterTo |
| + middleware: does it hide a production problem a test should catch? |
| +6. Census verdicts: OpenRootFenceStore and the three envelopes. |
| + |
| +Answer each: OK, or a finding with file:line, failure scenario and fix, |
| +marked P1 or P2. End with exactly one line: CHECK PASSED, or CHECK FAILED |
| +with the P1s. Do not edit files, spawn reviewers or run full suites. |
diff --git a/docs/superpowers/reviews/CHECK-aws-followups-1143-R1-fix.md b/docs/superpowers/reviews/CHECK-aws-followups-1143-R1-fix.md| new file mode 100644 |
| index 000000000..0729cb891 |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/CHECK-aws-followups-1143-R1-fix.md |
| @@ -0,0 +1,48 @@ |
| +Reviewed `ee93b00131bb59ca98a3ee6e58a801b7bee3ee45`, limited to fix `e140ec55` and its census card. This is the required scoped check after round 1, not another review round. |
| + |
| +**No P1 or P2 findings.** |
| + |
| +1. **Round-1 P2s — OK, all resolved.** |
| + |
| + - Container credential exchanges now receive the bounded transport; owned loads refuse login-session credentials. |
| + - The fence writer’s STS and S3 clients receive the bounded transport. Non-group host-env now loads through rootaws. Both obsolete allowlist entries are removed. |
| + - Credential tests explicitly honor configured endpoints and enforce loopback-only connections without a proxy. |
| + |
| +2. **Credential bounds and login-session refusal — OK.** |
| + |
| + [stall.go:124](/home/paulca/amadan.net/carlos/platform-aws-followups-1143/internal/rootaws/stall.go:124) installs credential hooks only when the loading client remains rootaws’s own. The endpoint hook at line 186 supplies a bounded client when none exists, then runs the caller’s hook, preserving its override. |
| + |
| + [boundConfig:310](/home/paulca/amadan.net/carlos/platform-aws-followups-1143/internal/rootaws/stall.go:310) detects a cached login-session provider and returns `errLoginSession` before credential retrieval. The pinned SDK constructs the provider during loading but reads its token and performs refresh during `Retrieve`. It already rejects login-session source profiles for assumed roles. |
| + |
| + This deliberately removes a previously available credential mode for non-root callers. Real affected entry points include `system host-env seed` and direct S3-backed CLI operations through [openStore:2347](/home/paulca/amadan.net/carlos/platform-aws-followups-1143/cli.go:2347), **if their selected profile uses `login_session`**. I found no configured or documented platform dependency on that mode. Root excludes shared profiles already; grouprollaws already rejects login-session profiles. SSO credentials remain supported. Repository inspection cannot establish whether an individual operator uses this profile type. |
| + |
| +3. **Host-env root read and census classification — OK.** |
| + |
| + [awsssm.go:58](/home/paulca/amadan.net/carlos/platform-aws-followups-1143/internal/hostenv/awsssm.go:58) changes credential selection as well as timeouts: non-group root invocations now consult `/etc/carlos/credentials` when complete environment keys are absent. A valid file takes precedence over IMDS; an unsafe file causes credential retrieval to fail instead of falling through. |
| + |
| + The path is fixed in [config.go:17](/home/paulca/amadan.net/carlos/platform-aws-followups-1143/internal/rootaws/config.go:17). Callers cannot select it through host-env flags or shared-profile variables. The existing reader rejects symlinks and special files, requires a single-link root-owned regular file without group/other write permission, and parses only literal credential keys. These checks prevent tenant-, app-, or box-agent-authored credentials from being accepted. |
| + |
| + **Envelope-only classification is correct.** `openSSMParamsMode` adds no direct census read site; it reaches an existing reader whose implementation and disposition are unchanged. The scanner explicitly uses envelopes to cover wrapper and indirect-call changes. The new reachability is assessed and approved here; no additional unit claim is owed. |
| + |
| +4. **OpenRootFenceStore — OK.** |
| + |
| + [writer.go:31](/home/paulca/amadan.net/carlos/platform-aws-followups-1143/internal/hostfence/writer.go:31) retains the root check, protected credential-file open, 0400/0600 checks, installation-receipt requirement for 0600, credential decoding and bucket validation. |
| + |
| + The literal config now supplies `rootaws.BoundedHTTPClient()` before constructing STS and S3. Credential selection remains exclusively the dedicated fence identity. No default credential loader, environment credentials, shared profiles or IMDS path is introduced. The transport’s bounds remain effective when the credential cache suppresses caller cancellation. |
| + |
| +5. **Test isolation and `withoutWriterTo` — OK for this scope.** |
| + |
| + [localStallLoad:228](/home/paulca/amadan.net/carlos/platform-aws-followups-1143/internal/rootaws/stall_test.go:228) disables proxies and rejects non-loopback destination addresses after resolution, before connection. The control survives the SDK’s dialer copies. Credential fixtures disable endpoint ignoring, isolate shared files and clear competing credential sources. I found no remaining HTTP route to real AWS in these tests. |
| + |
| + [withoutWriterTo:137](/home/paulca/amadan.net/carlos/platform-aws-followups-1143/internal/rootaws/stall_credentials_test.go:137) does suppress a real SDK/net/http request-body close race that could also occur in production. It does not bypass the response transport or timeout implementation under test: it hides an optional request-stream optimization so an unrelated early connection failure cannot prevent reaching the intended stalled-response condition. These tests establish timeout behavior; they do not establish freedom from that dependency race. |
| + |
| +6. **Census verdicts — approve all four.** |
| + |
| + - **`OpenRootFenceStore`: approve.** Existing authority disposition and protected-installation basis remain valid. |
| + - **`internal/hostfence`: approve.** Dedicated credential authority is unchanged. |
| + - **`internal/hostenv`: approve.** The additional root credential read uses the existing protected, fixed-path reader described above. |
| + - **`internal/rootaws`: approve.** Changes bound existing exchanges or refuse unsupported credentials; they introduce no new root-selected input and weaken no root validation. |
| + |
| +`git diff --check` passed. Targeted tests could not start: Go attempted to update `go.mod`, which the read-only sandbox refused. No runtime or census-test pass is claimed. No files were changed, reviewers spawned, or full suites run. |
| + |
| +CHECK PASSED |
| \ No newline at end of file |
diff --git a/docs/superpowers/reviews/FINDINGS-aws-followups-1143-R1.md b/docs/superpowers/reviews/FINDINGS-aws-followups-1143-R1.md| new file mode 100644 |
| index 000000000..4eabcea03 |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/FINDINGS-aws-followups-1143-R1.md |
| @@ -0,0 +1,73 @@ |
| +Reviewed `78f8d936d7dc3d2f72c83d60291768ed3bbbcbf4` against merge base `a23423b7c8b5f5c4105e7a797feaf4d88061054b`, round **1 of 3**. The requested tip adds only the brief after its named implementation commit. |
| + |
| +**No P1 findings. Three P2 findings and two P3 follow-ups.** The failure scenarios below are verified from source; test execution was blocked by the sandbox. |
| + |
| +1. **P2 — Container and login-session credentials remain unbounded.** |
| + |
| + [stall.go:170](/home/paulca/amadan.net/carlos/platform-aws-followups-1143/internal/rootaws/stall.go:170) wraps STS, SSO and SSO OIDC providers, but leaves two credential paths outside the stated response-bound invariant. |
| + |
| + In the pinned SDK, container credentials construct a separate HTTP client without inheriting `cfg.HTTPClient`: see [resolve_credentials.go:339](/home/paulca/go/pkg/mod/github.com/aws/aws-sdk-go-v2/config@v1.32.6/resolve_credentials.go:339) and [client.go:60](/home/paulca/go/pkg/mod/github.com/aws/aws-sdk-go-v2/credentials@v1.19.6/endpointcreds/internal/client/client.go:60). This path lacks even the injected response-header bound. Login-session credentials build a Signin client during loading, before `boundConfig`, at [resolve_credentials.go:641](/home/paulca/go/pkg/mod/github.com/aws/aws-sdk-go-v2/config@v1.32.6/resolve_credentials.go:641). |
| + |
| + **Failure scenario:** A non-root caller uses container credentials or an expired login-session token. Its credential endpoint stalls while returning credentials. Retrieval remains blocked despite loading the application’s service config through `rootaws`. |
| + |
| + **Fix:** Bound endpoint credentials through `EndpointCredentialOptions`, preserving caller overrides. Give login-session refresh an equivalent bound, or explicitly refuse that unsupported credential mode. Add local stalled-response tests for both. |
| + |
| + **Invariant / fault family:** Credential-refresh liveness — every supported credential exchange must terminate when its response stops progressing. These are pre-existing gaps left unresolved by this follow-up, rather than regressions introduced by the wrappers. Root’s startup environment scrub limits their production-root reach. |
| + |
| +2. **P2 — Two allowlist entries lack the bounds their exemption needs.** |
| + |
| + The exceptions at [guard_test.go:47](/home/paulca/amadan.net/carlos/platform-aws-followups-1143/internal/rootaws/guard_test.go:47) and [guard_test.go:51](/home/paulca/amadan.net/carlos/platform-aws-followups-1143/internal/rootaws/guard_test.go:51) preserve unbounded work: |
| + |
| + - **Fence writer:** [writer.go:60](/home/paulca/amadan.net/carlos/platform-aws-followups-1143/internal/hostfence/writer.go:60) builds an unbounded STS client and wraps its assume-role provider in `aws.CredentialsCache`. That cache retrieves credentials using a [suppressed context](/home/paulca/go/pkg/mod/github.com/aws/aws-sdk-go-v2@v1.44.0/aws/credential_cache.go:103), which removes [deadline and cancellation](/home/paulca/go/pkg/mod/github.com/aws/aws-sdk-go-v2@v1.44.0/aws/context.go:12). The two-minute pass deadline releases the waiting caller, but cannot stop the underlying STS request. Repeated passes can leave additional stalled requests behind. |
| + - **Non-group host-env:** [cli.go:49](/home/paulca/amadan.net/carlos/platform-aws-followups-1143/internal/hostenv/cli.go:49) supplies `context.Background()`, and [awsssm.go:55](/home/paulca/amadan.net/carlos/platform-aws-followups-1143/internal/hostenv/awsssm.go:55) uses the SDK loader directly. Being a one-shot command does not prevent it from hanging indefinitely on an SSM response. |
| + |
| + **Fix:** Install `rootaws.BoundedHTTPClient()` in the fence writer’s literal config before constructing STS and S3, retaining its dedicated credential selection. Route non-group host-env through `rootaws.LoadDefaultConfig`. Update the exact allowlist entries accordingly, and test cancellation-independent credential completion. |
| + |
| + **Invariant / fault family:** AWS-request liveness — an exception must have an effective bound on the underlying operation, including credential refresh. These existing exceptions were explicitly included in this review’s allowlist check. |
| + |
| +3. **P2 — The new credential tests do not reliably prevent real AWS traffic.** |
| + |
| + [stall_credentials_test.go:63](/home/paulca/amadan.net/carlos/platform-aws-followups-1143/internal/rootaws/stall_credentials_test.go:63) sets local endpoint overrides and a dead proxy, but does not neutralize `AWS_IGNORE_CONFIGURED_ENDPOINT_URLS` or `NO_PROXY`. |
| + |
| + **Failure scenario:** With `AWS_IGNORE_CONFIGURED_ENDPOINT_URLS=true` and `NO_PROXY=*`, the SDK ignores the local fixtures and connects directly to AWS. Additionally, Go caches environment proxy configuration on first use, so changing proxy variables inside this helper is not a dependable network barrier after another test has made a request. |
| + |
| + **Fix:** Explicitly disable “ignore configured endpoints” in these tests and enforce a local-address-only dial policy on the test loading transport. Preserve its ownership identity so the tests still exercise the production wrapping path. Do not rely on environment proxy changes as the barrier. |
| + |
| + **Invariant / fault family:** Test isolation — credential tests must contact only their local fixtures, regardless of ambient configuration. |
| + |
| +4. **P3 — The guard has additional zero-config escape forms.** |
| + |
| + [guard_test.go:463](/home/paulca/amadan.net/carlos/platform-aws-followups-1143/internal/rootaws/guard_test.go:463) exempts every directly returned `aws.Config{}`, without verifying that it accompanies an error. A helper returning a zero config successfully can therefore feed an unbounded service constructor. The documented zero-valued struct-field case also escapes detection. |
| + |
| + **Fix:** Track fixtures and enforcement for successful zero-config returns and zero-valued fields. I did not establish a current production client exploiting these forms. |
| + |
| + **Invariant:** Guard coverage — zero configs that become service clients must not silently bypass the transport requirement. Follow-up only. |
| + |
| +5. **P3 — Direct dependencies remain marked indirect.** |
| + |
| + [go.mod:49](/home/paulca/amadan.net/carlos/platform-aws-followups-1143/go.mod:49) still marks SSO and SSO OIDC indirect, although `stall.go` now imports both directly. |
| + |
| + **Fix:** Correct their dependency classification in a follow-up. This does not itself break compilation. |
| + |
| + **Invariant:** Dependency metadata reflects direct imports. |
| + |
| +The remaining requested checks are satisfactory, with these qualifications: |
| + |
| +- **STS/SSO behavior:** The wrappers retain the SDK-created clients and replace only the per-operation HTTP client. Provider caching, refresh logic, region and endpoint resolution remain in place. CA-bundle and defaults-mode changes have already reached the client being wrapped. Caller credential hooks run afterward, and operation options run after the injected option, so their explicit replacements still win. |
| +- **Client ownership:** The identity check happens before SDK resolution. An explicit caller `BuildableClient`, including its later CA-bundle clone, remains caller-owned. The ordinary injected client remains owned and receives the bound. |
| +- **Root credential refusal:** Shared-file suppression and profile refusal remain intact. The suspected non-group host-env `credential_process` exposure is **not established**: [main.go:25](/home/paulca/amadan.net/carlos/platform-aws-followups-1143/main.go:25) scrubs the environment before dispatch, including disabling both shared-file paths. Its timeout gap is finding 2. |
| +- **IMDS:** Leaving it unchanged is acceptable. The pinned SDK installs a five-second default operation timeout, in addition to its dial and header limits. |
| +- **Other allowlist entries:** `grouprollaws` has its own bounds, including credential-client middleware; the objstore wrapper preserves the bounded client and its non-nil production caller is console-only; `NewStagingMirrorAt` has test-only callers. |
| +- **Regression tests:** The credential stall cases target the old missing body bound. Explicit BuildableClient preservation cases target the old ownership mistake. The guard fixtures exercise newly detected assignments, callbacks and zero constructions. Compatibility tests, such as preservation of an ordinary caller HTTP client, need not fail on the old code. Credential-hook precedence, successful refresh/cache reuse and credential-specific CA/defaults-mode combinations are supported by source inspection, not directly demonstrated by the new tests. |
| + |
| +**Census verdict: approve the `internal/rootaws` envelope at the reviewed tip.** |
| + |
| +I reviewed the changed loader functions in [config.go:39](/home/paulca/amadan.net/carlos/platform-aws-followups-1143/internal/rootaws/config.go:39), ownership and option handling in [stall.go:94](/home/paulca/amadan.net/carlos/platform-aws-followups-1143/internal/rootaws/stall.go:94), all credential wrappers at lines 170–265, and `boundConfig`, `BoundedHTTPClient` and `mustBoundedClient` at lines 275–329, together with their SDK construction paths and changed tests. |
| + |
| +The changes add timeout handling to existing credential exchanges. They introduce no new root-selected file, executable, endpoint or credential authority, and weaken no existing root refusal. The card contains **one envelope and no individual disposition changes**. This approves the census authority boundary, not the functional completeness described above. |
| + |
| +`git diff --check` passed. Targeted tests could not start because Go could not create its work directory in the read-only sandbox; no test or census-test pass is claimed. Network restrictions prevented reading amadan #1143. No files were edited, no reviewers spawned, and no full suites run. |
| + |
| +This is the first round without P1s. Stop the full review here; apply P2 fixes within the existing budget, with the required scoped checks for newly changed production-storage behavior and census coverage. Keep P3s on the follow-up list. |
| + |
| +READY AFTER FIXES |
| \ No newline at end of file |
diff --git a/docs/superpowers/reviews/REVIEW-BRIEF-aws-followups-1143.md b/docs/superpowers/reviews/REVIEW-BRIEF-aws-followups-1143.md| new file mode 100644 |
| index 000000000..176e9c087 |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/REVIEW-BRIEF-aws-followups-1143.md |
| @@ -0,0 +1,52 @@ |
| +# Review brief: branch aws-followups-1143, round 1 of 3 |
| + |
| +Repo carlos/platform, branch `aws-followups-1143`, commit 228d6beeb6435254ccc18c416466eb7967e0f808. |
| +Under review: the diff `origin/main...228d6beeb6435254ccc18c416466eb7967e0f808` (base a23423b7). |
| +Authorities: amadan #1143 (the three follow-ups from the scoped check of |
| +0374ac2), AGENTS.md ("The census", "Writing Go here", "Stopping rules"). |
| + |
| +You are the independent reviewer and census reviewer (card: |
| +`docs/superpowers/notes/census-proposal-aws-followups-1143.md`, envelope |
| +internal/rootaws only). Production storage and root-side credential |
| +loading: every AWS client the platform builds goes through this code. |
| + |
| +## What to check |
| + |
| +1. Credential clients (STS web identity and assume-role, SSO, SSO OIDC) |
| + now get the body bound through wrapped credential-option hooks; IMDS |
| + untouched. Any loss of an existing credential behaviour (refresh, |
| + caching, CA bundle, defaults mode, region, endpoint resolution)? Does a |
| + caller's own credential options hook still win? Does the root path's |
| + refusal of shared profiles / credential files still hold? |
| +2. Ours-vs-caller decided by identity before the SDK resolves: an explicit |
| + BuildableClient (and the SDK's CA-bundle clone of it) stays the |
| + caller's; our default is still replaced by the bounded client. Any way |
| + our default escapes the bound, or a caller's client gets replaced? |
| +3. The guard rewritten with type information: catches HTTPClient set on |
| + any SDK struct, zero aws.Config / Options built three ways; allowlist |
| + now per construction (grouprollaws newAdapter, objstore |
| + NewAWSProvisionerWith console-only, and the existing ones). Any bypass |
| + left that matters? Is each allowlist entry justified? |
| +4. Tests: would each fail on the old code; anything reaching real AWS |
| + (must not)? |
| +5. The implementer's open questions: (a) root `carlos system host-env |
| + write` without --group loads with the SDK's LoadDefaultConfig, so root |
| + reads shared profiles including credential_process: is that a real |
| + gap to file? (b) paths still without the body bound (IMDS, login- |
| + session and container-endpoint credentials): acceptable? (c) go.mod |
| + marks service/sso and ssooidc indirect though now imported directly: |
| + P3? (d) a zero config held as a struct field is not caught. |
| + |
| +## Severity |
| + |
| +- **P1**: unsafe, would not compile, a test fails, or it would not work. |
| +- **P2**: wrong or missing. Fixed without reopening this review (storage |
| + and census changes in the fix still get a scoped check). |
| +- **P3**: clarity or polish. Follow-up list only. |
| + |
| +## Output |
| + |
| +Findings ranked P1, P2, P3 with file:line, failure scenario and fix, and |
| +the invariant each breaks. Then the census verdict. End with exactly one |
| +verdict: READY, READY AFTER FIXES, or NOT READY. Do not edit files, spawn |
| +reviewers or run full suites. |
diff --git a/internal/hostenv/awsssm.go b/internal/hostenv/awsssm.go| index 5c09b5b8e..d0d5375db 100644 |
| --- a/internal/hostenv/awsssm.go |
| +++ b/internal/hostenv/awsssm.go |
| @@ -52,11 +52,10 @@ func openSSMParamsMode(ctx context.Context, awsRegion, kmsKey string, group bool |
| if group { |
| opts = append(opts, config.WithRetryMaxAttempts(1)) |
| } |
| - load := config.LoadDefaultConfig |
| - if group { |
| - load = rootaws.LoadDefaultConfig |
| - } |
| - cfg, err := load(ctx, opts...) |
| + // Both paths load through rootaws, for its stall bounds: write and seed |
| + // run on context.Background(), so nothing else would end a stalled SSM |
| + // call. |
| + cfg, err := rootaws.LoadDefaultConfig(ctx, opts...) |
| if err != nil { |
| return nil, err |
| } |
diff --git a/internal/hostfence/writer.go b/internal/hostfence/writer.go| index 1b2372998..3e9df6c80 100644 |
| --- a/internal/hostfence/writer.go |
| +++ b/internal/hostfence/writer.go |
| @@ -15,6 +15,7 @@ import ( |
| "github.com/aws/aws-sdk-go-v2/service/sts" |
| "github.com/carlosframework/platform/internal/hostfloor" |
| "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/rootaws" |
| ) |
| type fenceCredentials struct { |
| @@ -57,7 +58,11 @@ func OpenRootFenceStore(ctx context.Context, bucket string) (release.Store, erro |
| if err != nil { |
| return nil, err |
| } |
| - cfg := aws.Config{Region: c.Region, Credentials: aws.NewCredentialsCache(credentials.NewStaticCredentialsProvider(c.AccessKey, c.SecretKey, ""))} |
| + // The bounded client carries the STS exchange too: the credentials |
| + // cache retrieves with the caller's deadline removed, so only the |
| + // client's own bounds can end a stalled AssumeRole (rootaws stall.go). |
| + cfg := aws.Config{Region: c.Region, HTTPClient: rootaws.BoundedHTTPClient(), |
| + Credentials: aws.NewCredentialsCache(credentials.NewStaticCredentialsProvider(c.AccessKey, c.SecretKey, ""))} |
| provider := stscreds.NewAssumeRoleProvider(sts.NewFromConfig(cfg), c.Role, func(o *stscreds.AssumeRoleOptions) { o.RoleSessionName = "carlos-root-fence" }) |
| cfg.Credentials = aws.NewCredentialsCache(provider) |
| return &release.S3Store{Client: s3.NewFromConfig(cfg), Bucket: c.Bucket}, nil |
diff --git a/internal/provision/testdata/plan14-root-reads-aws-followups-1143.tsv b/internal/provision/testdata/plan14-root-reads-aws-followups-1143.tsv| new file mode 100644 |
| index 000000000..68458a66f |
| --- /dev/null |
| +++ b/internal/provision/testdata/plan14-root-reads-aws-followups-1143.tsv |
| @@ -0,0 +1,6 @@ |
| +# Census overlay aws-followups-1143, written by census-propose (#369). census-ruling-aws-followups-1143, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-aws-followups-1143.md. |
| +# 1 body, 0 sites, 3 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| +internal/hostfence/writer.go OpenRootFenceStore authority F,J4 rev3=PROPOSED-activation-tools;identity=root fence service and explicit installer uid 0;basis=dedicated root fence credentials retain 0400 compatibility; 0600 needs a matching protected installation receipt; absent explicit installation keeps prior refusal;rev3=census-ruling-aws-followups-1143;basis=the literal config now carries rootaws.BoundedHTTPClient(), so the STS AssumeRole exchange (which the credentials cache runs with the deadline removed) and the S3 client have header and body stall bounds; credentials file reads, mode checks, receipt check and credential selection unchanged; no read added file:Stat@346 686ef27f7a39a4586ab23ba19dd5905bc383176601c62c36bb2afd904ffd7e0c |
| +@coverage internal/hostenv 21ba98aa5bbda53c35ad2a8472ff5357d5339d3e7740888d6a658194c47ef8ed |
| +@coverage internal/hostfence 942080a512bc30b3b0634943158fc8ea79cd85d2eaa6557ede65de416f00c008 |
| +@coverage internal/rootaws 822d20f32f53fb4895201366687f677dd7c02ea9dce9b64f58c8068843ae7703 |
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv| index ad53385a9..c664be3b0 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -246,3 +246,4 @@ plan14-root-reads-audit-bugs-2.tsv 1610abfc476fe45d259494242243756dac9cfec49cdd7 |
| plan14-root-reads-bounded-systemctl.tsv 16cae3931aadfa57a5293d69becf318645681400777cc08972cf08eb449c2457 |
| plan14-root-reads-mail-submission-followups.tsv c9cd3c8fdf31240b83affa0b2798422f3a99e1d0d400dbaf68665c1127996448 |
| plan14-root-reads-staticcheck-sa4006.tsv 33e5eaaa9b2d80f6f8f5de8d04e908e39ecfc820c5fe7b44c870e671565e1063 |
| +plan14-root-reads-aws-followups-1143.tsv 33e5eaaa9b2d80f6f8f5de8d04e908e39ecfc820c5fe7b44c870e671565e1063 |
diff --git a/internal/rootaws/config.go b/internal/rootaws/config.go| index 07cdecea7..1bd489fee 100644 |
| --- a/internal/rootaws/config.go |
| +++ b/internal/rootaws/config.go |
| @@ -37,7 +37,13 @@ func offcloudCredentials(path string) (aws.Credentials, error) { |
| // both shared-file lists, including paths selected through HOME or AWS_* vars. |
| // Both get the stall bounds (stall.go). |
| func LoadDefaultConfig(ctx context.Context, opts ...func(*awsconfig.LoadOptions) error) (aws.Config, error) { |
| - opts = withStallBounds(opts) |
| + return loadDefaultConfig(ctx, newStallLoad(ResponseHeaderTimeout, BodyIdleTimeout), opts...) |
| +} |
| + |
| +// loadDefaultConfig is LoadDefaultConfig under l's bounds (tests use short |
| +// ones). |
| +func loadDefaultConfig(ctx context.Context, l *stallLoad, opts ...func(*awsconfig.LoadOptions) error) (aws.Config, error) { |
| + opts = l.options(opts) |
| var cfg aws.Config |
| var err error |
| if os.Geteuid() != 0 { |
| @@ -48,7 +54,7 @@ func LoadDefaultConfig(ctx context.Context, opts ...func(*awsconfig.LoadOptions) |
| if err != nil { |
| return cfg, err |
| } |
| - return boundConfig(cfg, BodyIdleTimeout) |
| + return boundConfig(cfg, l) |
| } |
| func LoadStaticConfig(ctx context.Context, accessKeyID, secretAccessKey string, opts ...func(*awsconfig.LoadOptions) error) (aws.Config, error) { |
| @@ -61,7 +67,8 @@ func LoadStaticConfig(ctx context.Context, accessKeyID, secretAccessKey string, |
| if os.Getenv("AWS_PROFILE") != "" || os.Getenv("AWS_DEFAULT_PROFILE") != "" { |
| return aws.Config{}, errors.New("static AWS clients do not support AWS_PROFILE or AWS_DEFAULT_PROFILE") |
| } |
| - opts = append(withStallBounds(opts), awsconfig.WithSharedConfigFiles([]string{}), |
| + opts, l := withStallBounds(opts) |
| + opts = append(opts, awsconfig.WithSharedConfigFiles([]string{}), |
| awsconfig.WithSharedCredentialsFiles([]string{}), awsconfig.WithSharedConfigProfile(""), |
| awsconfig.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(accessKeyID, secretAccessKey, "")), |
| func(o *awsconfig.LoadOptions) error { |
| @@ -74,7 +81,7 @@ func LoadStaticConfig(ctx context.Context, accessKeyID, secretAccessKey string, |
| if err != nil { |
| return cfg, err |
| } |
| - return boundConfig(cfg, BodyIdleTimeout) |
| + return boundConfig(cfg, l) |
| } |
| func loadRootConfig(ctx context.Context, path string, opts ...func(*awsconfig.LoadOptions) error) (aws.Config, error) { |
diff --git a/internal/rootaws/guard_test.go b/internal/rootaws/guard_test.go| index dc30ebb47..8c172a628 100644 |
| --- a/internal/rootaws/guard_test.go |
| +++ b/internal/rootaws/guard_test.go |
| @@ -4,117 +4,273 @@ import ( |
| "bytes" |
| "fmt" |
| "go/ast" |
| - "go/parser" |
| "go/token" |
| + "go/types" |
| "os" |
| "os/exec" |
| "path/filepath" |
| "sort" |
| - "strconv" |
| "strings" |
| "testing" |
| + |
| + "golang.org/x/tools/go/packages" |
| ) |
| -// boundedClientAllowlist names the root-graph files that build an AWS config |
| -// or client some other way, and why each may. A file here is exempt from |
| -// every rule below; anything else in the root binary's graph must get its |
| -// config from this package's loaders or set BoundedHTTPClient. |
| -var boundedClientAllowlist = map[string]string{ |
| +// allowedConstruction is one construction in the root binary's graph that |
| +// the rules below catch and that may stay: n hits of what, inside fn |
| +// (a function, "T.Method", or "var name"), in file. |
| +type allowedConstruction struct { |
| + file, fn, what string |
| + n int |
| + reason string |
| +} |
| + |
| +// boundedClientAllowlist names each construction that builds an AWS config |
| +// or client some other way, and why it may. Anything else in the root |
| +// binary's graph must get its config from this package's loaders or set |
| +// BoundedHTTPClient. An entry that matches nothing, or a different number of |
| +// hits, fails the test. |
| +var boundedClientAllowlist = []allowedConstruction{ |
| // Its own 2 s connect, header and body-read bounds that no defaults |
| // mode can replace (timedClient, boundBody), one attempt per call. |
| - "internal/grouprollaws/config.go": "own bounds: 2 s connect, header and body read", |
| - // A literal config for the root fence writer's assumed role; its only |
| - // caller (hostfencepass.go) wraps every pass in a 2 min deadline. |
| - "internal/hostfence/writer.go": "caller's 2 min pass deadline", |
| - // The non-group path loads with the SDK directly for non-root callers |
| - // (carlos host-env), a one-shot command; the group path uses rootaws. |
| - "internal/hostenv/awsssm.go": "one-shot command; group path is bounded", |
| + {"internal/grouprollaws/config.go", "New", "config.LoadDefaultConfig", 1, "own bounds: 2 s connect, header and body read"}, |
| + {"internal/grouprollaws/config.go", "New", "config.WithHTTPClient", 1, "own bounds: 2 s connect, header and body read"}, |
| + // The same adapter's config: timedClient when none was given, then |
| + // frozen so no defaults mode rewrites it, with boundBodyOption on |
| + // every client. |
| + {"internal/grouprollaws/group.go", "newAdapter", "aws.Config.HTTPClient set", 2, "own bounds: 2 s connect, header and body read"}, |
| + // A wrap around the S3 client's own HTTP client, which S3ClientFor |
| + // bounded; only the console passes one (console.TimeS3HTTP). |
| + {"internal/objstore/aws.go", "NewAWSProvisionerWith", "s3.Options.HTTPClient set", 1, "wraps the bounded client; console-only"}, |
| // NewStagingMirrorAt: the test constructor against a local S3 |
| // (leasetest); production uses NewStagingMirror over rootaws. |
| - "internal/lease/staging.go": "test-only constructor NewStagingMirrorAt", |
| + {"internal/lease/staging.go", "NewStagingMirrorAt", "s3.Options literal without rootaws.BoundedHTTPClient()", 1, "test-only constructor NewStagingMirrorAt"}, |
| } |
| // The rules, over every non-test Go file of every module package the root |
| -// binary links (linux, amd64 and arm64), outside this package: |
| +// binary links (linux, amd64 and arm64), outside this package, read with |
| +// type information so an import alias, a dot import or a method value |
| +// cannot hide a construction: |
| // - no use of the SDK config package's LoadDefaultConfig or |
| // WithHTTPClient, called or taken as a value; |
| -// - no aws.Config composite literal with fields (an empty one is a zero |
| -// value returned beside an error); |
| +// - no aws.Config composite literal with fields unless it sets |
| +// HTTPClient to rootaws.BoundedHTTPClient(), and no zero aws.Config |
| +// to fill in field by field: no empty literal (except as a value |
| +// returned, which is a zero value beside an error), no `var c |
| +// aws.Config` without a value, no new(aws.Config); |
| // - no service Options composite literal (github.com/aws/aws-sdk-go-v2/ |
| -// service/...) unless it sets HTTPClient to rootaws.BoundedHTTPClient(). |
| +// service/...) unless it sets HTTPClient to rootaws.BoundedHTTPClient(), |
| +// and no zero service Options the same ways as aws.Config; |
| +// - no assignment to, and no literal setting, the HTTPClient field of any |
| +// SDK struct (aws.Config, a service's Options in an option callback, |
| +// config.LoadOptions, ...) other than to rootaws.BoundedHTTPClient(). |
| // |
| // Clients built FROM a loaded config or from another client's Options() |
| -// carry its HTTP client, so they need no rule. Outside the scan, because |
| -// the root binary does not link them: cmd/moveprobe (a diagnostic tool), |
| +// carry its HTTP client, so they need no rule. A config or Options held as |
| +// a struct field and left zero is not caught. Outside the scan, because the |
| +// root binary does not link them: cmd/moveprobe (a diagnostic tool), |
| // internal/mail/sessend.go (the console's SES sender), the console's own |
| // packages, and test files. |
| func TestAWSClientsAreBounded(t *testing.T) { |
| if testing.Short() { |
| - t.Skip("lists the root binary's packages with go list") |
| + t.Skip("type-checks the root binary's packages") |
| } |
| root := moduleRoot(t) |
| - files := rootBinaryFiles(t, root) |
| + byArch, files := rootBinaryFiles(t, root) |
| if len(files) < 100 { |
| t.Fatalf("listed only %d root-binary files; the scan would prove nothing", len(files)) |
| } |
| - var bad []string |
| - seen := map[string]bool{} |
| - for _, rel := range files { |
| - if strings.HasPrefix(rel, "internal/rootaws/") { |
| - continue |
| + hits := scanRootBinary(t, root, byArch, files) |
| + |
| + type key struct{ file, fn, what string } |
| + got := map[key][]string{} |
| + for rel, hs := range hits { |
| + for _, h := range hs { |
| + k := key{rel, h.fn, h.what} |
| + got[k] = append(got[k], fmt.Sprintf("%s:%d: %s: %s", rel, h.line, h.fn, h.what)) |
| } |
| - hits := unboundedAWSClients(t, filepath.Join(root, rel)) |
| - if _, ok := boundedClientAllowlist[rel]; ok { |
| - seen[rel] = len(hits) > 0 |
| + } |
| + allowed := map[key]allowedConstruction{} |
| + for _, a := range boundedClientAllowlist { |
| + allowed[key{a.file, a.fn, a.what}] = a |
| + } |
| + var bad []string |
| + for k, where := range got { |
| + if a, ok := allowed[k]; ok && a.n == len(where) { |
| continue |
| } |
| - for _, h := range hits { |
| - bad = append(bad, rel+":"+h) |
| - } |
| + bad = append(bad, where...) |
| } |
| sort.Strings(bad) |
| for _, b := range bad { |
| t.Errorf("%s: an AWS client without rootaws's bounded transport (load the config with rootaws, or set HTTPClient: rootaws.BoundedHTTPClient())", b) |
| } |
| - for rel := range boundedClientAllowlist { |
| - if !seen[rel] { |
| - t.Errorf("%s is allowlisted but builds nothing the rules catch (or left the root binary): drop it from the allowlist", rel) |
| + for k, a := range allowed { |
| + if n := len(got[k]); n != a.n { |
| + t.Errorf("allowlisted %s: %s: %s %d time(s), found %d: correct or drop the entry", a.file, a.fn, a.what, a.n, n) |
| } |
| } |
| } |
| -// The scan itself catches each shape, and lets the bounded ones through. |
| -func TestUnboundedAWSClientsScan(t *testing.T) { |
| - src := `package x |
| -import ( |
| - "github.com/aws/aws-sdk-go-v2/aws" |
| - cfgpkg "github.com/aws/aws-sdk-go-v2/config" |
| - s3 "github.com/aws/aws-sdk-go-v2/service/s3" |
| - "github.com/carlosframework/platform/internal/rootaws" |
| -) |
| -func f() { |
| - cfgpkg.LoadDefaultConfig(nil) |
| +// Each fixture file holds constructions the scan must catch, each named |
| +// with its function, and ones it must let through. |
| +var awsGuardFixtures = map[string]struct { |
| + src string |
| + want []string |
| +}{ |
| + "sdkloader.go": {` |
| +func Load(ctx context.Context) { |
| + cfgpkg.LoadDefaultConfig(ctx) |
| cfgpkg.WithHTTPClient(nil) |
| - _ = aws.Config{Region: "r"} |
| - _ = aws.Config{} |
| load := cfgpkg.LoadDefaultConfig |
| _ = load |
| +} |
| +`, []string{"Load: config.LoadDefaultConfig", "Load: config.LoadDefaultConfig", "Load: config.WithHTTPClient"}}, |
| + "literals.go": {` |
| +func Literals() (aws.Config, error) { |
| + _ = aws.Config{Region: "r"} |
| _ = s3.Options{Region: "r"} |
| _ = s3.Options{HTTPClient: nil} |
| _ = s3.Options{HTTPClient: rootaws.BoundedHTTPClient()} |
| _ = &s3.Options{HTTPClient: rootaws.BoundedHTTPClient()} |
| + _ = cfgpkg.LoadOptions{HTTPClient: &http.Client{}} |
| + _ = aws.Config{Region: "r", HTTPClient: rootaws.BoundedHTTPClient()} |
| + return aws.Config{}, nil |
| } |
| -` |
| - path := filepath.Join(t.TempDir(), "x.go") |
| - if err := os.WriteFile(path, []byte(src), 0o600); err != nil { |
| - t.Fatal(err) |
| +`, []string{"Literals: aws.Config literal", "Literals: config.LoadOptions literal sets HTTPClient", |
| + "Literals: s3.Options literal without rootaws.BoundedHTTPClient()", "Literals: s3.Options literal without rootaws.BoundedHTTPClient()"}}, |
| + // #1143: a loaded config whose client is then replaced. |
| + "assigned.go": {` |
| +func Assigned(ctx context.Context) *s3.Client { |
| + cfg, _ := rootaws.LoadDefaultConfig(ctx) |
| + cfg.Region = "r" |
| + cfg.HTTPClient = &http.Client{} |
| + return s3.NewFromConfig(cfg) |
| +} |
| + |
| +func AssignedBounded(ctx context.Context) *s3.Client { |
| + cfg, _ := rootaws.LoadDefaultConfig(ctx) |
| + cfg.HTTPClient = rootaws.BoundedHTTPClient() |
| + return s3.NewFromConfig(cfg) |
| +} |
| +`, []string{"Assigned: aws.Config.HTTPClient set"}}, |
| + // #1143: a zero config filled in field by field, three ways. |
| + "zero.go": {` |
| +func ZeroVar() *s3.Client { |
| + var cfg aws.Config |
| + cfg.Region = "r" |
| + cfg.Credentials = credentials.NewStaticCredentialsProvider("A", "S", "") |
| + return s3.NewFromConfig(cfg) |
| +} |
| + |
| +func ZeroLiteral() *s3.Client { |
| + cfg := aws.Config{} |
| + cfg.Region = "r" |
| + return s3.NewFromConfig(cfg) |
| +} |
| + |
| +func ZeroNew() *s3.Client { |
| + cfg := new(aws.Config) |
| + cfg.Region = "r" |
| + return s3.NewFromConfig(*cfg) |
| +} |
| + |
| +func ZeroOptions() *s3.Client { |
| + var o s3.Options |
| + o.Region = "r" |
| + return s3.New(o) |
| +} |
| + |
| +func NotZero(ctx context.Context) *s3.Client { |
| + var p *aws.Config |
| + _ = p |
| + cfg, _ := rootaws.LoadDefaultConfig(ctx) |
| + cfg.Region = "r" |
| + return s3.NewFromConfig(cfg) |
| +} |
| +`, []string{"ZeroLiteral: zero aws.Config", "ZeroNew: zero aws.Config", "ZeroOptions: zero s3.Options", "ZeroVar: zero aws.Config"}}, |
| + // #1143: option callbacks that swap the client. |
| + "callbacks.go": {` |
| +func Callback(ctx context.Context) *s3.Client { |
| + cfg, _ := rootaws.LoadDefaultConfig(ctx, func(o *cfgpkg.LoadOptions) error { |
| + o.HTTPClient = &http.Client{} |
| + return nil |
| + }) |
| + return s3.NewFromConfig(cfg, func(o *s3.Options) { |
| + o.HTTPClient = &http.Client{} |
| + }) |
| +} |
| + |
| +func CallbackBounded(ctx context.Context) *s3.Client { |
| + cfg, _ := rootaws.LoadDefaultConfig(ctx) |
| + return s3.NewFromConfig(cfg, func(o *s3.Options) { |
| + o.HTTPClient = rootaws.BoundedHTTPClient() |
| + o.UsePathStyle = true |
| + }) |
| +} |
| +`, []string{"Callback: config.LoadOptions.HTTPClient set", "Callback: s3.Options.HTTPClient set"}}, |
| + "pkgvar.go": {` |
| +var zeroAtPackageLevel aws.Config |
| +`, []string{"var zeroAtPackageLevel: zero aws.Config"}}, |
| +} |
| + |
| +// The scan catches each form and lets the bounded ones through. The |
| +// fixtures are a package that exists only in an overlay. |
| +func TestUnboundedAWSClientsScan(t *testing.T) { |
| + root := moduleRoot(t) |
| + dir := filepath.Join(root, "internal", "rootaws", "zzawsguardfixture") |
| + overlay := map[string][]byte{} |
| + for name, f := range awsGuardFixtures { |
| + overlay[filepath.Join(dir, name)] = []byte(fixtureFile(f.src)) |
| } |
| - got := unboundedAWSClients(t, path) |
| - if len(got) != 6 { |
| - t.Fatalf("caught %d, want 6: %v", len(got), got) |
| + pkgs := loadTyped(t, root, "amd64", overlay, "./internal/rootaws/zzawsguardfixture") |
| + got := map[string][]string{} |
| + for _, pkg := range pkgs { |
| + for _, f := range pkg.Syntax { |
| + name := filepath.Base(pkg.Fset.File(f.Pos()).Name()) |
| + for _, h := range unboundedAWSClients(pkg.Fset, pkg.TypesInfo, f) { |
| + got[name] = append(got[name], h.fn+": "+h.what) |
| + } |
| + } |
| + } |
| + for name, f := range awsGuardFixtures { |
| + want := append([]string(nil), f.want...) |
| + sort.Strings(want) |
| + sort.Strings(got[name]) |
| + if fmt.Sprint(got[name]) != fmt.Sprint(want) { |
| + t.Errorf("%s: caught %q, want %q", name, got[name], want) |
| + } |
| } |
| } |
| +// fixtureFile is a fixture's source in the fixture package, with every |
| +// import it might use kept in use. |
| +func fixtureFile(src string) string { |
| + return `package zzawsguardfixture |
| + |
| +import ( |
| + "context" |
| + "net/http" |
| + |
| + "github.com/aws/aws-sdk-go-v2/aws" |
| + cfgpkg "github.com/aws/aws-sdk-go-v2/config" |
| + "github.com/aws/aws-sdk-go-v2/credentials" |
| + s3 "github.com/aws/aws-sdk-go-v2/service/s3" |
| + "github.com/carlosframework/platform/internal/rootaws" |
| +) |
| + |
| +var ( |
| + _ context.Context |
| + _ http.Client |
| + _ = aws.String |
| + _ = cfgpkg.WithRegion |
| + _ = credentials.NewStaticCredentialsProvider |
| + _ = s3.New |
| + _ = rootaws.BoundedHTTPClient |
| +) |
| +` + src |
| +} |
| + |
| func moduleRoot(t *testing.T) string { |
| t.Helper() |
| dir, err := os.Getwd() |
| @@ -133,13 +289,18 @@ func moduleRoot(t *testing.T) string { |
| } |
| } |
| -// rootBinaryFiles is every non-test Go file, relative to root, of every |
| -// module package the root binary links on linux/amd64 or linux/arm64. |
| -func rootBinaryFiles(t *testing.T, root string) []string { |
| +var rootBinaryArchs = []string{"amd64", "arm64"} |
| + |
| +// rootBinaryFiles lists the module packages the root binary links on |
| +// linux/amd64 and linux/arm64, with their non-test Go files relative to |
| +// root (byArch: arch -> import path -> files), and every such file of |
| +// either architecture (files). |
| +func rootBinaryFiles(t *testing.T, root string) (byArch map[string]map[string][]string, files []string) { |
| t.Helper() |
| + byArch = map[string]map[string][]string{} |
| set := map[string]bool{} |
| - for _, arch := range []string{"amd64", "arm64"} { |
| - cmd := exec.Command("go", "list", "-deps", "-f", `{{if not .Standard}}{{.Dir}}|{{join .GoFiles ","}}{{end}}`, ".") |
| + for _, arch := range rootBinaryArchs { |
| + cmd := exec.Command("go", "list", "-deps", "-f", `{{if not .Standard}}{{.ImportPath}}|{{.Dir}}|{{join .GoFiles ","}}{{end}}`, ".") |
| cmd.Dir = root |
| cmd.Env = append(os.Environ(), "GOOS=linux", "GOARCH="+arch, "CGO_ENABLED=0") |
| var stderr bytes.Buffer |
| @@ -148,77 +309,207 @@ func rootBinaryFiles(t *testing.T, root string) []string { |
| if err != nil { |
| t.Fatalf("go list (linux/%s): %v: %s", arch, err, stderr.String()) |
| } |
| + pkgs := map[string][]string{} |
| for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") { |
| - dir, names, _ := strings.Cut(line, "|") |
| + parts := strings.SplitN(line, "|", 3) |
| + if len(parts) != 3 { |
| + continue |
| + } |
| + path, dir, names := parts[0], parts[1], parts[2] |
| rel, err := filepath.Rel(root, dir) |
| if dir == "" || err != nil || strings.HasPrefix(rel, "..") { |
| continue // the standard library and other modules |
| } |
| for _, n := range strings.Split(names, ",") { |
| if n != "" { |
| - set[filepath.ToSlash(filepath.Join(rel, n))] = true |
| + f := filepath.ToSlash(filepath.Join(rel, n)) |
| + pkgs[path] = append(pkgs[path], f) |
| + set[f] = true |
| } |
| } |
| } |
| + byArch[arch] = pkgs |
| } |
| - files := make([]string, 0, len(set)) |
| for f := range set { |
| files = append(files, f) |
| } |
| sort.Strings(files) |
| - return files |
| + return byArch, files |
| } |
| -// unboundedAWSClients reports, as line:what, each construction in the file |
| -// the rules forbid. |
| -func unboundedAWSClients(t *testing.T, path string) []string { |
| +// scanRootBinary type-checks every root-binary file outside this package |
| +// once, under amd64 and then, for any file only arm64 compiles, under |
| +// arm64, and returns the scan's hits by file. |
| +func scanRootBinary(t *testing.T, root string, byArch map[string]map[string][]string, files []string) map[string][]awsHit { |
| t.Helper() |
| - fset := token.NewFileSet() |
| - f, err := parser.ParseFile(fset, path, nil, parser.SkipObjectResolution) |
| - if err != nil { |
| - t.Fatalf("parse %s: %v", path, err) |
| + want := map[string]bool{} |
| + for _, f := range files { |
| + if !strings.HasPrefix(f, "internal/rootaws/") { |
| + want[f] = true |
| + } |
| } |
| - names := map[string]string{} // local import name -> path |
| - for _, imp := range f.Imports { |
| - p, _ := strconv.Unquote(imp.Path.Value) |
| - name := p[strings.LastIndex(p, "/")+1:] |
| - if imp.Name != nil { |
| - name = imp.Name.Name |
| + hits := map[string][]awsHit{} |
| + done := map[string]bool{} |
| + for _, arch := range rootBinaryArchs { |
| + var paths []string |
| + for path, fs := range byArch[arch] { |
| + for _, f := range fs { |
| + if want[f] && !done[f] { |
| + paths = append(paths, path) |
| + break |
| + } |
| + } |
| + } |
| + if len(paths) == 0 { |
| + continue |
| + } |
| + sort.Strings(paths) |
| + for _, pkg := range loadTyped(t, root, arch, nil, paths...) { |
| + for _, f := range pkg.Syntax { |
| + rel, err := filepath.Rel(root, pkg.Fset.File(f.Pos()).Name()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + rel = filepath.ToSlash(rel) |
| + if !want[rel] || done[rel] { |
| + continue |
| + } |
| + done[rel] = true |
| + if hs := unboundedAWSClients(pkg.Fset, pkg.TypesInfo, f); len(hs) > 0 { |
| + hits[rel] = hs |
| + } |
| + } |
| } |
| - names[name] = p |
| } |
| - pkgOf := func(e ast.Expr) (pkg, sel string) { |
| - s, ok := e.(*ast.SelectorExpr) |
| - if !ok { |
| - return "", "" |
| + for f := range want { |
| + if !done[f] { |
| + t.Errorf("%s: in the root binary but never type-checked", f) |
| } |
| - id, ok := s.X.(*ast.Ident) |
| - if !ok { |
| - return "", "" |
| + } |
| + return hits |
| +} |
| + |
| +// loadTyped loads patterns with syntax and type information for |
| +// linux/arch, and fails the test on any load or type error. |
| +func loadTyped(t *testing.T, root, arch string, overlay map[string][]byte, patterns ...string) []*packages.Package { |
| + t.Helper() |
| + cfg := &packages.Config{Dir: root, Overlay: overlay, |
| + Env: append(os.Environ(), "GOOS=linux", "GOARCH="+arch, "CGO_ENABLED=0"), |
| + Mode: packages.NeedName | packages.NeedFiles | packages.NeedCompiledGoFiles | packages.NeedSyntax | packages.NeedTypes | packages.NeedTypesInfo | packages.NeedImports} |
| + pkgs, err := packages.Load(cfg, patterns...) |
| + if err != nil { |
| + t.Fatalf("load (linux/%s): %v", arch, err) |
| + } |
| + var errs []string |
| + for _, p := range pkgs { |
| + for _, e := range p.Errors { |
| + errs = append(errs, e.Error()) |
| } |
| - return names[id.Name], s.Sel.Name |
| } |
| - const sdk = "github.com/aws/aws-sdk-go-v2/" |
| - var hits []string |
| + if len(errs) > 0 || len(pkgs) == 0 { |
| + t.Fatalf("load (linux/%s) of %d package(s): %s", arch, len(pkgs), strings.Join(errs, "; ")) |
| + } |
| + return pkgs |
| +} |
| + |
| +const ( |
| + sdkPath = "github.com/aws/aws-sdk-go-v2/" |
| + rootawsPath = "github.com/carlosframework/platform/internal/rootaws" |
| +) |
| + |
| +// awsHit is one construction the rules forbid: its line, the function (or |
| +// package-level var) holding it, and what it is. |
| +type awsHit struct { |
| + line int |
| + fn, what string |
| +} |
| + |
| +// unboundedAWSClients reports each construction in f the rules forbid. |
| +func unboundedAWSClients(fset *token.FileSet, info *types.Info, f *ast.File) []awsHit { |
| + var hits []awsHit |
| + var stack []ast.Node |
| hit := func(n ast.Node, what string) { |
| - hits = append(hits, fmt.Sprintf("%d: %s", fset.Position(n.Pos()).Line, what)) |
| + hits = append(hits, awsHit{line: fset.Position(n.Pos()).Line, fn: enclosing(stack), what: what}) |
| } |
| ast.Inspect(f, func(n ast.Node) bool { |
| + if n == nil { |
| + stack = stack[:len(stack)-1] |
| + return true |
| + } |
| + var parent ast.Node |
| + if len(stack) > 0 { |
| + parent = stack[len(stack)-1] |
| + } |
| + stack = append(stack, n) |
| switch n := n.(type) { |
| - case *ast.SelectorExpr: |
| + case *ast.Ident: |
| // A call or a func value (load := config.LoadDefaultConfig). |
| - if pkg, sel := pkgOf(n); pkg == sdk+"config" && (sel == "LoadDefaultConfig" || sel == "WithHTTPClient") { |
| - hit(n, "config."+sel) |
| + if fn, ok := info.Uses[n].(*types.Func); ok && fn.Pkg() != nil && fn.Pkg().Path() == sdkPath+"config" && |
| + (fn.Name() == "LoadDefaultConfig" || fn.Name() == "WithHTTPClient") { |
| + hit(n, "config."+fn.Name()) |
| } |
| case *ast.CompositeLit: |
| - pkg, sel := pkgOf(n.Type) |
| + named := namedStruct(info.TypeOf(n)) |
| switch { |
| - case pkg == sdk+"aws" && sel == "Config" && len(n.Elts) > 0: |
| - // An empty aws.Config{} is a zero value returned beside an |
| - // error; it configures nothing. |
| - hit(n, "aws.Config literal") |
| - case strings.HasPrefix(pkg, sdk+"service/") && sel == "Options" && !setsBoundedClient(n, names): |
| - hit(n, pkg[len(sdk):]+".Options literal without rootaws.BoundedHTTPClient()") |
| + case named == nil: |
| + case isAWSConfig(named): |
| + if len(n.Elts) > 0 { |
| + if !setsBoundedClient(info, n) { |
| + hit(n, "aws.Config literal") |
| + } |
| + } else if _, ok := parent.(*ast.ReturnStmt); !ok { |
| + // An empty aws.Config{} returned is a zero value beside |
| + // an error; anywhere else it is a config to fill in. |
| + hit(n, "zero aws.Config") |
| + } |
| + case isServiceOptions(named): |
| + if !setsBoundedClient(info, n) { |
| + hit(n, typeName(named)+" literal without rootaws.BoundedHTTPClient()") |
| + } |
| + case isSDK(named): |
| + for _, e := range n.Elts { |
| + if kv, ok := e.(*ast.KeyValueExpr); ok && keyName(kv) == "HTTPClient" && !isBoundedCall(info, kv.Value) { |
| + hit(n, typeName(named)+" literal sets HTTPClient") |
| + } |
| + } |
| + } |
| + case *ast.ValueSpec: |
| + if n.Type != nil && len(n.Values) == 0 { |
| + // A nil pointer is not a config; a value is a zero one. |
| + if _, ptr := info.TypeOf(n.Type).(*types.Pointer); ptr { |
| + break |
| + } |
| + if named := namedStruct(info.TypeOf(n.Type)); named != nil && isConfigType(named) { |
| + hit(n, "zero "+typeName(named)) |
| + } |
| + } |
| + case *ast.CallExpr: |
| + if id, ok := n.Fun.(*ast.Ident); ok && len(n.Args) == 1 { |
| + if _, builtin := info.Uses[id].(*types.Builtin); builtin && id.Name == "new" { |
| + if named := namedStruct(info.TypeOf(n.Args[0])); named != nil && isConfigType(named) { |
| + hit(n, "zero "+typeName(named)) |
| + } |
| + } |
| + } |
| + case *ast.AssignStmt: |
| + for i, lhs := range n.Lhs { |
| + sel, ok := lhs.(*ast.SelectorExpr) |
| + if !ok { |
| + continue |
| + } |
| + s := info.Selections[sel] |
| + if s == nil || s.Kind() != types.FieldVal || s.Obj().Name() != "HTTPClient" || s.Obj().Pkg() == nil || |
| + !strings.HasPrefix(s.Obj().Pkg().Path(), sdkPath) { |
| + continue |
| + } |
| + if len(n.Rhs) == len(n.Lhs) && isBoundedCall(info, n.Rhs[i]) { |
| + continue |
| + } |
| + recv := "?" |
| + if named := namedStruct(s.Recv()); named != nil { |
| + recv = typeName(named) |
| + } |
| + hit(sel, recv+".HTTPClient set") |
| } |
| } |
| return true |
| @@ -226,25 +517,99 @@ func unboundedAWSClients(t *testing.T, path string) []string { |
| return hits |
| } |
| -func setsBoundedClient(lit *ast.CompositeLit, names map[string]string) bool { |
| - for _, e := range lit.Elts { |
| - kv, ok := e.(*ast.KeyValueExpr) |
| - if !ok { |
| - continue |
| - } |
| - if k, ok := kv.Key.(*ast.Ident); !ok || k.Name != "HTTPClient" { |
| - continue |
| - } |
| - call, ok := kv.Value.(*ast.CallExpr) |
| - if !ok || len(call.Args) != 0 { |
| - return false |
| +// enclosing names the function declaration (or package-level var) on the |
| +// stack: "F", "T.M", or "var v". |
| +func enclosing(stack []ast.Node) string { |
| + for _, n := range stack { |
| + switch n := n.(type) { |
| + case *ast.FuncDecl: |
| + if n.Recv != nil && len(n.Recv.List) == 1 { |
| + r := n.Recv.List[0].Type |
| + if s, ok := r.(*ast.StarExpr); ok { |
| + r = s.X |
| + } |
| + if ix, ok := r.(*ast.IndexExpr); ok { |
| + r = ix.X |
| + } |
| + if id, ok := r.(*ast.Ident); ok { |
| + return id.Name + "." + n.Name.Name |
| + } |
| + } |
| + return n.Name.Name |
| + case *ast.ValueSpec: |
| + if len(n.Names) > 0 { |
| + return "var " + n.Names[0].Name |
| + } |
| } |
| - s, ok := call.Fun.(*ast.SelectorExpr) |
| - if !ok { |
| - return false |
| + } |
| + return "package" |
| +} |
| + |
| +// namedStruct is t (or what it points to) as a named struct type, or nil. |
| +func namedStruct(t types.Type) *types.Named { |
| + if p, ok := t.(*types.Pointer); ok { |
| + t = p.Elem() |
| + } |
| + n, ok := types.Unalias(t).(*types.Named) |
| + if !ok { |
| + return nil |
| + } |
| + if _, ok := n.Underlying().(*types.Struct); !ok { |
| + return nil |
| + } |
| + return n |
| +} |
| + |
| +func isSDK(n *types.Named) bool { |
| + return n.Obj().Pkg() != nil && strings.HasPrefix(n.Obj().Pkg().Path(), sdkPath) |
| +} |
| + |
| +func isAWSConfig(n *types.Named) bool { |
| + return n.Obj().Pkg() != nil && n.Obj().Pkg().Path() == sdkPath+"aws" && n.Obj().Name() == "Config" |
| +} |
| + |
| +func isServiceOptions(n *types.Named) bool { |
| + return n.Obj().Pkg() != nil && strings.HasPrefix(n.Obj().Pkg().Path(), sdkPath+"service/") && n.Obj().Name() == "Options" |
| +} |
| + |
| +// isConfigType is a struct an AWS client is built from: aws.Config or a |
| +// service's Options. |
| +func isConfigType(n *types.Named) bool { return isAWSConfig(n) || isServiceOptions(n) } |
| + |
| +// typeName is "s3.Options", "aws.Config": the package's name and the type's. |
| +func typeName(n *types.Named) string { return n.Obj().Pkg().Name() + "." + n.Obj().Name() } |
| + |
| +func keyName(kv *ast.KeyValueExpr) string { |
| + if id, ok := kv.Key.(*ast.Ident); ok { |
| + return id.Name |
| + } |
| + return "" |
| +} |
| + |
| +func setsBoundedClient(info *types.Info, lit *ast.CompositeLit) bool { |
| + for _, e := range lit.Elts { |
| + if kv, ok := e.(*ast.KeyValueExpr); ok && keyName(kv) == "HTTPClient" { |
| + return isBoundedCall(info, kv.Value) |
| } |
| - id, ok := s.X.(*ast.Ident) |
| - return ok && names[id.Name] == "github.com/carlosframework/platform/internal/rootaws" && s.Sel.Name == "BoundedHTTPClient" |
| } |
| return false |
| } |
| + |
| +// isBoundedCall is a call of rootaws.BoundedHTTPClient(). |
| +func isBoundedCall(info *types.Info, e ast.Expr) bool { |
| + call, ok := ast.Unparen(e).(*ast.CallExpr) |
| + if !ok || len(call.Args) != 0 { |
| + return false |
| + } |
| + var id *ast.Ident |
| + switch f := ast.Unparen(call.Fun).(type) { |
| + case *ast.SelectorExpr: |
| + id = f.Sel |
| + case *ast.Ident: |
| + id = f |
| + default: |
| + return false |
| + } |
| + fn, ok := info.Uses[id].(*types.Func) |
| + return ok && fn.Pkg() != nil && fn.Pkg().Path() == rootawsPath && fn.Name() == "BoundedHTTPClient" |
| +} |
diff --git a/internal/rootaws/stall.go b/internal/rootaws/stall.go| index 394d5123e..fe5b5dac2 100644 |
| --- a/internal/rootaws/stall.go |
| +++ b/internal/rootaws/stall.go |
| @@ -3,6 +3,7 @@ package rootaws |
| import ( |
| "context" |
| "crypto/tls" |
| + "errors" |
| "fmt" |
| "io" |
| "net" |
| @@ -17,6 +18,13 @@ import ( |
| "github.com/aws/aws-sdk-go-v2/aws/defaults" |
| awshttp "github.com/aws/aws-sdk-go-v2/aws/transport/http" |
| awsconfig "github.com/aws/aws-sdk-go-v2/config" |
| + "github.com/aws/aws-sdk-go-v2/credentials/endpointcreds" |
| + "github.com/aws/aws-sdk-go-v2/credentials/logincreds" |
| + "github.com/aws/aws-sdk-go-v2/credentials/ssocreds" |
| + "github.com/aws/aws-sdk-go-v2/credentials/stscreds" |
| + "github.com/aws/aws-sdk-go-v2/service/sso" |
| + "github.com/aws/aws-sdk-go-v2/service/ssooidc" |
| + "github.com/aws/aws-sdk-go-v2/service/sts" |
| ) |
| // The invariant (stopping rule 2, root-worker liveness): every response a |
| @@ -25,8 +33,11 @@ import ( |
| // limit measured per response, before net/http's own client sees the |
| // response, so a redirect body the client drains is bounded too. The |
| // loaders here (LoadDefaultConfig, LoadStaticConfig) hand out configs whose |
| -// HTTPClient is that transport's client, and BoundedHTTPClient is the same |
| -// client for one built from bare service options. TestAWSClientsAreBounded |
| +// HTTPClient is that transport's client, the credential clients the SDK |
| +// builds while loading (STS, SSO, container credentials) call through it |
| +// too, login-session credentials, which cannot, are refused, and |
| +// BoundedHTTPClient is the same client for one built from bare service |
| +// options. TestAWSClientsAreBounded |
| // fails when root-graph code builds an AWS config or client another way, |
| // apart from its commented allowlist. |
| // |
| @@ -67,24 +78,75 @@ const ( |
| BodyIdleTimeout = 120 * time.Second |
| ) |
| -// withStallBounds puts the loading client ahead of the caller's options, so |
| -// an explicit WithHTTPClient from a caller still wins: a deliberate |
| -// override, which only tests use (awsmanaged's fake transports) and |
| -// TestAWSClientsAreBounded keeps out of the root binary's production code. |
| -// boundConfig finishes the job once the config loads. |
| -func withStallBounds(opts []func(*awsconfig.LoadOptions) error) []func(*awsconfig.LoadOptions) error { |
| - return append([]func(*awsconfig.LoadOptions) error{awsconfig.WithHTTPClient(loadingClient(ResponseHeaderTimeout))}, opts...) |
| +// stallLoad is one config load under the stall bounds: the body bound, the |
| +// loading client it injects (which carries the header bound), and whether |
| +// that client is still the one the SDK loads over once every option has run |
| +// (owned). A caller's explicit |
| +// client (WithHTTPClient, or an option setting LoadOptions.HTTPClient) is a |
| +// deliberate override, which only tests use (awsmanaged's fake transports) |
| +// and TestAWSClientsAreBounded keeps out of the root binary's production |
| +// code: it is left as given, and so are the credential clients built over |
| +// it. Ownership is decided by identity before the SDK resolves anything, |
| +// so a CA bundle, which the SDK applies to a copy of whichever |
| +// BuildableClient it was given, does not blur ours with a caller's. |
| +type stallLoad struct { |
| + idle time.Duration |
| + loading *awshttp.BuildableClient |
| + owned bool // set while the options run, before the SDK resolves |
| + // login is set when a credential the load resolved is a login session |
| + // (logincreds), directly or as an assumed role's source: its sign-in |
| + // client cannot be bounded, so boundConfig refuses the load. |
| + login bool |
| +} |
| + |
| +// errLoginSession refuses login-session credentials (a profile's |
| +// login_session): the SDK builds their sign-in client from the config while |
| +// it loads and offers no hook to replace it, so their refresh would have the |
| +// header bound but no body bound. |
| +var errLoginSession = errors.New("rootaws: login-session credentials (login_session) are not supported: their sign-in client cannot be bounded; use another credential source") |
| + |
| +func newStallLoad(header, idle time.Duration) *stallLoad { |
| + return &stallLoad{idle: idle, loading: loadingClient(header)} |
| +} |
| + |
| +// withStallBounds is the production bounds around the caller's options. |
| +func withStallBounds(opts []func(*awsconfig.LoadOptions) error) ([]func(*awsconfig.LoadOptions) error, *stallLoad) { |
| + l := newStallLoad(ResponseHeaderTimeout, BodyIdleTimeout) |
| + return l.options(opts), l |
| +} |
| + |
| +// options puts the loading client ahead of the caller's options, so a |
| +// caller's own client still wins, and an option after them that records |
| +// whether it did and, if not, bounds the credential clients |
| +// (boundCredentialClients). The loaders' own options that follow set neither |
| +// the HTTP client nor a credential provider's options. boundConfig finishes |
| +// the job once the config loads. |
| +func (l *stallLoad) options(opts []func(*awsconfig.LoadOptions) error) []func(*awsconfig.LoadOptions) error { |
| + out := make([]func(*awsconfig.LoadOptions) error, 0, len(opts)+2) |
| + out = append(out, awsconfig.WithHTTPClient(l.loading)) |
| + out = append(out, opts...) |
| + return append(out, func(o *awsconfig.LoadOptions) error { |
| + l.owned = o.HTTPClient == aws.HTTPClient(l.loading) |
| + if l.owned { |
| + l.boundCredentialClients(o) |
| + } |
| + return nil |
| + }) |
| } |
| // loadingClient is the HTTP client the SDK loads the config over: a |
| // BuildableClient, because the SDK applies a CA bundle (AWS_CA_BUNDLE) only |
| // to one and refuses to load a bundle over anything else, with the header |
| // timeout and HTTP/1.1 only already set (http1Only). The credential clients |
| -// the loader builds (STS, SSO, IMDS) keep this client, so they get the |
| -// header timeout but not the body limit; IMDS adds its own 250 ms dial and |
| -// 500 ms header timeouts to a BuildableClient, which a non-buildable client |
| -// would lose. Service clients built from the loaded config get |
| -// boundConfig's client instead. |
| +// the loader builds over it (STS for assume-role and web identity, SSO and |
| +// SSO OIDC) are bounded when their providers are built, and container |
| +// credentials, which the SDK would give a default client of their own, get |
| +// a bounded one (boundCredentialClients). Login-session credentials are |
| +// refused (errLoginSession). IMDS keeps this client as the SDK builds it: |
| +// IMDS adds its own 250 ms dial and 500 ms header timeouts to a |
| +// BuildableClient, which a non-buildable client would lose, and its |
| +// provider builds the client after every option has run. Service clients |
| +// built from the loaded config get boundConfig's client. |
| func loadingClient(header time.Duration) *awshttp.BuildableClient { |
| return awshttp.NewBuildableClient().WithTransportOptions(func(t *http.Transport) { |
| t.ResponseHeaderTimeout = header |
| @@ -113,19 +175,150 @@ func http1Only(t *http.Transport) { |
| } |
| } |
| +// boundCredentialClients bounds the clients the SDK builds for credential |
| +// providers while it loads: each provider's options hook gets ours first, |
| +// then any hook the caller set, so a client the caller's hook supplies stays |
| +// as given. Ours wraps the SDK's client so every call it makes passes the |
| +// bounded client as a per-operation option, built from that client's own |
| +// HTTP client: the loading client with the CA bundle and defaults mode the |
| +// SDK applied. Rebuilding the service client instead would rerun its |
| +// constructor's finalizers on options that already carry them. |
| +func (l *stallLoad) boundCredentialClients(o *awsconfig.LoadOptions) { |
| + endpoint := o.EndpointCredentialOptions |
| + o.EndpointCredentialOptions = func(eo *endpointcreds.Options) { |
| + // Container credentials (AWS_CONTAINER_CREDENTIALS_*): with no |
| + // client the provider would build a default one with no bounds. The |
| + // loading client without its CA bundle, as that default has none. |
| + if eo.HTTPClient == nil { |
| + eo.HTTPClient = mustBoundedClient(l.loading, l.idle) |
| + } |
| + if endpoint != nil { |
| + endpoint(eo) |
| + } |
| + } |
| + assumeRole := o.AssumeRoleCredentialOptions |
| + o.AssumeRoleCredentialOptions = func(ro *stscreds.AssumeRoleOptions) { |
| + if c, ok := ro.Client.(*sts.Client); ok { |
| + // The source credentials the role is assumed with. This SDK |
| + // refuses a login-session source profile itself; the check |
| + // keeps the refusal if a later one accepts it. |
| + if aws.IsCredentialsProvider(c.Options().Credentials, (*logincreds.Provider)(nil)) { |
| + l.login = true |
| + } |
| + if hc, ok := l.credentialClient(c.Options().HTTPClient); ok { |
| + ro.Client = boundedSTS{c: c, hc: hc} |
| + } |
| + } |
| + if assumeRole != nil { |
| + assumeRole(ro) |
| + } |
| + } |
| + webIdentity := o.WebIdentityRoleCredentialOptions |
| + o.WebIdentityRoleCredentialOptions = func(wo *stscreds.WebIdentityRoleOptions) { |
| + // The SDK runs this hook twice: once with no client, to see whether |
| + // the options name one, then on the provider over its own client. |
| + if c, ok := wo.Client.(*sts.Client); ok { |
| + if hc, ok := l.credentialClient(c.Options().HTTPClient); ok { |
| + wo.Client = boundedSTS{c: c, hc: hc} |
| + } |
| + } |
| + if webIdentity != nil { |
| + webIdentity(wo) |
| + } |
| + } |
| + ssoProvider := o.SSOProviderOptions |
| + o.SSOProviderOptions = func(so *ssocreds.Options) { |
| + if c, ok := so.Client.(*sso.Client); ok { |
| + if hc, ok := l.credentialClient(c.Options().HTTPClient); ok { |
| + so.Client = boundedSSO{c: c, hc: hc} |
| + } |
| + } |
| + if ssoProvider != nil { |
| + ssoProvider(so) |
| + } |
| + } |
| + ssoToken := o.SSOTokenProviderOptions |
| + o.SSOTokenProviderOptions = func(to *ssocreds.SSOTokenProviderOptions) { |
| + if c, ok := to.Client.(*ssooidc.Client); ok { |
| + if hc, ok := l.credentialClient(c.Options().HTTPClient); ok { |
| + to.Client = boundedSSOOIDC{c: c, hc: hc} |
| + } |
| + } |
| + if ssoToken != nil { |
| + ssoToken(to) |
| + } |
| + } |
| +} |
| + |
| +// credentialClient is the bounded client over a credential client's own |
| +// HTTP client, which is the loading client (or the SDK's CA-bundle copy of |
| +// it, with the client's defaults mode applied) while the load is owned. |
| +func (l *stallLoad) credentialClient(hc any) (aws.HTTPClient, bool) { |
| + bc, ok := hc.(*awshttp.BuildableClient) |
| + if !ok { |
| + return nil, false |
| + } |
| + return mustBoundedClient(bc, l.idle), true |
| +} |
| + |
| +// boundedSTS, boundedSSO and boundedSSOOIDC are the SDK's credential |
| +// clients with the bounded HTTP client set ahead of the provider's own |
| +// per-operation options. |
| +type boundedSTS struct { |
| + c *sts.Client |
| + hc aws.HTTPClient |
| +} |
| + |
| +func (b boundedSTS) use(o *sts.Options) { o.HTTPClient = b.hc } |
| + |
| +func (b boundedSTS) AssumeRole(ctx context.Context, in *sts.AssumeRoleInput, optFns ...func(*sts.Options)) (*sts.AssumeRoleOutput, error) { |
| + return b.c.AssumeRole(ctx, in, append([]func(*sts.Options){b.use}, optFns...)...) |
| +} |
| + |
| +func (b boundedSTS) AssumeRoleWithWebIdentity(ctx context.Context, in *sts.AssumeRoleWithWebIdentityInput, optFns ...func(*sts.Options)) (*sts.AssumeRoleWithWebIdentityOutput, error) { |
| + return b.c.AssumeRoleWithWebIdentity(ctx, in, append([]func(*sts.Options){b.use}, optFns...)...) |
| +} |
| + |
| +type boundedSSO struct { |
| + c *sso.Client |
| + hc aws.HTTPClient |
| +} |
| + |
| +func (b boundedSSO) GetRoleCredentials(ctx context.Context, in *sso.GetRoleCredentialsInput, optFns ...func(*sso.Options)) (*sso.GetRoleCredentialsOutput, error) { |
| + use := func(o *sso.Options) { o.HTTPClient = b.hc } |
| + return b.c.GetRoleCredentials(ctx, in, append([]func(*sso.Options){use}, optFns...)...) |
| +} |
| + |
| +type boundedSSOOIDC struct { |
| + c *ssooidc.Client |
| + hc aws.HTTPClient |
| +} |
| + |
| +func (b boundedSSOOIDC) CreateToken(ctx context.Context, in *ssooidc.CreateTokenInput, optFns ...func(*ssooidc.Options)) (*ssooidc.CreateTokenOutput, error) { |
| + use := func(o *ssooidc.Options) { o.HTTPClient = b.hc } |
| + return b.c.CreateToken(ctx, in, append([]func(*ssooidc.Options){use}, optFns...)...) |
| +} |
| + |
| // boundConfig replaces the loaded config's HTTP client with the bounded |
| // one, built from the client the SDK loaded over (so a CA bundle it applied |
| // stays) with the config's defaults mode applied now, as each service client |
| // would have applied it. The result is not a BuildableClient, so no service |
| // client can rewrite its dialer and drop the progress wrap under a |
| -// non-legacy defaults mode. A client that is not a BuildableClient is a |
| -// caller's own (withStallBounds) and is left as given. |
| -func boundConfig(cfg aws.Config, idle time.Duration) (aws.Config, error) { |
| +// non-legacy defaults mode. A load whose client the caller overrode |
| +// (stallLoad) is left as given, whatever the client's type. A load that |
| +// resolved login-session credentials is refused (errLoginSession). |
| +func boundConfig(cfg aws.Config, l *stallLoad) (aws.Config, error) { |
| + if !l.owned { |
| + return cfg, nil |
| + } |
| + if l.login || aws.IsCredentialsProvider(cfg.Credentials, (*logincreds.Provider)(nil)) { |
| + return aws.Config{}, errLoginSession |
| + } |
| bc, ok := cfg.HTTPClient.(*awshttp.BuildableClient) |
| if !ok { |
| - return cfg, nil |
| + return aws.Config{}, fmt.Errorf("rootaws: the SDK loaded over a %T, not the loading client", cfg.HTTPClient) |
| } |
| - client, err := boundedClient(withDefaultsMode(bc, cfg), idle) |
| + client, err := boundedClient(withDefaultsMode(bc, cfg), l.idle) |
| if err != nil { |
| return aws.Config{}, err |
| } |
| @@ -161,7 +354,11 @@ func withDefaultsMode(bc *awshttp.BuildableClient, cfg aws.Config) *awshttp.Buil |
| // service options rather than a loaded config: set it as the options' |
| // HTTPClient. |
| func BoundedHTTPClient() aws.HTTPClient { |
| - c, err := boundedClient(loadingClient(ResponseHeaderTimeout), BodyIdleTimeout) |
| + return mustBoundedClient(loadingClient(ResponseHeaderTimeout), BodyIdleTimeout) |
| +} |
| + |
| +func mustBoundedClient(bc *awshttp.BuildableClient, idle time.Duration) aws.HTTPClient { |
| + c, err := boundedClient(bc, idle) |
| if err != nil { |
| // Only an SDK whose frozen client is no longer an *http.Client gets |
| // here, and TestExportedStallBounds fails on it first. |
diff --git a/internal/rootaws/stall_credentials_test.go b/internal/rootaws/stall_credentials_test.go| new file mode 100644 |
| index 000000000..f6b1c8b1e |
| --- /dev/null |
| +++ b/internal/rootaws/stall_credentials_test.go |
| @@ -0,0 +1,339 @@ |
| +package rootaws |
| + |
| +import ( |
| + "context" |
| + "crypto/sha1" |
| + "encoding/hex" |
| + "errors" |
| + "io" |
| + "net/http" |
| + "os" |
| + "path/filepath" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "github.com/aws/aws-sdk-go-v2/aws" |
| + "github.com/aws/aws-sdk-go-v2/aws/retry" |
| + awsconfig "github.com/aws/aws-sdk-go-v2/config" |
| + "github.com/aws/aws-sdk-go-v2/credentials" |
| + "github.com/aws/aws-sdk-go-v2/credentials/endpointcreds" |
| + "github.com/aws/aws-sdk-go-v2/credentials/stscreds" |
| + "github.com/aws/aws-sdk-go-v2/service/sts" |
| + "github.com/aws/smithy-go/middleware" |
| + smithyhttp "github.com/aws/smithy-go/transport/http" |
| +) |
| + |
| +// credentialStallServer is a fake credential endpoint for STS (query |
| +// protocol), SSO's GetRoleCredentials, SSO OIDC's CreateToken and container |
| +// credentials (/container): it sends headers and the start of a well-formed |
| +// answer, then nothing more until the test ends. It counts the requests it |
| +// gets, and sends on ended (buffered) when a request's connection closes |
| +// under it. |
| +func credentialStallServer(t *testing.T) (url string, hits *atomic.Int32, ended <-chan struct{}) { |
| + t.Helper() |
| + hits = new(atomic.Int32) |
| + gone := make(chan struct{}, 16) |
| + url = stallServer(t, func(w http.ResponseWriter, r *http.Request, done <-chan struct{}) { |
| + hits.Add(1) |
| + var head string |
| + switch r.URL.Path { |
| + case "/federation/credentials": |
| + w.Header().Set("Content-Type", "application/json") |
| + head = `{"roleCredentials":{"accessKeyId":"A` |
| + case "/token": |
| + w.Header().Set("Content-Type", "application/json") |
| + head = `{"accessToken":"A` |
| + case "/container": |
| + w.Header().Set("Content-Type", "application/json") |
| + head = `{"AccessKeyId":"A` |
| + default: |
| + if err := r.ParseForm(); err != nil { |
| + t.Errorf("STS request form: %v", err) |
| + return |
| + } |
| + action := r.PostForm.Get("Action") |
| + w.Header().Set("Content-Type", "text/xml") |
| + head = `<` + action + `Response xmlns="https://sts.amazonaws.com/doc/2011-06-15/"><` + action + `Result><Credentials><AccessKeyId>A` |
| + } |
| + w.Header().Set("Content-Length", "1048576") |
| + w.WriteHeader(http.StatusOK) |
| + io.WriteString(w, head) |
| + w.(http.Flusher).Flush() |
| + block(r, done) |
| + if r.Context().Err() != nil { |
| + select { |
| + case gone <- struct{}{}: |
| + default: |
| + } |
| + } |
| + }) |
| + return url, hits, gone |
| +} |
| + |
| +// credentialEnv points every credential service at endpoint, makes sure the |
| +// SDK honours that (AWS_IGNORE_CONFIGURED_ENDPOINT_URLS would otherwise send |
| +// it to AWS), and gives the loader a home and shared files of its own |
| +// (absent unless a case writes them). It returns the home. The loads' |
| +// clients dial only loopback (localStallLoad), which is the barrier; the |
| +// endpoints are what make the fixtures the place they dial. |
| +func credentialEnv(t *testing.T, endpoint string) string { |
| + t.Helper() |
| + home := t.TempDir() |
| + t.Setenv("HOME", home) |
| + t.Setenv("AWS_CONFIG_FILE", filepath.Join(home, "config")) |
| + t.Setenv("AWS_SHARED_CREDENTIALS_FILE", filepath.Join(home, "credentials")) |
| + t.Setenv("AWS_IGNORE_CONFIGURED_ENDPOINT_URLS", "false") |
| + t.Setenv("AWS_DEFAULTS_MODE", "") |
| + t.Setenv("AWS_CA_BUNDLE", "") |
| + for _, svc := range []string{"STS", "SSO", "SSO_OIDC"} { |
| + t.Setenv("AWS_ENDPOINT_URL_"+svc, endpoint) |
| + } |
| + return home |
| +} |
| + |
| +func writeFile(t *testing.T, path, body string) { |
| + t.Helper() |
| + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.WriteFile(path, []byte(body), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func webIdentityEnv(t *testing.T, home, _ string) { |
| + t.Helper() |
| + token := filepath.Join(home, "token") |
| + writeFile(t, token, "header.payload.signature") |
| + t.Setenv("AWS_WEB_IDENTITY_TOKEN_FILE", token) |
| + t.Setenv("AWS_ROLE_ARN", "arn:aws:iam::123456789012:role/r") |
| + t.Setenv("AWS_ROLE_SESSION_NAME", "s") |
| +} |
| + |
| +func containerEnv(t *testing.T, _, url string) { |
| + t.Helper() |
| + t.Setenv("AWS_CONTAINER_CREDENTIALS_FULL_URI", url+"/container") |
| +} |
| + |
| +// ssoCachedToken writes the SSO token cache entry the SDK reads for key (a |
| +// start URL, or an sso-session name). |
| +func ssoCachedToken(t *testing.T, home, key, body string) { |
| + t.Helper() |
| + sum := sha1.Sum([]byte(key)) |
| + writeFile(t, filepath.Join(home, ".aws", "sso", "cache", hex.EncodeToString(sum[:])+".json"), body) |
| +} |
| + |
| +// withoutWriterTo hides the request stream's WriterTo from net/http. It |
| +// works around a race in the SDK and net/http that a loopback fixture |
| +// answering at once can hit (it is not in the code under test): smithy |
| +// closes a request body as soon as the response headers arrive, a closed |
| +// body's WriteTo returns io.EOF, and net/http, still finishing the request |
| +// write with a WriteTo-based copy, takes that io.EOF for a write error and |
| +// closes the connection under the response. A plain Read returns the same |
| +// io.EOF, which the copy treats as the end of the body. Without this, about |
| +// one STS fixture run in five fails at once with "use of closed network |
| +// connection" instead of at the bound. |
| +func withoutWriterTo(stack *middleware.Stack) error { |
| + return stack.Finalize.Add(middleware.FinalizeMiddlewareFunc("rootawsTestWithoutWriterTo", |
| + func(ctx context.Context, in middleware.FinalizeInput, next middleware.FinalizeHandler) (middleware.FinalizeOutput, middleware.Metadata, error) { |
| + if req, ok := in.Request.(*smithyhttp.Request); ok { |
| + if rs, ok := req.GetStream().(io.ReadSeeker); ok { |
| + r, err := req.SetStream(struct{ io.ReadSeeker }{rs}) |
| + if err != nil { |
| + return middleware.FinalizeOutput{}, middleware.Metadata{}, err |
| + } |
| + in.Request = r |
| + } |
| + } |
| + return next.HandleFinalize(ctx, in) |
| + }), middleware.After) |
| +} |
| + |
| +// testLoadOptions are the options every fixture load takes: one attempt |
| +// per call, the container provider included, and withoutWriterTo. |
| +var testLoadOptions = []func(*awsconfig.LoadOptions) error{ |
| + awsconfig.WithRetryMaxAttempts(1), |
| + awsconfig.WithAPIOptions([]func(*middleware.Stack) error{withoutWriterTo}), |
| + awsconfig.WithEndpointCredentialOptions(func(o *endpointcreds.Options) { |
| + o.Retryer = retry.AddWithMaxAttempts(retry.NewStandard(), 1) |
| + }), |
| +} |
| + |
| +type credentialLoader func(l *stallLoad, opts ...func(*awsconfig.LoadOptions) error) (aws.Config, error) |
| + |
| +// The non-root branch of LoadDefaultConfig, and its root branch with the |
| +// bounds around it as LoadDefaultConfig puts them. |
| +var ( |
| + loadThroughDefault credentialLoader = func(l *stallLoad, opts ...func(*awsconfig.LoadOptions) error) (aws.Config, error) { |
| + return loadDefaultConfig(context.Background(), l, opts...) |
| + } |
| + loadThroughRoot credentialLoader = func(l *stallLoad, opts ...func(*awsconfig.LoadOptions) error) (aws.Config, error) { |
| + cfg, err := loadRootConfig(context.Background(), filepath.Join(os.Getenv("HOME"), "absent"), l.options(opts)...) |
| + if err != nil { |
| + return cfg, err |
| + } |
| + return boundConfig(cfg, l) |
| + } |
| +) |
| + |
| +var profileTarget = []func(*awsconfig.LoadOptions) error{awsconfig.WithSharedConfigProfile("target")} |
| + |
| +// A credential response that stalls mid-body fails at the body bound, |
| +// through the real loader, for each client the SDK builds while loading |
| +// (#1143): STS for web identity and assume-role, SSO, SSO OIDC's token |
| +// refresh, and container credentials. Before, the first four had the |
| +// header bound only and container credentials no bound at all, so a |
| +// stalled body held the credential refresh for good. |
| +func TestStallCredentialBodyFails(t *testing.T) { |
| + cases := []struct { |
| + name string |
| + nonRoot bool // the case reads shared files, which root's branch refuses |
| + load credentialLoader |
| + setup func(t *testing.T, home, url string) |
| + loadOpts []func(*awsconfig.LoadOptions) error |
| + }{ |
| + {name: "web identity", load: loadThroughDefault, setup: webIdentityEnv}, |
| + {name: "web identity, root branch", load: loadThroughRoot, setup: webIdentityEnv}, |
| + {name: "container", load: loadThroughDefault, setup: containerEnv}, |
| + {name: "container, root branch", load: loadThroughRoot, setup: containerEnv}, |
| + {name: "assume role", nonRoot: true, load: loadThroughDefault, loadOpts: profileTarget, |
| + setup: func(t *testing.T, home, _ string) { |
| + writeFile(t, os.Getenv("AWS_CONFIG_FILE"), "[profile target]\nrole_arn = arn:aws:iam::123456789012:role/r\nsource_profile = source\n"+ |
| + "[profile source]\naws_access_key_id = ACCESS\naws_secret_access_key = SECRET\n") |
| + }}, |
| + {name: "sso", nonRoot: true, load: loadThroughDefault, loadOpts: profileTarget, |
| + setup: func(t *testing.T, home, _ string) { |
| + writeFile(t, os.Getenv("AWS_CONFIG_FILE"), "[profile target]\nsso_start_url = https://start.example.com/start\nsso_region = eu-west-1\n"+ |
| + "sso_account_id = 123456789012\nsso_role_name = r\n") |
| + ssoCachedToken(t, home, "https://start.example.com/start", `{"accessToken":"T","expiresAt":"2999-01-01T00:00:00Z"}`) |
| + }}, |
| + {name: "sso session token refresh", nonRoot: true, load: loadThroughDefault, loadOpts: profileTarget, |
| + setup: func(t *testing.T, home, _ string) { |
| + writeFile(t, os.Getenv("AWS_CONFIG_FILE"), "[profile target]\nsso_session = s\nsso_account_id = 123456789012\nsso_role_name = r\n"+ |
| + "[sso-session s]\nsso_start_url = https://start.example.com/start\nsso_region = eu-west-1\n") |
| + ssoCachedToken(t, home, "s", `{"accessToken":"T","expiresAt":"2000-01-01T00:00:00Z","refreshToken":"R",`+ |
| + `"clientId":"C","clientSecret":"S","registrationExpiresAt":"2999-01-01T00:00:00Z"}`) |
| + }}, |
| + } |
| + for _, c := range cases { |
| + t.Run(c.name, func(t *testing.T) { |
| + if c.nonRoot && os.Geteuid() == 0 { |
| + t.Skip("reads shared config, which LoadDefaultConfig's root branch refuses") |
| + } |
| + url, hits, _ := credentialStallServer(t) |
| + home := credentialEnv(t, url) |
| + c.setup(t, home, url) |
| + l := localStallLoad(testHeaderTimeout, testIdleTimeout) |
| + cfg, err := c.load(l, append(append([]func(*awsconfig.LoadOptions) error{}, c.loadOpts...), testLoadOptions...)...) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + wantBodyStall(t, stalls(t, func() error { |
| + _, err := cfg.Credentials.Retrieve(context.Background()) |
| + return err |
| + })) |
| + if hits.Load() == 0 { |
| + t.Fatal("the fake credential endpoint was never asked") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// Login-session credentials, whose sign-in client the SDK gives no way to |
| +// bound, are refused at load, before any request. As an assumed role's |
| +// source this SDK refuses the profile itself; rootaws's check on the |
| +// role's source credentials (boundCredentialClients) is there for an SDK |
| +// that accepts it. |
| +func TestLoginSessionCredentialsRefused(t *testing.T) { |
| + if os.Geteuid() == 0 { |
| + t.Skip("reads shared config, which LoadDefaultConfig's root branch refuses") |
| + } |
| + cases := map[string]struct { |
| + profile string |
| + ours bool // refused by rootaws, not by the SDK |
| + }{ |
| + "login session": {"[profile target]\nlogin_session = arn:aws:iam::123456789012:user/u\n", true}, |
| + "assumed from a login session": {"[profile target]\nrole_arn = arn:aws:iam::123456789012:role/r\nsource_profile = source\n" + |
| + "[profile source]\nlogin_session = arn:aws:iam::123456789012:user/u\n", false}, |
| + } |
| + for name, c := range cases { |
| + t.Run(name, func(t *testing.T) { |
| + url, hits, _ := credentialStallServer(t) |
| + credentialEnv(t, url) |
| + t.Setenv("AWS_ENDPOINT_URL_SIGNIN", url) |
| + writeFile(t, os.Getenv("AWS_CONFIG_FILE"), c.profile) |
| + _, err := loadDefaultConfig(context.Background(), localStallLoad(testHeaderTimeout, testIdleTimeout), |
| + append(append([]func(*awsconfig.LoadOptions) error{}, profileTarget...), testLoadOptions...)...) |
| + if err == nil || (c.ours && !errors.Is(err, errLoginSession)) { |
| + t.Fatalf("loaded login-session credentials: %v", err) |
| + } |
| + if hits.Load() != 0 { |
| + t.Fatal("the refusal came after a request") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// The credentials cache retrieves with the caller's deadline removed, so a |
| +// caller that gives up does not end a stalled exchange; the bounded client |
| +// does. This is the fence writer's shape (hostfence.OpenRootFenceStore): a |
| +// literal config over the bounded client, an assume-role provider over STS |
| +// built from it, cached. The caller's short deadline returns at once, and |
| +// the STS request itself still ends at the body bound; a retrieval with no |
| +// deadline at all fails there too. |
| +func TestStallCredentialCacheEndsWithoutCallerContext(t *testing.T) { |
| + url, hits, ended := credentialStallServer(t) |
| + credentialEnv(t, url) |
| + cfg := aws.Config{Region: "eu-west-1", HTTPClient: mustBoundedClient(localStallLoad(testHeaderTimeout, testIdleTimeout).loading, testIdleTimeout), |
| + RetryMaxAttempts: 1, APIOptions: []func(*middleware.Stack) error{withoutWriterTo}, |
| + Credentials: aws.NewCredentialsCache(credentials.NewStaticCredentialsProvider("ACCESS", "SECRET", ""))} |
| + client := sts.NewFromConfig(cfg, func(o *sts.Options) { o.BaseEndpoint = aws.String(url) }) |
| + cache := aws.NewCredentialsCache(stscreds.NewAssumeRoleProvider(client, "arn:aws:iam::123456789012:role/r")) |
| + |
| + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond) |
| + defer cancel() |
| + if _, err := cache.Retrieve(ctx); !errors.Is(err, context.DeadlineExceeded) { |
| + t.Fatalf("the caller's deadline did not return it: %v", err) |
| + } |
| + select { |
| + case <-ended: |
| + case <-time.After(stallDeadline): |
| + t.Fatalf("the STS request the caller gave up on was still open after %s", stallDeadline) |
| + } |
| + wantBodyStall(t, stalls(t, func() error { |
| + _, err := cache.Retrieve(context.Background()) |
| + return err |
| + })) |
| + if hits.Load() == 0 { |
| + t.Fatal("the fake STS endpoint was never asked") |
| + } |
| +} |
| + |
| +type roundTripFunc func(*http.Request) (*http.Response, error) |
| + |
| +func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } |
| + |
| +// A caller's explicit client carries the credential calls too: the loader |
| +// bounds only the clients it built over its own. |
| +func TestCallerClientCarriesCredentialCalls(t *testing.T) { |
| + url, hits, _ := credentialStallServer(t) |
| + home := credentialEnv(t, url) |
| + webIdentityEnv(t, home, url) |
| + var seen atomic.Int32 |
| + own := &http.Client{Transport: roundTripFunc(func(*http.Request) (*http.Response, error) { |
| + seen.Add(1) |
| + return nil, errors.New("the caller's transport") |
| + })} |
| + l := localStallLoad(testHeaderTimeout, testIdleTimeout) |
| + cfg, err := loadDefaultConfig(context.Background(), l, append([]func(*awsconfig.LoadOptions) error{awsconfig.WithHTTPClient(own)}, testLoadOptions...)...) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := cfg.Credentials.Retrieve(context.Background()); err == nil { |
| + t.Fatal("retrieval through a failing transport succeeded") |
| + } |
| + if seen.Load() == 0 || hits.Load() != 0 { |
| + t.Fatalf("the STS call went %d times through the caller's client and %d times past it", seen.Load(), hits.Load()) |
| + } |
| +} |
diff --git a/internal/rootaws/stall_test.go b/internal/rootaws/stall_test.go| index efaacf73a..568a0319f 100644 |
| --- a/internal/rootaws/stall_test.go |
| +++ b/internal/rootaws/stall_test.go |
| @@ -17,10 +17,12 @@ import ( |
| "strings" |
| "sync" |
| "sync/atomic" |
| + "syscall" |
| "testing" |
| "time" |
| "github.com/aws/aws-sdk-go-v2/aws" |
| + awshttp "github.com/aws/aws-sdk-go-v2/aws/transport/http" |
| awsconfig "github.com/aws/aws-sdk-go-v2/config" |
| "github.com/aws/aws-sdk-go-v2/credentials" |
| awss3 "github.com/aws/aws-sdk-go-v2/service/s3" |
| @@ -52,11 +54,12 @@ func TestLoadersInstallStallBounds(t *testing.T) { |
| // LoadDefaultConfig's root branch: its own options come after the |
| // caller's, and the config is bounded after it loads. |
| "loadRootConfig": func(t *testing.T) (aws.Config, error) { |
| - cfg, err := loadRootConfig(context.Background(), filepath.Join(t.TempDir(), "absent"), withStallBounds(nil)...) |
| + opts, l := withStallBounds(nil) |
| + cfg, err := loadRootConfig(context.Background(), filepath.Join(t.TempDir(), "absent"), opts...) |
| if err != nil { |
| return cfg, err |
| } |
| - return boundConfig(cfg, BodyIdleTimeout) |
| + return boundConfig(cfg, l) |
| }, |
| } |
| for name, load := range loaders { |
| @@ -75,16 +78,61 @@ func TestLoadersInstallStallBounds(t *testing.T) { |
| } |
| // A caller's explicit HTTP client is a deliberate override and stays as |
| -// given (awsmanaged's tests inject fake transports this way). |
| +// given (awsmanaged's tests inject fake transports this way), whether or not |
| +// it is a BuildableClient like the one the loaders inject (#1143), and |
| +// however the caller sets it. |
| func TestCallerHTTPClientStays(t *testing.T) { |
| + overrides := map[string]func() aws.HTTPClient{ |
| + "http.Client": func() aws.HTTPClient { return &http.Client{} }, |
| + "BuildableClient": func() aws.HTTPClient { return awshttp.NewBuildableClient() }, |
| + } |
| + for name, client := range overrides { |
| + for _, set := range []string{"WithHTTPClient", "option"} { |
| + t.Run(name+"/"+set, func(t *testing.T) { |
| + isolatedAWSEnv(t) |
| + own := client() |
| + opt := awsconfig.WithHTTPClient(own) |
| + if set == "option" { |
| + opt = func(o *awsconfig.LoadOptions) error { o.HTTPClient = own; return nil } |
| + } |
| + cfg, err := LoadStaticConfig(context.Background(), "ACCESS", "SECRET", opt) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if cfg.HTTPClient != own { |
| + t.Fatalf("the caller's client was replaced by %T", cfg.HTTPClient) |
| + } |
| + }) |
| + } |
| + } |
| +} |
| + |
| +// With a CA bundle the SDK hands back its own copy of a caller's |
| +// BuildableClient, carrying the bundle: still the caller's, so it is not |
| +// bounded, while the loaders' own client under the same bundle is |
| +// (TestStallBoundsKeepCABundle). |
| +func TestCallerBuildableClientStaysUnderCABundle(t *testing.T) { |
| isolatedAWSEnv(t) |
| - own := &http.Client{} |
| + srv := httptest.NewTLSServer(http.NotFoundHandler()) |
| + defer srv.Close() |
| + t.Setenv("AWS_CA_BUNDLE", caBundle(t, srv)) |
| + own := awshttp.NewBuildableClient() |
| cfg, err := LoadStaticConfig(context.Background(), "ACCESS", "SECRET", awsconfig.WithHTTPClient(own)) |
| if err != nil { |
| t.Fatal(err) |
| } |
| - if cfg.HTTPClient != own { |
| - t.Fatalf("the caller's client was replaced by %T", cfg.HTTPClient) |
| + if IsBounded(cfg.HTTPClient) { |
| + t.Fatal("the caller's BuildableClient was replaced by the bounded client") |
| + } |
| + bc, ok := cfg.HTTPClient.(*awshttp.BuildableClient) |
| + if !ok { |
| + t.Fatalf("the caller's client came back as %T", cfg.HTTPClient) |
| + } |
| + if h := bc.GetTransport().ResponseHeaderTimeout; h != 0 { |
| + t.Fatalf("the caller's client picked up a header timeout: %s", h) |
| + } |
| + if bc.GetTransport().TLSClientConfig == nil || bc.GetTransport().TLSClientConfig.RootCAs == nil { |
| + t.Fatal("the CA bundle did not reach the caller's client") |
| } |
| } |
| @@ -155,21 +203,61 @@ const ( |
| stallDeadline = 10 * time.Second |
| ) |
| +// errNotLocal is a test client's refusal to dial anything but loopback. |
| +var errNotLocal = errors.New("rootaws test: refusing to dial a non-loopback address") |
| + |
| +// loopbackOnly is a dialer Control that refuses every address but a |
| +// loopback one. It runs on the address actually dialed, after name |
| +// resolution and before any packet is sent, and survives the dialer copies |
| +// a defaults mode and the bounded client make. |
| +func loopbackOnly(network, address string, _ syscall.RawConn) error { |
| + host, _, err := net.SplitHostPort(address) |
| + if err != nil { |
| + return err |
| + } |
| + if ip := net.ParseIP(host); ip == nil || !ip.IsLoopback() { |
| + return fmt.Errorf("%w: %s %s", errNotLocal, network, address) |
| + } |
| + return nil |
| +} |
| + |
| +// localStallLoad is newStallLoad for tests: its loading client dials only |
| +// loopback addresses and uses no proxy, whatever the environment says, so a |
| +// test can reach nothing but its own fixtures. The client stays the one the |
| +// load injects, so the loads it runs are owned and take the production |
| +// wrapping path. |
| +func localStallLoad(header, idle time.Duration) *stallLoad { |
| + l := newStallLoad(header, idle) |
| + l.loading = l.loading.WithDialerOptions(func(d *net.Dialer) { d.Control = loopbackOnly }). |
| + WithTransportOptions(func(t *http.Transport) { t.Proxy = nil }) |
| + return l |
| +} |
| + |
| +// The test clients refuse a non-loopback address before dialing it. |
| +func TestLocalStallLoadDialsOnlyLoopback(t *testing.T) { |
| + isolatedAWSEnv(t) |
| + _, err := get(stallClient(t, "http://192.0.2.1", testIdleTimeout)) |
| + if !errors.Is(err, errNotLocal) { |
| + t.Fatalf("a non-loopback dial was not refused: %v", err) |
| + } |
| +} |
| + |
| // stallClient is an S3 client built the way the loaders build one, with |
| // the test bounds (testHeaderTimeout and idle), one attempt per call, |
| // against url. The environment (AWS_CA_BUNDLE, AWS_DEFAULTS_MODE) applies. |
| func stallClient(t *testing.T, url string, idle time.Duration) *awss3.Client { |
| t.Helper() |
| - cfg, err := awsconfig.LoadDefaultConfig(context.Background(), |
| + l := localStallLoad(testHeaderTimeout, idle) |
| + cfg, err := awsconfig.LoadDefaultConfig(context.Background(), l.options([]func(*awsconfig.LoadOptions) error{ |
| awsconfig.WithRegion("us-east-1"), |
| awsconfig.WithSharedConfigFiles([]string{}), awsconfig.WithSharedCredentialsFiles([]string{}), |
| awsconfig.WithCredentialsProvider(credentials.NewStaticCredentialsProvider("ACCESS", "SECRET", "")), |
| awsconfig.WithRetryMaxAttempts(1), |
| - awsconfig.WithHTTPClient(loadingClient(testHeaderTimeout))) |
| + })...) |
| if err != nil { |
| t.Fatal(err) |
| } |
| - if cfg, err = boundConfig(cfg, idle); err != nil { |
| + if cfg, err = boundConfig(cfg, l); err != nil { |
| t.Fatal(err) |
| } |
| return awss3.NewFromConfig(cfg, func(o *awss3.Options) { |