Skip to content
Merged
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
4 changes: 2 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,11 +121,11 @@ Created automatically on first run with defaults. Supports emulator types: `aws`

Only one `[[containers]]` block may be enabled at a time. `container.Start` rejects a config with more than one block up front (before health/auth checks and image pulls), since running multiple emulators together (e.g. AWS + Snowflake) is unsupported and would otherwise fail later during startup with container-name conflicts or port collisions. The guard lives on the start path (not `config.Get()`) on purpose: recovery/reporting commands like `stop`, `status`, and `logout` must still enumerate multiple running emulators.

Each `[[containers]]` block may set an optional `image` (override the default Docker Hub image) and a `volumes` list of Docker-style bind specs (persistence dir, init hooks, arbitrary mounts). Image/tag precedence, `volume` vs `volumes` semantics, and path-resolution rules are documented in `internal/config/CLAUDE.md`.
Each `[[containers]]` block may set an optional `container_name` (override the derived container name; also what the emulator reports as `MAIN_CONTAINER_NAME`), an optional `image` (override the default Docker Hub image), and a `volumes` list of Docker-style bind specs (persistence dir, init hooks, arbitrary mounts). Container-name derivation and its deliberate decoupling from the default persistence directory, image/tag precedence, `volume` vs `volumes` semantics, and path-resolution rules are documented in `internal/config/CLAUDE.md`.

## Selecting the emulator (`--type`)

`lstk start --type <aws|snowflake|azure>` (shorthand `-t`; also on the bare root) is the non-interactive answer to the first-run emulator picker. It is a flag only — a positional (`lstk start azure`) is rejected with a hint pointing at `--type`, to avoid implying the root-level `lstk aws`/`lstk az` proxy names mean "start that emulator". It is defined as "rewrite the `type` line in config", not an ephemeral per-run override — downstream commands (`stop`, `status`, `logs`, `volume`, snapshot auto-load) all resolve from the configured type, so persisting keeps config and reality in sync. First run creates the config with the selected type (same `EnsureCreated`/`SetEmulatorType` path the picker uses); a matching config is a no-op; a differing config is switched in place via the surgical type-line rewrite (comments/formatting preserved) with a note naming the file. On switch: a custom `image` is a hard error (it pins a product that can't be reinterpreted under a new type — use `--config` for a separate profile), a non-`latest` `tag` and any `volumes`/`volume` are kept with a warning, and `port`/`env`/`snapshot` are kept silently. Domain logic is `container.ApplyEmulatorType` (parallel to `container.SelectEmulator`); it is applied at the top of `startEmulator` (`cmd/root.go`) before snapshot/start-options are resolved, so it runs before the TUI and its messages go through a plain sink.
`lstk start --type <aws|snowflake|azure>` (shorthand `-t`; also on the bare root) is the non-interactive answer to the first-run emulator picker. It is a flag only — a positional (`lstk start azure`) is rejected with a hint pointing at `--type`, to avoid implying the root-level `lstk aws`/`lstk az` proxy names mean "start that emulator". It is defined as "rewrite the `type` line in config", not an ephemeral per-run override — downstream commands (`stop`, `status`, `logs`, `volume`, snapshot auto-load) all resolve from the configured type, so persisting keeps config and reality in sync. First run creates the config with the selected type (same `EnsureCreated`/`SetEmulatorType` path the picker uses); a matching config is a no-op; a differing config is switched in place via the surgical type-line rewrite (comments/formatting preserved) with a note naming the file. On switch: a custom `image` is a hard error (it pins a product that can't be reinterpreted under a new type — use `--config` for a separate profile), a non-`latest` `tag` and any `volumes`/`volume` are kept with a warning, and `container_name`/`port`/`env`/`snapshot` are kept silently (they describe the user's topology rather than pinning a product). Domain logic is `container.ApplyEmulatorType` (parallel to `container.SelectEmulator`); it is applied at the top of `startEmulator` (`cmd/root.go`) before snapshot/start-options are resolved, so it runs before the TUI and its messages go through a plain sink.

`GATEWAY_LISTEN` (host exposure and published ports) is read from the container's resolved env, not hardcoded; parsing and derivation are documented in `internal/container/CLAUDE.md`.

Expand Down
10 changes: 10 additions & 0 deletions internal/config/CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,16 @@

Detail moved out of the root CLAUDE.md; see the root file for the config search order and creation policy.

## Container name

Each `[[containers]]` block may set an optional `container_name` to override the derived container name. The key is `container_name` rather than a bare `name` because a `[[containers]]` block already carries several names (the image, the emulator type) and an unqualified `name` reads ambiguously against them. The struct field is `CustomName` (not `Name`) because `ContainerConfig.Name()` is already a method — the same pairing as `CustomImage`/`Image()`. `Name()` returns `CustomName` when set, otherwise `defaultName()` (`localstack-{type}`, or `localstack-{type}-{tag}` when the tag is set and not `latest`).

The name is load-bearing, not cosmetic: `start.go` exports it as `MAIN_CONTAINER_NAME`, which the emulator uses to introspect itself over the Docker socket and to derive the names of containers it spawns (e.g. `<main-container-name>-lambda-<fn>-<id>`). Setting `MAIN_CONTAINER_NAME` in an `[env.*]` profile instead is a trap — it never reached `docker run --name`, so the container's real and self-reported names disagreed; `startOnce` now warns and points at this field.

`VolumeDir()`'s default deliberately uses `defaultName()`, **not** `Name()`, so setting or changing `container_name` never silently orphans the persistence directory (and the path stays byte-identical to what existing users already have). Per-instance state is expressible explicitly via `volume`/`volumes`.

Validation is `validate.ContainerName` (`internal/validate`), called from `ContainerConfig.Validate()`; it mirrors Docker's own `^[a-zA-Z0-9][a-zA-Z0-9_.-]*$` rule so an invalid name fails at config load rather than at container creation. A custom `container_name` survives a `lstk start --type` switch silently (like `port`/`env`/`snapshot`) — it identifies the user's container, it does not pin a product the way `image` does.

## Container image override

Each `[[containers]]` block may set an optional `image` to override the default Docker Hub image (e.g. an internal registry mirror or a locally loaded offline image). `ContainerConfig.Image()` returns `image` as-is when it already carries a tag (so the separately-configured `tag` is dropped in that case), otherwise it appends `tag` (or `latest`); the default `localstack/<product>:<tag>` is used when `image` is unset.
Expand Down
31 changes: 28 additions & 3 deletions internal/config/containers.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import (
"strconv"
"strings"
"time"

"github.com/localstack/lstk/internal/validate"
)

type EmulatorType string
Expand Down Expand Up @@ -122,6 +124,12 @@ type ContainerConfig struct {
// the default localstack image from Docker Hub. If it carries no tag, Tag (or "latest")
// is appended; if it already carries a tag, Tag is dropped.
CustomImage string `mapstructure:"image"`
// CustomName overrides the derived container name (see Name). It is also exported into
// the container as MAIN_CONTAINER_NAME, which the emulator uses to introspect itself over
// the Docker socket and to name the containers it spawns (e.g. Lambda). Set it when
// something outside lstk has to address the emulator by a fixed name, such as a sidecar
// proxy on a CI agent.
CustomName string `mapstructure:"container_name"`
// Volume is the legacy single-host-directory knob for the persistence mount
// (target /var/lib/localstack). It is still honored; new configs can express the
// same mount as a Volumes entry targeting persistenceTarget instead.
Expand Down Expand Up @@ -274,7 +282,11 @@ func (c *ContainerConfig) ExtraVolumes() ([]VolumeMount, error) {
// (the mount targeting /var/lib/localstack). Resolution precedence:
// 1. A Volumes entry targeting persistenceTarget — its resolved host source.
// 2. The legacy Volume field, if set — returned as-is.
// 3. The default os.UserCacheDir()/lstk/volume/<container-name>.
// 3. The default os.UserCacheDir()/lstk/volume/<derived container name>.
//
// The default deliberately uses defaultName rather than Name: keying it to the derived name
// means setting or changing the container's `container_name` never silently orphans existing state.
// Per-instance state is still expressible explicitly via Volume/Volumes.
func (c *ContainerConfig) VolumeDir() (string, error) {
mounts, err := c.parsedVolumes()
if err != nil {
Expand All @@ -292,7 +304,7 @@ func (c *ContainerConfig) VolumeDir() (string, error) {
if err != nil {
return "", fmt.Errorf("failed to determine cache directory: %w", err)
}
return filepath.Join(cacheDir, "lstk", "volume", c.Name()), nil
return filepath.Join(cacheDir, "lstk", "volume", c.defaultName()), nil
}

// TagSuggestion returns an actionable hint naming a recent calendar tag and
Expand Down Expand Up @@ -339,6 +351,11 @@ func (c *ContainerConfig) Validate() error {
if err := validateTag(c.Tag); err != nil {
return err
}
if c.CustomName != "" {
if err := validate.ContainerName(c.CustomName); err != nil {
return fmt.Errorf("invalid container name %q: %w", c.CustomName, err)
}
}
if c.Port == "" {
return fmt.Errorf("port is required for %s emulator", c.Type)
}
Expand Down Expand Up @@ -424,8 +441,16 @@ func imageHasTag(image string) bool {
return strings.Contains(lastSegment, ":")
}

// Name returns the container name: "localstack-{type}" or "localstack-{type}-{tag}" if tag != latest
// Name returns the container name: CustomName when set, otherwise the derived defaultName.
func (c *ContainerConfig) Name() string {
if c.CustomName != "" {
return c.CustomName
}
return c.defaultName()
}

// defaultName is the derived container name: "localstack-{type}" or "localstack-{type}-{tag}" if tag != latest
func (c *ContainerConfig) defaultName() string {
tag := c.Tag
if tag == "" || tag == "latest" {
return fmt.Sprintf("localstack-%s", c.Type)
Expand Down
71 changes: 71 additions & 0 deletions internal/config/containers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,77 @@ func TestImage_DefaultWhenNoCustomImage(t *testing.T) {
assert.Equal(t, "localstack/localstack-pro:latest", image)
}

func TestName_DerivedWhenNoCustomName(t *testing.T) {
tests := []struct {
name string
emulatorType EmulatorType
tag string
want string
}{
{"aws latest", EmulatorAWS, "latest", "localstack-aws"},
{"aws empty tag", EmulatorAWS, "", "localstack-aws"},
{"aws pinned tag", EmulatorAWS, "2026.4", "localstack-aws-2026.4"},
{"snowflake latest", EmulatorSnowflake, "latest", "localstack-snowflake"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := &ContainerConfig{Type: tt.emulatorType, Port: "4566", Tag: tt.tag}
assert.Equal(t, tt.want, c.Name())
})
}
}

func TestName_CustomNameWins(t *testing.T) {
c := &ContainerConfig{Type: EmulatorAWS, Port: "4566", Tag: "2026.4", CustomName: "ls-jenkins"}
assert.Equal(t, "ls-jenkins", c.Name())
}

// A custom name must not move the default persistence directory: renaming the
// container would otherwise silently start the emulator from empty state.
func TestVolumeDir_DefaultIgnoresCustomName(t *testing.T) {
cacheDir, err := os.UserCacheDir()
require.NoError(t, err)
want := filepath.Join(cacheDir, "lstk", "volume", "localstack-aws")

plain := &ContainerConfig{Type: EmulatorAWS, Port: "4566", Tag: "latest"}
plainDir, err := plain.VolumeDir()
require.NoError(t, err)
assert.Equal(t, want, plainDir)

renamed := &ContainerConfig{Type: EmulatorAWS, Port: "4566", Tag: "latest", CustomName: "ls-jenkins"}
renamedDir, err := renamed.VolumeDir()
require.NoError(t, err)
assert.Equal(t, want, renamedDir)
}

func TestValidate_ContainerName(t *testing.T) {
tests := []struct {
name string
customName string
wantErr bool
}{
{"unset is allowed", "", false},
{"simple name", "ls-jenkins", false},
{"dots and underscores", "ls.jenkins_1", false},
{"leading hyphen rejected", "-ls", true},
{"slash rejected", "team/ls", true},
{"shell metachar rejected", "ls;rm -rf /", true},
{"space rejected", "my emulator", true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c := &ContainerConfig{Type: EmulatorAWS, Port: "4566", Tag: "latest", CustomName: tt.customName}
err := c.Validate()
if tt.wantErr {
require.Error(t, err)
assert.Contains(t, err.Error(), "invalid container name")
} else {
require.NoError(t, err)
}
})
}
}

func TestSelfValidatesLicense(t *testing.T) {
// Snowflake and Azure containers activate their own license against the
// licensing server, so lstk skips its pre-flight platform license check.
Expand Down
4 changes: 4 additions & 0 deletions internal/config/default_config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@
type = "aws" # Emulator type. Currently supported: "aws", "snowflake", "azure"
tag = "latest" # Docker image tag, e.g. "latest", "2026.4"
port = "4566" # Host port the emulator will be accessible on
# container_name = "" # Container name (default: "localstack-<type>", plus "-<tag>"
# # when tag is not "latest"). Set it when something outside lstk
# # addresses the emulator by a fixed name, e.g. a sidecar proxy on a
# # CI agent. It is also what the emulator reports as MAIN_CONTAINER_NAME.
# image = "" # Custom image to use instead of the default Docker Hub image, e.g.
# # an internal registry mirror or a locally loaded offline image.
# # If it carries no tag, 'tag' above is appended; if it already
Expand Down
12 changes: 12 additions & 0 deletions internal/container/start.go
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,18 @@ func startOnce(ctx context.Context, rt runtime.Runtime, sink output.Sink, opts S
gatewayDefaulted := strings.TrimSpace(gatewayValue) == ""

containerName := c.Name()

// MAIN_CONTAINER_NAME is derived from the container's name, not taken from an
// [env.*] profile: the profile value never reached `docker run --name`, so setting
// it there produced a container whose real name and self-reported name disagreed.
// lstk's value is appended after resolvedEnv and wins; say so rather than let the
// user's value vanish silently.
if envHasKey(resolvedEnv, "MAIN_CONTAINER_NAME") {
sink.Emit(output.MessageEvent{
Severity: output.SeverityWarning,
Text: fmt.Sprintf("Ignoring MAIN_CONTAINER_NAME from your env profile — the emulator is named %q. Set 'container_name' in the [[containers]] block to rename it.", containerName),
})
}
env := append(resolvedEnv,
"LOCALSTACK_AUTH_TOKEN="+token,
"GATEWAY_LISTEN="+gateway.containerEnvValue(),
Expand Down
30 changes: 30 additions & 0 deletions internal/validate/validate.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,36 @@ func PodName(value string) error {
return nil
}

// containerNameRegexp mirrors Docker's own container-name rule: the first character
// must be alphanumeric, the rest may also include underscores, dots, and hyphens.
// The daemon rejects anything else with "Invalid container name", so accepting it
// here would only defer the failure to container creation.
var containerNameRegexp = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_.-]*$`)

// ContainerName validates a user-supplied Docker container name. Like PodName it runs
// ordered deny-checks so the most specific reason wins, then the allow-list. The
// 128-character cap is a local sanity limit against absurd inputs, not a Docker rule.
func ContainerName(value string) error {
const field = "container name"
switch {
case value == "":
return newError(field, RuleEmpty, "must not be empty")
case containsControlChars(value):
return newError(field, RuleControlChars, "contains control characters")
case strings.Contains(value, "%"):
return newError(field, RuleEncoding, "contains percent-encoding (pass the decoded value)")
case strings.ContainsAny(value, "/?#"):
return newError(field, RuleEmbedded, "contains path or query characters (/, ?, #)")
case strings.ContainsAny(value, shellMetaChars):
return newError(field, RuleMetachars, "contains shell metacharacters")
case len(value) > 128:
return newError(field, RuleRange, "must be 128 characters or fewer")
case !containerNameRegexp.MatchString(value):
return newError(field, RuleFormat, "must start with a letter or digit and use only letters, digits, dots, hyphens, and underscores")
}
return nil
}

// serviceListRegexp matches a comma-delimited list of service-name tokens:
// letters, digits, underscores, and hyphens, with optional whitespace around
// each item and separator. Mirrors the legacy CLI's is_comma_delimited_list
Expand Down
52 changes: 52 additions & 0 deletions internal/validate/validate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,58 @@ func TestPodName(t *testing.T) {
}
}

func TestContainerName(t *testing.T) {
t.Parallel()
tests := []struct {
name string
value string
wantErr bool
wantRule string
}{
{"default derived name", "localstack-aws", false, ""},
{"derived name with tag", "localstack-aws-2026.4", false, ""},
{"single char", "a", false, ""},
{"digit start", "1st-emulator", false, ""},
{"underscore", "ls_jenkins", false, ""},
{"period", "ls.jenkins", false, ""},
{"maximum length", strings.Repeat("a", 128), false, ""},
{"too long", strings.Repeat("a", 129), true, RuleRange},
{"empty", "", true, RuleEmpty},
{"control char", "ba\x00d", true, RuleControlChars},
{"percent encoding", "ls%2Fmain", true, RuleEncoding},
{"slash", "team/ls", true, RuleEmbedded},
{"path traversal", "../etc", true, RuleEmbedded},
{"embedded query", "ls?fields=name", true, RuleEmbedded},
{"fragment", "ls#frag", true, RuleEmbedded},
{"shell metachar semicolon", "ls;rm", true, RuleMetachars},
{"shell metachar subshell", "ls$(id)", true, RuleMetachars},
{"shell metachar backtick", "ls`id`", true, RuleMetachars},
{"leading hyphen", "-ls", true, RuleFormat},
{"leading underscore", "_ls", true, RuleFormat},
{"leading dot", ".ls", true, RuleFormat},
{"space", "my emulator", true, RuleFormat},
{"colon", "ls:1", true, RuleFormat},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
err := ContainerName(tt.value)
if (err != nil) != tt.wantErr {
t.Fatalf("ContainerName(%q) error = %v, wantErr %v", tt.value, err, tt.wantErr)
}
if tt.wantRule != "" {
var ve *Error
if !errors.As(err, &ve) {
t.Fatalf("ContainerName(%q) error is not *validate.Error: %v", tt.value, err)
}
if ve.Rule != tt.wantRule {
t.Errorf("ContainerName(%q) Rule = %q, want %q", tt.value, ve.Rule, tt.wantRule)
}
}
})
}
}

func TestAuthToken(t *testing.T) {
t.Parallel()
tests := []struct {
Expand Down
Loading