awesome-emulator-cli 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
  <img src="./assets/social-preview-v2.png" alt="Awesome Emulator CLI — Local emulator testing for AWS SDKs" width="100%">
5
5
  </p>
6
6
 
7
- Awesome Emulator CLI is a Docker wrapper for AWS Emulator: it starts a local container and supplies connection settings to your test command. The CLI is distributed with Node.js, but the project under test can use any AWS SDK language and does not need to be a Node.js project.
7
+ A Node.js CLI that manages AWS Emulator in Docker and passes its connection settings to your test command. Your tests can use any AWS SDK language; they do not need to run in Node.js.
8
8
 
9
9
  This is an independent project and is not affiliated with or endorsed by Amazon Web Services.
10
10
 
@@ -14,118 +14,61 @@ This is an independent project and is not affiliated with or endorsed by Amazon
14
14
  - Docker Engine or Docker Desktop
15
15
  - x86_64/amd64 or ARM64/aarch64
16
16
 
17
- Node.js is required to run the CLI. Your application and test project can use any language.
17
+ On first use, Docker downloads the selected AWS Emulator RPM and signature, verifies the signature, and builds an image. The image is reused on later runs. To prepare it before tests start, run `npx awesome-emulator prepare`; use `--version` or `AWS_EMULATOR_VERSION` to select a release.
18
18
 
19
- On first start, Docker downloads the selected AWS Emulator RPM and its signature, verifies the signature, and builds a local image. Later starts reuse the image for that version and architecture.
20
-
21
- Prepare the image ahead of the first test run with:
22
-
23
- ```sh
24
- npx awesome-emulator prepare
25
- ```
26
-
27
- This builds or reuses the same versioned image as `start` and `run`, without starting a container or creating emulator state files. It can be run during CI setup or alongside other independent setup work so image construction does not delay the first test command. Pass `--version` or set `AWS_EMULATOR_VERSION` when you want to prepare a specific release.
28
-
29
- ## Run a test command
19
+ ## Run tests
30
20
 
31
21
  ```sh
32
22
  npm install --save-dev awesome-emulator-cli
33
23
  npx awesome-emulator run -- npm test
34
24
  ```
35
25
 
36
- `run` starts the emulator, supplies the connection settings to the child process, then stops the container. Use `--version` to select a release and `--port 0` to choose a free local port. Run `npx awesome-emulator --help` for all options.
37
-
38
- Set the child's default AWS region with `--region`:
26
+ `run` starts the emulator, supplies its endpoint and TLS settings to the child process, then stops the container. Set the child's default region with `--region`:
39
27
 
40
28
  ```sh
41
29
  npx awesome-emulator run --region ap-northeast-1 -- npm test
42
30
  ```
43
31
 
44
- By default, both `AWS_REGION` and `AWS_DEFAULT_REGION` are `us-east-1`. `--region` sets both for the child command without changing the emulator endpoint. An SDK client configured with its own region continues to use that explicit region.
45
-
46
- ### Run non-Node projects
32
+ Both `AWS_REGION` and `AWS_DEFAULT_REGION` default to `us-east-1`. An explicit region on an SDK client still takes precedence.
47
33
 
48
- You can run an existing project command even when the project has no `package.json`. Use `npm exec` to download the CLI for the run:
49
-
50
- ```sh
51
- npm exec --yes --package=awesome-emulator-cli -- awesome-emulator run -- python -m pytest
52
- ```
34
+ The CLI removes inherited AWS credentials, profiles, and service endpoints from the child environment. Credentials or endpoints explicitly set in project or build configuration still need to target the emulator. Commands run without a shell by default; on Windows, `.cmd` and `.bat` commands need `--shell`, which should only be used with trusted arguments.
53
35
 
54
- The same pattern works with other SDK projects:
36
+ Credentials are read from the emulator's shared credentials file by default. If an SDK or application needs standard AWS credential environment variables, opt in for a wrapped command with `--credentials env`:
55
37
 
56
38
  ```sh
57
- # AWS CLI v2, Boto3, and AWS SDK for Go v2 use AWS_CA_BUNDLE automatically.
58
- npm exec --yes --package=awesome-emulator-cli -- awesome-emulator run -- aws sts get-caller-identity
59
- npm exec --yes --package=awesome-emulator-cli -- awesome-emulator run -- python -m pytest
60
- npm exec --yes --package=awesome-emulator-cli -- awesome-emulator run -- go test ./...
61
-
62
- # AWS SDK for JavaScript v3 uses NODE_EXTRA_CA_CERTS, which the CLI sets by default.
63
- npm exec --yes --package=awesome-emulator-cli -- awesome-emulator run -- npm test
64
-
65
- # Java, Rust, and .NET need an additional TLS setting.
66
- npm exec --yes --package=awesome-emulator-cli -- awesome-emulator run --sdk java-v2 -- ./mvnw -B -o test
67
- npm exec --yes --package=awesome-emulator-cli -- awesome-emulator run --sdk rust -- cargo test --offline
68
- npm exec --yes --package=awesome-emulator-cli -- awesome-emulator run --sdk dotnet -- dotnet test --no-restore
39
+ npx awesome-emulator run --credentials env -- npm test
69
40
  ```
70
41
 
71
- Resolve Java, Rust, and .NET dependencies before the wrapped command when they are not already cached. For example, run `./mvnw -B dependency:go-offline`, `cargo fetch`, or `dotnet restore` before starting the emulator.
72
-
73
- The repository runs an integration smoke check for AWS CLI v2, Boto3, AWS SDK for JavaScript v3, Java 2.x, Go v2, Rust, and .NET. It verifies that each client reaches the emulator's STS endpoint with TLS enabled and receives the emulator account ID.
74
-
75
- The common child environment sets `AWS_ENDPOINT_URL`, the emulator credentials and config files, `AWS_CA_BUNDLE`, and the region. The CLI removes inherited credential variables, profile selectors, and service-specific endpoint variables so those host environment settings cannot redirect or authenticate the test. `AWS_DISABLE_HOST_PREFIX_INJECTION` is enabled for SDKs that otherwise rewrite the local host. The wrapper manages inherited environment and JVM option variables; project code or build configuration that explicitly sets credentials or endpoints must be configured for the emulator.
76
-
77
- Use `--sdk` only when a process needs SDK-specific TLS configuration. It can be repeated when one command runs more than one SDK:
78
-
79
- | SDK | TLS configuration |
80
- | --- | --- |
81
- | AWS CLI v2, Boto3, AWS SDK for Go v2 | `AWS_CA_BUNDLE` |
82
- | AWS SDK for JavaScript v3 | `NODE_EXTRA_CA_CERTS` |
83
- | AWS SDK for Java 2.x | `--sdk java-v2` adds the emulator `truststore.p12` to `JAVA_TOOL_OPTIONS` |
84
- | AWS SDK for Rust | `--sdk rust` sets `SSL_CERT_FILE` to `ca.pem` |
85
- | AWS SDK for .NET | `--sdk dotnet` sets `SSL_CERT_FILE` to `ca.pem` |
86
-
87
- Java's `JAVA_TOOL_OPTIONS` applies to every JVM started by the child command, including Maven or Gradle and test workers. Resolve Java build dependencies before invoking `awesome-emulator run`, or use a truststore that contains both the emulator certificate and the certificates for other HTTPS hosts. The emulator truststore contains only the emulator certificate, so HTTPS calls to Maven Central, AWS, or other hosts can fail while it is active. The CLI appends to existing `JAVA_TOOL_OPTIONS`; if `JAVA_TOOL_OPTIONS`, `JDK_JAVA_OPTIONS`, or `_JAVA_OPTIONS` already sets `javax.net.ssl.trustStore`, it preserves that truststore. If only `javax.net.ssl.trustStoreType=PKCS12` is set, the CLI adds the emulator truststore path and preserves the type. An incompatible truststore type requires a custom truststore path. A preserved truststore must also trust the emulator. `MAVEN_OPTS` and `GRADLE_OPTS` remain in their own variables; if either sets a separate truststore, make sure the Java test JVM trusts the emulator too.
42
+ This passes only credentials generated by the emulator as `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and, when present, `AWS_SESSION_TOKEN`. See the [SDK configuration guide](./docs/sdk-configuration.md) for the CA and truststore paths exposed to child commands.
88
43
 
89
- The AWS SDK for Java gives JVM system properties precedence over environment variables. When `--sdk java-v2` is selected, the CLI checks inherited `JAVA_TOOL_OPTIONS`, `JDK_JAVA_OPTIONS`, `_JAVA_OPTIONS`, `JAVA_OPTS`, `MAVEN_OPTS`, `GRADLE_OPTS`, `ANT_OPTS`, and `SBT_OPTS` values and rejects AWS credential, profile, or endpoint properties and `@argument-file` references so inherited JVM options cannot bypass the emulator settings.
90
-
91
- `AWS_CA_BUNDLE` and `SSL_CERT_FILE` replace the default CA bundle for SDKs that read them. If the same process must contact other HTTPS services, create a combined bundle with the emulator CA and the roots it needs. `NODE_EXTRA_CA_CERTS` is additive to Node.js's default trust roots.
92
-
93
- Child commands run without a shell by default, so each argument is passed as data. On Windows, `.cmd` and `.bat` launchers such as `npm`, and shell built-ins such as `echo` and `dir`, require an explicit shell opt-in:
44
+ The CLI can run commands from projects without a `package.json` too. For example, run Python tests with:
94
45
 
95
46
  ```sh
96
- npx awesome-emulator run --shell -- npm test
47
+ npm exec --yes --package=awesome-emulator-cli -- awesome-emulator run -- python -m pytest
97
48
  ```
98
49
 
99
- Use `--shell` only with trusted command and argument values. Shell metacharacters are interpreted in this mode. Node.js API callers can opt in with `runWithEmulator(command, args, { shell: true })` under the same restriction.
50
+ The same pattern works with AWS CLI, Go, Java, Rust, and .NET projects. Use `--sdk` when a command needs SDK-specific TLS settings; see the [SDK configuration guide](./docs/sdk-configuration.md).
100
51
 
101
- ## Reuse an emulator across commands
52
+ ## Reuse the emulator across commands
102
53
 
103
- Use a named session when setup and tests run in separate commands or CI steps. The session metadata is stored under `~/.aws/emulator/sessions/` with restrictive file permissions on Unix systems; it contains container and connection details, not credential values. `exec` supplies the same emulator environment as `run` and can be called repeatedly:
54
+ Use a named session when setup and tests run as separate commands or CI steps. Set `AWS_EMULATOR_STATE_DIR` to keep emulator files outside `~/.aws/emulator` without changing `HOME`; the same value is used by `up`, `exec`, and `down`:
104
55
 
105
56
  ```sh
106
- npx awesome-emulator up --session ci-tests --port 0
107
- npx awesome-emulator exec --session ci-tests -- npm run seed
57
+ export AWS_EMULATOR_STATE_DIR="${RUNNER_TEMP:-/tmp}/awesome-emulator-cli"
58
+ npx awesome-emulator up --session ci-tests --init -- node scripts/seed-emulator.js
108
59
  npx awesome-emulator exec --session ci-tests -- npm test
109
60
  npx awesome-emulator down --session ci-tests
110
61
  ```
111
62
 
112
- In CI, put the final `down` command in an always-run cleanup step so the container is removed even when a test step fails. Each CI job should use its own session name. `up` prints the connection settings as JSON; it does not print the container ID or credential values.
113
-
114
- Persistent sessions use `ps` on Unix or Windows PowerShell on Windows to distinguish an active startup from an abandoned session record.
63
+ Use `--state-dir <path>` to override the environment variable for one command. Relative paths are resolved from the current working directory. The Node.js API accepts the same setting as `stateDirectory`.
115
64
 
116
- Run a one-time seed or setup command after the emulator becomes healthy with `--init`. The initializer receives the same emulator environment as `exec`; a non-zero exit makes `up` fail and stops the session. Initializer stdout is sent to stderr so the JSON printed by `up` remains machine-readable:
65
+ `--init` runs once after the emulator is healthy. If it fails, `up` stops the container and exits with an error. Initializer output goes to stderr so `up`'s JSON output stays machine-readable. Use `down` in an always-run CI cleanup step to stop the session after failures.
117
66
 
118
- ```sh
119
- npx awesome-emulator up --session ci-tests --init -- node scripts/seed-emulator.js
120
- npx awesome-emulator exec --session ci-tests -- npm test
121
- npx awesome-emulator down --session ci-tests
122
- ```
123
-
124
- Initializer arguments are passed directly without a shell by default. Use `--shell` before `--` only when you need shell behavior and trust all command values.
67
+ Session metadata is stored in `<state-dir>/sessions/` and contains connection details, not credential values. The default directory is `~/.aws/emulator/` (Windows: `%USERPROFILE%\.aws\emulator\`).
125
68
 
126
69
  ## Use from Node.js
127
70
 
128
- Use the API when your test harness needs to control the emulator lifecycle directly:
71
+ Use the API when a test harness needs to control the emulator directly:
129
72
 
130
73
  ```js
131
74
  import { startEmulator } from "awesome-emulator-cli";
@@ -138,24 +81,18 @@ try {
138
81
  }
139
82
  ```
140
83
 
141
- Pass an `AbortSignal` as `signal` to cancel image building or startup. `NODE_EXTRA_CA_CERTS` is read when Node.js starts. For an already-running Node.js process, configure the AWS SDK's HTTPS handler with `emulator.caFile`; use `awesome-emulator run` when you want the wrapper to start a child process with TLS settings already applied.
84
+ Pass an `AbortSignal` as `signal` to cancel image building or startup. For an already-running Node.js process, configure the AWS SDK's HTTPS handler with `emulator.caFile`; `NODE_EXTRA_CA_CERTS` is only read when Node.js starts.
142
85
 
143
86
  ## Local files and telemetry
144
87
 
145
- The emulator writes its config, credentials, and CA certificate under `~/.aws/emulator/<port>/` (Windows: `%USERPROFILE%\.aws\emulator\<port>\`). The emulator keeps resources in memory; a clean stop removes the per-port files and resources.
146
-
147
- Telemetry is on by default. AWS says it collects aggregate usage and error data, not requests, responses, code, credentials, or personal data. Turn it off for a run with:
148
-
149
- ```sh
150
- npx awesome-emulator run --telemetry off -- npm test
151
- ```
88
+ The emulator stores its config, credentials, and CA certificate under `<state-dir>/<port>/`. Resources stay in memory and are removed when the container stops.
152
89
 
153
- Read the [AWS Emulator telemetry details](https://docs.aws.amazon.com/emulator/latest/userguide/telemetry.html) before choosing whether to leave telemetry on.
90
+ Telemetry is on by default. Turn it off for a run with `--telemetry off`. See [AWS Emulator telemetry details](https://docs.aws.amazon.com/emulator/latest/userguide/telemetry.html) for what it collects.
154
91
 
155
92
  AWS Emulator is for building and testing. Do not use it for production workloads or security testing. See the [official limitations](https://docs.aws.amazon.com/emulator/latest/userguide/) and [security guidance](https://docs.aws.amazon.com/emulator/latest/userguide/security.html).
156
93
 
157
- See [CONTRIBUTING.md](./CONTRIBUTING.md) to contribute and [SECURITY.md](./SECURITY.md) to report a vulnerability.
158
-
159
94
  ## License
160
95
 
161
96
  MIT. See [LICENSE](./LICENSE). This license covers the wrapper; downloaded AWS Emulator binaries retain their own license and notices.
97
+
98
+ See [CONTRIBUTING.md](./CONTRIBUTING.md) to contribute and [SECURITY.md](./SECURITY.md) to report a vulnerability.
package/dist/cli.js CHANGED
@@ -6,21 +6,23 @@ import { DEFAULT_AWS_REGION, SUPPORTED_EMULATOR_SDKS } from "./emulator-environm
6
6
  function usage() {
7
7
  console.log(`Usage:
8
8
  awesome-emulator prepare [--version <version>]
9
- awesome-emulator start [options]
10
- awesome-emulator run [options] [--region <region>] [--sdk <family>]... [--shell] -- <command> [args...]
11
- awesome-emulator up --session <name> [options] [--init [child options] -- <command> [args...]]
12
- awesome-emulator exec --session <name> [--region <region>] [--sdk <family>]... [--shell] -- <command> [args...]
13
- awesome-emulator down --session <name>
9
+ awesome-emulator start [options] [--state-dir <path>]
10
+ awesome-emulator run [options] [--state-dir <path>] [--region <region>] [--sdk <family>]... [--credentials <files|env>] [--shell] -- <command> [args...]
11
+ awesome-emulator up --session <name> [options] [--state-dir <path>] [--init [child options] -- <command> [args...]]
12
+ awesome-emulator exec --session <name> [--state-dir <path>] [--region <region>] [--sdk <family>]... [--credentials <files|env>] [--shell] -- <command> [args...]
13
+ awesome-emulator down --session <name> [--state-dir <path>]
14
14
 
15
15
  Options:
16
16
  -v, --version <version> AWS Emulator version (default: ${DEFAULT_VERSION})
17
17
  -p, --port <port> (start/run/up) Host port; 0 chooses an available port (default: 9297)
18
18
  -t, --telemetry <on|off> (start/run/up) Telemetry setting (default: on)
19
19
  --memory <limit> (start/run/up) Container memory limit (default: 2g)
20
+ --state-dir <path> (start/run/up/exec/down) Emulator state directory (default: AWS_EMULATOR_STATE_DIR or ~/.aws/emulator)
20
21
  --region <region> (run/exec/up --init) Default region for the child command (default: ${DEFAULT_AWS_REGION})
21
22
  --session <name> (up/exec/down) Persistent emulator session name
22
23
  --sdk <family> (run/exec/up --init) Add SDK-specific TLS settings; repeatable
23
24
  (${SUPPORTED_EMULATOR_SDKS.join(", ")})
25
+ --credentials <mode> (run/exec/up --init) Credentials delivery: files (default) or env
24
26
  --shell (run/exec/up --init) Enable .cmd/.bat and built-ins; trusted values only
25
27
  --init (up only) Run a command after the emulator becomes healthy
26
28
  -h, --help Show this help`);
@@ -83,6 +85,8 @@ function parse(argv) {
83
85
  "--memory": "memory",
84
86
  "--region": "region",
85
87
  "--session": "session",
88
+ "--state-dir": "stateDirectory",
89
+ "--credentials": "credentials",
86
90
  };
87
91
  const key = optionNames[token];
88
92
  if (!key)
@@ -93,16 +97,29 @@ function parse(argv) {
93
97
  if (key === "session" && command !== "up" && command !== "exec" && command !== "down") {
94
98
  throw new Error("--session can only be used with the up, exec, or down command.");
95
99
  }
100
+ if (key === "stateDirectory" && !["start", "run", "up", "exec", "down"].includes(command ?? "")) {
101
+ throw new Error("--state-dir can only be used with start, run, up, exec, or down.");
102
+ }
103
+ if (key === "credentials" && command !== "run" && command !== "exec" && command !== "up") {
104
+ throw new Error("--credentials can only be used with the run or exec command, or with up --init.");
105
+ }
96
106
  if (command === "prepare" && key !== "version") {
97
107
  throw new Error(`${token} can only be used with the start or run command.`);
98
108
  }
99
- if ((command === "exec" || command === "down") && key !== "region" && key !== "session") {
109
+ if ((command === "exec" || command === "down") && key !== "region" && key !== "session" && key !== "stateDirectory" && key !== "credentials") {
100
110
  throw new Error(`${token} cannot be used with the ${command} command.`);
101
111
  }
102
112
  const value = argv[index + 1];
103
113
  if (!value || value.startsWith("--"))
104
114
  throw new Error(`Missing value for ${token}`);
105
- options[key] = value;
115
+ if (key === "credentials") {
116
+ if (value !== "files" && value !== "env")
117
+ throw new Error("--credentials must be files or env.");
118
+ options.credentials = value === "env" ? "environment" : "files";
119
+ }
120
+ else {
121
+ options[key] = value;
122
+ }
106
123
  index += 1;
107
124
  }
108
125
  if ((command === "up" || command === "exec" || command === "down") && !options.session) {
@@ -112,7 +129,7 @@ function parse(argv) {
112
129
  if (initRequested && (!separator || commandArgs.length === 0)) {
113
130
  throw new Error("Usage: awesome-emulator up --session <name> [options] --init -- <command> [args...]");
114
131
  }
115
- if (!initRequested && (separator || options.region || options.sdks || options.shell)) {
132
+ if (!initRequested && (separator || options.region || options.sdks || options.shell || options.credentials)) {
116
133
  throw new Error("Child command options and arguments for up require --init.");
117
134
  }
118
135
  }
@@ -152,6 +169,7 @@ async function main(signal) {
152
169
  port: parsed.options.port,
153
170
  telemetry: parsed.options.telemetry,
154
171
  memory: parsed.options.memory,
172
+ stateDirectory: parsed.options.stateDirectory,
155
173
  signal,
156
174
  init: parsed.options.init ? {
157
175
  command: initCommand,
@@ -159,6 +177,7 @@ async function main(signal) {
159
177
  region: parsed.options.region,
160
178
  sdks: parsed.options.sdks,
161
179
  shell: parsed.options.shell,
180
+ credentials: parsed.options.credentials,
162
181
  } : undefined,
163
182
  });
164
183
  console.log(JSON.stringify(session, null, 2));
@@ -172,13 +191,15 @@ async function main(signal) {
172
191
  region: parsed.options.region,
173
192
  sdks: parsed.options.sdks,
174
193
  shell: parsed.options.shell,
194
+ stateDirectory: parsed.options.stateDirectory,
195
+ credentials: parsed.options.credentials,
175
196
  signal,
176
197
  });
177
198
  }
178
199
  if (parsed.command === "down") {
179
200
  if (parsed.commandArgs.length > 0)
180
201
  throw new Error("The down command does not accept child command arguments.");
181
- await downEmulatorSession(parsed.options.session);
202
+ await downEmulatorSession(parsed.options.session, { stateDirectory: parsed.options.stateDirectory });
182
203
  console.log(`Emulator session "${parsed.options.session}" stopped.`);
183
204
  return 0;
184
205
  }
@@ -193,6 +214,7 @@ async function main(signal) {
193
214
  port: parsed.options.port,
194
215
  telemetry: parsed.options.telemetry,
195
216
  memory: parsed.options.memory,
217
+ stateDirectory: parsed.options.stateDirectory,
196
218
  signal,
197
219
  });
198
220
  try {
@@ -0,0 +1,6 @@
1
+ export type EmulatorCredentialEnvironment = {
2
+ AWS_ACCESS_KEY_ID: string;
3
+ AWS_SECRET_ACCESS_KEY: string;
4
+ AWS_SESSION_TOKEN?: string;
5
+ };
6
+ export declare function readEmulatorCredentialEnvironment(credentialsFile: string): Promise<EmulatorCredentialEnvironment>;
@@ -0,0 +1,35 @@
1
+ import { readFile } from "node:fs/promises";
2
+ export async function readEmulatorCredentialEnvironment(credentialsFile) {
3
+ const contents = await readFile(credentialsFile, "utf8");
4
+ const credentials = {};
5
+ let inDefaultProfile = false;
6
+ for (const rawLine of contents.replace(/^\uFEFF/, "").split(/\r?\n/)) {
7
+ const line = rawLine.trim();
8
+ if (line.length === 0 || line.startsWith("#") || line.startsWith(";"))
9
+ continue;
10
+ const section = /^\[([^\]]+)\]$/.exec(line);
11
+ if (section) {
12
+ inDefaultProfile = section[1].trim().toLowerCase() === "default";
13
+ continue;
14
+ }
15
+ if (!inDefaultProfile)
16
+ continue;
17
+ const entry = /^([^=]+?)\s*=\s*(.*)$/.exec(line);
18
+ if (!entry)
19
+ continue;
20
+ const key = entry[1].trim().toLowerCase();
21
+ if (["aws_access_key_id", "aws_secret_access_key", "aws_session_token"].includes(key)) {
22
+ credentials[key] = entry[2].trim();
23
+ }
24
+ }
25
+ const accessKeyId = credentials.aws_access_key_id;
26
+ const secretAccessKey = credentials.aws_secret_access_key;
27
+ if (!accessKeyId || !secretAccessKey) {
28
+ throw new Error("The Emulator credentials file does not contain a usable [default] access key and secret key.");
29
+ }
30
+ return {
31
+ AWS_ACCESS_KEY_ID: accessKeyId,
32
+ AWS_SECRET_ACCESS_KEY: secretAccessKey,
33
+ ...(credentials.aws_session_token ? { AWS_SESSION_TOKEN: credentials.aws_session_token } : {}),
34
+ };
35
+ }
@@ -1,4 +1,7 @@
1
1
  export type EmulatorEnvironment = {
2
+ AWS_EMULATOR_STATE_DIR: string;
3
+ AWS_EMULATOR_CA_FILE: string;
4
+ AWS_EMULATOR_TRUSTSTORE_FILE: string;
2
5
  AWS_ENDPOINT_URL: string;
3
6
  AWS_SHARED_CREDENTIALS_FILE: string;
4
7
  AWS_CONFIG_FILE: string;
@@ -37,6 +37,8 @@ const JAVA_OPTION_ENVIRONMENT_KEYS = [
37
37
  "ANT_OPTS",
38
38
  "SBT_OPTS",
39
39
  ];
40
+ // npm exec --package exports its selector to children; nested npx must use its own requested package.
41
+ const NPM_LAUNCHER_ENVIRONMENT_KEYS = ["npm_config_package"];
40
42
  const JVM_WIDE_JAVA_OPTION_ENVIRONMENT_KEYS = [
41
43
  "JAVA_TOOL_OPTIONS",
42
44
  "JDK_JAVA_OPTIONS",
@@ -59,6 +61,9 @@ export function createEmulatorConnectionSettings(port, stateDirectory) {
59
61
  const endpointUrl = `https://127.0.0.1:${port}`;
60
62
  const portDirectory = path.join(stateDirectory, String(port));
61
63
  const environment = {
64
+ AWS_EMULATOR_STATE_DIR: stateDirectory,
65
+ AWS_EMULATOR_CA_FILE: path.join(portDirectory, "ca.pem"),
66
+ AWS_EMULATOR_TRUSTSTORE_FILE: path.join(portDirectory, "truststore.p12"),
62
67
  AWS_ENDPOINT_URL: endpointUrl,
63
68
  AWS_SHARED_CREDENTIALS_FILE: path.join(portDirectory, "emulator_credentials"),
64
69
  AWS_CONFIG_FILE: path.join(portDirectory, "config"),
@@ -86,6 +91,7 @@ export function createChildEnvironment(parentEnvironment, emulatorEnvironment, o
86
91
  const controlledEnvironmentKeys = new Set([
87
92
  ...Object.keys(emulatorEnvironment),
88
93
  ...AWS_CREDENTIAL_ENVIRONMENT_KEYS,
94
+ ...NPM_LAUNCHER_ENVIRONMENT_KEYS,
89
95
  ...(sdks.includes("rust") || sdks.includes("dotnet") ? ["SSL_CERT_FILE"] : []),
90
96
  ].map(normalizeName));
91
97
  for (const key of Object.keys(childEnvironment)) {
@@ -1,6 +1,9 @@
1
1
  import type { EmulatorSdk } from "./emulator-environment.js";
2
+ export type EmulatorCredentialsMode = "files" | "environment";
3
+ export declare function resolveEmulatorCredentialsMode(value: string | undefined): EmulatorCredentialsMode;
2
4
  export type StartEmulatorOptions = {
3
5
  version?: string;
6
+ stateDirectory?: string;
4
7
  port?: number | string;
5
8
  telemetry?: string;
6
9
  memory?: string;
@@ -18,6 +21,8 @@ export type RunWithEmulatorOptions = StartEmulatorOptions & {
18
21
  region?: string;
19
22
  /** Add SDK-specific TLS settings for the selected SDK families. */
20
23
  sdks?: EmulatorSdk[];
24
+ /** Pass Emulator-generated credentials through AWS credential environment variables instead of relying only on files. */
25
+ credentials?: EmulatorCredentialsMode;
21
26
  };
22
27
  export type PrepareEmulatorOptions = Pick<StartEmulatorOptions, "version" | "signal">;
23
28
  export type ResolvedEmulatorOptions = {
@@ -27,6 +32,7 @@ export type ResolvedEmulatorOptions = {
27
32
  memory: string;
28
33
  startupTimeoutMs: number;
29
34
  };
35
+ export declare function resolveEmulatorStateDirectory(value: string | undefined, environment?: NodeJS.ProcessEnv, homeDirectory?: string, workingDirectory?: string): string;
30
36
  export declare const DEFAULT_VERSION = "1.0.533";
31
37
  export declare function resolveEmulatorVersion(value: string | undefined, environment?: NodeJS.ProcessEnv): string;
32
38
  export declare function resolveEmulatorOptions(options: StartEmulatorOptions, environment?: NodeJS.ProcessEnv): ResolvedEmulatorOptions;
@@ -1,3 +1,19 @@
1
+ import os from "node:os";
2
+ import path from "node:path";
3
+ export function resolveEmulatorCredentialsMode(value) {
4
+ const mode = value ?? "files";
5
+ if (mode !== "files" && mode !== "environment") {
6
+ throw new Error("Credentials mode must be files or environment.");
7
+ }
8
+ return mode;
9
+ }
10
+ export function resolveEmulatorStateDirectory(value, environment = process.env, homeDirectory = os.homedir(), workingDirectory = process.cwd()) {
11
+ const configuredDirectory = value ?? environment.AWS_EMULATOR_STATE_DIR;
12
+ if (configuredDirectory !== undefined && configuredDirectory.trim().length === 0) {
13
+ throw new Error("Emulator state directory must not be empty.");
14
+ }
15
+ return path.resolve(workingDirectory, configuredDirectory ?? path.join(homeDirectory, ".aws", "emulator"));
16
+ }
1
17
  export const DEFAULT_VERSION = "1.0.533";
2
18
  const DEFAULT_PORT = 9297;
3
19
  const DEFAULT_MEMORY = "2g";
package/dist/index.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { type EmulatorEnvironment, type EmulatorSdk } from "./emulator-environment.js";
2
- import { type PrepareEmulatorOptions, type RunWithEmulatorOptions, type StartEmulatorOptions } from "./emulator-options.js";
2
+ import { type PrepareEmulatorOptions, type EmulatorCredentialsMode, type RunWithEmulatorOptions, type StartEmulatorOptions } from "./emulator-options.js";
3
3
  export type { PrepareEmulatorOptions, RunWithEmulatorOptions, StartEmulatorOptions } from "./emulator-options.js";
4
+ export type { EmulatorCredentialsMode } from "./emulator-options.js";
4
5
  export type { EmulatorEnvironment, EmulatorSdk } from "./emulator-environment.js";
5
6
  export type EmulatorSession = {
6
7
  version: string;
@@ -17,13 +18,14 @@ export type EmulatorSession = {
17
18
  export type PersistentEmulatorSession = Omit<EmulatorSession, "containerId" | "stop"> & {
18
19
  name: string;
19
20
  };
20
- export type EmulatorSessionExecOptions = Pick<RunWithEmulatorOptions, "shell" | "sdks" | "region" | "signal">;
21
+ export type EmulatorSessionExecOptions = Pick<RunWithEmulatorOptions, "shell" | "sdks" | "region" | "signal" | "stateDirectory" | "credentials">;
21
22
  export type EmulatorSessionInitCommand = {
22
23
  command: string;
23
24
  args?: string[];
24
25
  shell?: boolean;
25
26
  sdks?: EmulatorSdk[];
26
27
  region?: string;
28
+ credentials?: EmulatorCredentialsMode;
27
29
  };
28
30
  export type UpEmulatorSessionOptions = StartEmulatorOptions & {
29
31
  init?: EmulatorSessionInitCommand;
@@ -33,7 +35,7 @@ export declare function prepareEmulatorImage(options?: PrepareEmulatorOptions):
33
35
  export declare function startEmulator(options?: StartEmulatorOptions): Promise<EmulatorSession>;
34
36
  export declare function upEmulatorSession(name: string, options?: UpEmulatorSessionOptions): Promise<PersistentEmulatorSession>;
35
37
  export declare function execEmulatorSession(name: string, command: string, args?: string[], options?: EmulatorSessionExecOptions): Promise<number>;
36
- export declare function downEmulatorSession(name: string): Promise<void>;
38
+ export declare function downEmulatorSession(name: string, options?: Pick<StartEmulatorOptions, "stateDirectory">): Promise<void>;
37
39
  /**
38
40
  * Run a child process with AWS Emulator settings and stop the emulator afterward.
39
41
  */
package/dist/index.js CHANGED
@@ -2,20 +2,26 @@ import { randomBytes } from "node:crypto";
2
2
  import { mkdir, readFile } from "node:fs/promises";
3
3
  import https from "node:https";
4
4
  import net from "node:net";
5
- import os from "node:os";
6
5
  import path from "node:path";
7
6
  import { createRetryableStop, startContainer, stopContainer, withEmulator } from "./container-lifecycle.js";
8
7
  import { docker, throwIfAborted } from "./docker.js";
9
8
  import { createChildEnvironment, createEmulatorConnectionSettings, normalizeEmulatorSdks, resolveAwsRegion, } from "./emulator-environment.js";
9
+ import { readEmulatorCredentialEnvironment } from "./emulator-credentials.js";
10
10
  import { ensureEmulatorImage, getArchitecture } from "./emulator-image.js";
11
11
  import { isSessionOwnerRunning, readSession, removeSession, reserveSession, validateSessionName, writeRunningSession } from "./session-store.js";
12
- import { resolveEmulatorOptions, resolveEmulatorVersion, } from "./emulator-options.js";
12
+ import { resolveEmulatorOptions, resolveEmulatorStateDirectory, resolveEmulatorCredentialsMode, resolveEmulatorVersion, } from "./emulator-options.js";
13
13
  import { runCommand } from "./process.js";
14
+ async function createCommandEnvironment(parentEnvironment, emulatorEnvironment, options = {}) {
15
+ const { credentials, ...environmentOptions } = options;
16
+ const credentialsMode = resolveEmulatorCredentialsMode(credentials);
17
+ const childEnvironment = createChildEnvironment(parentEnvironment, emulatorEnvironment, environmentOptions);
18
+ if (credentialsMode === "environment") {
19
+ Object.assign(childEnvironment, await readEmulatorCredentialEnvironment(emulatorEnvironment.AWS_SHARED_CREDENTIALS_FILE));
20
+ }
21
+ return childEnvironment;
22
+ }
14
23
  const MANAGED_CONTAINER_LABEL = "io.github.c19yamamoto.awesome-emulator-cli.managed";
15
24
  const SESSION_CONTAINER_LABEL = "io.github.c19yamamoto.awesome-emulator-cli.session";
16
- function emulatorStateDirectory() {
17
- return path.join(os.homedir(), ".aws", "emulator");
18
- }
19
25
  /** Build or reuse the selected AWS Emulator Docker image without starting a container. */
20
26
  export async function prepareEmulatorImage(options = {}) {
21
27
  throwIfAborted(options.signal);
@@ -116,13 +122,12 @@ async function waitUntilHealthy(containerId, port, stateDirectory, timeoutMs, si
116
122
  * The returned object includes SDK environment variables and an idempotent
117
123
  * stop() function. Port 0 asks the wrapper to choose an available local port.
118
124
  */
119
- async function startEmulatorWithIdentity(options, containerName, labels) {
125
+ async function startEmulatorWithIdentity(options, containerName, labels, stateDirectory = resolveEmulatorStateDirectory(options.stateDirectory)) {
120
126
  throwIfAborted(options.signal);
121
127
  const { version, requestedPort, telemetry, memory, startupTimeoutMs } = resolveEmulatorOptions(options);
122
128
  const port = requestedPort === 0 ? await getAvailablePort() : requestedPort;
123
129
  throwIfAborted(options.signal);
124
130
  const architecture = getArchitecture();
125
- const stateDirectory = emulatorStateDirectory();
126
131
  await mkdir(stateDirectory, { recursive: true, mode: 0o700 });
127
132
  const image = await ensureEmulatorImage(version, architecture, options.signal);
128
133
  throwIfAborted(options.signal);
@@ -167,11 +172,15 @@ export async function upEmulatorSession(name, options = {}) {
167
172
  validateSessionName(name);
168
173
  const { init, ...emulatorOptions } = options;
169
174
  const initOptions = init
170
- ? { sdks: normalizeEmulatorSdks(init.sdks), region: resolveAwsRegion(init.region) }
175
+ ? {
176
+ sdks: normalizeEmulatorSdks(init.sdks),
177
+ region: resolveAwsRegion(init.region),
178
+ credentials: resolveEmulatorCredentialsMode(init.credentials),
179
+ }
171
180
  : undefined;
172
181
  if (init && !init.command)
173
182
  throw new Error("An initialization command is required.");
174
- const stateDirectory = emulatorStateDirectory();
183
+ const stateDirectory = resolveEmulatorStateDirectory(emulatorOptions.stateDirectory);
175
184
  const containerName = `awesome-emulator-cli-session-${randomBytes(4).toString("hex")}-${name}`;
176
185
  await reserveSession(stateDirectory, name, containerName);
177
186
  let emulator;
@@ -179,9 +188,9 @@ export async function upEmulatorSession(name, options = {}) {
179
188
  emulator = await startEmulatorWithIdentity(emulatorOptions, containerName, {
180
189
  [MANAGED_CONTAINER_LABEL]: "true",
181
190
  [SESSION_CONTAINER_LABEL]: name,
182
- });
191
+ }, stateDirectory);
183
192
  if (init && initOptions) {
184
- const childEnvironment = createChildEnvironment(process.env, emulator.environment, initOptions);
193
+ const childEnvironment = await createCommandEnvironment(process.env, emulator.environment, initOptions);
185
194
  const exitCode = await runCommand(init.command, init.args ?? [], childEnvironment, options.signal, init.shell ?? false, "stderr");
186
195
  if (exitCode !== 0) {
187
196
  throwIfAborted(options.signal);
@@ -254,10 +263,11 @@ export async function execEmulatorSession(name, command, args = [], options = {}
254
263
  if (!command)
255
264
  throw new Error("A command is required.");
256
265
  validateSessionName(name);
257
- const { signal, shell = false, sdks: requestedSdks = [], region } = options;
266
+ const { signal, shell = false, sdks: requestedSdks = [], region, stateDirectory: requestedStateDirectory } = options;
267
+ const credentials = resolveEmulatorCredentialsMode(options.credentials);
258
268
  const childRegion = resolveAwsRegion(region);
259
269
  const sdks = normalizeEmulatorSdks(requestedSdks);
260
- const stateDirectory = emulatorStateDirectory();
270
+ const stateDirectory = resolveEmulatorStateDirectory(requestedStateDirectory);
261
271
  const session = await readSession(stateDirectory, name);
262
272
  if (session.state !== "running") {
263
273
  throw new Error(`Emulator session "${name}" is still starting. Wait for "awesome-emulator up" to finish before running commands.`);
@@ -273,12 +283,16 @@ export async function execEmulatorSession(name, command, args = [], options = {}
273
283
  throw new Error(`Emulator session "${name}" is not running. Run "awesome-emulator down --session ${name}" to remove it.`);
274
284
  }
275
285
  const emulator = createEmulatorConnectionSettings(session.port, stateDirectory);
276
- const childEnvironment = createChildEnvironment(process.env, emulator.environment, { sdks, region: childRegion });
286
+ const childEnvironment = await createCommandEnvironment(process.env, emulator.environment, {
287
+ sdks,
288
+ region: childRegion,
289
+ credentials,
290
+ });
277
291
  return runCommand(command, args, childEnvironment, signal, shell);
278
292
  }
279
- export async function downEmulatorSession(name) {
293
+ export async function downEmulatorSession(name, options = {}) {
280
294
  validateSessionName(name);
281
- const stateDirectory = emulatorStateDirectory();
295
+ const stateDirectory = resolveEmulatorStateDirectory(options.stateDirectory);
282
296
  const session = await readSession(stateDirectory, name);
283
297
  if (session.state === "starting" && isSessionOwnerRunning(session)) {
284
298
  throw new Error(`Emulator session "${name}" is still starting. Retry after "awesome-emulator up" finishes.`);
@@ -295,10 +309,15 @@ export async function runWithEmulator(command, args = [], options = {}) {
295
309
  if (!command)
296
310
  throw new Error("A command is required.");
297
311
  const { shell = false, sdks: requestedSdks = [], region, ...emulatorOptions } = options;
312
+ const credentials = resolveEmulatorCredentialsMode(options.credentials);
298
313
  const childRegion = resolveAwsRegion(region);
299
314
  const sdks = normalizeEmulatorSdks(requestedSdks);
300
315
  return withEmulator(() => startEmulator(emulatorOptions), async (emulator) => {
301
- const childEnvironment = createChildEnvironment(process.env, emulator.environment, { sdks, region: childRegion });
316
+ const childEnvironment = await createCommandEnvironment(process.env, emulator.environment, {
317
+ sdks,
318
+ region: childRegion,
319
+ credentials,
320
+ });
302
321
  return runCommand(command, args, childEnvironment, emulatorOptions.signal, shell);
303
322
  });
304
323
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "awesome-emulator-cli",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "Run tests for AWS SDKs in any language; the CLI manages the local emulator in Docker.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",