grouprollaws: Auto Scaling, ELB and EC2 calls behind the Group interface
Core types (Phase, GroupView, Group, WriteResult, ...) in internal/grouproll/provider.go; the AWS adapter in internal/grouprollaws: the script's group, targets, hooks, online, activities, instance, ec2_instance, template_release and the H4-guarded writes, plus CallerIdentity for the engine. IsolateEnvironment and the stable caller identity rule (spec section 4). Adds elasticloadbalancingv2 v1.59.0, the release that matches the pinned aws-sdk-go-v2 v1.44.0.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
go.mod+1 −0go.sum+2 −0internal/grouproll/provider.go+108 −0internal/grouprollaws/config.go+221 −0internal/grouprollaws/config_test.go+431 −0internal/grouprollaws/group.go+584 −0internal/grouprollaws/group_test.go+543 −0internal/grouprollaws/phase.go+30 −0internal/grouprollaws/phase_test.go+40 −0internal/grouprollaws/recorder_test.go+186 −0region_ha_boundary_test.go+4 −0
CI failed — run details
Intent
<task-notification> <task-id>ad559eb8263bb4396</task-id> <tool-use-id>toolu_014cJnRN3mJbVXv6iQF2tiNA</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/669506ff-23ec-45f1-9035-1d29593f2c37/tasks/ad559eb8263bb4396.output</output-file> <status>completed</status> <summary>Agent "Implement Task 2: box protocol" 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. Task 2 is built and committed; the concerns are small parity notes. - **Commit:** `22fd6358 grouproll: framed box commands, byte-identical to the script` on `group-roll-verb`, not pushed. - **Tests:** `go test ./internal/grouproll` passes. That covers all 22 golden commands byte for byte and all 27 refusals. Every command also matches `tool-pattern.txt`, which compiles unchanged as RE2. The 91 parse cases come from the script's own `AWS.request`, run with a fake transport. `go vet`, `TestRegionHA` and the darwin and windows cross-builds pass. Tests were written first and failed to build until `box.go` existed. Every deliberate break of the code was caught by a test, after I added cases for two that first slipped through. - **Concerns:** - Task 1's encoder writes non-ASCII text differently from the script's `json.dumps`, so the permit body has its own Python-compatible encoder. - The script accepts a drain report with `"v":1.0`, so a report can contain floats. Task 1's journal encoder refuses floats, so a later engine task must handle them when it records the report. - Session text that is not valid UTF-8 is refused as `record`, as in the script. An empty `SHA256` is refused as `prepare`, because Go cannot tell a missing value from an empty one. - The session timeouts and reading session ids are left to whatever implements `Box` against AWS; nothing here builds that. - Go commands ran outside the sandbox because the default build cache is read-only there; `GOCACHE` was left at its default. - **Report:** `/home/paulca/amadan.net/carlos/platform/.claude/worktrees/design-group-roll-verb/.superpowers/sdd/2026-11-09-group-roll-verb/task-2-report.md`</result> <usage><subagent_tokens>142579</subagent_tokens><tool_uses>37</tool_uses><duration_ms>595199</duration_ms></usage> </task-notification>
<task-notification> <task-id>ad1d59a30ce47bb9e</task-id> <tool-use-id>toolu_01UUFq9H2uzmSQRcNgusRY3F</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/669506ff-23ec-45f1-9035-1d29593f2c37/tasks/ad1d59a30ce47bb9e.output</output-file> <status>completed</status> <summary>Agent "Review Task 2 (spec + quality)" 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>### Spec Compliance - ✅ Spec compliant. Every item in the brief is present: `RemoteCommand`, `BoxStatus`, `ParseFramed`, the `Box` interface, the golden file, the generator, and the `regionHACoreFiles` entry (`region_ha_boundary_test.go`). The `Uncertain` type is separate from `Refusal`, and `TestParseFramed` asserts that an `Uncertain` is not also a `Refusal`. - Checked against the script, `scripts/region-group-roll.py:824-867` (`remote_command`), `:975-990` (the session branch of `request`), `:1103-1135` (`drain_output`, `edge_stop_output`). - **`RemoteCommand`** (`box.go` 107-157): follows the script branch for branch. That covers the verb set, the TX rule with no leading dash, the SHA check, all bounds and kill-after values, the `status` chaining, the frame script and the outer `shellQuote`. - **Regex anchors** (`config.go:46-48`): `^…$` without `(?m)` means end of text in Go, which equals Python's `\Z`. - **`ParseFramed`** (`box.go` 422-460): the 124 check on drain comes first, as in the script. The `code in ("0","1")` and 1 MiB cap come second. The `drain-cancel` exit "1" detail is the last 512 runes of the stripped body. The 8192-byte cap counts bytes, not runes. Exit codes compare as strings, so "00" is not "0". - **Whitespace and line splitting**: Python `strip` and `splitlines` are ported (`pythonSpace` at `config.go:275`, `pythonSplitLines`). I checked the set against `str.isspace` and the `splitlines` separators. The golden covers each separator. - **`edgeStopOutput`**: matches case for case, including the duplicate-key and no-`=` refusals. - **`BoxStatus`**: fields and JSON keys match `internal/host/group_maintenance_verbs.go:245-301` exactly. Section fields use the script's lenient `.get()` semantics, and unknown fields stay in `Raw`. - ⚠️ Cannot verify from the diff: - The adapter must call `CancelSession` after an `Uncertain{Timeout:true}`, and must scrape session ids and apply the per-verb session timeouts. Both are explicitly deferred to a later task. - How `main.tf` builds `allowedPattern` from `tool-pattern.txt` is taken from the test comment. The test uses `"^"+pattern+"$"`, which I did not check against `main.tf`. ### Strengths - The golden is the script's own output. The generator runs the script's real `AWS.request("session", …)` with only `invoke` and `uuid4` stubbed, so parser expectations come from the script and not from the Go code. - The 91 parse cases cover the hard edges: CRLF, END at EOF, nested BEGIN, two frames, wrong nonce, the cap at exactly 8192 bytes and one byte over (including multibyte), every `splitlines` separator, NBSP and the `\x1f` strip, `v` as true / 1.0 / "1", NaN, duplicate keys, and non-ASCII digits in MainPID. - `pythonEncoded` is a separate encoder that matches `json.dumps(ensure_ascii=True)`, including surrogate pairs and DEL. The implementer noticed Task 1's `encodeRow` differs from it for non-ASCII and kept the two apart. The golden pins the non-ASCII permit. - The document-pattern test is not vacuous. It runs 200 random rounds across all 10 verbs plus four negative mutants. - The 1 MiB drain cap is tested at the boundary, and 124 over the cap is still `Uncertain`. - The `Details()` shape is tested against the script's `exc.details`. - The code has a clear single responsibility, no AWS imports, and comments that cite the script's line numbers. ### Issues #### Critical (Must Fix) None. #### Important (Should Fix) None. #### Minor (Nice to Have) - `box.go:422-424`: `ParseFramed` compiles the frame regex on every call. A drain body can be 1 MiB and a status can be polled often. Compile once per call site, or cache by nonce. It is not a correctness issue. - `scripts/grouproll-golden/remote_commands.py:~25`: importing the script writes `scripts/__pycache__/`, and the report says the implementer had to delete it. Set `sys.dont_write_bytecode = True` before the import so a regeneration leaves no stray directory. - `box.go` `pyInt` (json.Number branch): it goes through `ParseFloat`, which loses precision for integers above 2^53. In practice `decodeValue` (`journal.go:241`) already turns integral numbers into `int64`, so this only affects odd forms such as `1e3`. It is harmless, but the comment could say so. - `box.go` `Uncertain.Details`: `output_too_large` is emitted whenever `ExitCode` is set, as in the script. Nothing in `Uncertain` stops an adapter from setting `OutputTooLarge` without `ExitCode` and losing it silently. A one-line doc note would help. - The implementer's concern about floats in the drain report is real and carries to the engine task. `{"v":1.0}` is accepted here, but `encodeRow` refuses floats when journaling. The engine task must handle that, and I agree with it failing loudly. ### Assessment **Task quality:** Approved **Reasoning:** The command builder and the parsers are faithful ports, backed by golden output generated from the script itself and by a non-vacuous test against the SSM document pattern. The only findings are minor performance and hygiene points.</result> <usage><subagent_tokens>89790</subagent_tokens><tool_uses>9</tool_uses><duration_ms>83699</duration_ms></usage> </task-notification>
Attributed to this commit: 21.7 g CO₂e (2,738,494 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/go.mod b/go.mod| index bf65ac4ba..a93f38095 100644 |
| --- a/go.mod |
| +++ b/go.mod |
| @@ -11,6 +11,7 @@ require ( |
| github.com/aws/aws-sdk-go-v2/service/cloudwatch v1.68.0 |
| github.com/aws/aws-sdk-go-v2/service/costexplorer v1.67.5 |
| github.com/aws/aws-sdk-go-v2/service/ec2 v1.324.0 |
| + github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2 v1.59.0 |
| github.com/aws/aws-sdk-go-v2/service/iam v1.58.2 |
| github.com/aws/aws-sdk-go-v2/service/resourcegroupstaggingapi v1.37.0 |
| github.com/aws/aws-sdk-go-v2/service/route53 v1.64.1 |
diff --git a/go.sum b/go.sum| index 74537b15b..05db7882e 100644 |
| --- a/go.sum |
| +++ b/go.sum |
| @@ -50,6 +50,8 @@ github.com/aws/aws-sdk-go-v2/service/costexplorer v1.67.5 h1:hiJJTfio1+i/xnfLwu6 |
| github.com/aws/aws-sdk-go-v2/service/costexplorer v1.67.5/go.mod h1:gy1JJMsby9XLbrwMhJcMu0IuMJF4DvDe4pD1wqMmwkk= |
| github.com/aws/aws-sdk-go-v2/service/ec2 v1.324.0 h1:A1hZCv8Ev0jc8o7pGqnjprJokn21pGmPWZrzPJ5Sp+E= |
| github.com/aws/aws-sdk-go-v2/service/ec2 v1.324.0/go.mod h1:6eOsONObU8u+Edct3ZmszxCTACyTeITJG7yPbbqp3L8= |
| +github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2 v1.59.0 h1:H3vlr3Gl9tv5DvI+Z+hphz9X7BGYcMEP46L39VW2S2Q= |
| +github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2 v1.59.0/go.mod h1:2WTv8huhRUxCeLfI9Vtb/5ncA5GJ0Hj5Lt5KH00G/jY= |
| github.com/aws/aws-sdk-go-v2/service/iam v1.58.2 h1:/6iRcqrC6k1rMA6uCZMzFE9inOrBpNmhbrZ90X8qH50= |
| github.com/aws/aws-sdk-go-v2/service/iam v1.58.2/go.mod h1:Wm74PIQWDrV2tGPFYtwLqh8jZ7JU/rnq/leiC6UI4dg= |
| github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.19 h1:bAdDl/HkGCcGPoe25ToSHEw23VIxt6CT5fLcg111BKg= |
diff --git a/internal/grouproll/provider.go b/internal/grouproll/provider.go| new file mode 100644 |
| index 000000000..6490a7fe9 |
| --- /dev/null |
| +++ b/internal/grouproll/provider.go |
| @@ -0,0 +1,108 @@ |
| +package grouproll |
| + |
| +import "context" |
| + |
| +// Phase is a member's provider-neutral lifecycle phase (spec §5.2). The core |
| +// decides on phases; each adapter maps its raw states to exactly one, and the |
| +// journal keeps the raw state beside the phase for operators. |
| +type Phase string |
| + |
| +const ( |
| + Serving Phase = "Serving" // InService |
| + Parking Phase = "Parking" // EnteringStandby |
| + Parked Phase = "Parked" // Standby |
| + Returning Phase = "Returning" // Pending, PreInService, Pending:Proceed |
| + ReturnHeld Phase = "ReturnHeld" // Pending:Wait |
| + Leaving Phase = "Leaving" // every Terminat* state |
| + Absent Phase = "Absent" // not in the group |
| + Unknown Phase = "Unknown" // anything else (warm pools, detach, ...) |
| +) |
| + |
| +// Member is one group member as the group description lists it. |
| +type Member struct { |
| + Phase Phase |
| + Raw string |
| + Healthy bool |
| +} |
| + |
| +// GroupView is the script's "group" response: the group's identity, its |
| +// capacity, its members and the launch template it pins. Template holds the |
| +// provider's template reference exactly as described (nil when the group has |
| +// none); the core compares it whole. |
| +type GroupView struct { |
| + Name, ARN, Deployment, Region string |
| + Minimum, Desired, Maximum int |
| + Members map[string]Member |
| + Template map[string]any |
| + TargetGroups []string |
| +} |
| + |
| +// MemberRow is one member's own membership row (the script's "instance" |
| +// response), which the probe reconciles against Describe. |
| +type MemberRow struct { |
| + IID string |
| + Group string |
| + Template map[string]any |
| + Raw string |
| + Phase Phase |
| + Healthy bool |
| +} |
| + |
| +// Activity is one scaling activity naming a member, classified as the |
| +// script's "activities" response does. Kind is "enter", "exit" or |
| +// "terminate"; Status is the provider's status code ("" when absent). Time |
| +// is the activity's start in integer milliseconds since the epoch (the |
| +// script held float seconds; format 2 journals hold integers only). |
| +type Activity struct { |
| + ID, Kind, Status string |
| + Time int64 |
| +} |
| + |
| +// Hook is the group's launch lifecycle hook as described. |
| +type Hook struct { |
| + Name string |
| + Timeout int |
| + Default string |
| + Transition string |
| +} |
| + |
| +// InstanceState is whether an instance still exists (close-lost evidence). |
| +// State is the provider's instance state, or "not-found" when a successful, |
| +// filtered describe returned no instance; an error is never absence. |
| +// Describe holds the fields of the describe response the adapter read. |
| +type InstanceState struct { |
| + IID string |
| + State string |
| + Describe map[string]any |
| +} |
| + |
| +// WriteResult is a provider write's outcome. Activity is the write's activity |
| +// id when the response named exactly one. Uncertain is set when the provider |
| +// answered success without one ("uncertain-success" in the script): a |
| +// describe must settle the outcome before another write. Response keeps the |
| +// provider's answer for the journal. |
| +type WriteResult struct { |
| + Activity string |
| + Uncertain bool |
| + Response any |
| +} |
| + |
| +// Group is the provider's group calls (spec §5.1). Every failed or malformed |
| +// provider call is an Uncertain{Key: "api"}; validation failures are a |
| +// Refusal. No method can lower desired capacity except Park, which parks one |
| +// member with decrement (H4). |
| +type Group interface { |
| + Describe(ctx context.Context) (GroupView, error) |
| + Targets(ctx context.Context, arn string) (map[string]string, error) |
| + Hook(ctx context.Context) (Hook, error) |
| + Online(ctx context.Context, iid string) (bool, error) |
| + Activities(ctx context.Context, iid string) ([]Activity, error) |
| + Membership(ctx context.Context, iid string) (row MemberRow, found bool, err error) |
| + Instance(ctx context.Context, iid string) (InstanceState, error) |
| + TemplateRelease(ctx context.Context, tpl map[string]any) (string, error) |
| + SetMinimum(ctx context.Context, n int) (WriteResult, error) |
| + RaiseDesired(ctx context.Context, n int) (WriteResult, error) |
| + Park(ctx context.Context, iid string) (WriteResult, error) |
| + Unpark(ctx context.Context, iid string) (WriteResult, error) |
| + Terminate(ctx context.Context, iid string) (WriteResult, error) |
| +} |
diff --git a/internal/grouprollaws/config.go b/internal/grouprollaws/config.go| new file mode 100644 |
| index 000000000..7d997a68e |
| --- /dev/null |
| +++ b/internal/grouprollaws/config.go |
| @@ -0,0 +1,221 @@ |
| +// Package grouprollaws is the AWS adapter for carlos system group (spec |
| +// §5.1): Auto Scaling, Elastic Load Balancing, EC2, Systems Manager and STS |
| +// calls behind grouproll.Group. The core (internal/grouproll) names no |
| +// provider; this package is where AWS lives. |
| +package grouprollaws |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "net" |
| + "net/http" |
| + "os" |
| + "strings" |
| + "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/feature/ec2/imds" |
| + |
| + "github.com/carlosframework/platform/internal/grouproll" |
| +) |
| + |
| +// allowedNames are the variables IsolateEnvironment keeps (spec §4 item 1), |
| +// besides every LC_* variable. |
| +var allowedNames = map[string]bool{ |
| + "HOME": true, "PATH": true, "TMPDIR": true, "TERM": true, "LANG": true, "USER": true, |
| + "AWS_CONFIG_FILE": true, "AWS_SHARED_CREDENTIALS_FILE": true, "AWS_CA_BUNDLE": true, |
| +} |
| + |
| +// allowedEnvironment is the allow-listed part of environ, in its order. |
| +func allowedEnvironment(environ []string) []string { |
| + var kept []string |
| + for _, kv := range environ { |
| + name, _, ok := strings.Cut(kv, "=") |
| + if !ok || name == "" { |
| + continue |
| + } |
| + if allowedNames[name] || (strings.HasPrefix(name, "LC_") && len(name) > len("LC_")) { |
| + kept = append(kept, kv) |
| + } |
| + } |
| + return kept |
| +} |
| + |
| +// IsolateEnvironment rebuilds the process environment from the spec §4 |
| +// allow-list, then sets AWS_IGNORE_CONFIGURED_ENDPOINT_URLS=true, |
| +// AWS_EC2_METADATA_DISABLED=true and AWS_PROFILE to profile. Ambient keys, |
| +// AWS_DEFAULT_PROFILE, container and web-identity variables and endpoint |
| +// overrides are gone for the SDK and for the Session Manager plugin. |
| +// |
| +// The CLI calls it first, before any goroutine starts, after resolving the |
| +// state directory and the shared files (ResolveSharedFiles). |
| +func IsolateEnvironment(profile string) error { |
| + if profile == "" { |
| + return grouproll.Refusal{Key: "config_invalid"} |
| + } |
| + kept := allowedEnvironment(os.Environ()) |
| + os.Clearenv() |
| + for _, kv := range kept { |
| + name, value, _ := strings.Cut(kv, "=") |
| + if err := os.Setenv(name, value); err != nil { |
| + return err |
| + } |
| + } |
| + for _, kv := range [][2]string{ |
| + {"AWS_IGNORE_CONFIGURED_ENDPOINT_URLS", "true"}, |
| + {"AWS_EC2_METADATA_DISABLED", "true"}, |
| + {"AWS_PROFILE", profile}, |
| + } { |
| + if err := os.Setenv(kv[0], kv[1]); err != nil { |
| + return err |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +// SharedFiles are the shared config and credentials files, resolved once. |
| +// Validation and loading both get these lists, so they read the same files. |
| +type SharedFiles struct { |
| + Config []string |
| + Credentials []string |
| +} |
| + |
| +// ResolveSharedFiles names the files the SDK would read: AWS_CONFIG_FILE |
| +// and AWS_SHARED_CREDENTIALS_FILE, else the defaults under the home |
| +// directory. The CLI calls it before IsolateEnvironment. |
| +func ResolveSharedFiles() SharedFiles { |
| + f := SharedFiles{ |
| + Config: []string{awsconfig.DefaultSharedConfigFilename()}, |
| + Credentials: []string{awsconfig.DefaultSharedCredentialsFilename()}, |
| + } |
| + if v := os.Getenv("AWS_CONFIG_FILE"); v != "" { |
| + f.Config = []string{v} |
| + } |
| + if v := os.Getenv("AWS_SHARED_CREDENTIALS_FILE"); v != "" { |
| + f.Credentials = []string{v} |
| + } |
| + return f |
| +} |
| + |
| +// checkProfileIdentity is spec §4's stable caller identity rule. It walks |
| +// the profile's source_profile chain as the SDK resolves it and accepts |
| +// exactly static keys, an SSO profile, and assume-role links that name |
| +// role_session_name over an accepted source. Everything else is refused |
| +// before any call: credential_source (any value), credential_process, web |
| +// identity, an assume-role link without role_session_name, and a profile |
| +// whose credentials would come from anywhere else. |
| +func checkProfileIdentity(ctx context.Context, profile string, files SharedFiles) error { |
| + refuse := func(why string) error { |
| + return grouproll.Refusal{Key: "profile_identity", Args: map[string]string{"profile": profile, "why": why}} |
| + } |
| + sc, err := awsconfig.LoadSharedConfigProfile(ctx, profile, func(o *awsconfig.LoadSharedConfigOptions) { |
| + o.ConfigFiles = files.Config |
| + o.CredentialsFiles = files.Credentials |
| + }) |
| + if err != nil { |
| + var missing awsconfig.SharedConfigProfileNotExistError |
| + if errors.As(err, &missing) { |
| + return refuse("profile " + missing.Profile + " not found") |
| + } |
| + return refuse("the shared config cannot be read") |
| + } |
| + for link := ≻ link != nil; link = link.Source { |
| + name := link.Profile |
| + switch { |
| + case link.CredentialSource != "": |
| + return refuse("credential_source is set in " + name) |
| + case link.CredentialProcess != "": |
| + return refuse("credential_process is set in " + name) |
| + case link.WebIdentityTokenFile != "": |
| + return refuse("web_identity_token_file is set in " + name) |
| + case link.RoleARN != "" && link.RoleSessionName == "": |
| + return refuse("role_arn without role_session_name in " + name) |
| + case link.Source != nil: |
| + continue |
| + case link.Credentials.HasKeys(): |
| + case link.SSOSessionName != "" || link.SSOStartURL != "" || link.SSORegion != "" || |
| + link.SSOAccountID != "" || link.SSORoleName != "": |
| + default: |
| + return refuse("no static keys, SSO or source_profile in " + name) |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +type options struct { |
| + files *SharedFiles |
| + httpClient aws.HTTPClient |
| +} |
| + |
| +// Option configures New. |
| +type Option func(*options) |
| + |
| +// WithSharedFiles passes the shared files the CLI resolved before isolating |
| +// the environment. Without it New resolves them itself. |
| +func WithSharedFiles(f SharedFiles) Option { |
| + return func(o *options) { o.files = &f } |
| +} |
| + |
| +// withHTTPClient replaces the HTTP client (tests record requests with it). |
| +func withHTTPClient(c aws.HTTPClient) Option { |
| + return func(o *options) { o.httpClient = c } |
| +} |
| + |
| +// Timeouts copied from the script's AWS CLI invocation: --cli-connect-timeout |
| +// 2, --cli-read-timeout 2, AWS_MAX_ATTEMPTS=1, and the 15-second process |
| +// bound (`invoke(timeout=15)`). |
| +const ( |
| + connectTimeout = 2 * time.Second |
| + readTimeout = 2 * time.Second |
| + callTimeout = 15 * time.Second |
| +) |
| + |
| +// 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 |
| +// 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) { |
| + var o options |
| + for _, fn := range opts { |
| + fn(&o) |
| + } |
| + files := ResolveSharedFiles() |
| + if o.files != nil { |
| + files = *o.files |
| + } |
| + 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 |
| + }) |
| + if o.httpClient != nil { |
| + httpClient = o.httpClient |
| + } |
| + cfg, err := awsconfig.LoadDefaultConfig(ctx, |
| + awsconfig.WithSharedConfigProfile(c.Profile), |
| + awsconfig.WithRegion(c.Region), |
| + awsconfig.WithSharedConfigFiles(files.Config), |
| + awsconfig.WithSharedCredentialsFiles(files.Credentials), |
| + awsconfig.WithEC2IMDSClientEnableState(imds.ClientDisabled), |
| + awsconfig.WithRetryMaxAttempts(1), |
| + awsconfig.WithHTTPClient(httpClient), |
| + func(lo *awsconfig.LoadOptions) error { |
| + lo.DefaultsModeOptions.IMDSClient = imds.New(imds.Options{ClientEnableState: imds.ClientDisabled}) |
| + return nil |
| + }) |
| + if err != nil { |
| + return nil, grouproll.Refusal{Key: "profile_identity", Args: map[string]string{ |
| + "profile": c.Profile, "why": "the SDK cannot load the profile"}} |
| + } |
| + // No configured endpoint applies, whatever the environment or profile |
| + // says: every client resolves the AWS regional endpoint. |
| + cfg.BaseEndpoint = nil |
| + return newAdapter(cfg, c), nil |
| +} |
diff --git a/internal/grouprollaws/config_test.go b/internal/grouprollaws/config_test.go| new file mode 100644 |
| index 000000000..db8cbb69a |
| --- /dev/null |
| +++ b/internal/grouprollaws/config_test.go |
| @@ -0,0 +1,431 @@ |
| +package grouprollaws |
| + |
| +import ( |
| + "crypto/sha1" |
| + "encoding/hex" |
| + "encoding/json" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "reflect" |
| + "sort" |
| + "strings" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/grouproll" |
| +) |
| + |
| +// The helper subprocess: IsolateEnvironment clears the process environment, |
| +// so the tests that call it run in a re-executed copy of the test binary. |
| +const helperEnv = "GROUPROLLAWS_HELPER" |
| + |
| +func TestMain(m *testing.M) { |
| + if name := os.Getenv(helperEnv); name != "" { |
| + runHelper(name) |
| + os.Exit(0) |
| + } |
| + os.Exit(m.Run()) |
| +} |
| + |
| +type helperOutput struct { |
| + NewError string `json:"new_error,omitempty"` |
| + AccessKey string `json:"access_key,omitempty"` |
| + Hosts map[string]string `json:"hosts,omitempty"` |
| + Auth []string `json:"auth,omitempty"` |
| + Actions []string `json:"actions"` |
| + Errors map[string]string `json:"errors,omitempty"` |
| + Env []string `json:"env"` |
| +} |
| + |
| +func describeError(err error) string { |
| + switch e := err.(type) { |
| + case nil: |
| + return "" |
| + case grouproll.Refusal: |
| + return "refusal:" + e.Key |
| + case grouproll.Uncertain: |
| + if e.Timeout { |
| + return "uncertain-timeout:" + e.Key |
| + } |
| + return "uncertain:" + e.Key |
| + default: |
| + return "other:" + err.Error() |
| + } |
| +} |
| + |
| +func runHelper(name string) { |
| + profile := os.Getenv("GROUPROLLAWS_PROFILE") |
| + files := ResolveSharedFiles() |
| + if v := os.Getenv("GROUPROLLAWS_FILES_CONFIG"); v != "" { |
| + files.Config = []string{v} |
| + } |
| + if err := IsolateEnvironment(profile); err != nil { |
| + panic(err) |
| + } |
| + out := helperOutput{Hosts: map[string]string{}, Errors: map[string]string{}} |
| + rec := newRecorder(). |
| + on("DescribeAutoScalingGroups", groupXML(2, 2, 2, [][2]string{{testIID, "InService"}, {otherIID, "InService"}})). |
| + on("DescribeTargetHealth", targetsXML([3]string{testIID, "80", "healthy"})). |
| + on("DescribeInstances", instancesXML("")). |
| + on("DescribeInstanceInformation", `{"InstanceInformationList":[]}`). |
| + on("DescribeLaunchTemplateVersions", templateXML("7", "")). |
| + 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 { |
| + out.NewError = describeError(err) |
| + } else { |
| + if creds, err := a.cfg.Credentials.Retrieve(ctx); err == nil { |
| + out.AccessKey = creds.AccessKeyID |
| + } else { |
| + out.Errors["retrieve"] = "other" |
| + } |
| + _, err := a.Describe(ctx) |
| + out.Errors["describe"] = describeError(err) |
| + if name == "isolate" { |
| + _, err = a.Targets(ctx, testTG) |
| + out.Errors["targets"] = describeError(err) |
| + _, err = a.Instance(ctx, testIID) |
| + out.Errors["instance"] = describeError(err) |
| + _, err = a.Online(ctx, testIID) |
| + out.Errors["online"] = describeError(err) |
| + _, err = a.TemplateRelease(ctx, map[string]any{"LaunchTemplateId": "lt-0abc", "Version": "7"}) |
| + out.Errors["template"] = describeError(err) |
| + _, _, err = a.CallerIdentity(ctx) |
| + out.Errors["caller"] = describeError(err) |
| + } |
| + if name == "sso" { |
| + _, err = a.Park(ctx, testIID) |
| + out.Errors["park"] = describeError(err) |
| + _, err = a.SetMinimum(ctx, 1) |
| + out.Errors["minimum"] = describeError(err) |
| + } |
| + } |
| + for _, q := range rec.requests() { |
| + out.Hosts[q.Action] = q.Host |
| + out.Auth = append(out.Auth, q.Auth) |
| + out.Actions = append(out.Actions, q.Action) |
| + } |
| + out.Env = os.Environ() |
| + sort.Strings(out.Env) |
| + if err := json.NewEncoder(os.Stdout).Encode(out); err != nil { |
| + panic(err) |
| + } |
| +} |
| + |
| +func runHelperProcess(t *testing.T, name, profile string, env ...string) helperOutput { |
| + t.Helper() |
| + cmd := exec.Command(os.Args[0], "-test.run=^$") |
| + cmd.Env = append([]string{helperEnv + "=" + name, "GROUPROLLAWS_PROFILE=" + profile}, env...) |
| + stdout, err := cmd.Output() |
| + if err != nil { |
| + var stderr string |
| + if ee, ok := err.(*exec.ExitError); ok { |
| + stderr = string(ee.Stderr) |
| + } |
| + t.Fatalf("helper %s: %v\n%s\n%s", name, err, stdout, stderr) |
| + } |
| + var out helperOutput |
| + if err := json.Unmarshal(stdout, &out); err != nil { |
| + t.Fatalf("helper %s output %q: %v", name, stdout, err) |
| + } |
| + return out |
| +} |
| + |
| +func writeFile(t *testing.T, path, content string) { |
| + t.Helper() |
| + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.WriteFile(path, []byte(content), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +func TestIsolatedEnvironment(t *testing.T) { |
| + dir := t.TempDir() |
| + home := filepath.Join(dir, "home") |
| + cfgFile := filepath.Join(dir, "config") |
| + credFile := filepath.Join(dir, "credentials") |
| + writeFile(t, cfgFile, `[profile op] |
| +region = us-east-1 |
| +endpoint_url = http://127.0.0.1:1 |
| +services = local |
| + |
| +[services local] |
| +ec2 = |
| + endpoint_url = http://127.0.0.1:1 |
| +sts = |
| + endpoint_url = http://127.0.0.1:1 |
| + |
| +[profile other] |
| +aws_access_key_id = AKIAOTHER |
| +aws_secret_access_key = other |
| +`) |
| + writeFile(t, credFile, "[op]\naws_access_key_id = AKIAPROFILE\naws_secret_access_key = profile\n") |
| + out := runHelperProcess(t, "isolate", "op", |
| + "HOME="+home, "PATH=/usr/bin:/bin", "TMPDIR="+dir, "TERM=xterm", "LANG=C.UTF-8", "LC_ALL=C", "USER=op", |
| + "AWS_CONFIG_FILE="+cfgFile, "AWS_SHARED_CREDENTIALS_FILE="+credFile, |
| + "AWS_ACCESS_KEY_ID=AKIAAMBIENT", "AWS_SECRET_ACCESS_KEY=ambient", "AWS_SESSION_TOKEN=ambient", |
| + "AWS_PROFILE=other", "AWS_DEFAULT_PROFILE=other", |
| + "AWS_ENDPOINT_URL=http://127.0.0.1:1", "AWS_ENDPOINT_URL_AUTO_SCALING=http://127.0.0.1:1", |
| + "AWS_ENDPOINT_URL_SSM=http://127.0.0.1:1", "AWS_ENDPOINT_URL_STS=http://127.0.0.1:1", |
| + "AWS_ENDPOINT_URL_ELASTIC_LOAD_BALANCING_V2=http://127.0.0.1:1", "AWS_ENDPOINT_URL_EC2=http://127.0.0.1:1", |
| + "AWS_CONTAINER_CREDENTIALS_FULL_URI=http://127.0.0.1:1/creds", "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI=/creds", |
| + "AWS_WEB_IDENTITY_TOKEN_FILE="+filepath.Join(dir, "token"), "AWS_ROLE_ARN=arn:aws:iam::123456789012:role/x", |
| + "AWS_REGION=us-west-2", "AWS_DEFAULT_REGION=us-west-2", "AWS_IGNORE_CONFIGURED_ENDPOINT_URLS=false", |
| + "AWS_EC2_METADATA_DISABLED=false", "SSH_AUTH_SOCK=/x", "FOO=bar") |
| + if out.NewError != "" { |
| + t.Fatalf("New: %s", out.NewError) |
| + } |
| + if out.AccessKey != "AKIAPROFILE" { |
| + t.Fatalf("credentials %q, want the profile's static keys", out.AccessKey) |
| + } |
| + for _, auth := range out.Auth { |
| + if !strings.Contains(auth, "Credential=AKIAPROFILE/") { |
| + t.Fatalf("request signed with %q", auth) |
| + } |
| + } |
| + wantHosts := map[string]string{ |
| + "DescribeAutoScalingGroups": "autoscaling.eu-west-1.amazonaws.com", |
| + "DescribeTargetHealth": "elasticloadbalancing.eu-west-1.amazonaws.com", |
| + "DescribeInstances": "ec2.eu-west-1.amazonaws.com", |
| + "DescribeLaunchTemplateVersions": "ec2.eu-west-1.amazonaws.com", |
| + "DescribeInstanceInformation": "ssm.eu-west-1.amazonaws.com", |
| + "GetCallerIdentity": "sts.eu-west-1.amazonaws.com", |
| + } |
| + if !reflect.DeepEqual(out.Hosts, wantHosts) { |
| + t.Fatalf("hosts %v\nwant %v (errors %v)", out.Hosts, wantHosts, out.Errors) |
| + } |
| + wantEnv := []string{ |
| + "AWS_CONFIG_FILE=" + cfgFile, "AWS_EC2_METADATA_DISABLED=true", "AWS_IGNORE_CONFIGURED_ENDPOINT_URLS=true", |
| + "AWS_PROFILE=op", "AWS_SHARED_CREDENTIALS_FILE=" + credFile, "HOME=" + home, "LANG=C.UTF-8", "LC_ALL=C", |
| + "PATH=/usr/bin:/bin", "TERM=xterm", "TMPDIR=" + dir, "USER=op", |
| + } |
| + if !reflect.DeepEqual(out.Env, wantEnv) { |
| + t.Fatalf("environment after isolation\n%v\nwant\n%v", out.Env, wantEnv) |
| + } |
| +} |
| + |
| +func TestAllowedEnvironment(t *testing.T) { |
| + got := allowedEnvironment([]string{ |
| + "HOME=/h", "PATH=/p", "TMPDIR=/t", "TERM=x", "LANG=C", "LC_ALL=C", "LC_CTYPE=C", "USER=u", |
| + "AWS_CONFIG_FILE=/c", "AWS_SHARED_CREDENTIALS_FILE=/s", "AWS_CA_BUNDLE=/ca", |
| + "LC=x", "LCX=y", "AWS_PROFILE=x", "AWS_ACCESS_KEY_ID=x", "HOMEX=y", "=C:=C:\\", "noequals", |
| + "AWS_CA_BUNDLE_X=1", "USERNAME=u", |
| + }) |
| + want := []string{"HOME=/h", "PATH=/p", "TMPDIR=/t", "TERM=x", "LANG=C", "LC_ALL=C", "LC_CTYPE=C", "USER=u", |
| + "AWS_CONFIG_FILE=/c", "AWS_SHARED_CREDENTIALS_FILE=/s", "AWS_CA_BUNDLE=/ca"} |
| + if !reflect.DeepEqual(got, want) { |
| + t.Fatalf("allowedEnvironment = %v\nwant %v", got, want) |
| + } |
| +} |
| + |
| +// TestProfileFromAllowedFile: validation and loading read the same explicit |
| +// files, so a profile only in AWS_CONFIG_FILE's file validates and loads, |
| +// and one only in the default file (not named) is refused, not half-loaded. |
| +func TestProfileFromAllowedFile(t *testing.T) { |
| + dir := t.TempDir() |
| + home := filepath.Join(dir, "home") |
| + cfgFile := filepath.Join(dir, "elsewhere", "config") |
| + writeFile(t, cfgFile, "[profile op]\naws_access_key_id = AKIAELSEWHERE\naws_secret_access_key = s\n") |
| + writeFile(t, filepath.Join(home, ".aws", "config"), "[profile homeonly]\naws_access_key_id = AKIAHOME\naws_secret_access_key = s\n") |
| + env := []string{"HOME=" + home, "AWS_CONFIG_FILE=" + cfgFile, "AWS_SHARED_CREDENTIALS_FILE=" + filepath.Join(dir, "none")} |
| + out := runHelperProcess(t, "load", "op", env...) |
| + if out.NewError != "" || out.AccessKey != "AKIAELSEWHERE" || out.Errors["describe"] != "" { |
| + t.Fatalf("profile in AWS_CONFIG_FILE: %+v", out) |
| + } |
| + out = runHelperProcess(t, "load", "homeonly", env...) |
| + if out.NewError != "refusal:profile_identity" || len(out.Actions) != 0 { |
| + t.Fatalf("profile only in the default file: %+v", out) |
| + } |
| + // The loader reads the list it was given, not what the environment names |
| + // after isolation: both the rule and the SDK see the passed file. |
| + passed := filepath.Join(dir, "passed") |
| + writeFile(t, passed, "[profile op]\naws_access_key_id = AKIAPASSED\naws_secret_access_key = s\n") |
| + out = runHelperProcess(t, "load", "op", append(env, "GROUPROLLAWS_FILES_CONFIG="+passed)...) |
| + if out.NewError != "" || out.AccessKey != "AKIAPASSED" { |
| + t.Fatalf("passed file: %+v", out) |
| + } |
| + // Without AWS_CONFIG_FILE the default file under HOME is the one read. |
| + out = runHelperProcess(t, "load", "homeonly", "HOME="+home) |
| + if out.NewError != "" || out.AccessKey != "AKIAHOME" { |
| + t.Fatalf("default file: %+v", out) |
| + } |
| +} |
| + |
| +const ssoConfig = `[profile sso] |
| +sso_session = corp |
| +sso_account_id = 123456789012 |
| +sso_role_name = Operator |
| +region = eu-west-1 |
| + |
| +[sso-session corp] |
| +sso_region = eu-west-1 |
| +sso_start_url = https://example.awsapps.com/start |
| +sso_registration_scopes = sso:account:access |
| +` |
| + |
| +// TestExpiredSSOIsAPIRefusal is Review Focus 4: an SSO profile whose cached |
| +// token has expired fails the first describe as api, and nothing reaches |
| +// the group. |
| +func TestExpiredSSOIsAPIRefusal(t *testing.T) { |
| + dir := t.TempDir() |
| + home := filepath.Join(dir, "home") |
| + cfgFile := filepath.Join(dir, "config") |
| + writeFile(t, cfgFile, ssoConfig) |
| + sum := sha1.Sum([]byte("corp")) |
| + writeFile(t, filepath.Join(home, ".aws", "sso", "cache", hex.EncodeToString(sum[:])+".json"), |
| + `{"accessToken":"expired","expiresAt":"2020-01-01T00:00:00Z","region":"eu-west-1","startUrl":"https://example.awsapps.com/start"}`) |
| + out := runHelperProcess(t, "sso", "sso", "HOME="+home, "AWS_CONFIG_FILE="+cfgFile, |
| + "AWS_SHARED_CREDENTIALS_FILE="+filepath.Join(dir, "none")) |
| + if out.NewError != "" { |
| + t.Fatalf("New: %s", out.NewError) |
| + } |
| + for _, call := range []string{"describe", "park", "minimum"} { |
| + if out.Errors[call] != "uncertain:api" { |
| + t.Fatalf("%s: %q, want uncertain:api (%+v)", call, out.Errors[call], out) |
| + } |
| + } |
| + // The expired token stops credential retrieval before any request: |
| + // nothing reaches the SSO portal or the group. |
| + if len(out.Actions) != 0 { |
| + t.Fatalf("requests sent with an expired SSO token: %q", out.Actions) |
| + } |
| +} |
| + |
| +func TestProfileIdentityRule(t *testing.T) { |
| + dir := t.TempDir() |
| + cfgFile := filepath.Join(dir, "config") |
| + credFile := filepath.Join(dir, "credentials") |
| + writeFile(t, cfgFile, ssoConfig+` |
| +[profile static] |
| +aws_access_key_id = AKIASTATIC |
| +aws_secret_access_key = s |
| + |
| +[profile legacy-sso] |
| +sso_start_url = https://example.awsapps.com/start |
| +sso_region = eu-west-1 |
| +sso_account_id = 123456789012 |
| +sso_role_name = Operator |
| + |
| +[profile role] |
| +role_arn = arn:aws:iam::123456789012:role/op |
| +role_session_name = roll |
| +source_profile = static |
| + |
| +[profile role-over-credfile] |
| +role_arn = arn:aws:iam::123456789012:role/op |
| +role_session_name = roll |
| +source_profile = credfile |
| + |
| +[profile chain] |
| +role_arn = arn:aws:iam::123456789012:role/second |
| +role_session_name = roll-2 |
| +source_profile = role |
| + |
| +[profile role-over-sso] |
| +role_arn = arn:aws:iam::123456789012:role/op |
| +role_session_name = roll |
| +source_profile = sso |
| + |
| +[profile role-no-name] |
| +role_arn = arn:aws:iam::123456789012:role/op |
| +source_profile = static |
| + |
| +[profile chain-inner-no-name] |
| +role_arn = arn:aws:iam::123456789012:role/second |
| +role_session_name = roll-2 |
| +source_profile = role-no-name |
| + |
| +[profile chain-outer-no-name] |
| +role_arn = arn:aws:iam::123456789012:role/second |
| +source_profile = role |
| + |
| +[profile source-env] |
| +role_arn = arn:aws:iam::123456789012:role/op |
| +role_session_name = roll |
| +credential_source = Environment |
| + |
| +[profile source-imds] |
| +role_arn = arn:aws:iam::123456789012:role/op |
| +role_session_name = roll |
| +credential_source = Ec2InstanceMetadata |
| + |
| +[profile process] |
| +credential_process = /bin/echo {} |
| + |
| +[profile static-and-process] |
| +aws_access_key_id = AKIASTATIC |
| +aws_secret_access_key = s |
| +credential_process = /bin/echo {} |
| + |
| +[profile role-over-process] |
| +role_arn = arn:aws:iam::123456789012:role/op |
| +role_session_name = roll |
| +source_profile = process |
| + |
| +[profile chain-over-source-env] |
| +role_arn = arn:aws:iam::123456789012:role/second |
| +role_session_name = roll-2 |
| +source_profile = source-env |
| + |
| +[profile web] |
| +role_arn = arn:aws:iam::123456789012:role/op |
| +role_session_name = roll |
| +web_identity_token_file = /tmp/token |
| + |
| +[profile nothing] |
| +region = eu-west-1 |
| + |
| +[profile login] |
| +login_session = arn:aws:iam::123456789012:user/op |
| +`) |
| + writeFile(t, credFile, "[credfile]\naws_access_key_id = AKIACRED\naws_secret_access_key = s\n") |
| + files := SharedFiles{Config: []string{cfgFile}, Credentials: []string{credFile}} |
| + |
| + for _, p := range []string{"static", "credfile", "sso", "legacy-sso", "role", "role-over-credfile", "chain", "role-over-sso"} { |
| + if err := checkProfileIdentity(ctx, p, files); err != nil { |
| + t.Errorf("%s refused: %v", p, err) |
| + } |
| + } |
| + refused := map[string]string{ |
| + "role-no-name": "role_session_name", |
| + "chain-inner-no-name": "role_session_name", |
| + "chain-outer-no-name": "role_session_name", |
| + "source-env": "credential_source", |
| + "source-imds": "credential_source", |
| + "chain-over-source-env": "credential_source", |
| + "process": "credential_process", |
| + "static-and-process": "credential_process", |
| + "role-over-process": "credential_process", |
| + "web": "web_identity_token_file", |
| + "nothing": "no static keys", |
| + "login": "no static keys", |
| + "missing": "not found", |
| + } |
| + for p, why := range refused { |
| + err := checkProfileIdentity(ctx, p, files) |
| + r, ok := err.(grouproll.Refusal) |
| + if !ok || r.Key != "profile_identity" || r.Args["profile"] != p || !strings.Contains(r.Args["why"], why) { |
| + t.Errorf("%s: %#v, want profile_identity naming %q", p, err, why) |
| + continue |
| + } |
| + // The rendered text is the approved string. |
| + if !strings.HasPrefix(r.Error(), "Profile "+p+" does not provide one caller identity") { |
| + t.Errorf("%s: text %q", p, r.Error()) |
| + } |
| + // New refuses before any call. |
| + rec := newRecorder() |
| + c := testConfig() |
| + c.Profile = p |
| + if _, err := New(ctx, c, WithSharedFiles(files), withHTTPClient(rec)); refusalKey(t, err) != "profile_identity" || len(rec.requests()) != 0 { |
| + t.Errorf("%s: New = %v, requests %v", p, err, rec.actions()) |
| + } |
| + } |
| + // An unreadable config file refuses too. |
| + if err := checkProfileIdentity(ctx, "static", SharedFiles{Config: []string{filepath.Join(dir, "missing")}, Credentials: []string{credFile}}); err == nil { |
| + t.Error("missing file accepted") |
| + } |
| +} |
diff --git a/internal/grouprollaws/group.go b/internal/grouprollaws/group.go| new file mode 100644 |
| index 000000000..35c360f90 |
| --- /dev/null |
| +++ b/internal/grouprollaws/group.go |
| @@ -0,0 +1,584 @@ |
| +package grouprollaws |
| + |
| +import ( |
| + "bytes" |
| + "compress/gzip" |
| + "context" |
| + "encoding/base64" |
| + "errors" |
| + "io" |
| + "math" |
| + "net" |
| + "regexp" |
| + "strconv" |
| + "strings" |
| + "time" |
| + "unicode/utf8" |
| + |
| + "github.com/aws/aws-sdk-go-v2/aws" |
| + "github.com/aws/aws-sdk-go-v2/service/autoscaling" |
| + astypes "github.com/aws/aws-sdk-go-v2/service/autoscaling/types" |
| + "github.com/aws/aws-sdk-go-v2/service/ec2" |
| + ec2types "github.com/aws/aws-sdk-go-v2/service/ec2/types" |
| + elbv2 "github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2" |
| + "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/carlosframework/platform/internal/grouproll" |
| +) |
| + |
| +// Adapter is the AWS side of grouproll.Group: the script's AWS.request for |
| +// the group, target, hook, session-online, activity, membership, instance, |
| +// template and write operations. |
| +type Adapter struct { |
| + c grouproll.Config |
| + cfg aws.Config |
| + autoscaling *autoscaling.Client |
| + elb *elbv2.Client |
| + ec2 *ec2.Client |
| + ssm *ssm.Client |
| + sts *sts.Client |
| +} |
| + |
| +func newAdapter(cfg aws.Config, c grouproll.Config) *Adapter { |
| + // Applied after the SDK's own endpoint resolution, so neither a profile |
| + // nor the environment can redirect a client (spec §4). |
| + return &Adapter{ |
| + c: c, |
| + cfg: cfg, |
| + autoscaling: autoscaling.NewFromConfig(cfg, func(o *autoscaling.Options) { o.BaseEndpoint = nil }), |
| + elb: elbv2.NewFromConfig(cfg, func(o *elbv2.Options) { o.BaseEndpoint = nil }), |
| + ec2: ec2.NewFromConfig(cfg, func(o *ec2.Options) { o.BaseEndpoint = nil }), |
| + ssm: ssm.NewFromConfig(cfg, func(o *ssm.Options) { o.BaseEndpoint = nil }), |
| + sts: sts.NewFromConfig(cfg, func(o *sts.Options) { o.BaseEndpoint = nil }), |
| + } |
| +} |
| + |
| +// 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 |
| +// 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) |
| + defer cancel() |
| + out, err := fn(ctx) |
| + if err == nil { |
| + return out, nil |
| + } |
| + var zero T |
| + if parent.Err() != nil { |
| + return zero, parent.Err() |
| + } |
| + var netErr net.Error |
| + if errors.Is(err, context.DeadlineExceeded) || (errors.As(err, &netErr) && netErr.Timeout()) { |
| + return zero, grouproll.Uncertain{Key: "api", Timeout: true} |
| + } |
| + return zero, grouproll.Uncertain{Key: "api"} |
| +} |
| + |
| +// malformed is a response missing a field the script read with [] (a |
| +// KeyError there): the call's answer is unusable, as a failed call is. |
| +func malformed() error { return grouproll.Uncertain{Key: "api"} } |
| + |
| +func requireIID(iid, key string) error { |
| + if !grouproll.IID.MatchString(iid) { |
| + return grouproll.Refusal{Key: key} |
| + } |
| + return nil |
| +} |
| + |
| +func templateMap(t *astypes.LaunchTemplateSpecification) map[string]any { |
| + if t == nil { |
| + return nil |
| + } |
| + m := map[string]any{} |
| + if t.LaunchTemplateId != nil { |
| + m["LaunchTemplateId"] = *t.LaunchTemplateId |
| + } |
| + if t.LaunchTemplateName != nil { |
| + m["LaunchTemplateName"] = *t.LaunchTemplateName |
| + } |
| + if t.Version != nil { |
| + m["Version"] = *t.Version |
| + } |
| + return m |
| +} |
| + |
| +func intOf(p *int32) (int, bool) { |
| + if p == nil { |
| + return 0, false |
| + } |
| + return int(*p), true |
| +} |
| + |
| +// Describe is the script's "group": DescribeAutoScalingGroups for the |
| +// configured group, exactly one group or scope. |
| +func (a *Adapter) Describe(ctx context.Context) (grouproll.GroupView, error) { |
| + out, err := call(ctx, func(ctx context.Context) (*autoscaling.DescribeAutoScalingGroupsOutput, error) { |
| + return a.autoscaling.DescribeAutoScalingGroups(ctx, &autoscaling.DescribeAutoScalingGroupsInput{ |
| + AutoScalingGroupNames: []string{a.c.Group}, |
| + }) |
| + }) |
| + if err != nil { |
| + return grouproll.GroupView{}, err |
| + } |
| + if len(out.AutoScalingGroups) != 1 { |
| + return grouproll.GroupView{}, grouproll.Refusal{Key: "scope"} |
| + } |
| + g := out.AutoScalingGroups[0] |
| + 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 |
| + view.Minimum, ok[0] = intOf(g.MinSize) |
| + view.Desired, ok[1] = intOf(g.DesiredCapacity) |
| + view.Maximum, ok[2] = intOf(g.MaxSize) |
| + ok[3], ok[4] = g.AutoScalingGroupName != nil, g.AutoScalingGroupARN != nil |
| + for _, present := range ok { |
| + if !present { |
| + return grouproll.GroupView{}, malformed() |
| + } |
| + } |
| + view.Name, view.ARN = *g.AutoScalingGroupName, *g.AutoScalingGroupARN |
| + for _, tag := range g.Tags { |
| + if tag.Key == nil || tag.Value == nil { |
| + return grouproll.GroupView{}, malformed() |
| + } |
| + if *tag.Key == "carlos:deployment" { |
| + view.Deployment = *tag.Value |
| + } |
| + } |
| + for _, i := range g.Instances { |
| + if i.InstanceId == nil || i.HealthStatus == nil { |
| + return grouproll.GroupView{}, malformed() |
| + } |
| + raw := string(i.LifecycleState) |
| + view.Members[*i.InstanceId] = grouproll.Member{Phase: MapPhase(raw), Raw: raw, Healthy: *i.HealthStatus == "Healthy"} |
| + } |
| + return view, nil |
| +} |
| + |
| +// Targets is the script's "targets": iid -> target health state. A member |
| +// registered twice (another port) with different states is "unknown", so a |
| +// duplicate registration cannot hide draining. |
| +func (a *Adapter) Targets(ctx context.Context, arn string) (map[string]string, error) { |
| + out, err := call(ctx, func(ctx context.Context) (*elbv2.DescribeTargetHealthOutput, error) { |
| + return a.elb.DescribeTargetHealth(ctx, &elbv2.DescribeTargetHealthInput{TargetGroupArn: aws.String(arn)}) |
| + }) |
| + if err != nil { |
| + return nil, err |
| + } |
| + result := map[string]string{} |
| + for _, t := range out.TargetHealthDescriptions { |
| + if t.Target == nil || t.Target.Id == nil || t.TargetHealth == nil { |
| + return nil, malformed() |
| + } |
| + iid, state := *t.Target.Id, string(t.TargetHealth.State) |
| + if prev, seen := result[iid]; seen && prev != state { |
| + state = "unknown" |
| + } |
| + result[iid] = state |
| + } |
| + return result, nil |
| +} |
| + |
| +// Hook is the script's "hooks": exactly one configured hook, else hook. |
| +func (a *Adapter) Hook(ctx context.Context) (grouproll.Hook, error) { |
| + out, err := call(ctx, func(ctx context.Context) (*autoscaling.DescribeLifecycleHooksOutput, error) { |
| + return a.autoscaling.DescribeLifecycleHooks(ctx, &autoscaling.DescribeLifecycleHooksInput{ |
| + AutoScalingGroupName: aws.String(a.c.Group), |
| + LifecycleHookNames: []string{a.c.Hook}, |
| + }) |
| + }) |
| + if err != nil { |
| + return grouproll.Hook{}, err |
| + } |
| + if len(out.LifecycleHooks) != 1 { |
| + return grouproll.Hook{}, grouproll.Refusal{Key: "hook"} |
| + } |
| + h := out.LifecycleHooks[0] |
| + timeout, ok := intOf(h.HeartbeatTimeout) |
| + if !ok || h.LifecycleHookName == nil || h.DefaultResult == nil || h.LifecycleTransition == nil { |
| + return grouproll.Hook{}, malformed() |
| + } |
| + return grouproll.Hook{Name: *h.LifecycleHookName, Timeout: timeout, Default: *h.DefaultResult, |
| + Transition: *h.LifecycleTransition}, nil |
| +} |
| + |
| +// Online is the script's "online": the member is the one Session Manager |
| +// instance listed for its id, and its ping status is Online. |
| +func (a *Adapter) Online(ctx context.Context, iid string) (bool, error) { |
| + out, err := call(ctx, func(ctx context.Context) (*ssm.DescribeInstanceInformationOutput, error) { |
| + return a.ssm.DescribeInstanceInformation(ctx, &ssm.DescribeInstanceInformationInput{ |
| + Filters: []ssmtypes.InstanceInformationStringFilter{{Key: aws.String("InstanceIds"), Values: []string{iid}}}, |
| + }) |
| + }) |
| + if err != nil { |
| + return false, err |
| + } |
| + r := out.InstanceInformationList |
| + if len(r) != 1 { |
| + return false, nil |
| + } |
| + if r[0].InstanceId == nil { |
| + return false, malformed() |
| + } |
| + return *r[0].InstanceId == iid && r[0].PingStatus == ssmtypes.PingStatusOnline, nil |
| +} |
| + |
| +// activityKind classifies a description as the script does: AWS documents |
| +// "to Standby"; "into Standby" is accepted too. |
| +func activityKind(description string) string { |
| + switch { |
| + case strings.Contains(description, "out of Standby"): |
| + return "exit" |
| + case strings.Contains(description, "to Standby"), strings.Contains(description, "into Standby"): |
| + return "enter" |
| + case strings.HasPrefix(description, "Terminating EC2 instance"): |
| + return "terminate" |
| + } |
| + return "" |
| +} |
| + |
| +// Activities is the script's "activities": the group's scaling activities |
| +// whose description names iid as a whole word, classified enter, exit or |
| +// terminate; the rest are ignored. |
| +func (a *Adapter) Activities(ctx context.Context, iid string) ([]grouproll.Activity, error) { |
| + out, err := call(ctx, func(ctx context.Context) (*autoscaling.DescribeScalingActivitiesOutput, error) { |
| + return a.autoscaling.DescribeScalingActivities(ctx, &autoscaling.DescribeScalingActivitiesInput{ |
| + AutoScalingGroupName: aws.String(a.c.Group), |
| + }) |
| + }) |
| + if err != nil { |
| + return nil, err |
| + } |
| + named := regexp.MustCompile(`\b` + regexp.QuoteMeta(iid) + `\b`) |
| + result := []grouproll.Activity{} |
| + for _, row := range out.Activities { |
| + description := aws.ToString(row.Description) |
| + kind := activityKind(description) |
| + if kind == "" || !named.MatchString(description) { |
| + continue |
| + } |
| + if row.ActivityId == nil || row.StartTime == nil { |
| + return nil, malformed() |
| + } |
| + result = append(result, grouproll.Activity{ID: *row.ActivityId, Kind: kind, |
| + Status: string(row.StatusCode), Time: row.StartTime.UnixMilli()}) |
| + } |
| + return result, nil |
| +} |
| + |
| +// Membership is the script's "instance" as the probe reads it: the |
| +// member's own DescribeAutoScalingInstances row. More than one row is api. |
| +func (a *Adapter) Membership(ctx context.Context, iid string) (grouproll.MemberRow, bool, error) { |
| + out, err := call(ctx, func(ctx context.Context) (*autoscaling.DescribeAutoScalingInstancesOutput, error) { |
| + return a.autoscaling.DescribeAutoScalingInstances(ctx, &autoscaling.DescribeAutoScalingInstancesInput{ |
| + InstanceIds: []string{iid}, |
| + }) |
| + }) |
| + if err != nil { |
| + return grouproll.MemberRow{}, false, err |
| + } |
| + rows := out.AutoScalingInstances |
| + if len(rows) > 1 { |
| + return grouproll.MemberRow{}, false, grouproll.Refusal{Key: "api"} |
| + } |
| + if len(rows) == 0 { |
| + return grouproll.MemberRow{}, false, nil |
| + } |
| + m := rows[0] |
| + if m.InstanceId == nil || m.AutoScalingGroupName == nil || m.LifecycleState == nil { |
| + return grouproll.MemberRow{}, false, malformed() |
| + } |
| + raw := *m.LifecycleState |
| + // DescribeAutoScalingInstances uses HEALTHY; DescribeAutoScalingGroups uses Healthy. |
| + return grouproll.MemberRow{IID: *m.InstanceId, Group: *m.AutoScalingGroupName, |
| + Template: templateMap(m.LaunchTemplate), Raw: raw, Phase: MapPhase(raw), |
| + Healthy: strings.ToUpper(aws.ToString(m.HealthStatus)) == "HEALTHY"}, true, nil |
| +} |
| + |
| +var instanceStates = map[string]bool{"pending": true, "running": true, "shutting-down": true, |
| + "terminated": true, "stopping": true, "stopped": true} |
| + |
| +// Instance is the script's "ec2_instance": a filtered DescribeInstances, |
| +// whose empty successful answer is "not-found" (an expired id). A failed |
| +// call is never absence. |
| +func (a *Adapter) Instance(ctx context.Context, iid string) (grouproll.InstanceState, error) { |
| + if err := requireIID(iid, "record"); err != nil { |
| + return grouproll.InstanceState{}, err |
| + } |
| + out, err := call(ctx, func(ctx context.Context) (*ec2.DescribeInstancesOutput, error) { |
| + return a.ec2.DescribeInstances(ctx, &ec2.DescribeInstancesInput{ |
| + Filters: []ec2types.Filter{{Name: aws.String("instance-id"), Values: []string{iid}}}, |
| + }) |
| + }) |
| + if err != nil { |
| + return grouproll.InstanceState{}, err |
| + } |
| + api := grouproll.Refusal{Key: "api"} |
| + if aws.ToString(out.NextToken) != "" { |
| + return grouproll.InstanceState{}, api |
| + } |
| + reservations := []any{} |
| + var instances []ec2types.Instance |
| + for _, r := range out.Reservations { |
| + if aws.ToString(r.OwnerId) != a.c.Account { |
| + return grouproll.InstanceState{}, api |
| + } |
| + listed := []any{} |
| + for _, i := range r.Instances { |
| + row := map[string]any{"InstanceId": aws.ToString(i.InstanceId)} |
| + if i.State != nil { |
| + row["State"] = map[string]any{"Name": string(i.State.Name)} |
| + } |
| + listed = append(listed, row) |
| + } |
| + reservations = append(reservations, map[string]any{"OwnerId": aws.ToString(r.OwnerId), "Instances": listed}) |
| + instances = append(instances, r.Instances...) |
| + } |
| + if len(instances) > 1 { |
| + return grouproll.InstanceState{}, api |
| + } |
| + state := "not-found" |
| + if len(instances) == 1 { |
| + i := instances[0] |
| + if aws.ToString(i.InstanceId) != iid || i.State == nil || !instanceStates[string(i.State.Name)] { |
| + return grouproll.InstanceState{}, api |
| + } |
| + state = string(i.State.Name) |
| + } |
| + return grouproll.InstanceState{IID: iid, State: state, |
| + Describe: map[string]any{"Reservations": reservations}}, nil |
| +} |
| + |
| +var carlosRelease = regexp.MustCompile(`(?m)^CARLOS_RELEASE='([^']*)'$`) |
| + |
| +// TemplateRelease is the script's template_release: the CARLOS_RELEASE line |
| +// of the pinned launch template version's user data (plain or gzip). |
| +func (a *Adapter) TemplateRelease(ctx context.Context, tpl map[string]any) (string, error) { |
| + version, ok := tpl["Version"].(string) |
| + if tpl == nil || !ok { |
| + return "", grouproll.Refusal{Key: "scope"} |
| + } |
| + in := &ec2.DescribeLaunchTemplateVersionsInput{Versions: []string{version}} |
| + if id, _ := tpl["LaunchTemplateId"].(string); id != "" { |
| + in.LaunchTemplateId = aws.String(id) |
| + } else { |
| + name, _ := tpl["LaunchTemplateName"].(string) |
| + in.LaunchTemplateName = aws.String(name) |
| + } |
| + out, err := call(ctx, func(ctx context.Context) (*ec2.DescribeLaunchTemplateVersionsOutput, error) { |
| + return a.ec2.DescribeLaunchTemplateVersions(ctx, in) |
| + }) |
| + if err != nil { |
| + return "", err |
| + } |
| + api := grouproll.Refusal{Key: "api"} |
| + rows := out.LaunchTemplateVersions |
| + if len(rows) != 1 || rows[0].VersionNumber == nil || strconv.FormatInt(*rows[0].VersionNumber, 10) != version { |
| + return "", api |
| + } |
| + if rows[0].LaunchTemplateData == nil || rows[0].LaunchTemplateData.UserData == nil { |
| + return "", api |
| + } |
| + encoded := *rows[0].LaunchTemplateData.UserData |
| + // Python's b64decode(validate=True) refuses characters outside the |
| + // alphabet; Go's decoder would skip CR and LF. |
| + if strings.ContainsAny(encoded, "\r\n") { |
| + return "", api |
| + } |
| + raw, err := base64.StdEncoding.DecodeString(encoded) |
| + if err != nil { |
| + return "", api |
| + } |
| + if len(raw) >= 2 && raw[0] == 0x1f && raw[1] == 0x8b { |
| + zr, err := gzip.NewReader(bytes.NewReader(raw)) |
| + if err != nil { |
| + return "", api |
| + } |
| + raw, err = io.ReadAll(io.LimitReader(zr, 4<<20+1)) |
| + if err != nil || len(raw) > 4<<20 { |
| + return "", api |
| + } |
| + } |
| + if !utf8.Valid(raw) { |
| + return "", api |
| + } |
| + found := carlosRelease.FindAllStringSubmatch(string(raw), -1) |
| + if len(found) != 1 { |
| + return "", api |
| + } |
| + return found[0][1], nil |
| +} |
| + |
| +func int32Of(n int) (int32, bool) { |
| + if n < 0 || n > math.MaxInt32 { |
| + return 0, false |
| + } |
| + return int32(n), true |
| +} |
| + |
| +// SetMinimum is the script's "minimum": UpdateAutoScalingGroup MinSize only. |
| +func (a *Adapter) SetMinimum(ctx context.Context, n int) (grouproll.WriteResult, error) { |
| + v, ok := int32Of(n) |
| + if !ok { |
| + return grouproll.WriteResult{}, grouproll.Refusal{Key: "record"} |
| + } |
| + _, err := call(ctx, func(ctx context.Context) (*autoscaling.UpdateAutoScalingGroupOutput, error) { |
| + return a.autoscaling.UpdateAutoScalingGroup(ctx, &autoscaling.UpdateAutoScalingGroupInput{ |
| + AutoScalingGroupName: aws.String(a.c.Group), MinSize: aws.Int32(v), |
| + }) |
| + }) |
| + if err != nil { |
| + return grouproll.WriteResult{}, err |
| + } |
| + return grouproll.WriteResult{Response: map[string]any{}}, nil |
| +} |
| + |
| +// RaiseDesired is the script's "desired" (H4): it only raises desired, for |
| +// the transaction's restore. A fresh describe must show desired <= n <= |
| +// maximum, else h4 and nothing is sent. |
| +func (a *Adapter) RaiseDesired(ctx context.Context, n int) (grouproll.WriteResult, error) { |
| + g, err := a.Describe(ctx) |
| + if err != nil { |
| + return grouproll.WriteResult{}, err |
| + } |
| + v, ok := int32Of(n) |
| + if !ok || n < g.Desired || n > g.Maximum { |
| + return grouproll.WriteResult{}, grouproll.Refusal{Key: "h4"} |
| + } |
| + _, err = call(ctx, func(ctx context.Context) (*autoscaling.UpdateAutoScalingGroupOutput, error) { |
| + return a.autoscaling.UpdateAutoScalingGroup(ctx, &autoscaling.UpdateAutoScalingGroupInput{ |
| + AutoScalingGroupName: aws.String(a.c.Group), DesiredCapacity: aws.Int32(v), |
| + }) |
| + }) |
| + if err != nil { |
| + return grouproll.WriteResult{}, err |
| + } |
| + return grouproll.WriteResult{Response: map[string]any{}}, nil |
| +} |
| + |
| +func activityMap(r astypes.Activity) map[string]any { |
| + m := map[string]any{} |
| + put := func(k string, v *string) { |
| + if v != nil { |
| + m[k] = *v |
| + } |
| + } |
| + put("ActivityId", r.ActivityId) |
| + put("AutoScalingGroupName", r.AutoScalingGroupName) |
| + put("Description", r.Description) |
| + put("Cause", r.Cause) |
| + put("StatusMessage", r.StatusMessage) |
| + if r.StatusCode != "" { |
| + m["StatusCode"] = string(r.StatusCode) |
| + } |
| + if r.StartTime != nil { |
| + m["StartTime"] = r.StartTime.UTC().Format(time.RFC3339Nano) |
| + } |
| + if r.Progress != nil { |
| + m["Progress"] = int64(*r.Progress) |
| + } |
| + return m |
| +} |
| + |
| +// activityResponse is the script's activity_response: exactly one activity |
| +// with an id names the write; any other success is uncertain-success and |
| +// keeps the response, and a describe must settle it before another write. |
| +func activityResponse(rows []astypes.Activity) grouproll.WriteResult { |
| + if len(rows) == 1 && aws.ToString(rows[0].ActivityId) != "" { |
| + return grouproll.WriteResult{Activity: *rows[0].ActivityId, Response: map[string]any{"Activities": []any{activityMap(rows[0])}}} |
| + } |
| + listed := []any{} |
| + for _, r := range rows { |
| + listed = append(listed, activityMap(r)) |
| + } |
| + return grouproll.WriteResult{Uncertain: true, Response: map[string]any{"Activities": listed}} |
| +} |
| + |
| +// Park is the script's "enter": EnterStandby for exactly this member with |
| +// ShouldDecrementDesiredCapacity=true, the one call that lowers desired (H4). |
| +func (a *Adapter) Park(ctx context.Context, iid string) (grouproll.WriteResult, error) { |
| + if err := requireIID(iid, "record"); err != nil { |
| + return grouproll.WriteResult{}, err |
| + } |
| + out, err := call(ctx, func(ctx context.Context) (*autoscaling.EnterStandbyOutput, error) { |
| + return a.autoscaling.EnterStandby(ctx, &autoscaling.EnterStandbyInput{ |
| + AutoScalingGroupName: aws.String(a.c.Group), |
| + InstanceIds: []string{iid}, |
| + ShouldDecrementDesiredCapacity: aws.Bool(true), |
| + }) |
| + }) |
| + if err != nil { |
| + return grouproll.WriteResult{}, err |
| + } |
| + return activityResponse(out.Activities), nil |
| +} |
| + |
| +// Unpark is the script's "exit": ExitStandby for exactly this member. |
| +func (a *Adapter) Unpark(ctx context.Context, iid string) (grouproll.WriteResult, error) { |
| + if err := requireIID(iid, "record"); err != nil { |
| + return grouproll.WriteResult{}, err |
| + } |
| + out, err := call(ctx, func(ctx context.Context) (*autoscaling.ExitStandbyOutput, error) { |
| + return a.autoscaling.ExitStandby(ctx, &autoscaling.ExitStandbyInput{ |
| + AutoScalingGroupName: aws.String(a.c.Group), |
| + InstanceIds: []string{iid}, |
| + }) |
| + }) |
| + if err != nil { |
| + return grouproll.WriteResult{}, err |
| + } |
| + return activityResponse(out.Activities), nil |
| +} |
| + |
| +// Terminate is the script's "terminate" (H4): a parked member, terminated |
| +// without decrement. A Standby member entered with decrement is already |
| +// outside desired, so with desired == minimum nothing launches to replace |
| +// it. A fresh describe must show the member Standby and desired == minimum, |
| +// else h4 and nothing is sent. |
| +func (a *Adapter) Terminate(ctx context.Context, iid string) (grouproll.WriteResult, error) { |
| + if err := requireIID(iid, "h4"); err != nil { |
| + return grouproll.WriteResult{}, err |
| + } |
| + g, err := a.Describe(ctx) |
| + if err != nil { |
| + return grouproll.WriteResult{}, err |
| + } |
| + if m, ok := g.Members[iid]; !ok || m.Raw != "Standby" || g.Desired != g.Minimum { |
| + return grouproll.WriteResult{}, grouproll.Refusal{Key: "h4"} |
| + } |
| + out, err := call(ctx, func(ctx context.Context) (*autoscaling.TerminateInstanceInAutoScalingGroupOutput, error) { |
| + return a.autoscaling.TerminateInstanceInAutoScalingGroup(ctx, &autoscaling.TerminateInstanceInAutoScalingGroupInput{ |
| + InstanceId: aws.String(iid), |
| + ShouldDecrementDesiredCapacity: aws.Bool(false), |
| + }) |
| + }) |
| + if err != nil { |
| + return grouproll.WriteResult{}, err |
| + } |
| + if out.Activity != nil && aws.ToString(out.Activity.ActivityId) != "" { |
| + return grouproll.WriteResult{Activity: *out.Activity.ActivityId, |
| + Response: map[string]any{"Activity": activityMap(*out.Activity)}}, nil |
| + } |
| + response := map[string]any{} |
| + if out.Activity != nil { |
| + response["Activity"] = activityMap(*out.Activity) |
| + } |
| + return grouproll.WriteResult{Uncertain: true, Response: response}, nil |
| +} |
| + |
| +// CallerIdentity is sts:GetCallerIdentity; the engine journals the UserId. |
| +func (a *Adapter) CallerIdentity(ctx context.Context) (userID, arn string, err error) { |
| + out, err := call(ctx, func(ctx context.Context) (*sts.GetCallerIdentityOutput, error) { |
| + return a.sts.GetCallerIdentity(ctx, &sts.GetCallerIdentityInput{}) |
| + }) |
| + if err != nil { |
| + return "", "", err |
| + } |
| + if aws.ToString(out.UserId) == "" || aws.ToString(out.Arn) == "" { |
| + return "", "", malformed() |
| + } |
| + return *out.UserId, *out.Arn, nil |
| +} |
diff --git a/internal/grouprollaws/group_test.go b/internal/grouprollaws/group_test.go| new file mode 100644 |
| index 000000000..98b8c89c6 |
| --- /dev/null |
| +++ b/internal/grouprollaws/group_test.go |
| @@ -0,0 +1,543 @@ |
| +package grouprollaws |
| + |
| +import ( |
| + "bytes" |
| + "compress/gzip" |
| + "encoding/base64" |
| + "reflect" |
| + "sort" |
| + "strings" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/grouproll" |
| +) |
| + |
| +var _ grouproll.Group = (*Adapter)(nil) |
| + |
| +func TestDescribe(t *testing.T) { |
| + rec := newRecorder().on("DescribeAutoScalingGroups", groupXML(2, 2, 3, [][2]string{ |
| + {testIID, "InService"}, {otherIID, "Standby"}, {thirdIID, "Warmed:Pending"}}, otherIID)) |
| + g, err := testAdapter(t, rec).Describe(ctx) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + want := grouproll.GroupView{ |
| + Name: testGroup, ARN: testARN, Deployment: "dev", Region: "eu-west-1", |
| + Minimum: 2, Desired: 2, Maximum: 3, |
| + Members: map[string]grouproll.Member{ |
| + testIID: {Phase: grouproll.Serving, Raw: "InService", Healthy: true}, |
| + otherIID: {Phase: grouproll.Parked, Raw: "Standby", Healthy: false}, |
| + thirdIID: {Phase: grouproll.Unknown, Raw: "Warmed:Pending", Healthy: true}, |
| + }, |
| + Template: map[string]any{"LaunchTemplateId": "lt-0abc", "LaunchTemplateName": "carlos-dev", "Version": "7"}, |
| + TargetGroups: []string{testTG}, |
| + } |
| + if !reflect.DeepEqual(g, want) { |
| + t.Fatalf("Describe = %+v\nwant %+v", g, want) |
| + } |
| + q := rec.requests() |
| + if len(q) != 1 || q[0].Form.Get("AutoScalingGroupNames.member.1") != testGroup || q[0].Form.Has("AutoScalingGroupNames.member.2") { |
| + t.Fatalf("request %+v", q) |
| + } |
| + |
| + empty := `<DescribeAutoScalingGroupsResponse><DescribeAutoScalingGroupsResult><AutoScalingGroups/></DescribeAutoScalingGroupsResult></DescribeAutoScalingGroupsResponse>` |
| + if _, err := testAdapter(t, newRecorder().on("DescribeAutoScalingGroups", empty)).Describe(ctx); refusalKey(t, err) != "scope" { |
| + t.Fatalf("no group: %v", err) |
| + } |
| + u := uncertainKey(t, func() error { _, err := testAdapter(t, newRecorder()).Describe(ctx); return err }()) |
| + if u.Key != "api" || u.Timeout { |
| + t.Fatalf("failed describe: %+v", u) |
| + } |
| + // A group without a launch template (a mixed instances policy) has a |
| + // nil template; the core refuses it on scope. |
| + noTemplate := strings.Replace(groupXML(2, 2, 2, [][2]string{{testIID, "InService"}}), |
| + `<LaunchTemplate><LaunchTemplateId>lt-0abc</LaunchTemplateId><LaunchTemplateName>carlos-dev</LaunchTemplateName><Version>7</Version></LaunchTemplate>`, "", 1) |
| + g, err = testAdapter(t, newRecorder().on("DescribeAutoScalingGroups", noTemplate)).Describe(ctx) |
| + if err != nil || g.Template != nil { |
| + t.Fatalf("no template: %v %v", g.Template, err) |
| + } |
| + // A missing capacity field is a malformed response. |
| + noMin := strings.Replace(groupXML(2, 2, 2, nil), "<MinSize>2</MinSize>", "", 1) |
| + if _, err := testAdapter(t, newRecorder().on("DescribeAutoScalingGroups", noMin)).Describe(ctx); uncertainKey(t, err).Key != "api" { |
| + t.Fatalf("no MinSize: %v", err) |
| + } |
| +} |
| + |
| +func targetsXML(rows ...[3]string) string { |
| + var b strings.Builder |
| + b.WriteString(`<DescribeTargetHealthResponse xmlns="http://elasticloadbalancing.amazonaws.com/doc/2015-12-01/"><DescribeTargetHealthResult><TargetHealthDescriptions>`) |
| + for _, r := range rows { |
| + b.WriteString(`<member><Target><Id>` + r[0] + `</Id><Port>` + r[1] + `</Port></Target><TargetHealth><State>` + r[2] + `</State></TargetHealth></member>`) |
| + } |
| + b.WriteString(`</TargetHealthDescriptions></DescribeTargetHealthResult></DescribeTargetHealthResponse>`) |
| + return b.String() |
| +} |
| + |
| +func TestTargetsDuplicatePort(t *testing.T) { |
| + rec := newRecorder().on("DescribeTargetHealth", targetsXML( |
| + [3]string{testIID, "80", "healthy"}, [3]string{testIID, "8080", "draining"}, |
| + [3]string{otherIID, "80", "healthy"}, [3]string{otherIID, "8080", "healthy"}, |
| + [3]string{thirdIID, "80", "unused"})) |
| + got, err := testAdapter(t, rec).Targets(ctx, testTG) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + want := map[string]string{testIID: "unknown", otherIID: "healthy", thirdIID: "unused"} |
| + if !reflect.DeepEqual(got, want) { |
| + t.Fatalf("Targets = %v, want %v", got, want) |
| + } |
| + q := rec.requests() |
| + if len(q) != 1 || q[0].Form.Get("TargetGroupArn") != testTG || q[0].Host != "elasticloadbalancing.eu-west-1.amazonaws.com" { |
| + t.Fatalf("request %+v", q) |
| + } |
| + // A third registration back in the first state stays unknown. |
| + rec = newRecorder().on("DescribeTargetHealth", targetsXML( |
| + [3]string{testIID, "80", "healthy"}, [3]string{testIID, "81", "draining"}, [3]string{testIID, "82", "healthy"})) |
| + if got, _ := testAdapter(t, rec).Targets(ctx, testTG); got[testIID] != "unknown" { |
| + t.Fatalf("three registrations: %v", got) |
| + } |
| + if _, err := testAdapter(t, newRecorder()).Targets(ctx, testTG); uncertainKey(t, err).Key != "api" { |
| + t.Fatalf("failed targets: %v", err) |
| + } |
| +} |
| + |
| +func TestHook(t *testing.T) { |
| + hook := `<DescribeLifecycleHooksResponse><DescribeLifecycleHooksResult><LifecycleHooks><member><LifecycleHookName>carlos-launch</LifecycleHookName><AutoScalingGroupName>carlos-dev-g</AutoScalingGroupName><LifecycleTransition>autoscaling:EC2_INSTANCE_LAUNCHING</LifecycleTransition><HeartbeatTimeout>900</HeartbeatTimeout><DefaultResult>ABANDON</DefaultResult></member></LifecycleHooks></DescribeLifecycleHooksResult></DescribeLifecycleHooksResponse>` |
| + rec := newRecorder().on("DescribeLifecycleHooks", hook) |
| + h, err := testAdapter(t, rec).Hook(ctx) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if h != (grouproll.Hook{Name: "carlos-launch", Timeout: 900, Default: "ABANDON", Transition: "autoscaling:EC2_INSTANCE_LAUNCHING"}) { |
| + t.Fatalf("Hook = %+v", h) |
| + } |
| + f := rec.requests()[0].Form |
| + if f.Get("AutoScalingGroupName") != testGroup || f.Get("LifecycleHookNames.member.1") != "carlos-launch" { |
| + t.Fatalf("request %v", f) |
| + } |
| + none := `<DescribeLifecycleHooksResponse><DescribeLifecycleHooksResult><LifecycleHooks/></DescribeLifecycleHooksResult></DescribeLifecycleHooksResponse>` |
| + if _, err := testAdapter(t, newRecorder().on("DescribeLifecycleHooks", none)).Hook(ctx); refusalKey(t, err) != "hook" { |
| + t.Fatalf("no hook: %v", err) |
| + } |
| +} |
| + |
| +func TestOnline(t *testing.T) { |
| + for _, c := range []struct { |
| + body string |
| + want bool |
| + }{ |
| + {`{"InstanceInformationList":[{"InstanceId":"` + testIID + `","PingStatus":"Online"}]}`, true}, |
| + {`{"InstanceInformationList":[{"InstanceId":"` + testIID + `","PingStatus":"ConnectionLost"}]}`, false}, |
| + {`{"InstanceInformationList":[{"InstanceId":"` + otherIID + `","PingStatus":"Online"}]}`, false}, |
| + {`{"InstanceInformationList":[]}`, false}, |
| + {`{"InstanceInformationList":[{"InstanceId":"` + testIID + `","PingStatus":"Online"},{"InstanceId":"` + testIID + `","PingStatus":"Online"}]}`, false}, |
| + } { |
| + rec := newRecorder().on("DescribeInstanceInformation", c.body) |
| + got, err := testAdapter(t, rec).Online(ctx, testIID) |
| + if err != nil || got != c.want { |
| + t.Fatalf("%s: %v %v", c.body, got, err) |
| + } |
| + q := rec.requests()[0] |
| + want := map[string]any{"Filters": []any{map[string]any{"Key": "InstanceIds", "Values": []any{testIID}}}} |
| + if !reflect.DeepEqual(q.JSON, want) || q.Host != "ssm.eu-west-1.amazonaws.com" { |
| + t.Fatalf("request %+v", q) |
| + } |
| + } |
| + if _, err := testAdapter(t, newRecorder()).Online(ctx, testIID); uncertainKey(t, err).Key != "api" { |
| + t.Fatalf("failed online: %v", err) |
| + } |
| +} |
| + |
| +func activitiesXML(rows ...[4]string) string { |
| + var b strings.Builder |
| + b.WriteString(`<DescribeScalingActivitiesResponse><DescribeScalingActivitiesResult><Activities>`) |
| + for _, r := range rows { |
| + b.WriteString(`<member><ActivityId>` + r[0] + `</ActivityId><AutoScalingGroupName>carlos-dev-g</AutoScalingGroupName><Description>` + r[1] + `</Description><Cause>c</Cause><StartTime>` + r[2] + `</StartTime>`) |
| + if r[3] != "" { |
| + b.WriteString(`<StatusCode>` + r[3] + `</StatusCode>`) |
| + } |
| + b.WriteString(`</member>`) |
| + } |
| + b.WriteString(`</Activities></DescribeScalingActivitiesResult></DescribeScalingActivitiesResponse>`) |
| + return b.String() |
| +} |
| + |
| +func TestActivitiesKinds(t *testing.T) { |
| + rec := newRecorder().on("DescribeScalingActivities", activitiesXML( |
| + [4]string{"a1", "Moving EC2 instance out of Standby: " + testIID, "2026-11-09T10:00:00Z", "Successful"}, |
| + [4]string{"a2", "Moving EC2 instance to Standby: " + testIID, "2026-11-09T10:00:01.500Z", "InProgress"}, |
| + [4]string{"a3", "Moving EC2 instance into Standby: " + testIID, "2026-11-09T10:00:02Z", ""}, |
| + [4]string{"a4", "Terminating EC2 instance: " + testIID, "2026-11-09T10:00:03Z", "Successful"}, |
| + [4]string{"a5", "Launching a new EC2 instance: " + testIID, "2026-11-09T10:00:04Z", "Successful"}, |
| + [4]string{"a6", "Terminating EC2 instance: " + otherIID, "2026-11-09T10:00:05Z", "Successful"}, |
| + [4]string{"a7", "Moving EC2 instance to Standby: " + testIID + "1", "2026-11-09T10:00:06Z", "Successful"}, |
| + [4]string{"a8", "Note: Terminating EC2 instance " + testIID, "2026-11-09T10:00:07Z", "Successful"}, |
| + [4]string{"a9", "Moving EC2 instance out of Standby: " + otherIID, "2026-11-09T10:00:08Z", "Successful"}, |
| + )) |
| + got, err := testAdapter(t, rec).Activities(ctx, testIID) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + base := int64(1794218400000) // 2026-11-09T10:00:00Z |
| + want := []grouproll.Activity{ |
| + {ID: "a1", Kind: "exit", Status: "Successful", Time: base}, |
| + {ID: "a2", Kind: "enter", Status: "InProgress", Time: base + 1500}, |
| + {ID: "a3", Kind: "enter", Status: "", Time: base + 2000}, |
| + {ID: "a4", Kind: "terminate", Status: "Successful", Time: base + 3000}, |
| + } |
| + if !reflect.DeepEqual(got, want) { |
| + t.Fatalf("Activities =\n%+v\nwant\n%+v", got, want) |
| + } |
| + if f := rec.requests()[0].Form; f.Get("AutoScalingGroupName") != testGroup || f.Has("InstanceIds.member.1") { |
| + t.Fatalf("request %v", f) |
| + } |
| + if _, err := testAdapter(t, newRecorder()).Activities(ctx, testIID); uncertainKey(t, err).Key != "api" { |
| + t.Fatalf("failed activities: %v", err) |
| + } |
| +} |
| + |
| +func TestMembership(t *testing.T) { |
| + row := func(iid, state, health string) string { |
| + return `<member><InstanceId>` + iid + `</InstanceId><AutoScalingGroupName>carlos-dev-g</AutoScalingGroupName><AvailabilityZone>eu-west-1a</AvailabilityZone><LifecycleState>` + state + `</LifecycleState><HealthStatus>` + health + `</HealthStatus><LaunchTemplate><LaunchTemplateId>lt-0abc</LaunchTemplateId><LaunchTemplateName>carlos-dev</LaunchTemplateName><Version>7</Version></LaunchTemplate><ProtectedFromScaleIn>false</ProtectedFromScaleIn></member>` |
| + } |
| + wrap := func(rows ...string) string { |
| + return `<DescribeAutoScalingInstancesResponse><DescribeAutoScalingInstancesResult><AutoScalingInstances>` + strings.Join(rows, "") + `</AutoScalingInstances></DescribeAutoScalingInstancesResult></DescribeAutoScalingInstancesResponse>` |
| + } |
| + rec := newRecorder().on("DescribeAutoScalingInstances", wrap(row(testIID, "Pending:Wait", "HEALTHY"))) |
| + got, found, err := testAdapter(t, rec).Membership(ctx, testIID) |
| + if err != nil || !found { |
| + t.Fatal(found, err) |
| + } |
| + want := grouproll.MemberRow{IID: testIID, Group: testGroup, Raw: "Pending:Wait", Phase: grouproll.ReturnHeld, Healthy: true, |
| + Template: map[string]any{"LaunchTemplateId": "lt-0abc", "LaunchTemplateName": "carlos-dev", "Version": "7"}} |
| + if !reflect.DeepEqual(got, want) { |
| + t.Fatalf("Membership = %+v", got) |
| + } |
| + if f := rec.requests()[0].Form; f.Get("InstanceIds.member.1") != testIID || f.Has("InstanceIds.member.2") { |
| + t.Fatalf("request %v", f) |
| + } |
| + got, _, _ = testAdapter(t, newRecorder().on("DescribeAutoScalingInstances", wrap(row(testIID, "InService", "UNHEALTHY")))).Membership(ctx, testIID) |
| + if got.Healthy { |
| + t.Fatal("UNHEALTHY read as healthy") |
| + } |
| + if _, found, err := testAdapter(t, newRecorder().on("DescribeAutoScalingInstances", wrap())).Membership(ctx, testIID); found || err != nil { |
| + t.Fatalf("absent: %v %v", found, err) |
| + } |
| + two := wrap(row(testIID, "InService", "HEALTHY"), row(testIID, "InService", "HEALTHY")) |
| + if _, _, err := testAdapter(t, newRecorder().on("DescribeAutoScalingInstances", two)).Membership(ctx, testIID); refusalKey(t, err) != "api" { |
| + t.Fatalf("two rows: %v", err) |
| + } |
| + if _, _, err := testAdapter(t, newRecorder()).Membership(ctx, testIID); uncertainKey(t, err).Key != "api" { |
| + t.Fatalf("failed membership: %v", err) |
| + } |
| +} |
| + |
| +func instancesXML(owner string, instances ...[2]string) string { |
| + var b strings.Builder |
| + b.WriteString(`<DescribeInstancesResponse xmlns="http://ec2.amazonaws.com/doc/2016-11-15/"><requestId>r</requestId><reservationSet>`) |
| + if len(instances) > 0 { |
| + b.WriteString(`<item><reservationId>r-1</reservationId><ownerId>` + owner + `</ownerId><instancesSet>`) |
| + for _, i := range instances { |
| + b.WriteString(`<item><instanceId>` + i[0] + `</instanceId><instanceState><code>48</code><name>` + i[1] + `</name></instanceState></item>`) |
| + } |
| + b.WriteString(`</instancesSet></item>`) |
| + } |
| + b.WriteString(`</reservationSet></DescribeInstancesResponse>`) |
| + return b.String() |
| +} |
| + |
| +func TestInstanceNotFound(t *testing.T) { |
| + rec := newRecorder().on("DescribeInstances", instancesXML("")) |
| + got, err := testAdapter(t, rec).Instance(ctx, testIID) |
| + if err != nil || got.IID != testIID || got.State != "not-found" { |
| + t.Fatalf("empty: %+v %v", got, err) |
| + } |
| + f := rec.requests()[0].Form |
| + if f.Get("Filter.1.Name") != "instance-id" || f.Get("Filter.1.Value.1") != testIID || f.Has("InstanceId.1") || f.Has("Filter.2.Name") { |
| + t.Fatalf("request %v", f) |
| + } |
| + got, err = testAdapter(t, newRecorder().on("DescribeInstances", instancesXML("123456789012", [2]string{testIID, "terminated"}))).Instance(ctx, testIID) |
| + if err != nil || got.State != "terminated" || got.Describe == nil { |
| + t.Fatalf("terminated: %+v %v", got, err) |
| + } |
| + // An API error is never absence. |
| + if _, err := testAdapter(t, newRecorder()).Instance(ctx, testIID); uncertainKey(t, err).Key != "api" { |
| + t.Fatalf("failed describe: %v", err) |
| + } |
| + if _, err := testAdapter(t, newRecorder().onStatus("DescribeInstances", 400, |
| + `<Response><Errors><Error><Code>InvalidInstanceID.NotFound</Code><Message>x</Message></Error></Errors><RequestID>r</RequestID></Response>`)).Instance(ctx, testIID); uncertainKey(t, err).Key != "api" { |
| + t.Fatalf("NotFound error: %v", err) |
| + } |
| + for name, body := range map[string]string{ |
| + "other owner": instancesXML("999999999999", [2]string{testIID, "running"}), |
| + "two instances": instancesXML("123456789012", [2]string{testIID, "running"}, [2]string{testIID, "running"}), |
| + "other iid": instancesXML("123456789012", [2]string{otherIID, "running"}), |
| + "odd state": instancesXML("123456789012", [2]string{testIID, "rebooting"}), |
| + "next token": strings.Replace(instancesXML(""), "</reservationSet>", "</reservationSet><nextToken>t</nextToken>", 1), |
| + } { |
| + if _, err := testAdapter(t, newRecorder().on("DescribeInstances", body)).Instance(ctx, testIID); refusalKey(t, err) != "api" { |
| + t.Fatalf("%s: %v", name, err) |
| + } |
| + } |
| + rec = newRecorder() |
| + if _, err := testAdapter(t, rec).Instance(ctx, "i-bad"); refusalKey(t, err) != "record" || len(rec.requests()) != 0 { |
| + t.Fatalf("bad iid: %v %v", err, rec.actions()) |
| + } |
| +} |
| + |
| +func templateXML(version, userData string) string { |
| + data := "" |
| + if userData != "" { |
| + data = `<userData>` + userData + `</userData>` |
| + } |
| + return `<DescribeLaunchTemplateVersionsResponse xmlns="http://ec2.amazonaws.com/doc/2016-11-15/"><requestId>r</requestId><launchTemplateVersionSet><item><launchTemplateId>lt-0abc</launchTemplateId><versionNumber>` + version + `</versionNumber><launchTemplateData>` + data + `</launchTemplateData></item></launchTemplateVersionSet></DescribeLaunchTemplateVersionsResponse>` |
| +} |
| + |
| +func TestTemplateRelease(t *testing.T) { |
| + script := "#!/bin/sh\nset -eu\nCARLOS_RELEASE='v0.34.36'\nexport CARLOS_RELEASE\n" |
| + plain := base64.StdEncoding.EncodeToString([]byte(script)) |
| + var z bytes.Buffer |
| + w := gzip.NewWriter(&z) |
| + w.Write([]byte(script)) |
| + w.Close() |
| + zipped := base64.StdEncoding.EncodeToString(z.Bytes()) |
| + tpl := map[string]any{"LaunchTemplateId": "lt-0abc", "LaunchTemplateName": "carlos-dev", "Version": "7"} |
| + |
| + for name, data := range map[string]string{"plain": plain, "gzip": zipped} { |
| + rec := newRecorder().on("DescribeLaunchTemplateVersions", templateXML("7", data)) |
| + got, err := testAdapter(t, rec).TemplateRelease(ctx, tpl) |
| + if err != nil || got != "v0.34.36" { |
| + t.Fatalf("%s: %q %v", name, got, err) |
| + } |
| + f := rec.requests()[0].Form |
| + if f.Get("LaunchTemplateId") != "lt-0abc" || f.Has("LaunchTemplateName") || f.Get("LaunchTemplateVersion.1") != "7" { |
| + t.Fatalf("%s request %v", name, f) |
| + } |
| + } |
| + // Without an id the name is used. |
| + rec := newRecorder().on("DescribeLaunchTemplateVersions", templateXML("7", plain)) |
| + if _, err := testAdapter(t, rec).TemplateRelease(ctx, map[string]any{"LaunchTemplateName": "carlos-dev", "Version": "7"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if f := rec.requests()[0].Form; f.Get("LaunchTemplateName") != "carlos-dev" || f.Has("LaunchTemplateId") { |
| + t.Fatalf("by name: %v", f) |
| + } |
| + |
| + enc := func(s string) string { return base64.StdEncoding.EncodeToString([]byte(s)) } |
| + for name, body := range map[string]string{ |
| + "no line": templateXML("7", enc("#!/bin/sh\n")), |
| + "two lines": templateXML("7", enc("CARLOS_RELEASE='v1.0.0'\nCARLOS_RELEASE='v1.0.1'\n")), |
| + "unquoted": templateXML("7", enc("CARLOS_RELEASE=v1.0.0\n")), |
| + "indented": templateXML("7", enc(" CARLOS_RELEASE='v1.0.0'\n")), |
| + "version": templateXML("8", plain), |
| + "no user data": templateXML("7", ""), |
| + "bad base64": templateXML("7", "!!!!"), |
| + "bad padding": templateXML("7", strings.TrimRight(enc("CARLOS_RELEASE='v1.0.0'\n#"), "=")), |
| + "base64 newline": templateXML("7", plain[:8]+"\n"+plain[8:]), |
| + "not utf-8": templateXML("7", enc("CARLOS_RELEASE='v1.0.0'\n\xff\n")), |
| + "bad gzip": templateXML("7", base64.StdEncoding.EncodeToString([]byte("\x1f\x8bnot gzip"))), |
| + } { |
| + _, err := testAdapter(t, newRecorder().on("DescribeLaunchTemplateVersions", body)).TemplateRelease(ctx, tpl) |
| + if r, ok := err.(grouproll.Refusal); !ok || r.Key != "api" { |
| + t.Fatalf("%s: %v", name, err) |
| + } |
| + } |
| + // A release value may span lines, as the script's [^']* does. |
| + if got, err := testAdapter(t, newRecorder().on("DescribeLaunchTemplateVersions", templateXML("7", enc("x\nCARLOS_RELEASE='v1.0.0'\n")))).TemplateRelease(ctx, tpl); err != nil || got != "v1.0.0" { |
| + t.Fatalf("after a line: %q %v", got, err) |
| + } |
| + for name, bad := range map[string]map[string]any{ |
| + "nil": nil, |
| + "no version": {"LaunchTemplateId": "lt-0abc"}, |
| + "int": {"LaunchTemplateId": "lt-0abc", "Version": 7}, |
| + } { |
| + rec := newRecorder() |
| + if _, err := testAdapter(t, rec).TemplateRelease(ctx, bad); refusalKey(t, err) != "scope" || len(rec.requests()) != 0 { |
| + t.Fatalf("%s: %v", name, err) |
| + } |
| + } |
| + if _, err := testAdapter(t, newRecorder()).TemplateRelease(ctx, tpl); uncertainKey(t, err).Key != "api" { |
| + t.Fatalf("failed describe: %v", err) |
| + } |
| +} |
| + |
| +const updateOK = `<UpdateAutoScalingGroupResponse><ResponseMetadata><RequestId>r</RequestId></ResponseMetadata></UpdateAutoScalingGroupResponse>` |
| + |
| +func standbyXML(ids ...string) string { |
| + var b strings.Builder |
| + b.WriteString(`<EnterStandbyResponse><EnterStandbyResult><Activities>`) |
| + for _, id := range ids { |
| + b.WriteString(`<member><ActivityId>` + id + `</ActivityId><AutoScalingGroupName>carlos-dev-g</AutoScalingGroupName><Cause>c</Cause><StartTime>2026-11-09T10:00:00Z</StartTime><StatusCode>InProgress</StatusCode><Description>Moving EC2 instance to Standby: ` + testIID + `</Description></member>`) |
| + } |
| + b.WriteString(`</Activities></EnterStandbyResult></EnterStandbyResponse>`) |
| + return b.String() |
| +} |
| + |
| +func TestWriteShapes(t *testing.T) { |
| + t.Run("park", func(t *testing.T) { |
| + rec := newRecorder().on("EnterStandby", standbyXML("act-1")) |
| + r, err := testAdapter(t, rec).Park(ctx, testIID) |
| + if err != nil || r.Activity != "act-1" || r.Uncertain { |
| + t.Fatalf("Park = %+v %v", r, err) |
| + } |
| + q := rec.requests() |
| + if len(q) != 1 || q[0].Action != "EnterStandby" { |
| + t.Fatalf("requests %v", rec.actions()) |
| + } |
| + f := q[0].Form |
| + if f.Get("ShouldDecrementDesiredCapacity") != "true" || f.Get("InstanceIds.member.1") != testIID || |
| + f.Has("InstanceIds.member.2") || f.Get("AutoScalingGroupName") != testGroup { |
| + t.Fatalf("EnterStandby form %v", f) |
| + } |
| + for _, body := range []string{standbyXML(), standbyXML("a", "b"), standbyXML("")} { |
| + r, err := testAdapter(t, newRecorder().on("EnterStandby", body)).Park(ctx, testIID) |
| + if err != nil || !r.Uncertain || r.Activity != "" || r.Response == nil { |
| + t.Fatalf("uncertain success: %+v %v", r, err) |
| + } |
| + } |
| + if _, err := testAdapter(t, newRecorder()).Park(ctx, testIID); uncertainKey(t, err).Key != "api" { |
| + t.Fatalf("failed park: %v", err) |
| + } |
| + rec = newRecorder() |
| + if _, err := testAdapter(t, rec).Park(ctx, "i-bad"); refusalKey(t, err) != "record" || len(rec.requests()) != 0 { |
| + t.Fatalf("bad iid: %v", err) |
| + } |
| + }) |
| + t.Run("unpark", func(t *testing.T) { |
| + exit := strings.NewReplacer("EnterStandby", "ExitStandby", "to Standby", "out of Standby").Replace(standbyXML("act-2")) |
| + rec := newRecorder().on("ExitStandby", exit) |
| + r, err := testAdapter(t, rec).Unpark(ctx, testIID) |
| + if err != nil || r.Activity != "act-2" { |
| + t.Fatalf("Unpark = %+v %v", r, err) |
| + } |
| + f := rec.requests()[0].Form |
| + if f.Get("Action") != "ExitStandby" || f.Get("InstanceIds.member.1") != testIID || f.Has("InstanceIds.member.2") || f.Get("AutoScalingGroupName") != testGroup { |
| + t.Fatalf("ExitStandby form %v", f) |
| + } |
| + }) |
| + t.Run("terminate", func(t *testing.T) { |
| + term := `<TerminateInstanceInAutoScalingGroupResponse><TerminateInstanceInAutoScalingGroupResult><Activity><ActivityId>act-3</ActivityId><AutoScalingGroupName>carlos-dev-g</AutoScalingGroupName><Cause>c</Cause><StartTime>2026-11-09T10:00:00Z</StartTime><StatusCode>InProgress</StatusCode></Activity></TerminateInstanceInAutoScalingGroupResult></TerminateInstanceInAutoScalingGroupResponse>` |
| + parked := groupXML(1, 1, 2, [][2]string{{otherIID, "InService"}, {testIID, "Standby"}}) |
| + rec := newRecorder().on("DescribeAutoScalingGroups", parked).on("TerminateInstanceInAutoScalingGroup", term) |
| + r, err := testAdapter(t, rec).Terminate(ctx, testIID) |
| + if err != nil || r.Activity != "act-3" || r.Uncertain { |
| + t.Fatalf("Terminate = %+v %v", r, err) |
| + } |
| + if got := rec.actions(); !reflect.DeepEqual(got, []string{"DescribeAutoScalingGroups", "TerminateInstanceInAutoScalingGroup"}) { |
| + t.Fatalf("actions %v", got) |
| + } |
| + f := rec.requests()[1].Form |
| + if f.Get("ShouldDecrementDesiredCapacity") != "false" || f.Get("InstanceId") != testIID { |
| + t.Fatalf("terminate form %v", f) |
| + } |
| + noActivity := `<TerminateInstanceInAutoScalingGroupResponse><TerminateInstanceInAutoScalingGroupResult/></TerminateInstanceInAutoScalingGroupResponse>` |
| + r, err = testAdapter(t, newRecorder().on("DescribeAutoScalingGroups", parked).on("TerminateInstanceInAutoScalingGroup", noActivity)).Terminate(ctx, testIID) |
| + if err != nil || !r.Uncertain || r.Response == nil { |
| + t.Fatalf("uncertain success: %+v %v", r, err) |
| + } |
| + // H4: a fresh describe must show the member Standby and desired == minimum. |
| + for name, body := range map[string]string{ |
| + "in service": groupXML(1, 1, 2, [][2]string{{otherIID, "InService"}, {testIID, "InService"}}), |
| + "entering standby": groupXML(1, 1, 2, [][2]string{{otherIID, "InService"}, {testIID, "EnteringStandby"}}), |
| + "absent": groupXML(1, 1, 2, [][2]string{{otherIID, "InService"}}), |
| + "desired above min": groupXML(1, 2, 2, [][2]string{{otherIID, "InService"}, {testIID, "Standby"}}), |
| + "desired below min": groupXML(2, 1, 2, [][2]string{{otherIID, "InService"}, {testIID, "Standby"}}), |
| + } { |
| + rec := newRecorder().on("DescribeAutoScalingGroups", body).on("TerminateInstanceInAutoScalingGroup", term) |
| + if _, err := testAdapter(t, rec).Terminate(ctx, testIID); refusalKey(t, err) != "h4" { |
| + t.Fatalf("%s: %v", name, err) |
| + } |
| + if got := rec.actions(); !reflect.DeepEqual(got, []string{"DescribeAutoScalingGroups"}) { |
| + t.Fatalf("%s: actions %v", name, got) |
| + } |
| + } |
| + rec = newRecorder() |
| + if _, err := testAdapter(t, rec).Terminate(ctx, "i-bad"); refusalKey(t, err) != "h4" || len(rec.requests()) != 0 { |
| + t.Fatalf("bad iid: %v", err) |
| + } |
| + // A failed fresh describe sends nothing. |
| + rec = newRecorder().on("TerminateInstanceInAutoScalingGroup", term) |
| + if _, err := testAdapter(t, rec).Terminate(ctx, testIID); uncertainKey(t, err).Key != "api" || len(rec.requests()) != 1 { |
| + t.Fatalf("failed describe: %v %v", err, rec.actions()) |
| + } |
| + }) |
| + t.Run("raise desired", func(t *testing.T) { |
| + g := groupXML(1, 2, 4, [][2]string{{otherIID, "InService"}, {testIID, "InService"}}) |
| + for _, n := range []int{2, 3, 4} { |
| + rec := newRecorder().on("DescribeAutoScalingGroups", g).on("UpdateAutoScalingGroup", updateOK) |
| + r, err := testAdapter(t, rec).RaiseDesired(ctx, n) |
| + if err != nil || r.Uncertain { |
| + t.Fatalf("RaiseDesired(%d) = %+v %v", n, r, err) |
| + } |
| + if got := rec.actions(); !reflect.DeepEqual(got, []string{"DescribeAutoScalingGroups", "UpdateAutoScalingGroup"}) { |
| + t.Fatalf("actions %v", got) |
| + } |
| + f := rec.requests()[1].Form |
| + if f.Get("DesiredCapacity") != itoa(n) || f.Get("AutoScalingGroupName") != testGroup || f.Has("MinSize") || f.Has("MaxSize") { |
| + t.Fatalf("update form %v", f) |
| + } |
| + } |
| + for _, n := range []int{-1, 0, 1, 5} { |
| + rec := newRecorder().on("DescribeAutoScalingGroups", g).on("UpdateAutoScalingGroup", updateOK) |
| + if _, err := testAdapter(t, rec).RaiseDesired(ctx, n); refusalKey(t, err) != "h4" { |
| + t.Fatalf("RaiseDesired(%d): %v", n, err) |
| + } |
| + if got := rec.actions(); !reflect.DeepEqual(got, []string{"DescribeAutoScalingGroups"}) { |
| + t.Fatalf("RaiseDesired(%d) actions %v", n, got) |
| + } |
| + } |
| + }) |
| + t.Run("set minimum", func(t *testing.T) { |
| + rec := newRecorder().on("UpdateAutoScalingGroup", updateOK) |
| + r, err := testAdapter(t, rec).SetMinimum(ctx, 1) |
| + if err != nil || r.Uncertain { |
| + t.Fatalf("SetMinimum = %+v %v", r, err) |
| + } |
| + f := rec.requests()[0].Form |
| + if f.Get("MinSize") != "1" || f.Get("AutoScalingGroupName") != testGroup || f.Has("DesiredCapacity") || f.Has("MaxSize") { |
| + t.Fatalf("update form %v", f) |
| + } |
| + if _, err := testAdapter(t, newRecorder()).SetMinimum(ctx, 1); uncertainKey(t, err).Key != "api" { |
| + t.Fatalf("failed update: %v", err) |
| + } |
| + rec = newRecorder() |
| + if _, err := testAdapter(t, rec).SetMinimum(ctx, -1); err == nil || len(rec.requests()) != 0 { |
| + t.Fatalf("negative minimum: %v", err) |
| + } |
| + }) |
| + t.Run("no method lowers desired", func(t *testing.T) { |
| + // The adapter's exported methods are exactly the reviewed set: a new |
| + // write path (one that could lower desired) fails here until reviewed. |
| + var names []string |
| + typ := reflect.TypeOf(&Adapter{}) |
| + for i := 0; i < typ.NumMethod(); i++ { |
| + names = append(names, typ.Method(i).Name) |
| + } |
| + sort.Strings(names) |
| + want := []string{"Activities", "CallerIdentity", "Describe", "Hook", "Instance", "Membership", "Online", |
| + "Park", "RaiseDesired", "SetMinimum", "Targets", "TemplateRelease", "Terminate", "Unpark"} |
| + if !reflect.DeepEqual(names, want) { |
| + t.Fatalf("Adapter methods = %v\nwant %v", names, want) |
| + } |
| + }) |
| +} |
| + |
| +func TestCallerIdentity(t *testing.T) { |
| + body := `<GetCallerIdentityResponse xmlns="https://sts.amazonaws.com/doc/2011-06-15/"><GetCallerIdentityResult><Arn>arn:aws:sts::123456789012:assumed-role/op/roll</Arn><UserId>AROAEXAMPLE:roll</UserId><Account>123456789012</Account></GetCallerIdentityResult><ResponseMetadata><RequestId>r</RequestId></ResponseMetadata></GetCallerIdentityResponse>` |
| + rec := newRecorder().on("GetCallerIdentity", body) |
| + user, arn, err := testAdapter(t, rec).CallerIdentity(ctx) |
| + if err != nil || user != "AROAEXAMPLE:roll" || arn != "arn:aws:sts::123456789012:assumed-role/op/roll" { |
| + t.Fatalf("CallerIdentity = %q %q %v", user, arn, err) |
| + } |
| + q := rec.requests() |
| + if len(q) != 1 || q[0].Host != "sts.eu-west-1.amazonaws.com" || q[0].Action != "GetCallerIdentity" { |
| + t.Fatalf("requests %+v", q) |
| + } |
| + if _, _, err := testAdapter(t, newRecorder()).CallerIdentity(ctx); uncertainKey(t, err).Key != "api" { |
| + t.Fatalf("failed call: %v", err) |
| + } |
| + noUser := strings.Replace(body, "<UserId>AROAEXAMPLE:roll</UserId>", "", 1) |
| + if _, _, err := testAdapter(t, newRecorder().on("GetCallerIdentity", noUser)).CallerIdentity(ctx); uncertainKey(t, err).Key != "api" { |
| + t.Fatalf("no UserId: %v", err) |
| + } |
| +} |
diff --git a/internal/grouprollaws/phase.go b/internal/grouprollaws/phase.go| new file mode 100644 |
| index 000000000..f6cbc165b |
| --- /dev/null |
| +++ b/internal/grouprollaws/phase.go |
| @@ -0,0 +1,30 @@ |
| +package grouprollaws |
| + |
| +import ( |
| + "strings" |
| + |
| + "github.com/carlosframework/platform/internal/grouproll" |
| +) |
| + |
| +// MapPhase maps an Auto Scaling LifecycleState to exactly one phase (spec |
| +// §5.2). The table is total: a state it does not list is Unknown, which the |
| +// core refuses as unknown_phase. Absent is never a state; it is a member the |
| +// group does not list. |
| +func MapPhase(state string) grouproll.Phase { |
| + switch state { |
| + case "InService": |
| + return grouproll.Serving |
| + case "EnteringStandby": |
| + return grouproll.Parking |
| + case "Standby": |
| + return grouproll.Parked |
| + case "Pending", "PreInService", "Pending:Proceed": |
| + return grouproll.Returning |
| + case "Pending:Wait": |
| + return grouproll.ReturnHeld |
| + } |
| + if strings.HasPrefix(state, "Terminat") { |
| + return grouproll.Leaving |
| + } |
| + return grouproll.Unknown |
| +} |
diff --git a/internal/grouprollaws/phase_test.go b/internal/grouprollaws/phase_test.go| new file mode 100644 |
| index 000000000..ea62da637 |
| --- /dev/null |
| +++ b/internal/grouprollaws/phase_test.go |
| @@ -0,0 +1,40 @@ |
| +package grouprollaws |
| + |
| +import ( |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/grouproll" |
| +) |
| + |
| +// TestMapPhaseTotal pins spec §5.2's table: each Auto Scaling lifecycle state |
| +// maps to exactly one phase, and anything unlisted is Unknown. |
| +func TestMapPhaseTotal(t *testing.T) { |
| + cases := map[string]grouproll.Phase{ |
| + "InService": grouproll.Serving, |
| + "EnteringStandby": grouproll.Parking, |
| + "Standby": grouproll.Parked, |
| + "Pending": grouproll.Returning, |
| + "PreInService": grouproll.Returning, |
| + "Pending:Proceed": grouproll.Returning, |
| + "Pending:Wait": grouproll.ReturnHeld, |
| + "Terminating": grouproll.Leaving, |
| + "Terminating:Wait": grouproll.Leaving, |
| + "Terminating:Proceed": grouproll.Leaving, |
| + "Terminated": grouproll.Leaving, |
| + "Terminating:Retained": grouproll.Leaving, |
| + "Warmed:Pending": grouproll.Unknown, |
| + "Warmed:Running": grouproll.Unknown, |
| + "Warmed:Hibernated": grouproll.Unknown, |
| + "Detaching": grouproll.Unknown, |
| + "Detached": grouproll.Unknown, |
| + "": grouproll.Unknown, |
| + "inservice": grouproll.Unknown, |
| + "Standby ": grouproll.Unknown, |
| + "terminating": grouproll.Unknown, |
| + } |
| + for state, want := range cases { |
| + if got := MapPhase(state); got != want { |
| + t.Errorf("MapPhase(%q) = %q, want %q", state, got, want) |
| + } |
| + } |
| +} |
diff --git a/internal/grouprollaws/recorder_test.go b/internal/grouprollaws/recorder_test.go| new file mode 100644 |
| index 000000000..31fc38021 |
| --- /dev/null |
| +++ b/internal/grouprollaws/recorder_test.go |
| @@ -0,0 +1,186 @@ |
| +package grouprollaws |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "io" |
| + "net/http" |
| + "net/url" |
| + "strconv" |
| + "strings" |
| + "sync" |
| + "testing" |
| + |
| + "github.com/aws/aws-sdk-go-v2/aws" |
| + "github.com/aws/aws-sdk-go-v2/credentials" |
| + |
| + "github.com/carlosframework/platform/internal/grouproll" |
| +) |
| + |
| +// recorded is one request the SDK tried to send. Nothing leaves the process: |
| +// the recorder is the clients' HTTP client. |
| +type recorded struct { |
| + Host string |
| + Action string // query Action, or the JSON X-Amz-Target operation |
| + Form url.Values |
| + JSON map[string]any |
| + Auth string |
| +} |
| + |
| +type canned struct { |
| + status int |
| + body string |
| +} |
| + |
| +// recorder records every request and answers from canned bodies keyed by |
| +// action. An action without a canned body answers 500 (an API failure). |
| +type recorder struct { |
| + mu sync.Mutex |
| + reqs []recorded |
| + responses map[string][]canned |
| +} |
| + |
| +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) } |
| + |
| +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}) |
| + return r |
| +} |
| + |
| +func (r *recorder) Do(req *http.Request) (*http.Response, error) { |
| + var body []byte |
| + if req.Body != nil { |
| + body, _ = io.ReadAll(req.Body) |
| + } |
| + rec := recorded{Host: req.URL.Host, Auth: req.Header.Get("Authorization")} |
| + contentType := "text/xml" |
| + if target := req.Header.Get("X-Amz-Target"); target != "" { |
| + rec.Action = target[strings.LastIndex(target, ".")+1:] |
| + _ = json.Unmarshal(body, &rec.JSON) |
| + contentType = "application/x-amz-json-1.1" |
| + } else { |
| + rec.Form, _ = url.ParseQuery(string(body)) |
| + rec.Action = rec.Form.Get("Action") |
| + } |
| + r.mu.Lock() |
| + r.reqs = append(r.reqs, rec) |
| + queue := r.responses[rec.Action] |
| + answer := canned{500, ""} |
| + if len(queue) > 0 { |
| + answer = queue[0] |
| + if len(queue) > 1 { |
| + r.responses[rec.Action] = queue[1:] |
| + } |
| + } |
| + r.mu.Unlock() |
| + if answer.status != 200 && answer.body == "" { |
| + if contentType == "text/xml" { |
| + answer.body = `<ErrorResponse><Error><Type>Receiver</Type><Code>InternalFailure</Code><Message>x</Message></Error><RequestId>r</RequestId></ErrorResponse>` |
| + } else { |
| + answer.body = `{"__type":"InternalServerError","message":"x"}` |
| + } |
| + } |
| + return &http.Response{ |
| + StatusCode: answer.status, |
| + Status: http.StatusText(answer.status), |
| + Header: http.Header{"Content-Type": []string{contentType}, "X-Amzn-Requestid": []string{"r"}}, |
| + Body: io.NopCloser(bytes.NewReader([]byte(answer.body))), |
| + Request: req, |
| + }, nil |
| +} |
| + |
| +func (r *recorder) requests() []recorded { |
| + r.mu.Lock() |
| + defer r.mu.Unlock() |
| + return append([]recorded(nil), r.reqs...) |
| +} |
| + |
| +func (r *recorder) actions() []string { |
| + var out []string |
| + for _, q := range r.requests() { |
| + out = append(out, q.Action) |
| + } |
| + return out |
| +} |
| + |
| +const ( |
| + testIID = "i-0123456789abcdef0" |
| + otherIID = "i-0fedcba9876543210" |
| + thirdIID = "i-00000000000000003" |
| + testGroup = "carlos-dev-g" |
| + testARN = "arn:aws:autoscaling:eu-west-1:123456789012:autoScalingGroup:11111111-2222-3333-4444-555555555555:autoScalingGroupName/carlos-dev-g" |
| + testTG = "arn:aws:elasticloadbalancing:eu-west-1:123456789012:targetgroup/edge/0123456789abcdef" |
| +) |
| + |
| +func testConfig() grouproll.Config { |
| + return grouproll.Config{ |
| + Deployment: "dev", Account: "123456789012", Region: "eu-west-1", Group: testGroup, |
| + GroupARN: testARN, Hook: "carlos-launch", TargetGroups: []string{testTG}, |
| + Bucket: "carlos-dev-store", Document: "carlos-group-roll", Profile: "op", |
| + } |
| +} |
| + |
| +// 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() |
| + cfg := aws.Config{ |
| + Region: "eu-west-1", |
| + Credentials: credentials.NewStaticCredentialsProvider("AKIATEST", "secret", ""), |
| + HTTPClient: rec, |
| + RetryMaxAttempts: 1, |
| + } |
| + return newAdapter(cfg, testConfig()) |
| +} |
| + |
| +func refusalKey(t *testing.T, err error) string { |
| + t.Helper() |
| + r, ok := err.(grouproll.Refusal) |
| + if !ok { |
| + t.Fatalf("error %T %v, want a Refusal", err, err) |
| + } |
| + return r.Key |
| +} |
| + |
| +func uncertainKey(t *testing.T, err error) grouproll.Uncertain { |
| + t.Helper() |
| + u, ok := err.(grouproll.Uncertain) |
| + if !ok { |
| + t.Fatalf("error %T %v, want an Uncertain", err, err) |
| + } |
| + return u |
| +} |
| + |
| +var ctx = context.Background() |
| + |
| +// groupXML is a DescribeAutoScalingGroups answer. members is iid -> state; |
| +// every member is Healthy unless named in unhealthy. |
| +func groupXML(min, desired, max int, members [][2]string, unhealthy ...string) string { |
| + var b strings.Builder |
| + b.WriteString(`<DescribeAutoScalingGroupsResponse xmlns="http://autoscaling.amazonaws.com/doc/2011-01-01/"><DescribeAutoScalingGroupsResult><AutoScalingGroups><member>`) |
| + b.WriteString(`<AutoScalingGroupName>` + testGroup + `</AutoScalingGroupName><AutoScalingGroupARN>` + testARN + `</AutoScalingGroupARN>`) |
| + b.WriteString(`<MinSize>` + itoa(min) + `</MinSize><DesiredCapacity>` + itoa(desired) + `</DesiredCapacity><MaxSize>` + itoa(max) + `</MaxSize>`) |
| + b.WriteString(`<Instances>`) |
| + for _, m := range members { |
| + health := "Healthy" |
| + for _, u := range unhealthy { |
| + if u == m[0] { |
| + health = "Unhealthy" |
| + } |
| + } |
| + b.WriteString(`<member><InstanceId>` + m[0] + `</InstanceId><LifecycleState>` + m[1] + `</LifecycleState><HealthStatus>` + health + `</HealthStatus></member>`) |
| + } |
| + b.WriteString(`</Instances><TargetGroupARNs><member>` + testTG + `</member></TargetGroupARNs>`) |
| + b.WriteString(`<LaunchTemplate><LaunchTemplateId>lt-0abc</LaunchTemplateId><LaunchTemplateName>carlos-dev</LaunchTemplateName><Version>7</Version></LaunchTemplate>`) |
| + b.WriteString(`<Tags><member><Key>carlos:deployment</Key><Value>dev</Value></member><member><Key>other</Key><Value>x</Value></member></Tags>`) |
| + b.WriteString(`</member></AutoScalingGroups></DescribeAutoScalingGroupsResult><ResponseMetadata><RequestId>r</RequestId></ResponseMetadata></DescribeAutoScalingGroupsResponse>`) |
| + return b.String() |
| +} |
| + |
| +func itoa(n int) string { return strconv.Itoa(n) } |
diff --git a/region_ha_boundary_test.go b/region_ha_boundary_test.go| index ed89fe974..f85674658 100644 |
| --- a/region_ha_boundary_test.go |
| +++ b/region_ha_boundary_test.go |
| @@ -48,6 +48,7 @@ var regionHACoreFiles = []string{ |
| "internal/grouproll/state_other.go", |
| "internal/grouproll/text.go", |
| "internal/grouproll/box.go", |
| + "internal/grouproll/provider.go", |
| } |
| // regionHAAdapterFiles are spec 2's AWS adapters. Each is named for AWS so |
| @@ -56,6 +57,9 @@ var regionHAAdapterFiles = []string{ |
| "internal/host/awsaddr.go", |
| "internal/console/awsregionmetric.go", |
| "internal/hostenv/awsssm.go", |
| + "internal/grouprollaws/config.go", |
| + "internal/grouprollaws/group.go", |
| + "internal/grouprollaws/phase.go", |
| } |
| // regionHAPackages are the packages spec 2 touches. Every S3 client built |