carlos / platform Public

grouprollaws: bound credential-client answers too

Review round 2 for c547529a. The 2 s body-read bound and the 4 MiB cap
move from an HTTP client wrapper into a deserialize-step middleware,
passed to LoadDefaultConfig as an APIOption, so the STS, SSO and OIDC
clients the SDK builds for credentials read through it as well. The
client stays a BuildableClient while loading so AWS_CA_BUNDLE applies,
and is frozen for the service clients.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev a493072c258afb26739ea4581a2b723ca8cd1321 parent fbfa790
6 files changed, +134 −27
  • internal/grouprollaws/config.go +6 −1
  • internal/grouprollaws/config_test.go +55 −1
  • internal/grouprollaws/group.go +3 −1
  • internal/grouprollaws/recorder_test.go +15 −2
  • internal/grouprollaws/transport.go +54 −21
  • internal/grouprollaws/transport_test.go +1 −1

CI failed — run details

Intent

Human

<task-notification> <task-id>a0293bed8650bafbf</task-id> <tool-use-id>toolu_013pLyQgnt9RWGdPPNyS7NxA</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/669506ff-23ec-45f1-9035-1d29593f2c37/tasks/a0293bed8650bafbf.output</output-file> <status>completed</status> <summary>Agent "Implement Task 3: AWS adapter" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>All three review findings are fixed and committed as `fbfa790a` on `group-roll-verb` (not pushed). The tests, vet and darwin/windows cross-builds pass. 1. **Missing collections are never absence.** A list the response leaves out (or an empty body) is now an `api` error. Only an explicitly empty list can mean "none", so `Instance` can no longer report `not-found` from a bad answer. This also covers `Describe`, `Membership`, targets, hooks, online and activities. - **Decision for you:** in `Instance` this is `Refusal api`, not `Uncertain api` as the review asked. The script raises it with `require(..., "api")` at :891-899, and your earlier rule was that `require` failures are Refusals. Either way it can never mean absent. Switching is a two-line change if you want `Uncertain`. 2. **The 2 s bounds hold.** The HTTP client is frozen and defaults mode is forced to legacy, so a profile's `defaults_mode` can no longer replace the timeouts. Any body read that stalls longer than 2 s fails as a timeout. `AWS_CA_BUNDLE` still works. 3. **The 4 MiB cap.** Responses are now read whole before decoding, as the script did. Reading on demand was not enough, because the SDK's XML decoder stops early and never sees an oversized tail. An over-cap success or error body is `Uncertain api` with `output_too_large`. To make that show in the error details without a process exit code, I made a one-branch change to `Uncertain.Details()` in core (`box.go`). Covering tests are in the new `transport_test.go`: omitted vs explicit-empty collections, empty bodies, a stalled body, a body exactly at the cap and one over it, and a `defaults_mode=standard` profile. I also broke the code on purpose in nine places, and each break fails a test. The stall test adds about 2 s to the package's test time. The fix report (changes, tests, commands and output) is appended to `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-group-roll-verb/.superpowers/sdd/2026-11-09-group-roll-verb/task-3-report.md`.</result> <usage><subagent_tokens>243594</subagent_tokens><tool_uses>18</tool_uses><duration_ms>751858</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>bk6rys7ae</task-id> <tool-use-id>toolu_01H1xTHyLWQnkhgqJKMUoHtB</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/669506ff-23ec-45f1-9035-1d29593f2c37/tasks/bk6rys7ae.output</output-file> <status>completed</status> <summary>Background command "Wait for Astra re-review" completed (exit code 0)</summary> </task-notification>

Attributed to this commit: 31.5 g CO₂e (4,051,815 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on group-roll-verb, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/internal/grouprollaws/config.go b/internal/grouprollaws/config.go
index c2279516d..5873fa02c 100644
--- a/internal/grouprollaws/config.go
+++ b/internal/grouprollaws/config.go
@@ -17,6 +17,7 @@ import (
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/feature/ec2/imds"
+ "github.com/aws/smithy-go/middleware"
"github.com/carlosframework/platform/internal/grouproll"
)
@@ -202,7 +203,8 @@ func New(ctx context.Context, c grouproll.Config, opts ...Option) (*Adapter, err
return nil, err
}
// A BuildableClient while loading, so AWS_CA_BUNDLE can still apply;
- // newAdapter freezes it, so no defaults mode can change these values.
+ // newAdapter freezes it for the service clients, and legacy defaults mode
+ // keeps the credential clients' copies at these values.
var httpClient aws.HTTPClient = timedClient()
if o.httpClient != nil {
httpClient = o.httpClient
@@ -218,6 +220,9 @@ func New(ctx context.Context, c grouproll.Config, opts ...Option) (*Adapter, err
// Legacy mode leaves the explicit timeouts alone, also for the
// credential clients (SSO, STS) the loader builds over this client.
awsconfig.WithDefaultsMode(aws.DefaultsModeLegacy),
+ // The body bounds reach every client the loader builds, credential
+ // clients included (they copy the config's APIOptions).
+ awsconfig.WithAPIOptions([]func(*middleware.Stack) error{boundBodyOption}),
func(lo *awsconfig.LoadOptions) error {
lo.DefaultsModeOptions.IMDSClient = imds.New(imds.Options{ClientEnableState: imds.ClientDisabled})
return nil
diff --git a/internal/grouprollaws/config_test.go b/internal/grouprollaws/config_test.go
index e45de4af9..5c3048f16 100644
--- a/internal/grouprollaws/config_test.go
+++ b/internal/grouprollaws/config_test.go
@@ -12,6 +12,7 @@ import (
"sort"
"strings"
"testing"
+ "time"
"github.com/aws/aws-sdk-go-v2/aws"
@@ -39,6 +40,8 @@ type helperOutput struct {
Errors map[string]string `json:"errors,omitempty"`
Env []string `json:"env"`
Timeouts map[string]string `json:"timeouts,omitempty"`
+ // DescribeMillis is how long the first Describe took.
+ DescribeMillis int64 `json:"describe_ms"`
}
func describeError(err error) string {
@@ -48,6 +51,9 @@ func describeError(err error) string {
case grouproll.Refusal:
return "refusal:" + e.Key
case grouproll.Uncertain:
+ if e.OutputTooLarge {
+ return "uncertain-too-large:" + e.Key
+ }
if e.Timeout {
return "uncertain-timeout:" + e.Key
}
@@ -74,6 +80,13 @@ func runHelper(name string) {
on("DescribeInstanceInformation", `{"InstanceInformationList":[]}`).
on("DescribeLaunchTemplateVersions", templateXML("7", "")).
on("GetCallerIdentity", `<GetCallerIdentityResponse><GetCallerIdentityResult><Arn>a</Arn><UserId>u</UserId><Account>123456789012</Account></GetCallerIdentityResult></GetCallerIdentityResponse>`)
+ switch name {
+ case "assume-stall":
+ rec.onStall("AssumeRole")
+ case "assume-big":
+ rec.onStatus("AssumeRole", 403, `<ErrorResponse xmlns="https://sts.amazonaws.com/doc/2011-06-15/"><Error><Type>Sender</Type><Code>AccessDenied</Code><Message>`+
+ strings.Repeat("x", outputCap)+`</Message></Error><RequestId>r</RequestId></ErrorResponse>`)
+ }
c := testConfig()
c.Profile = profile
opts := []Option{WithSharedFiles(files), withHTTPClient(rec)}
@@ -93,13 +106,17 @@ func runHelper(name string) {
} else if err != nil {
out.NewError = describeError(err)
} else {
- if creds, err := a.cfg.Credentials.Retrieve(ctx); err == nil {
+ if strings.HasPrefix(name, "assume-") {
+ // Leave the credential fetch to the first call.
+ } else if creds, err := a.cfg.Credentials.Retrieve(ctx); err == nil {
out.AccessKey = creds.AccessKeyID
} else {
out.Errors["retrieve"] = "other"
}
+ start := time.Now()
_, err := a.Describe(ctx)
out.Errors["describe"] = describeError(err)
+ out.DescribeMillis = time.Since(start).Milliseconds()
if name == "isolate" {
_, err = a.Targets(ctx, testTG)
out.Errors["targets"] = describeError(err)
@@ -446,3 +463,40 @@ login_session = arn:aws:iam::123456789012:user/op
t.Error("missing file accepted")
}
}
+
+// TestAssumeRoleAnswersAreBounded: the STS client the SDK builds for an
+// assume-role profile while loading reads its answers under the same 2 s
+// read bound and 4 MiB cap as the service clients.
+func TestAssumeRoleAnswersAreBounded(t *testing.T) {
+ dir := t.TempDir()
+ cfgFile := filepath.Join(dir, "config")
+ writeFile(t, cfgFile, `[profile base]
+aws_access_key_id = AKIABASE
+aws_secret_access_key = s
+
+[profile op]
+role_arn = arn:aws:iam::123456789012:role/op
+role_session_name = roll
+source_profile = base
+`)
+ env := []string{"HOME=" + filepath.Join(dir, "home"), "AWS_CONFIG_FILE=" + cfgFile,
+ "AWS_SHARED_CREDENTIALS_FILE=" + filepath.Join(dir, "none")}
+ for name, want := range map[string]string{
+ "assume-stall": "uncertain-timeout:api",
+ "assume-big": "uncertain-too-large:api",
+ } {
+ out := runHelperProcess(t, name, "op", env...)
+ if out.NewError != "" {
+ t.Fatalf("%s: New %s", name, out.NewError)
+ }
+ if out.Errors["describe"] != want {
+ t.Errorf("%s: describe %q, want %q", name, out.Errors["describe"], want)
+ }
+ if !reflect.DeepEqual(out.Actions, []string{"AssumeRole"}) || out.Hosts["AssumeRole"] != "sts.eu-west-1.amazonaws.com" {
+ t.Errorf("%s: requests %v %v, want only AssumeRole to regional STS", name, out.Actions, out.Hosts)
+ }
+ if name == "assume-stall" && (out.DescribeMillis < 2000 || out.DescribeMillis > 5000) {
+ t.Errorf("stalled AssumeRole gave up after %d ms, want about 2000", out.DescribeMillis)
+ }
+ }
+}
diff --git a/internal/grouprollaws/group.go b/internal/grouprollaws/group.go
index 5463e2073..b57ad7946 100644
--- a/internal/grouprollaws/group.go
+++ b/internal/grouprollaws/group.go
@@ -24,6 +24,7 @@ import (
"github.com/aws/aws-sdk-go-v2/service/ssm"
ssmtypes "github.com/aws/aws-sdk-go-v2/service/ssm/types"
"github.com/aws/aws-sdk-go-v2/service/sts"
+ "github.com/aws/smithy-go/middleware"
"github.com/carlosframework/platform/internal/grouproll"
)
@@ -45,7 +46,8 @@ func newAdapter(cfg aws.Config, c grouproll.Config) *Adapter {
if cfg.HTTPClient == nil {
cfg.HTTPClient = timedClient()
}
- cfg.HTTPClient = bound(cfg.HTTPClient)
+ cfg.HTTPClient = freeze(cfg.HTTPClient)
+ cfg.APIOptions = append(append([]func(*middleware.Stack) error{}, cfg.APIOptions...), boundBodyOption)
// Applied after the SDK's own endpoint resolution, so neither a profile
// nor the environment can redirect a client (spec §4).
return &Adapter{
diff --git a/internal/grouprollaws/recorder_test.go b/internal/grouprollaws/recorder_test.go
index ede7c7315..2258087d2 100644
--- a/internal/grouprollaws/recorder_test.go
+++ b/internal/grouprollaws/recorder_test.go
@@ -31,6 +31,7 @@ type recorded struct {
type canned struct {
status int
body string
+ stall bool // headers at once, then a body that never arrives
}
// recorder records every request and answers from canned bodies keyed by
@@ -46,10 +47,18 @@ func newRecorder() *recorder { return &recorder{responses: map[string][]canned{}
// on queues one answer for action; the last queued answer repeats.
func (r *recorder) on(action, body string) *recorder { return r.onStatus(action, 200, body) }
+// onStall answers action with headers and a stalled body.
+func (r *recorder) onStall(action string) *recorder {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+ r.responses[action] = append(r.responses[action], canned{status: 200, stall: true})
+ return r
+}
+
func (r *recorder) onStatus(action string, status int, body string) *recorder {
r.mu.Lock()
defer r.mu.Unlock()
- r.responses[action] = append(r.responses[action], canned{status, body})
+ r.responses[action] = append(r.responses[action], canned{status: status, body: body})
return r
}
@@ -71,7 +80,7 @@ func (r *recorder) Do(req *http.Request) (*http.Response, error) {
r.mu.Lock()
r.reqs = append(r.reqs, rec)
queue := r.responses[rec.Action]
- answer := canned{500, ""}
+ answer := canned{status: 500}
if len(queue) > 0 {
answer = queue[0]
if len(queue) > 1 {
@@ -86,6 +95,10 @@ func (r *recorder) Do(req *http.Request) (*http.Response, error) {
answer.body = `{"__type":"InternalServerError","message":"x"}`
}
}
+ if answer.stall {
+ return &http.Response{StatusCode: 200, Header: http.Header{"Content-Type": []string{contentType}},
+ Body: &stallBody{closed: make(chan struct{})}, Request: req}, nil
+ }
return &http.Response{
StatusCode: answer.status,
Status: http.StatusText(answer.status),
diff --git a/internal/grouprollaws/transport.go b/internal/grouprollaws/transport.go
index 488faf31e..ee7164049 100644
--- a/internal/grouprollaws/transport.go
+++ b/internal/grouprollaws/transport.go
@@ -2,6 +2,7 @@ package grouprollaws
import (
"bytes"
+ "context"
"errors"
"io"
"net/http"
@@ -10,6 +11,8 @@ import (
"github.com/aws/aws-sdk-go-v2/aws"
awshttp "github.com/aws/aws-sdk-go-v2/aws/transport/http"
+ "github.com/aws/smithy-go/middleware"
+ smithyhttp "github.com/aws/smithy-go/transport/http"
)
// outputCap is the script's 4 MiB bound on a provider answer (invoke reads
@@ -31,45 +34,75 @@ func (readTimeoutError) Error() string { return "grouprollaws: response body r
func (readTimeoutError) Timeout() bool { return true }
func (readTimeoutError) Temporary() bool { return true }
-// boundedClient is the adapter's HTTP client. It is not a BuildableClient,
-// so no SDK defaults mode can replace its timeouts, and every response body
-// is read whole, bounded in size (4 MiB) and in read inactivity (2 s).
-type boundedClient struct {
+// frozenClient is the service clients' HTTP client. It is not a
+// BuildableClient, so no SDK defaults mode can replace its 2 s connect, TLS
+// and header timeouts.
+type frozenClient struct {
next aws.HTTPClient
// from is the BuildableClient the frozen client was built from (nil when
// the client was not buildable); it records the timeouts in force.
from *awshttp.BuildableClient
}
-// bound freezes a BuildableClient (Freeze: "prevent the SDK from applying
-// DefaultMode configuration values") and wraps any client's bodies.
-func bound(h aws.HTTPClient) *boundedClient {
- if b, ok := h.(*boundedClient); ok {
- return b
+// freeze freezes a BuildableClient (Freeze: "prevent the SDK from applying
+// DefaultMode configuration values to a buildable client").
+func freeze(h aws.HTTPClient) aws.HTTPClient {
+ switch c := h.(type) {
+ case *frozenClient:
+ return c
+ case *awshttp.BuildableClient:
+ return &frozenClient{next: c.Freeze(), from: c}
}
- if b, ok := h.(*awshttp.BuildableClient); ok {
- return &boundedClient{next: b.Freeze(), from: b}
+ return &frozenClient{next: h}
+}
+
+func (c *frozenClient) Do(req *http.Request) (*http.Response, error) { return c.next.Do(req) }
+
+// boundBodyID names the body-bounding middleware.
+const boundBodyID = "grouprollaws.BoundBody"
+
+// boundBodyOption is an aws.Config APIOption: every client built from the
+// config, including the credential clients the SDK builds while loading
+// (STS AssumeRole, SSO, SSO OIDC), reads its answers through it. It is a
+// middleware, not an HTTP client wrapper, because the SDK applies a CA
+// bundle (AWS_CA_BUNDLE, allow-listed) only to a BuildableClient.
+func boundBodyOption(stack *middleware.Stack) error {
+ if _, ok := stack.Deserialize.Get(boundBodyID); ok {
+ return nil
}
- return &boundedClient{next: h}
+ // After: innermost in the deserialize step, so it reads the raw answer
+ // before the operation's deserializer (success or error) sees it.
+ return stack.Deserialize.Add(boundBody{}, middleware.After)
}
-// Do reads the whole answer before the SDK decodes it, as the script read
-// the CLI's whole output: a decoder that stops early (the XML decoders stop
-// after the result element) must not leave an over-cap tail unseen.
-func (c *boundedClient) Do(req *http.Request) (*http.Response, error) {
- resp, err := c.next.Do(req)
- if err != nil || resp == nil || resp.Body == nil {
- return resp, err
+// boundBody reads the whole answer before the SDK decodes it, as the script
+// read the CLI's whole output: a decoder that stops early (the XML decoders
+// stop after the result element) must not leave an over-cap tail unseen.
+// Each read waits at most 2 s for data, and more than 4 MiB is an error,
+// never a truncated EOF.
+type boundBody struct{}
+
+func (boundBody) ID() string { return boundBodyID }
+
+func (boundBody) HandleDeserialize(ctx context.Context, in middleware.DeserializeInput, next middleware.DeserializeHandler) (
+ middleware.DeserializeOutput, middleware.Metadata, error) {
+ out, md, err := next.HandleDeserialize(ctx, in)
+ if err != nil {
+ return out, md, err
+ }
+ resp, ok := out.RawResponse.(*smithyhttp.Response)
+ if !ok || resp.Body == nil {
+ return out, md, nil
}
body := &boundedBody{rc: resp.Body}
data, err := io.ReadAll(body)
body.Close()
if err != nil {
- return nil, err
+ return out, md, err
}
resp.Body = io.NopCloser(bytes.NewReader(data))
resp.ContentLength = int64(len(data))
- return resp, nil
+ return out, md, nil
}
type boundedBody struct {
diff --git a/internal/grouprollaws/transport_test.go b/internal/grouprollaws/transport_test.go
index dba6a5d64..bd28bc5f6 100644
--- a/internal/grouprollaws/transport_test.go
+++ b/internal/grouprollaws/transport_test.go
@@ -189,7 +189,7 @@ func TestOutputCap(t *testing.T) {
func effectiveTimeouts(h aws.HTTPClient) (dial, tls, header time.Duration, frozen bool) {
var b *awshttp.BuildableClient
switch c := h.(type) {
- case *boundedClient:
+ case *frozenClient:
_, stillBuildable := c.next.(*awshttp.BuildableClient)
frozen = !stillBuildable
b = c.from