diff --git a/cmd/aws.go b/cmd/aws.go index 4259f07f..55180efa 100644 --- a/cmd/aws.go +++ b/cmd/aws.go @@ -46,6 +46,8 @@ Supported environment variables: AWS_ENDPOINT_URL Same as LSTK_ENDPOINT_URL (lower precedence if both are set) AWS_ACCESS_KEY_ID Fallback for --account +lstk aws only targets LocalStack: it refuses a --profile other than localstack, and an --endpoint-url that points at an AWS domain or at an IP address without a port, before running the AWS CLI. + Run 'lstk setup aws' to configure the LocalStack AWS profile for use with CLI and SDKs. Tab completion of AWS services, operations and parameters comes from the AWS CLI itself, and is enabled by 'lstk completion ' along with the rest of lstk's completion. @@ -145,6 +147,11 @@ Examples: return emitValidationError(sink, err) } + // Checked before the help short-circuit too, so the rule has no exceptions. + if refused, ok := awscli.FindRealAWSOption(awsArgs); ok { + return emitRealAWSOptionError(sink, refused) + } + // --help/-h never contacts LocalStack, so it runs directly without // requiring Docker or a running emulator (DEVX-1002). if awscli.IsHelp(awsArgs) { @@ -228,3 +235,34 @@ Examples: }, } } + +func emitRealAWSOptionError(sink output.Sink, refused awscli.RefusedOption) error { + var ev output.ErrorEvent + if refused.Option == "--profile" { + ev = output.ErrorEvent{ + Title: "only --profile localstack is supported: lstk aws only targets LocalStack, and another profile can sign with real AWS credentials", + Actions: []output.ErrorAction{ + {Label: "Select a LocalStack account:", Value: "lstk aws --account <12-digit id> ..."}, + {Label: "Configure the LocalStack AWS profile:", Value: "lstk setup aws"}, + }, + } + } else if refused.NoPort { + ev = output.ErrorEvent{ + Title: fmt.Sprintf("--endpoint-url needs a port for an IP address (%s): lstk aws only targets LocalStack", refused.Host), + Actions: []output.ErrorAction{ + {Label: "Add the emulator's port:", Value: "--endpoint-url http://:4566"}, + {Label: "Use the emulator lstk found:", Value: "remove --endpoint-url"}, + }, + } + } else { + ev = output.ErrorEvent{ + Title: fmt.Sprintf("--endpoint-url points at real AWS (%s): lstk aws only targets LocalStack", refused.Host), + Actions: []output.ErrorAction{ + {Label: "Use the emulator lstk found:", Value: "remove --endpoint-url"}, + {Label: "Target another emulator:", Value: "lstk --endpoint-url aws ..."}, + }, + } + } + sink.Emit(ev) + return output.NewSilentError(fmt.Errorf("refused %s", refused.Option)) +} diff --git a/internal/awscli/realaws.go b/internal/awscli/realaws.go new file mode 100644 index 00000000..4fb6be04 --- /dev/null +++ b/internal/awscli/realaws.go @@ -0,0 +1,91 @@ +package awscli + +import ( + "net" + "net/url" + "strings" + + "github.com/localstack/lstk/internal/awsconfig" +) + +// awsDNSSuffixes are the DNS suffixes of AWS's partitions (botocore's partition +// data), including the dual-stack api.aws domain. A fixed list rather than the +// user's botocore install: lstk must not depend on which aws CLI is present. +var awsDNSSuffixes = []string{ + "amazonaws.com", + "amazonaws.com.cn", + "api.aws", + "amazonaws.eu", + "c2s.ic.gov", + "sc2s.sgov.gov", + "cloud.adc-e.uk", + "csp.hci.ic.gov", +} + +// RefusedOption is an AWS CLI option lstk refuses to forward because it can send +// the call to real AWS (DEVX-1345). +type RefusedOption struct { + // Option is the canonical name, "--endpoint-url" or "--profile". + Option string + // Host is the host an --endpoint-url pointed at; empty for --profile. + Host string + // NoPort marks an --endpoint-url refused for being an IP address without a + // port, rather than an AWS domain. + NoPort bool +} + +// FindRealAWSOption returns the first argument that would make the AWS CLI talk +// to real AWS: an --endpoint-url whose host is an AWS domain or an IP address +// without a port, or a --profile other than the localstack one `lstk setup aws` +// writes. +// +// The CLI accepts any prefix of a global option name (`--endp`, `--p=prod`), and +// its global options win over a command's own when abbreviated, so every `--` +// prefix of those two names counts, in both `--opt value` and `--opt=value` +// forms, anywhere in args. Other hosts, and values without a host, are left to +// the CLI. +func FindRealAWSOption(args []string) (RefusedOption, bool) { + for i, arg := range args { + name, value, hasValue := strings.Cut(strings.TrimPrefix(arg, "--"), "=") + if !strings.HasPrefix(arg, "--") || name == "" { + continue + } + if !hasValue && i+1 < len(args) { + value = args[i+1] + } + switch { + case strings.HasPrefix("profile", name): + if value != awsconfig.ProfileName { + return RefusedOption{Option: "--profile"}, true + } + case strings.HasPrefix("endpoint-url", name): + if refused, ok := refuseEndpoint(value); ok { + return refused, true + } + } + } + return RefusedOption{}, false +} + +// refuseEndpoint reports an endpoint whose host is an AWS domain or a subdomain +// of one, or an IP address without an explicit port. A value without a scheme +// has no host here; the AWS CLI rejects it before sending anything. +func refuseEndpoint(endpoint string) (RefusedOption, bool) { + u, err := url.Parse(endpoint) + if err != nil { + return RefusedOption{}, false + } + host := strings.TrimSuffix(strings.ToLower(u.Hostname()), ".") + if net.ParseIP(host) != nil { + if u.Port() == "" { + return RefusedOption{Option: "--endpoint-url", Host: host, NoPort: true}, true + } + return RefusedOption{}, false + } + for _, suffix := range awsDNSSuffixes { + if host == suffix || strings.HasSuffix(host, "."+suffix) { + return RefusedOption{Option: "--endpoint-url", Host: host}, true + } + } + return RefusedOption{}, false +} diff --git a/internal/awscli/realaws_test.go b/internal/awscli/realaws_test.go new file mode 100644 index 00000000..79607147 --- /dev/null +++ b/internal/awscli/realaws_test.go @@ -0,0 +1,45 @@ +package awscli + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestFindRealAWSOption(t *testing.T) { + tests := []struct { + name string + args []string + want RefusedOption + ok bool + }{ + {"aws host", []string{"--endpoint-url", "https://sqs.us-east-1.amazonaws.com"}, RefusedOption{Option: "--endpoint-url", Host: "sqs.us-east-1.amazonaws.com"}, true}, + {"bare partition domain", []string{"--endpoint-url=https://amazonaws.com"}, RefusedOption{Option: "--endpoint-url", Host: "amazonaws.com"}, true}, + {"trailing dot", []string{"--endpoint-url", "https://s3.amazonaws.com."}, RefusedOption{Option: "--endpoint-url", Host: "s3.amazonaws.com"}, true}, + {"european sovereign cloud", []string{"--endpoint-url", "https://s3.eusc-de-east-1.amazonaws.eu"}, RefusedOption{Option: "--endpoint-url", Host: "s3.eusc-de-east-1.amazonaws.eu"}, true}, + {"isolated partition", []string{"--endpoint-url", "https://s3.us-iso-east-1.c2s.ic.gov"}, RefusedOption{Option: "--endpoint-url", Host: "s3.us-iso-east-1.c2s.ic.gov"}, true}, + {"single letter prefix", []string{"--e", "https://s3.amazonaws.com"}, RefusedOption{Option: "--endpoint-url", Host: "s3.amazonaws.com"}, true}, + {"profile", []string{"s3", "ls", "--profile", "prod"}, RefusedOption{Option: "--profile"}, true}, + {"other profile name case", []string{"--profile", "LocalStack"}, RefusedOption{Option: "--profile"}, true}, + {"ip address without port", []string{"--endpoint-url", "http://52.94.0.1"}, RefusedOption{Option: "--endpoint-url", Host: "52.94.0.1", NoPort: true}, true}, + {"ipv6 address without port", []string{"--endpoint-url", "https://[2600:1f18::1]"}, RefusedOption{Option: "--endpoint-url", Host: "2600:1f18::1", NoPort: true}, true}, + {"first refusal wins", []string{"--p", "x", "--endpoint-url", "https://s3.amazonaws.com"}, RefusedOption{Option: "--profile"}, true}, + + {"no options", []string{"s3", "ls"}, RefusedOption{}, false}, + {"localstack profile", []string{"s3", "ls", "--profile", "localstack"}, RefusedOption{}, false}, + {"localstack profile with equals", []string{"--p=localstack", "s3", "ls"}, RefusedOption{}, false}, + {"localstack profile then another", []string{"--profile", "localstack", "--profile", "prod"}, RefusedOption{Option: "--profile"}, true}, + {"bare double dash", []string{"--", "s3", "ls"}, RefusedOption{}, false}, + {"localhost", []string{"--endpoint-url", "http://localhost.localstack.cloud:4566"}, RefusedOption{}, false}, + {"ip address with port", []string{"--endpoint-url", "http://52.94.0.1:4566"}, RefusedOption{}, false}, + {"ipv6 address with port", []string{"--endpoint-url", "http://[::1]:4566"}, RefusedOption{}, false}, + {"lookalike suffix", []string{"--endpoint-url", "https://evilamazonaws.com"}, RefusedOption{}, false}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + got, ok := FindRealAWSOption(tc.args) + assert.Equal(t, tc.ok, ok) + assert.Equal(t, tc.want, got) + }) + } +} diff --git a/openspec/changes/refuse-real-aws-options/design.md b/openspec/changes/refuse-real-aws-options/design.md new file mode 100644 index 00000000..e22fa14b --- /dev/null +++ b/openspec/changes/refuse-real-aws-options/design.md @@ -0,0 +1,83 @@ +## Context + +`lstk aws` runs the AWS CLI with `--endpoint-url ` and LocalStack credentials in the environment. Two caller options undo that: + +- A caller's own `--endpoint-url` overrides lstk's. `external-endpoint` forwards it on purpose, so plain `aws --endpoint-url` habits keep working. +- A caller's `--profile` replaces lstk's credentials (`aws-proxy` specifies that it wins). A real profile can then run `credential_process`, refresh SSO tokens or call STS AssumeRole, all against real AWS. + +The MCP server (DEVX-1330) blocks both itself before calling `lstk aws`. Doing it in lstk covers every caller. + +Measured with AWS CLI 2.42.3: the CLI's global options win over a command's own when abbreviated. `--e`, `--en` and `--e=…` resolve to `--endpoint-url` before or after the operation, and `--p`/`--pro` resolve to `--profile` even in `s3api list-objects-v2`, which has its own `--prefix`. Only `--pre` reaches `--prefix`. + +## Goals / Non-Goals + +**Goals:** + +- Refuse the documented ways a caller's options send an `lstk aws` call to real AWS, with an error that says why and what to do instead. +- Keep `--endpoint-url` working for LocalStack under any hostname. + +**Non-Goals:** + +- A hard guarantee (see "Proxy considered" below). +- Aliases in `~/.aws/cli/alias`; `az`, `terraform`, `cdk`, `sam`. + +## Decisions + +### A guardrail, not a guarantee + +The ideal is that no request from `lstk aws` can reach AWS. Only a network-level control gets close to that, and even it leaves gaps (see below). Refusing the known options covers the cases the ticket found, with a clear message, at little cost. The rest is left to a follow-up. + +### Refuse `--endpoint-url` only when it points at AWS + +Allowing only the endpoint lstk resolved would break callers who run LocalStack under another hostname. So the rule is a denylist: a host equal to, or a subdomain of, an AWS partition DNS suffix is refused, and anything else passes through. The suffixes come from botocore's partition data and are kept as a fixed list in `internal/awscli`, so the check doesn't depend on which CLI is installed. An IP address is allowed only with an explicit port: a bare IP could be an AWS address, while an emulator is always reached on a port such as 4566. Values the CLI rejects itself are left to it rather than duplicated in lstk: a value without a scheme (`s3.amazonaws.com`, `52.94.0.1`), and an empty or missing one. Measured with AWS CLI 2.42.3, each fails before any request (`Bad value for --endpoint-url "…": scheme is missing` or `Invalid endpoint: …`); `TestAWSCommandSchemelessEndpointIsRejectedByTheCLI` runs the real CLI to keep that true. + +**Alternative considered: refuse every post-command `--endpoint-url`.** Rejected: it breaks scripts that pass the emulator's own address redundantly, and LocalStack under other hostnames. + +### Refuse every `--profile` except `localstack` + +lstk can't tell whether a profile only holds LocalStack credentials without parsing the user's config and credential sources, which is fragile. Account selection already has `--account`, and profile settings have the `localstack` profile (`lstk setup aws`). Ambient `AWS_PROFILE` is unchanged: lstk's own credentials outrank it on the no-profile path, and on the profile path lstk sets `AWS_PROFILE=localstack`. + +`--profile localstack` is allowed, matched exactly because profile names are case-sensitive. People used to `aws --profile localstack` would otherwise hit the error for the one profile lstk itself writes. It adds no trust lstk doesn't already extend: lstk selects that profile automatically through `AWS_PROFILE` without checking its contents, and its `endpoint_url` is outranked by lstk's `--endpoint-url` and `AWS_ENDPOINT_URL`. Naming it on the command line does drop the environment credential provider, so `--account` has no effect alongside it, as plain `aws --profile` would behave. + +What lstk does not check is whether the `localstack` profile has been edited to hold a real credential source (`credential_process`, `role_arn`, `sso_*`). That applies equally to the automatic `AWS_PROFILE` path, and is left to DEVX-1471. + +### Match every `--` prefix, anywhere, both forms + +`strings.HasPrefix("endpoint-url", name)` and `strings.HasPrefix("profile", name)` match exactly what the measured CLI resolves. The check scans every argument, because global options may come before or after the operation. A false positive would need a command option that is itself a prefix of `profile` or `endpoint-url`, which the CLI would already resolve to the global option. + +### Check before the help short-circuit + +Help never contacts AWS, but one rule with no exceptions is easier to state and test. The check also runs before endpoint resolution, so a refusal needs neither Docker nor a running emulator. + +### lstk's own error, not the tool's + +The refusal is an `ErrorEvent` and a silent error with exit code 1, not marked with `proc.MarkUserToolExit`: lstk refused, the tool never ran. + +### Proxy considered, left to a follow-up + +A local proxy (`HTTPS_PROXY`/`HTTP_PROXY` pointing at lstk) was measured as an alternative or a backstop: + +| Path to real AWS | Deny proxy, emulator in `NO_PROXY` | Every request through the proxy | +|---|---|---| +| `--endpoint-url https://sqs…amazonaws.com` (any prefix) | blocked | blocked | +| `--profile` with `role_arn` (STS) | blocked | blocked | +| MRAP ARN (S3 rewrites the URL) | **direct connection**: botocore picks a proxy per client from its configured endpoint, not per request | blocked | +| `credential_process` | runs anyway | runs anyway | +| `--endpoint-url` inside `~/.aws/cli/alias` | blocked | blocked | +| Error shown | `Failed to connect to proxy URL: "http://127.0.0.1:…"` | same | + +The deny-only variant is small but misses URL rewrites (MRAP is handled by `AWS_S3_DISABLE_MULTIREGION_ACCESS_POINTS` since #616). The variant that catches everything has to forward all emulator traffic, including HTTPS tunnels to ephemeral instances and streaming responses. Both override a user's corporate `HTTPS_PROXY`, which enterprise setups rely on to reach `*.localstack.cloud`. That trade-off gets its own ticket. + +## Risks / Trade-offs + +- **Breaking for `--profile` users.** Anyone running `lstk aws --profile …` today gets an error. The message points at `--account` and `lstk setup aws`. +- **A new AWS domain.** A partition added later isn't refused until the list is updated. +- **Gaps that remain:** aliases, a `--cli-input-json` that sets neither option (it can't), and anything outside the CLI's arguments. The MCP server keeps its private HOME for those. + +## Migration Plan + +Nothing to migrate. Rollback is reverting the commit. + +## Open Questions + +None. Follow-ups: the proxy backstop ticket, and aligning the MCP server's argument check with lstk's (it keeps its private HOME). diff --git a/openspec/changes/refuse-real-aws-options/proposal.md b/openspec/changes/refuse-real-aws-options/proposal.md new file mode 100644 index 00000000..1c8cdfa7 --- /dev/null +++ b/openspec/changes/refuse-real-aws-options/proposal.md @@ -0,0 +1,44 @@ +## Why + +`lstk aws` adds `--endpoint-url` for LocalStack, but options the caller passes can still send a call to real AWS, signed with real credentials (DEVX-1345): + +- `lstk aws sqs list-queues --endpoint-url https://sqs.us-east-1.amazonaws.com`: the caller's `--endpoint-url` overrides lstk's. +- `lstk aws sqs list-queues --profile prod`: signs with the `prod` profile's credentials, and runs its `credential_process`, SSO refresh or STS AssumeRole against real AWS. + +The AWS CLI accepts any unambiguous prefix of an option name, so `--endp`, `--e=…`, `--pro` and `--p=…` do the same. Both forms are allowed today on purpose: `external-endpoint` forwards a post-command `--endpoint-url` untouched, and `aws-proxy` lets a user's `--profile` win. + +## What Changes + +- Before starting the AWS CLI, `lstk aws` refuses: + - an `--endpoint-url` whose host is an AWS partition domain or a subdomain of one (`amazonaws.com`, `amazonaws.com.cn`, `api.aws`, `amazonaws.eu`, and the isolated partitions); + - a `--profile` other than `localstack`, the profile `lstk setup aws` writes. +- Any `--` prefix of either name counts, in `--opt value` and `--opt=value` forms, anywhere in the arguments, including on the help path. +- The refusal is lstk's own error, exit code 1. For an endpoint it suggests dropping the option or `lstk --endpoint-url aws …`; for a profile it suggests `--account` or `lstk setup aws`. +- An `--endpoint-url` that is an IP address without a port is refused too: a bare IP could be an AWS address, and an emulator always has a port. +- A value without a scheme, such as `s3.amazonaws.com`, is left to the AWS CLI, which rejects it before sending anything. +- An `--endpoint-url` pointing anywhere else (another hostname, an IP address with a port) is still forwarded unchanged, because people run LocalStack under their own hostnames. +- `lstk aws --help` mentions the rule. + +## Non-goals + +- A hard guarantee that no request leaves for AWS. This is a guardrail against the documented paths; see `design.md` for why a local proxy is left to a follow-up. +- `~/.aws/cli/alias` entries that carry `--endpoint-url`: lstk doesn't see the expanded command. +- `az`, `terraform`, `cdk` and `sam`. + +## Capabilities + +### New Capabilities + +None. + +### Modified Capabilities + +- `aws-proxy`: new requirement "Options that reach real AWS are refused"; "Selecting the localstack AWS profile" now refuses a user-supplied `--profile` instead of letting it win. +- `external-endpoint`: a post-command `--endpoint-url` on `aws` still passes through, except when its host is an AWS domain. + +## Impact + +- `internal/awscli/realaws.go`: `FindRealAWSOption` and the AWS domain list. +- `cmd/aws.go`: the check before the help short-circuit, the error, and one line of help text. +- Tests: `internal/awscli/realaws_test.go`, `test/integration/aws_real_aws_guard_test.go`. +- Release: a breaking change for anyone using `lstk aws --profile …`, or pointing `lstk aws` at real AWS. Both contradict what `lstk aws` is for. No docs change: `lstk aws --help` states the rule. diff --git a/openspec/changes/refuse-real-aws-options/specs/aws-proxy/spec.md b/openspec/changes/refuse-real-aws-options/specs/aws-proxy/spec.md new file mode 100644 index 00000000..66edb3e7 --- /dev/null +++ b/openspec/changes/refuse-real-aws-options/specs/aws-proxy/spec.md @@ -0,0 +1,124 @@ +## ADDED Requirements + +### Requirement: Options that reach real AWS are refused + +Before starting the `aws` subprocess, on every path including help, the system SHALL refuse a `--profile` option other than `--profile localstack`, and an `--endpoint-url` option whose host is an AWS partition domain, a subdomain of one, or an IP address without a port. Any `--` prefix of either name counts, in `--opt value` and `--opt=value` forms, anywhere in the arguments. The refusal is an lstk error with exit code 1 that says `lstk aws` only targets LocalStack. + +#### Scenario: An AWS endpoint is refused, abbreviated or not + +- **WHEN** the user runs `lstk aws sqs list-queues --endp https://sqs.us-east-1.amazonaws.com` or `lstk aws sqs list-queues --e=https://sqs.us-east-1.amazonaws.com` +- **THEN** lstk exits 1 with an error naming the AWS host, and does not start the `aws` binary + +#### Scenario: AWS domains of every partition count + +- **WHEN** the `--endpoint-url` host ends in `amazonaws.com`, `amazonaws.com.cn`, `api.aws`, `amazonaws.eu`, `c2s.ic.gov`, `sc2s.sgov.gov`, `cloud.adc-e.uk` or `csp.hci.ic.gov`, in any letter case +- **THEN** lstk refuses the command + +#### Scenario: Other endpoints pass through + +- **WHEN** the `--endpoint-url` host is not an AWS domain, for example `localhost`, `localstack.internal.example.com`, an IP address with a port such as `http://203.0.113.5:4566`, or `amazonaws.com.example.com` +- **THEN** lstk forwards it to the `aws` binary unchanged + +#### Scenario: An IP address without a port is refused + +- **WHEN** the user runs `lstk aws s3 ls --endpoint-url https://52.94.0.1` +- **THEN** lstk exits 1 with an error asking for the emulator's port, and does not start the `aws` binary + +#### Scenario: A value without a scheme is left to the AWS CLI + +- **WHEN** the user runs `lstk aws sqs list-queues --endpoint-url sqs.us-east-1.amazonaws.com` +- **THEN** lstk forwards it, and the AWS CLI rejects it without sending a request to the emulator or to AWS + +#### Scenario: A profile is refused, abbreviated or not + +- **WHEN** the user runs `lstk aws --pro prod sqs list-queues` or `lstk aws s3api list-objects-v2 --bucket b --p=prod` +- **THEN** lstk exits 1 with an error pointing at `--account` and `lstk setup aws`, and does not start the `aws` binary + +#### Scenario: The localstack profile may be named explicitly + +- **WHEN** the user runs `lstk aws s3 ls --profile localstack` or `lstk aws --pro=localstack s3 ls` +- **THEN** lstk forwards the command unchanged; any other profile name, including `LocalStack`, is refused + +#### Scenario: A command option that only shares letters is not refused + +- **WHEN** the user runs `lstk aws s3api list-objects-v2 --bucket b --prefix logs/` +- **THEN** lstk forwards the command unchanged, because `--prefix` is not a prefix of `--profile` + +#### Scenario: The help path is checked too + +- **WHEN** the user runs `lstk aws --profile prod s3 ls help` +- **THEN** lstk refuses the command + +## MODIFIED Requirements + +### Requirement: Selecting the localstack AWS profile + +When a `localstack` AWS profile is configured, the system SHALL select it by setting `AWS_PROFILE=localstack` in the `aws` subprocess environment, and SHALL NOT pass `--profile` on the command line. + +The two forms select the same profile but resolve credentials differently: an explicitly named profile on the command line removes the environment credential provider from the AWS CLI's resolver chain, while the environment form leaves it in place. Selecting the profile through the environment is therefore what allows an account to be expressed *and* the profile's other settings — `region`, `output`, `s3` addressing style, retry configuration, and anything else the user has put there — to continue applying. The profile is never dropped in order to select an account. + +Whenever the profile is in use, the system SHALL treat the credential triple as all-or-nothing: + +- When an account has been selected, it SHALL set both `AWS_ACCESS_KEY_ID` (to the resolved account) and `AWS_SECRET_ACCESS_KEY`, so the environment supplies a complete credential pair that outranks the profile's. +- When no account has been selected, it SHALL remove `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_SESSION_TOKEN` from the subprocess environment, so the profile is the sole credentials source. + +The system SHALL NOT leave a partial pair, because the AWS CLI fails outright on an access key id without a secret once the environment provider is in the chain. Removing the pair when no account is selected is likewise required rather than tidy: it prevents ambient credentials from beating the profile in cases where the command-line form shielded it, including a 12-digit `aws_access_key_id` written directly into the `[localstack]` credentials section, which is a legitimate way to pin an account and which lstk already honors. + +An account is selected when either a valid `--account` flag is supplied, or the ambient `AWS_ACCESS_KEY_ID` is itself exactly 12 digits — the documented way to address a specific LocalStack account. An ambient value of any other shape SHALL NOT count as a selection, so a stray real credential in the user's shell does not displace the profile. + +While the profile is in use, the system SHALL NOT seed `AWS_DEFAULT_REGION` or any other configuration default into the subprocess environment. Environment variables outrank config-file values, so seeding a default region would override the profile's `region` and reintroduce the silent misdirection this requirement exists to prevent. lstk supplies defaults only when there is no profile to supply them. + +The system SHALL continue to advise the user to run `lstk setup aws` when no `localstack` profile exists, based on the profile's presence and not on whether it supplied credentials for the current invocation. + +#### Scenario: Profile supplies credentials when no account is selected + +- **WHEN** a `localstack` profile exists and the user runs `lstk aws s3 ls` with no `--account` and no ambient `AWS_ACCESS_KEY_ID` +- **THEN** the subprocess environment sets `AWS_PROFILE=localstack` and carries no `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, or `AWS_SESSION_TOKEN` +- **AND** the credentials used are the profile's, as they are today + +#### Scenario: Explicit account applies without losing the profile + +- **WHEN** a `localstack` profile sets `region = eu-west-1` and the user runs `lstk aws --account 111111111111 s3 ls` +- **THEN** the subprocess environment sets `AWS_PROFILE=localstack`, `AWS_ACCESS_KEY_ID=111111111111`, and a secret, and no `--profile` argument is passed +- **AND** the call reads account `111111111111` in region `eu-west-1` — the account from the environment, the region from the profile + +#### Scenario: A 12-digit environment value applies without losing the profile + +- **WHEN** a `localstack` profile exists and the user runs `AWS_ACCESS_KEY_ID=111111111111 lstk aws s3 ls` +- **THEN** the subprocess sees `AWS_ACCESS_KEY_ID=111111111111` alongside `AWS_PROFILE=localstack`, and the result is the same as running the identical command with no profile configured except that the profile's other settings still apply + +#### Scenario: Non-credential profile settings always apply + +- **WHEN** a `localstack` profile sets `output`, `max_attempts`, or an `s3` addressing style, and any `lstk aws` command runs +- **THEN** those settings take effect, whether or not an account was selected + +#### Scenario: No default region is seeded over the profile + +- **WHEN** a `localstack` profile sets `region = eu-west-1` and an account is selected +- **THEN** lstk does not set `AWS_DEFAULT_REGION` in the subprocess environment, so the profile's region is not overridden + +#### Scenario: A partial ambient credential is never forwarded + +- **WHEN** a `localstack` profile exists and the environment sets `AWS_ACCESS_KEY_ID` without `AWS_SECRET_ACCESS_KEY` +- **THEN** lstk either supplies both (when the value selects an account) or removes both (when it does not), and the AWS CLI does not fail with a partial-credentials error + +#### Scenario: A real key in the environment does not displace the profile + +- **WHEN** a `localstack` profile exists and the environment sets `AWS_ACCESS_KEY_ID` to a real-looking key such as `AKIAIOSFODNN7EXAMPLE` +- **THEN** no account is selected, the ambient credentials are removed from the subprocess environment, and the profile supplies credentials +- **AND** the live key value is not sent to the emulator + +#### Scenario: An account pinned in the profile itself is honored + +- **WHEN** the `[localstack]` credentials section sets `aws_access_key_id = 111111111111` and the user runs `lstk aws s3 ls` with no `--account` and no ambient credentials +- **THEN** the call reads account `111111111111`, because lstk removes the ambient credential variables rather than seeding `test` over the profile + +#### Scenario: A user-supplied profile flag wins and disables account selection + +- **WHEN** the user runs `lstk aws --account 111111111111 --profile mine s3 ls` +- **THEN** lstk refuses the command and does not start the `aws` binary, because a named profile can sign with real AWS credentials (see "Options that reach real AWS are refused") + +#### Scenario: Setup advice tracks the profile, not the credentials source + +- **WHEN** no `localstack` profile exists +- **THEN** lstk notes that the user can run `lstk setup aws`, whether or not an account was selected for this invocation diff --git a/openspec/changes/refuse-real-aws-options/specs/external-endpoint/spec.md b/openspec/changes/refuse-real-aws-options/specs/external-endpoint/spec.md new file mode 100644 index 00000000..c4eb5895 --- /dev/null +++ b/openspec/changes/refuse-real-aws-options/specs/external-endpoint/spec.md @@ -0,0 +1,67 @@ +## MODIFIED Requirements + +### Requirement: Global endpoint URL flag and precedence + +The system SHALL provide a global `--endpoint-url ` persistent flag and an `LSTK_ENDPOINT_URL` environment variable that let `aws`, `az`, `terraform`/`tf`, `cdk`, `sam`, `snapshot save`/`load` (including the `lstk save`/`lstk load` aliases), `snapshot remove`, `snapshot list` (when given an `s3://...` argument), `reset`, and `status` target an emulator at an arbitrary URL instead of one discovered via local Docker inspection. The value SHALL include a scheme — `http` or `https` (e.g. `http://host:4566` or `https://host`) — and SHALL be validated as a URL at the command boundary; any other scheme is rejected. The resolved scheme SHALL be preserved unchanged all the way to whatever ultimately makes the request (the wrapped `aws`/`terraform`/`cdk`/`sam` tools, and the emulator API calls behind `snapshot`/`reset`/`status`), never normalized to `http`. Certificate trust for `https` endpoints follows standard TLS verification; there is no option to skip certificate verification. + +For `aws`, `az`, `terraform`/`tf`, `cdk`, and `sam` (which forward unrecognized arguments to a wrapped binary and disable lstk's own flag parsing for their args), the `--endpoint-url` flag SHALL be recognized only when it precedes the subcommand name (e.g. `lstk --endpoint-url http://localhost:4566 aws s3 ls`), the same placement rule already applied to `--json` for these five commands. This is required because the `aws` CLI itself has a native `--endpoint-url` flag: placed after the subcommand name (`lstk aws --endpoint-url http://localhost:4566 s3 ls`), it SHALL be forwarded to the wrapped binary unchanged rather than intercepted by lstk, so a user's own `aws --endpoint-url` usage against any LocalStack keeps working under `lstk aws`. The one exception is an `--endpoint-url` whose host is an AWS domain, which `lstk aws` refuses (see the `aws-proxy` capability's "Options that reach real AWS are refused"). The other four (`az`, `terraform`/`tf`, `cdk`, `sam`) have no such collision but get the identical pre-command-only rule for consistency. `snapshot`, `reset`, and `status` have ordinary Cobra flag parsing and accept `--endpoint-url` in the normal position after the command name. + +#### Scenario: Flag targets an arbitrary endpoint + +- **WHEN** a user runs `lstk --endpoint-url http://localhost:4566 aws s3 ls` +- **THEN** lstk uses `http://localhost:4566` as the emulator endpoint without performing Docker container discovery + +#### Scenario: Post-command --endpoint-url on aws passes through untouched + +- **WHEN** a user runs `lstk aws --endpoint-url http://localhost:4566 s3 ls` +- **THEN** lstk does not treat `--endpoint-url` as its own flag — it forwards `--endpoint-url http://localhost:4566 s3 ls` to the `aws` binary unchanged, and resolves its own emulator endpoint via existing Docker discovery (or another endpoint source) as if no `--endpoint-url` were given + +#### Scenario: Post-command --endpoint-url pointing at AWS is refused + +- **WHEN** a user runs `lstk aws sqs list-queues --endpoint-url https://sqs.us-east-1.amazonaws.com` +- **THEN** lstk refuses the command and does not start the `aws` binary + +#### Scenario: Environment variable is honored + +- **WHEN** `LSTK_ENDPOINT_URL` is set and no `--endpoint-url` flag is passed +- **THEN** lstk resolves the endpoint from the environment variable + +#### Scenario: AWS_ENDPOINT_URL is honored as a backup for every in-scope command + +- **WHEN** `AWS_ENDPOINT_URL` is set, and neither `--endpoint-url` nor `LSTK_ENDPOINT_URL` is set, and the user runs `lstk aws s3 ls`, `lstk az ...`, `lstk status`, `lstk reset`, or an in-scope `lstk snapshot` form +- **THEN** lstk resolves the endpoint from `AWS_ENDPOINT_URL` without performing Docker container discovery, in every one of those cases + +#### Scenario: AWS_ENDPOINT_URL pointing at a non-LocalStack endpoint fails closed + +- **WHEN** `AWS_ENDPOINT_URL` is set to a real AWS endpoint or an unrelated service, and neither `--endpoint-url` nor `LSTK_ENDPOINT_URL` is set, and the user runs `lstk status` +- **THEN** the reachability/type probe rejects it with a "doesn't look like a LocalStack emulator" error rather than silently proceeding against it + +#### Scenario: Flag takes precedence over environment sources + +- **WHEN** `--endpoint-url` is passed and `LSTK_ENDPOINT_URL` and/or `AWS_ENDPOINT_URL` are also set +- **THEN** the flag's value is used + +#### Scenario: LSTK_ENDPOINT_URL takes precedence over AWS_ENDPOINT_URL + +- **WHEN** both `LSTK_ENDPOINT_URL` and `AWS_ENDPOINT_URL` are set, and no `--endpoint-url` flag is passed +- **THEN** `LSTK_ENDPOINT_URL`'s value is used + +#### Scenario: Malformed endpoint URL + +- **WHEN** `--endpoint-url` (or `LSTK_ENDPOINT_URL`/`AWS_ENDPOINT_URL`, where applicable) is set to a value that is not a valid absolute URL with a scheme +- **THEN** the command fails immediately with an actionable error and does not attempt any network call + +#### Scenario: An unsupported scheme is rejected + +- **WHEN** `--endpoint-url` is set to a value with a scheme other than `http` or `https` (e.g. `ftp://host:4566`) +- **THEN** the command fails immediately with an actionable error naming the unsupported scheme and does not attempt any network call + +#### Scenario: https endpoint is accepted and used as-is + +- **WHEN** a user runs `lstk --endpoint-url https://my-instance.ephemeral-instances.localstack.cloud aws s3 ls` +- **THEN** lstk probes and targets that `https://` URL directly, with no local Docker involvement, and the `aws` binary receives `https://my-instance.ephemeral-instances.localstack.cloud` as its endpoint — not a value rewritten to `http://` + +#### Scenario: https endpoint reaches the emulator API layer unchanged + +- **WHEN** a user runs `lstk snapshot save --endpoint-url https://my-instance.ephemeral-instances.localstack.cloud my-baseline` +- **THEN** the save request is made against the given `https://` endpoint, not downgraded to `http://` diff --git a/openspec/changes/refuse-real-aws-options/tasks.md b/openspec/changes/refuse-real-aws-options/tasks.md new file mode 100644 index 00000000..a5244634 --- /dev/null +++ b/openspec/changes/refuse-real-aws-options/tasks.md @@ -0,0 +1,25 @@ +## 1. Research + +- [x] 1.1 Measure how AWS CLI 2.42.3 resolves abbreviated `--endpoint-url`/`--profile`, before and after the operation. +- [x] 1.2 Measure a deny proxy (with and without `NO_PROXY` for the emulator) against an AWS endpoint, an STS-backed profile, `credential_process` and an MRAP ARN (see `design.md`). + +## 2. Failing tests first (red) + +- [x] 2.1 Add `TestAWSCommandRefusesRealAWSEndpointAndProfile`: AWS endpoints (prefixes, `=` form, China and dual-stack domains, upper case) and profiles (prefixes, `=` form, help path) exit 1 without starting the CLI. Confirmed failing on all 11 cases. +- [x] 2.2 Add `TestAWSCommandAllowsNonAWSEndpoints`: localhost, another hostname, an IP with a port, lookalike hosts, and `--prefix` reach the CLI unchanged. Inputs the CLI rejects itself (empty or missing values, `--profiles`, `-p`, values without a scheme) have no cases of their own. +- [x] 2.3 Add `TestAWSCommandSchemelessEndpointIsRejectedByTheCLI`: with the real AWS CLI, `s3.amazonaws.com`, `sqs.us-east-1.amazonaws.com:443` and `52.94.0.1` are rejected by the CLI, and no request reaches the emulator or a recording proxy standing in for AWS. Confirmed failing while lstk refused them itself. + +## 3. Implementation (green) + +- [x] 3.1 `awscli.FindRealAWSOption` and the AWS domain list (`internal/awscli/realaws.go`). +- [x] 3.2 Call it in `cmd/aws.go` before the help short-circuit; render the refusal with actions; mention the rule in `lstk aws --help`. +- [x] 3.3 Run the tests from group 2 and confirm they pass. + +## 4. Unit coverage + +- [x] 4.1 `TestFindRealAWSOption`: the `localstack` profile (exact name, either form, followed by another profile), partition domains, trailing dot, single-letter prefix, first refusal wins, bare `--` (which the CLI accepts), IPs with and without a port (v4 and v6), lookalikes. + +## 5. Verify + +- [x] 5.1 Full `make test` and the `aws`/endpoint integration tests. Failures that also fail on `main` (Docker-backed `TestAWSCommandFailsWhenEmulatorNotRunning`, `TestAWSCommandWorksWithExternalContainer`, and `TestStart_SecondLicenseRejectionAfterReloginRendersErrorEvent`) are unrelated. +- [ ] 5.2 `make lint` (golangci-lint 2.14.0, not installed locally; CI runs it). diff --git a/test/integration/aws_real_aws_guard_test.go b/test/integration/aws_real_aws_guard_test.go new file mode 100644 index 00000000..d6cecde0 --- /dev/null +++ b/test/integration/aws_real_aws_guard_test.go @@ -0,0 +1,142 @@ +package integration_test + +import ( + "net/http" + "net/http/httptest" + "os/exec" + "strings" + "sync" + "testing" + + "github.com/localstack/lstk/test/integration/env" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// The AWS CLI resolves any unambiguous prefix of an option name, and its global +// options win over a command's own when abbreviated, so `--endp`/`--e=` mean +// --endpoint-url and `--p`/`--pro` mean --profile wherever they appear (DEVX-1345). +func TestAWSCommandRefusesRealAWSEndpointAndProfile(t *testing.T) { + t.Parallel() + srv := awsHealthServer(t) + t.Cleanup(srv.Close) + + fakeDir := writeFakeTool(t, "aws", fakeToolConfig{Stdout: []string{"INVOKED ARGS:{args}"}}) + + tests := []struct { + name string + args []string + want string + }{ + {"endpoint after operation", []string{"sqs", "list-queues", "--endpoint-url", "https://sqs.us-east-1.amazonaws.com"}, "--endpoint-url points at real AWS"}, + {"endpoint before service", []string{"--endpoint-url", "https://sqs.us-east-1.amazonaws.com", "sqs", "list-queues"}, "--endpoint-url points at real AWS"}, + {"endpoint prefix", []string{"--endp", "https://sqs.us-east-1.amazonaws.com", "sqs", "list-queues"}, "--endpoint-url points at real AWS"}, + {"endpoint prefix with equals", []string{"sqs", "list-queues", "--e=https://sqs.us-east-1.amazonaws.com"}, "--endpoint-url points at real AWS"}, + {"endpoint china partition", []string{"s3", "ls", "--endpoint-url", "https://s3.cn-north-1.amazonaws.com.cn"}, "--endpoint-url points at real AWS"}, + {"endpoint dualstack domain", []string{"sqs", "list-queues", "--endpoint-url", "https://sqs.us-east-1.api.aws"}, "--endpoint-url points at real AWS"}, + {"endpoint upper case host", []string{"sqs", "list-queues", "--endpoint-url", "https://SQS.US-EAST-1.AMAZONAWS.COM"}, "--endpoint-url points at real AWS"}, + {"endpoint ip address without port", []string{"sqs", "list-queues", "--endpoint-url", "https://52.94.0.1"}, "--endpoint-url needs a port for an IP address"}, + {"profile", []string{"sqs", "list-queues", "--profile", "prod"}, "only --profile localstack is supported"}, + {"profile prefix", []string{"--pro", "prod", "sqs", "list-queues"}, "only --profile localstack is supported"}, + {"profile shortest prefix with equals", []string{"s3api", "list-objects-v2", "--bucket", "b", "--p=prod"}, "only --profile localstack is supported"}, + {"profile on the help path", []string{"--profile", "prod", "s3", "ls", "help"}, "only --profile localstack is supported"}, + {"profile name is case-sensitive", []string{"sqs", "list-queues", "--profile", "LocalStack"}, "only --profile localstack is supported"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + e := env.With(env.DisableEvents, "1").With("PATH", fakeDir).WithHome(t.TempDir()) + e = append(e, unreachableDockerHost) + + args := append([]string{"--endpoint-url", srv.URL, "aws"}, tc.args...) + stdout, stderr, err := runLstk(t, testContext(t), t.TempDir(), e, args...) + require.Error(t, err) + requireExitCode(t, 1, err) + out := stdout + stderr + assert.Contains(t, out, tc.want) + assert.Contains(t, out, "lstk aws only targets LocalStack") + assert.NotContains(t, out, "INVOKED", "the AWS CLI must not be started") + }) + } +} + +func TestAWSCommandAllowsNonAWSEndpoints(t *testing.T) { + t.Parallel() + srv := awsHealthServer(t) + t.Cleanup(srv.Close) + + // Shift drops the --endpoint-url pair lstk itself prepends. + fakeDir := writeFakeTool(t, "aws", fakeToolConfig{Shift: 2, Stdout: []string{"INVOKED ARGS:{args}"}}) + + tests := []struct { + name string + args []string + }{ + {"local emulator", []string{"--endpoint-url", "http://localhost:4566", "s3", "ls"}}, + {"emulator under its own hostname", []string{"s3", "ls", "--endpoint-url", "https://localstack.internal.example.com:4566"}}, + {"ip address with port", []string{"s3", "ls", "--endpoint-url", "http://203.0.113.5:4566"}}, + {"lookalike host", []string{"s3", "ls", "--endpoint-url", "https://amazonaws.com.example.com"}}, + {"suffix without a dot boundary", []string{"s3", "ls", "--endpoint-url", "https://notamazonaws.com"}}, + {"command option sharing a letter with profile", []string{"s3api", "list-objects-v2", "--bucket", "b", "--prefix", "logs/"}}, + {"localstack profile", []string{"s3", "ls", "--profile", "localstack"}}, + {"localstack profile, abbreviated with equals", []string{"--pro=localstack", "s3", "ls"}}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + e := env.With(env.DisableEvents, "1").With("PATH", fakeDir).WithHome(t.TempDir()) + e = append(e, unreachableDockerHost) + + args := append([]string{"--endpoint-url", srv.URL, "aws"}, tc.args...) + stdout, stderr, err := runLstk(t, testContext(t), t.TempDir(), e, args...) + require.NoError(t, err, "stderr: %s", stderr) + assert.Contains(t, stdout, "INVOKED ARGS:"+strings.Join(tc.args, " ")) + }) + } +} + +// lstk leaves a scheme-less --endpoint-url to the AWS CLI, which rejects it before +// sending anything. A recording proxy stands in for AWS to prove no request leaves. +func TestAWSCommandSchemelessEndpointIsRejectedByTheCLI(t *testing.T) { + t.Parallel() + if _, err := exec.LookPath("aws"); err != nil { + t.Skip("aws CLI not installed") + } + + var mu sync.Mutex + var seen []string + record := func(who string, next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if !strings.HasPrefix(r.URL.Path, "/_localstack/") { + mu.Lock() + seen = append(seen, who+" "+r.Method+" "+r.Host) + mu.Unlock() + } + next.ServeHTTP(w, r) + }) + } + emulator := httptest.NewServer(record("emulator", awsHealthHandler())) + t.Cleanup(emulator.Close) + proxy := httptest.NewServer(record("proxy", http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(http.StatusForbidden) + }))) + t.Cleanup(proxy.Close) + + for _, value := range []string{"s3.amazonaws.com", "sqs.us-east-1.amazonaws.com:443", "52.94.0.1"} { + t.Run(value, func(t *testing.T) { + e := env.With(env.DisableEvents, "1").WithHome(t.TempDir()). + With("HTTPS_PROXY", proxy.URL).With("HTTP_PROXY", proxy.URL).With("NO_PROXY", "127.0.0.1") + e = append(e, unreachableDockerHost) + + stdout, stderr, err := runLstk(t, testContext(t), t.TempDir(), e, + "--endpoint-url", emulator.URL, "aws", "sqs", "list-queues", "--endpoint-url", value) + require.Error(t, err) + out := stdout + stderr + assert.Contains(t, out, value, "the AWS CLI's own error names the value") + assert.NotContains(t, out, "lstk aws only targets LocalStack", "the AWS CLI rejects it, not lstk") + }) + } + mu.Lock() + defer mu.Unlock() + assert.Empty(t, seen, "no request may reach the emulator or the proxy") +}