Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions cmd/aws.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 <shell>' along with the rest of lstk's completion.
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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://<ip>: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 <url> aws ..."},
},
}
}
sink.Emit(ev)
return output.NewSilentError(fmt.Errorf("refused %s", refused.Option))
}
91 changes: 91 additions & 0 deletions internal/awscli/realaws.go
Original file line number Diff line number Diff line change
@@ -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
}
45 changes: 45 additions & 0 deletions internal/awscli/realaws_test.go
Original file line number Diff line number Diff line change
@@ -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)
})
}
}
83 changes: 83 additions & 0 deletions openspec/changes/refuse-real-aws-options/design.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
## Context

`lstk aws` runs the AWS CLI with `--endpoint-url <emulator>` 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).
44 changes: 44 additions & 0 deletions openspec/changes/refuse-real-aws-options/proposal.md
Original file line number Diff line number Diff line change
@@ -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 <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.
Loading
Loading