grouprollaws: refuse absent collections, bound reads and answers
Review fixes for c547529a. An omitted response collection is a malformed answer, never absence (Instance can no longer read one as not-found). Response bodies are read whole before decoding, with a 2 s per-read inactivity bound and the script's 4 MiB cap (output_too_large); the BuildableClient is frozen and defaults mode is legacy, so a profile's defaults_mode cannot replace the 2 s connect, TLS and header bounds.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
internal/grouproll/box.go+5 −2internal/grouproll/box_test.go+1 −0internal/grouprollaws/config.go+19 −7internal/grouprollaws/config_test.go+19 −2internal/grouprollaws/group.go+36 −3internal/grouprollaws/recorder_test.go+6 −1internal/grouprollaws/transport.go+107 −0internal/grouprollaws/transport_test.go+226 −0region_ha_boundary_test.go+1 −0
Intent
<task-notification> <task-id>a0293bed8650bafbf</task-id> <tool-use-id>toolu_018WVnfWMKEutFncBnaYcz9F</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>Status: DONE_WITH_CONCERNS. The AWS adapter is built and committed as `c547529a` on `group-roll-verb` (not pushed). Git printed a `packed-refs.lock` error after the commit because another process held that lock in the shared repo, but the branch points at `c547529a` and the tree is clean. Tests: all of `internal/grouproll` and `internal/grouprollaws` pass, plus `TestRegionHA`, `go vet` and the darwin/windows cross-builds. Nothing calls AWS: a fake HTTP client records every request and returns canned answers, and the environment tests run in a subprocess. I also deliberately broke the code in 11 places, and each break fails a test. One break survived at first (the loader ignoring the file list passed in), so I added a test case that catches it. Findings and concerns: - **Expired SSO (Review Focus 4):** the first describe and every write fail as `api`, and zero requests are sent, not even to the SSO portal. - **Adapter naming rule:** the boundary test accepts a file if its name or its directory contains "aws". `internal/grouprollaws` passes on its directory, so I listed its three files as adapters. `provider.go` is in the core list. - **go.mod:** I added `elasticloadbalancingv2` v1.59.0, the one release built against the exact SDK versions we already pin, so no other module moved. I did not run `go mod tidy`, because it would also change unrelated lines that are already off on main. - **`New` signature:** the brief's `New(ctx, c)` still compiles, but it now takes options. The CLI should call `New(ctx, c, WithSharedFiles(files))` with the file lists resolved before isolating the environment. - **Activity times are integer milliseconds**, where the script used float seconds. The decider port in Tasks 5/6 must compare in ms. - **Smaller departures from the script:** an SDK failure records no exit code, so its error details are `{}`. The describe and write records keep only the fields read, not the full raw response. `Park`, `Unpark` and `SetMinimum` refuse bad arguments the script never checked. The identity rule refuses `credential_process` anywhere in the profile chain, even where the SDK would use static keys instead. - **`TestCallerJournaled`** is left for Task 5, as you directed; here there is only the `CallerIdentity` request-shape test. - **Sandbox:** the Go caches are read-only inside it, so `go get` and the tests ran with the sandbox disabled. `GOCACHE` stayed at its default. The full report, with signatures, is at `/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>206038</subagent_tokens><tool_uses>54</tool_uses><duration_ms>886350</duration_ms></usage> </task-notification>
<task-notification> <task-id>bwwgezmlx</task-id> <tool-use-id>toolu_01YN4QHrHMUVCTFtxE8Xcq2H</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/669506ff-23ec-45f1-9035-1d29593f2c37/tasks/bwwgezmlx.output</output-file> <status>completed</status> <summary>Background command "Ledger and wait for Astra Task 3 review" completed (exit code 0)</summary> </task-notification>
Attributed to this commit: 27.4 g CO₂e (3,584,152 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/grouproll/box.go b/internal/grouproll/box.go| index bc6b7b108..79ad3b408 100644 |
| --- a/internal/grouproll/box.go |
| +++ b/internal/grouproll/box.go |
| @@ -67,8 +67,8 @@ type Box interface { |
| type Uncertain struct { |
| Key string |
| Timeout bool |
| - ExitCode *int // set for a failed provider call (the script's api case) |
| - OutputTooLarge bool // meaningful only with ExitCode |
| + ExitCode *int // set for a failed provider process (the script's api case) |
| + OutputTooLarge bool // the provider's answer exceeded the 4 MiB output cap |
| } |
| func (u Uncertain) Error() string { return Text(u.Key) } |
| @@ -82,6 +82,9 @@ func (u Uncertain) Details() map[string]any { |
| if u.ExitCode != nil { |
| d["exit_code"] = int64(*u.ExitCode) |
| d["output_too_large"] = u.OutputTooLarge |
| + } else if u.OutputTooLarge { |
| + // An SDK adapter has no process exit code, only the cap. |
| + d["output_too_large"] = true |
| } |
| return d |
| } |
diff --git a/internal/grouproll/box_test.go b/internal/grouproll/box_test.go| index 9b6fd62bc..818b1f75f 100644 |
| --- a/internal/grouproll/box_test.go |
| +++ b/internal/grouproll/box_test.go |
| @@ -443,6 +443,7 @@ func TestUncertainDetails(t *testing.T) { |
| {Uncertain{Key: "remote", Timeout: true}, `{"timeout":true}`}, |
| {Uncertain{Key: "remote"}, `{}`}, |
| {Uncertain{Key: "api", ExitCode: &code, OutputTooLarge: true}, `{"exit_code":255,"output_too_large":true}`}, |
| + {Uncertain{Key: "api", OutputTooLarge: true}, `{"output_too_large":true}`}, |
| } { |
| got, err := pythonEncoded(c.u.Details()) |
| if err != nil || string(got) != c.want { |
diff --git a/internal/grouprollaws/config.go b/internal/grouprollaws/config.go| index 7d997a68e..c2279516d 100644 |
| --- a/internal/grouprollaws/config.go |
| +++ b/internal/grouprollaws/config.go |
| @@ -172,9 +172,21 @@ const ( |
| callTimeout = 15 * time.Second |
| ) |
| +// timedClient is the HTTP client with the script's connect and read bounds. |
| +// Body reads are bounded by boundedClient (transport.go). |
| +func timedClient() *awshttp.BuildableClient { |
| + return awshttp.NewBuildableClient(). |
| + WithDialerOptions(func(d *net.Dialer) { d.Timeout = connectTimeout }). |
| + WithTransportOptions(func(t *http.Transport) { |
| + t.ResponseHeaderTimeout = readTimeout |
| + t.TLSHandshakeTimeout = connectTimeout |
| + }) |
| +} |
| + |
| // New checks the profile's identity rule, then loads the SDK configuration |
| // for the config's profile and region from the same shared files, with IMDS |
| -// disabled, one attempt per call, 2-second connect and read timeouts, and no |
| +// disabled, one attempt per call, 2-second connect, header and body-read |
| +// timeouts that no defaults mode can replace, a 4 MiB answer cap, and no |
| // configured endpoint honoured. It makes no AWS call; the engine calls |
| // CallerIdentity and journals the UserId. |
| func New(ctx context.Context, c grouproll.Config, opts ...Option) (*Adapter, error) { |
| @@ -189,12 +201,9 @@ func New(ctx context.Context, c grouproll.Config, opts ...Option) (*Adapter, err |
| if err := checkProfileIdentity(ctx, c.Profile, files); err != nil { |
| return nil, err |
| } |
| - var httpClient aws.HTTPClient = awshttp.NewBuildableClient(). |
| - WithDialerOptions(func(d *net.Dialer) { d.Timeout = connectTimeout }). |
| - WithTransportOptions(func(t *http.Transport) { |
| - t.ResponseHeaderTimeout = readTimeout |
| - t.TLSHandshakeTimeout = connectTimeout |
| - }) |
| + // A BuildableClient while loading, so AWS_CA_BUNDLE can still apply; |
| + // newAdapter freezes it, so no defaults mode can change these values. |
| + var httpClient aws.HTTPClient = timedClient() |
| if o.httpClient != nil { |
| httpClient = o.httpClient |
| } |
| @@ -206,6 +215,9 @@ func New(ctx context.Context, c grouproll.Config, opts ...Option) (*Adapter, err |
| awsconfig.WithEC2IMDSClientEnableState(imds.ClientDisabled), |
| awsconfig.WithRetryMaxAttempts(1), |
| awsconfig.WithHTTPClient(httpClient), |
| + // Legacy mode leaves the explicit timeouts alone, also for the |
| + // credential clients (SSO, STS) the loader builds over this client. |
| + awsconfig.WithDefaultsMode(aws.DefaultsModeLegacy), |
| 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 db8cbb69a..e45de4af9 100644 |
| --- a/internal/grouprollaws/config_test.go |
| +++ b/internal/grouprollaws/config_test.go |
| @@ -4,6 +4,7 @@ import ( |
| "crypto/sha1" |
| "encoding/hex" |
| "encoding/json" |
| + "fmt" |
| "os" |
| "os/exec" |
| "path/filepath" |
| @@ -12,6 +13,8 @@ import ( |
| "strings" |
| "testing" |
| + "github.com/aws/aws-sdk-go-v2/aws" |
| + |
| "github.com/carlosframework/platform/internal/grouproll" |
| ) |
| @@ -35,6 +38,7 @@ type helperOutput struct { |
| Actions []string `json:"actions"` |
| Errors map[string]string `json:"errors,omitempty"` |
| Env []string `json:"env"` |
| + Timeouts map[string]string `json:"timeouts,omitempty"` |
| } |
| func describeError(err error) string { |
| @@ -72,8 +76,21 @@ func runHelper(name string) { |
| on("GetCallerIdentity", `<GetCallerIdentityResponse><GetCallerIdentityResult><Arn>a</Arn><UserId>u</UserId><Account>123456789012</Account></GetCallerIdentityResult></GetCallerIdentityResponse>`) |
| c := testConfig() |
| c.Profile = profile |
| - a, err := New(ctx, c, WithSharedFiles(files), withHTTPClient(rec)) |
| - if err != nil { |
| + opts := []Option{WithSharedFiles(files), withHTTPClient(rec)} |
| + if name == "transport" { |
| + opts = opts[:1] // the production client; no call is made |
| + } |
| + a, err := New(ctx, c, opts...) |
| + if err == nil && name == "transport" { |
| + out.Timeouts = map[string]string{} |
| + for client, h := range map[string]aws.HTTPClient{ |
| + "autoscaling": a.autoscaling.Options().HTTPClient, "elb": a.elb.Options().HTTPClient, |
| + "ec2": a.ec2.Options().HTTPClient, "ssm": a.ssm.Options().HTTPClient, "sts": a.sts.Options().HTTPClient, |
| + } { |
| + dial, tls, header, frozen := effectiveTimeouts(h) |
| + out.Timeouts[client] = fmt.Sprintf("dial=%v tls=%v header=%v frozen=%v", dial, tls, header, frozen) |
| + } |
| + } else if err != nil { |
| out.NewError = describeError(err) |
| } else { |
| if creds, err := a.cfg.Credentials.Retrieve(ctx); err == nil { |
diff --git a/internal/grouprollaws/group.go b/internal/grouprollaws/group.go| index 35c360f90..5463e2073 100644 |
| --- a/internal/grouprollaws/group.go |
| +++ b/internal/grouprollaws/group.go |
| @@ -42,6 +42,10 @@ type Adapter struct { |
| } |
| func newAdapter(cfg aws.Config, c grouproll.Config) *Adapter { |
| + if cfg.HTTPClient == nil { |
| + cfg.HTTPClient = timedClient() |
| + } |
| + cfg.HTTPClient = bound(cfg.HTTPClient) |
| // Applied after the SDK's own endpoint resolution, so neither a profile |
| // nor the environment can redirect a client (spec §4). |
| return &Adapter{ |
| @@ -57,7 +61,8 @@ func newAdapter(cfg aws.Config, c grouproll.Config) *Adapter { |
| // call runs one provider call under the script's 15-second process bound |
| // and turns every failure into Uncertain(api), as the script's invoke does: |
| -// a call past the bound is Uncertain{Timeout: true}. Cancellation by the |
| +// a call past the bound or a stalled read is Uncertain{Timeout: true}, an |
| +// answer over 4 MiB is Uncertain{OutputTooLarge: true}. Cancellation by the |
| // caller (Ctrl-C) is returned as the context's error. |
| func call[T any](parent context.Context, fn func(context.Context) (T, error)) (T, error) { |
| ctx, cancel := context.WithTimeout(parent, callTimeout) |
| @@ -70,6 +75,9 @@ func call[T any](parent context.Context, fn func(context.Context) (T, error)) (T |
| if parent.Err() != nil { |
| return zero, parent.Err() |
| } |
| + if errors.Is(err, errOutputTooLarge) { |
| + return zero, grouproll.Uncertain{Key: "api", OutputTooLarge: true} |
| + } |
| var netErr net.Error |
| if errors.Is(err, context.DeadlineExceeded) || (errors.As(err, &netErr) && netErr.Timeout()) { |
| return zero, grouproll.Uncertain{Key: "api", Timeout: true} |
| @@ -123,10 +131,18 @@ func (a *Adapter) Describe(ctx context.Context) (grouproll.GroupView, error) { |
| if err != nil { |
| return grouproll.GroupView{}, err |
| } |
| + // An absent collection is a malformed answer, never an empty one: the |
| + // SDK keeps an omitted list nil and an explicit empty list non-nil. |
| + if out.AutoScalingGroups == nil { |
| + return grouproll.GroupView{}, malformed() |
| + } |
| if len(out.AutoScalingGroups) != 1 { |
| return grouproll.GroupView{}, grouproll.Refusal{Key: "scope"} |
| } |
| g := out.AutoScalingGroups[0] |
| + if g.Instances == nil || g.TargetGroupARNs == nil || g.Tags == nil { |
| + return grouproll.GroupView{}, malformed() |
| + } |
| view := grouproll.GroupView{Region: a.c.Region, Members: map[string]grouproll.Member{}, |
| Template: templateMap(g.LaunchTemplate), TargetGroups: append([]string{}, g.TargetGroupARNs...)} |
| var ok [5]bool |
| @@ -168,6 +184,9 @@ func (a *Adapter) Targets(ctx context.Context, arn string) (map[string]string, e |
| if err != nil { |
| return nil, err |
| } |
| + if out.TargetHealthDescriptions == nil { |
| + return nil, malformed() |
| + } |
| result := map[string]string{} |
| for _, t := range out.TargetHealthDescriptions { |
| if t.Target == nil || t.Target.Id == nil || t.TargetHealth == nil { |
| @@ -193,6 +212,9 @@ func (a *Adapter) Hook(ctx context.Context) (grouproll.Hook, error) { |
| if err != nil { |
| return grouproll.Hook{}, err |
| } |
| + if out.LifecycleHooks == nil { |
| + return grouproll.Hook{}, malformed() |
| + } |
| if len(out.LifecycleHooks) != 1 { |
| return grouproll.Hook{}, grouproll.Refusal{Key: "hook"} |
| } |
| @@ -217,6 +239,9 @@ func (a *Adapter) Online(ctx context.Context, iid string) (bool, error) { |
| return false, err |
| } |
| r := out.InstanceInformationList |
| + if r == nil { |
| + return false, malformed() |
| + } |
| if len(r) != 1 { |
| return false, nil |
| } |
| @@ -252,6 +277,9 @@ func (a *Adapter) Activities(ctx context.Context, iid string) ([]grouproll.Activ |
| if err != nil { |
| return nil, err |
| } |
| + if out.Activities == nil { |
| + return nil, malformed() |
| + } |
| named := regexp.MustCompile(`\b` + regexp.QuoteMeta(iid) + `\b`) |
| result := []grouproll.Activity{} |
| for _, row := range out.Activities { |
| @@ -281,6 +309,9 @@ func (a *Adapter) Membership(ctx context.Context, iid string) (grouproll.MemberR |
| return grouproll.MemberRow{}, false, err |
| } |
| rows := out.AutoScalingInstances |
| + if rows == nil { |
| + return grouproll.MemberRow{}, false, malformed() |
| + } |
| if len(rows) > 1 { |
| return grouproll.MemberRow{}, false, grouproll.Refusal{Key: "api"} |
| } |
| @@ -317,13 +348,15 @@ func (a *Adapter) Instance(ctx context.Context, iid string) (grouproll.InstanceS |
| return grouproll.InstanceState{}, err |
| } |
| api := grouproll.Refusal{Key: "api"} |
| - if aws.ToString(out.NextToken) != "" { |
| + // The script requires both collections (isinstance(..., list)); an absent |
| + // one must never read as "not-found", which closes a lost member. |
| + if aws.ToString(out.NextToken) != "" || out.Reservations == nil { |
| return grouproll.InstanceState{}, api |
| } |
| reservations := []any{} |
| var instances []ec2types.Instance |
| for _, r := range out.Reservations { |
| - if aws.ToString(r.OwnerId) != a.c.Account { |
| + if aws.ToString(r.OwnerId) != a.c.Account || r.Instances == nil { |
| return grouproll.InstanceState{}, api |
| } |
| listed := []any{} |
diff --git a/internal/grouprollaws/recorder_test.go b/internal/grouprollaws/recorder_test.go| index 31fc38021..ede7c7315 100644 |
| --- a/internal/grouprollaws/recorder_test.go |
| +++ b/internal/grouprollaws/recorder_test.go |
| @@ -129,11 +129,16 @@ func testConfig() grouproll.Config { |
| // testAdapter builds an adapter over the recorder with static credentials, |
| // as New does after its checks. |
| func testAdapter(t *testing.T, rec *recorder) *Adapter { |
| + t.Helper() |
| + return testAdapterWith(t, rec) |
| +} |
| + |
| +func testAdapterWith(t *testing.T, h aws.HTTPClient) *Adapter { |
| t.Helper() |
| cfg := aws.Config{ |
| Region: "eu-west-1", |
| Credentials: credentials.NewStaticCredentialsProvider("AKIATEST", "secret", ""), |
| - HTTPClient: rec, |
| + HTTPClient: h, |
| RetryMaxAttempts: 1, |
| } |
| return newAdapter(cfg, testConfig()) |
diff --git a/internal/grouprollaws/transport.go b/internal/grouprollaws/transport.go| new file mode 100644 |
| index 000000000..488faf31e |
| --- /dev/null |
| +++ b/internal/grouprollaws/transport.go |
| @@ -0,0 +1,107 @@ |
| +package grouprollaws |
| + |
| +import ( |
| + "bytes" |
| + "errors" |
| + "io" |
| + "net/http" |
| + "sync/atomic" |
| + "time" |
| + |
| + "github.com/aws/aws-sdk-go-v2/aws" |
| + awshttp "github.com/aws/aws-sdk-go-v2/aws/transport/http" |
| +) |
| + |
| +// outputCap is the script's 4 MiB bound on a provider answer (invoke reads |
| +// 4 MiB + 1 and refuses more). It applies to success and error bodies alike. |
| +const outputCap = 4 << 20 |
| + |
| +// bodyReadTimeout is the script's --cli-read-timeout 2: no read of a |
| +// response body may wait longer for data. |
| +var bodyReadTimeout = readTimeout |
| + |
| +// errOutputTooLarge is a response body past outputCap. It is an error, never |
| +// a truncated EOF, so a decoder cannot read a cut answer as a whole one. |
| +var errOutputTooLarge = errors.New("grouprollaws: provider output over 4 MiB") |
| + |
| +// readTimeoutError is a body read that waited past bodyReadTimeout. |
| +type readTimeoutError struct{} |
| + |
| +func (readTimeoutError) Error() string { return "grouprollaws: response body read timed out" } |
| +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 { |
| + 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 |
| + } |
| + if b, ok := h.(*awshttp.BuildableClient); ok { |
| + return &boundedClient{next: b.Freeze(), from: b} |
| + } |
| + return &boundedClient{next: h} |
| +} |
| + |
| +// 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 |
| + } |
| + body := &boundedBody{rc: resp.Body} |
| + data, err := io.ReadAll(body) |
| + body.Close() |
| + if err != nil { |
| + return nil, err |
| + } |
| + resp.Body = io.NopCloser(bytes.NewReader(data)) |
| + resp.ContentLength = int64(len(data)) |
| + return resp, nil |
| +} |
| + |
| +type boundedBody struct { |
| + rc io.ReadCloser |
| + n int64 |
| + timedOut atomic.Bool |
| +} |
| + |
| +func (b *boundedBody) Read(p []byte) (int, error) { |
| + if b.n > outputCap { |
| + return 0, errOutputTooLarge |
| + } |
| + if b.timedOut.Load() { |
| + return 0, readTimeoutError{} |
| + } |
| + // Read at most one byte past the cap, to tell "at the cap" from "over". |
| + if room := outputCap + 1 - b.n; int64(len(p)) > room { |
| + p = p[:room] |
| + } |
| + timer := time.AfterFunc(bodyReadTimeout, func() { |
| + b.timedOut.Store(true) |
| + b.rc.Close() // unblocks the pending Read |
| + }) |
| + n, err := b.rc.Read(p) |
| + if !timer.Stop() && b.timedOut.Load() { |
| + return 0, readTimeoutError{} |
| + } |
| + b.n += int64(n) |
| + if b.n > outputCap { |
| + return 0, errOutputTooLarge |
| + } |
| + return n, err |
| +} |
| + |
| +func (b *boundedBody) Close() error { return b.rc.Close() } |
diff --git a/internal/grouprollaws/transport_test.go b/internal/grouprollaws/transport_test.go| new file mode 100644 |
| index 000000000..dba6a5d64 |
| --- /dev/null |
| +++ b/internal/grouprollaws/transport_test.go |
| @@ -0,0 +1,226 @@ |
| +package grouprollaws |
| + |
| +import ( |
| + "bytes" |
| + "io" |
| + "net/http" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/aws/aws-sdk-go-v2/aws" |
| + awshttp "github.com/aws/aws-sdk-go-v2/aws/transport/http" |
| + |
| + "github.com/carlosframework/platform/internal/grouproll" |
| +) |
| + |
| +// TestMissingCollectionsAreNeverAbsence: an omitted collection (or an empty |
| +// body) is a malformed answer; only an explicit empty collection may mean |
| +// "none". Instance evidence closes a lost member, so it matters most there. |
| +func TestMissingCollectionsAreNeverAbsence(t *testing.T) { |
| + isAPI := func(err error) bool { |
| + switch e := err.(type) { |
| + case grouproll.Uncertain: |
| + return e.Key == "api" |
| + case grouproll.Refusal: |
| + return e.Key == "api" |
| + } |
| + return false |
| + } |
| + ec2Head := `<DescribeInstancesResponse xmlns="http://ec2.amazonaws.com/doc/2016-11-15/"><requestId>r</requestId>` |
| + instance := map[string]string{ |
| + "omitted reservationSet": ec2Head + `</DescribeInstancesResponse>`, |
| + "empty body": "", |
| + "reservation no instances": ec2Head + `<reservationSet><item><reservationId>r-1</reservationId><ownerId>123456789012</ownerId></item></reservationSet></DescribeInstancesResponse>`, |
| + } |
| + for name, body := range instance { |
| + got, err := testAdapter(t, newRecorder().on("DescribeInstances", body)).Instance(ctx, testIID) |
| + if !isAPI(err) || got.State == "not-found" { |
| + t.Errorf("Instance %s: %+v %v, want api", name, got, err) |
| + } |
| + } |
| + // Script parity: the collection checks are the script's require(..., "api"). |
| + if _, err := testAdapter(t, newRecorder().on("DescribeInstances", instance["omitted reservationSet"])).Instance(ctx, testIID); refusalKey(t, err) != "api" { |
| + t.Errorf("omitted reservationSet: %v", err) |
| + } |
| + if got, err := testAdapter(t, newRecorder().on("DescribeInstances", ec2Head+`<reservationSet/></DescribeInstancesResponse>`)).Instance(ctx, testIID); err != nil || got.State != "not-found" { |
| + t.Errorf("explicit empty reservationSet: %+v %v, want not-found", got, err) |
| + } |
| + |
| + asgHead := `<DescribeAutoScalingGroupsResponse xmlns="http://autoscaling.amazonaws.com/doc/2011-01-01/"><DescribeAutoScalingGroupsResult>` |
| + full := groupXML(2, 2, 2, [][2]string{{testIID, "InService"}}) |
| + for name, body := range map[string]string{ |
| + "omitted groups": asgHead + `</DescribeAutoScalingGroupsResult></DescribeAutoScalingGroupsResponse>`, |
| + "empty body": "", |
| + "omitted members": strings.Replace(full, `<Instances><member><InstanceId>`+testIID+`</InstanceId><LifecycleState>InService</LifecycleState><HealthStatus>Healthy</HealthStatus></member></Instances>`, "", 1), |
| + "omitted tg arns": strings.Replace(full, `<TargetGroupARNs><member>`+testTG+`</member></TargetGroupARNs>`, "", 1), |
| + "omitted tags": full[:strings.Index(full, "<Tags>")] + full[strings.Index(full, "</Tags>")+len("</Tags>"):], |
| + } { |
| + if _, err := testAdapter(t, newRecorder().on("DescribeAutoScalingGroups", body)).Describe(ctx); uncertainKey(t, err).Key != "api" { |
| + t.Errorf("Describe %s: %v", name, err) |
| + } |
| + } |
| + emptyMembers := strings.Replace(full, `<Instances><member><InstanceId>`+testIID+`</InstanceId><LifecycleState>InService</LifecycleState><HealthStatus>Healthy</HealthStatus></member></Instances>`, "<Instances/>", 1) |
| + if g, err := testAdapter(t, newRecorder().on("DescribeAutoScalingGroups", emptyMembers)).Describe(ctx); err != nil || len(g.Members) != 0 || g.Members == nil { |
| + t.Errorf("explicit empty Instances: %+v %v", g, err) |
| + } |
| + |
| + for name, body := range map[string]string{ |
| + "omitted rows": `<DescribeAutoScalingInstancesResponse><DescribeAutoScalingInstancesResult></DescribeAutoScalingInstancesResult></DescribeAutoScalingInstancesResponse>`, |
| + "empty body": "", |
| + } { |
| + if _, found, err := testAdapter(t, newRecorder().on("DescribeAutoScalingInstances", body)).Membership(ctx, testIID); found || uncertainKey(t, err).Key != "api" { |
| + t.Errorf("Membership %s: %v %v", name, found, err) |
| + } |
| + } |
| + if _, found, err := testAdapter(t, newRecorder().on("DescribeAutoScalingInstances", |
| + `<DescribeAutoScalingInstancesResponse><DescribeAutoScalingInstancesResult><AutoScalingInstances/></DescribeAutoScalingInstancesResult></DescribeAutoScalingInstancesResponse>`)).Membership(ctx, testIID); found || err != nil { |
| + t.Errorf("explicit empty rows: %v %v", found, err) |
| + } |
| + |
| + // The other reads hold the same line. |
| + if _, err := testAdapter(t, newRecorder().on("DescribeTargetHealth", `<DescribeTargetHealthResponse><DescribeTargetHealthResult/></DescribeTargetHealthResponse>`)).Targets(ctx, testTG); uncertainKey(t, err).Key != "api" { |
| + t.Errorf("Targets omitted: %v", err) |
| + } |
| + if _, err := testAdapter(t, newRecorder().on("DescribeLifecycleHooks", `<DescribeLifecycleHooksResponse><DescribeLifecycleHooksResult/></DescribeLifecycleHooksResponse>`)).Hook(ctx); uncertainKey(t, err).Key != "api" { |
| + t.Errorf("Hook omitted: %v", err) |
| + } |
| + if _, err := testAdapter(t, newRecorder().on("DescribeInstanceInformation", `{}`)).Online(ctx, testIID); uncertainKey(t, err).Key != "api" { |
| + t.Errorf("Online omitted: %v", err) |
| + } |
| + if _, err := testAdapter(t, newRecorder().on("DescribeScalingActivities", `<DescribeScalingActivitiesResponse><DescribeScalingActivitiesResult/></DescribeScalingActivitiesResponse>`)).Activities(ctx, testIID); uncertainKey(t, err).Key != "api" { |
| + t.Errorf("Activities omitted: %v", err) |
| + } |
| +} |
| + |
| +// stallClient answers headers at once and then never sends the body. |
| +type stallClient struct{} |
| + |
| +type stallBody struct{ closed chan struct{} } |
| + |
| +// Read blocks until Close, or gives up after 6 s with an empty answer, so a |
| +// client without a read bound fails the elapsed-time check instead of hanging. |
| +func (b *stallBody) Read([]byte) (int, error) { |
| + select { |
| + case <-b.closed: |
| + return 0, io.ErrClosedPipe |
| + case <-time.After(6 * time.Second): |
| + return 0, io.EOF |
| + } |
| +} |
| +func (b *stallBody) Close() error { |
| + select { |
| + case <-b.closed: |
| + default: |
| + close(b.closed) |
| + } |
| + return nil |
| +} |
| + |
| +func (stallClient) Do(req *http.Request) (*http.Response, error) { |
| + return &http.Response{StatusCode: 200, Header: http.Header{"Content-Type": []string{"text/xml"}}, |
| + Body: &stallBody{closed: make(chan struct{})}, Request: req}, nil |
| +} |
| + |
| +func TestStalledBodyTimesOut(t *testing.T) { |
| + start := time.Now() |
| + _, err := testAdapterWith(t, stallClient{}).Describe(ctx) |
| + elapsed := time.Since(start) |
| + if elapsed < readTimeout || elapsed > readTimeout+3*time.Second { |
| + t.Fatalf("stalled body gave up after %v (%v), want about %v", elapsed, err, readTimeout) |
| + } |
| + u := uncertainKey(t, err) |
| + if u.Key != "api" || !u.Timeout { |
| + t.Fatalf("stalled body: %+v, want api with timeout", u) |
| + } |
| +} |
| + |
| +// bodyClient answers status with body. |
| +type bodyClient struct { |
| + status int |
| + body []byte |
| +} |
| + |
| +func (c bodyClient) Do(req *http.Request) (*http.Response, error) { |
| + return &http.Response{StatusCode: c.status, Header: http.Header{"Content-Type": []string{"text/xml"}}, |
| + Body: io.NopCloser(bytes.NewReader(c.body)), Request: req}, nil |
| +} |
| + |
| +// padTo pads a group answer with an unknown element to exactly size bytes. |
| +func padTo(t *testing.T, size int) []byte { |
| + t.Helper() |
| + body := groupXML(2, 2, 2, [][2]string{{testIID, "InService"}}) |
| + open, close := "<Padding>", "</Padding>" |
| + n := size - len(body) - len(open) - len(close) |
| + if n < 0 { |
| + t.Fatal("size too small") |
| + } |
| + at := strings.Index(body, "<MinSize>") |
| + return []byte(body[:at] + open + strings.Repeat("x", n) + close + body[at:]) |
| +} |
| + |
| +func TestOutputCap(t *testing.T) { |
| + // Exactly the cap decodes. |
| + if _, err := testAdapterWith(t, bodyClient{200, padTo(t, outputCap)}).Describe(ctx); err != nil { |
| + t.Fatalf("body at the cap: %v", err) |
| + } |
| + over := map[string]bodyClient{ |
| + "success": {200, padTo(t, outputCap+1)}, |
| + "error": {500, []byte(`<ErrorResponse><Error><Type>Receiver</Type><Code>InternalFailure</Code><Message>` + |
| + strings.Repeat("x", outputCap) + `</Message></Error><RequestId>r</RequestId></ErrorResponse>`)}, |
| + } |
| + for name, c := range over { |
| + _, err := testAdapterWith(t, c).Describe(ctx) |
| + if err == nil { |
| + t.Fatalf("%s over the cap: accepted", name) |
| + } |
| + u := uncertainKey(t, err) |
| + if u.Key != "api" || !u.OutputTooLarge || u.Timeout { |
| + t.Errorf("%s over the cap: %+v", name, u) |
| + } |
| + if got := u.Details(); got["output_too_large"] != true { |
| + t.Errorf("%s details %v", name, got) |
| + } |
| + } |
| +} |
| + |
| +// effectiveTimeouts reads the dial, TLS and header timeouts a client uses. |
| +func effectiveTimeouts(h aws.HTTPClient) (dial, tls, header time.Duration, frozen bool) { |
| + var b *awshttp.BuildableClient |
| + switch c := h.(type) { |
| + case *boundedClient: |
| + _, stillBuildable := c.next.(*awshttp.BuildableClient) |
| + frozen = !stillBuildable |
| + b = c.from |
| + case *awshttp.BuildableClient: |
| + b = c |
| + } |
| + if b == nil { |
| + return 0, 0, 0, frozen |
| + } |
| + tr := b.GetTransport() |
| + return b.GetDialer().Timeout, tr.TLSHandshakeTimeout, tr.ResponseHeaderTimeout, frozen |
| +} |
| + |
| +// TestDefaultsModeKeepsTimeouts: a profile selecting defaults_mode=standard |
| +// (3.1 s connect in the SDK's table) does not replace the 2 s bounds. |
| +func TestDefaultsModeKeepsTimeouts(t *testing.T) { |
| + dir := t.TempDir() |
| + cfgFile := filepath.Join(dir, "config") |
| + writeFile(t, cfgFile, "[profile op]\ndefaults_mode = standard\naws_access_key_id = AKIAPROFILE\naws_secret_access_key = s\n") |
| + out := runHelperProcess(t, "transport", "op", "HOME="+filepath.Join(dir, "home"), |
| + "AWS_CONFIG_FILE="+cfgFile, "AWS_SHARED_CREDENTIALS_FILE="+filepath.Join(dir, "none")) |
| + if out.NewError != "" { |
| + t.Fatalf("New: %s", out.NewError) |
| + } |
| + want := "dial=2s tls=2s header=2s frozen=true" |
| + if len(out.Timeouts) != 5 { |
| + t.Fatalf("timeouts %v", out.Timeouts) |
| + } |
| + for client, got := range out.Timeouts { |
| + if got != want { |
| + t.Errorf("%s: %s, want %s", client, got, want) |
| + } |
| + } |
| +} |
diff --git a/region_ha_boundary_test.go b/region_ha_boundary_test.go| index f85674658..a387fea7e 100644 |
| --- a/region_ha_boundary_test.go |
| +++ b/region_ha_boundary_test.go |
| @@ -60,6 +60,7 @@ var regionHAAdapterFiles = []string{ |
| "internal/grouprollaws/config.go", |
| "internal/grouprollaws/group.go", |
| "internal/grouprollaws/phase.go", |
| + "internal/grouprollaws/transport.go", |
| } |
| // regionHAPackages are the packages spec 2 touches. Every S3 client built |