跳到正文
DEV Community· NaveenKumar Namachivayam ⚡·· 2 小時前AI 評分72

AWS Emulator 實測:在 Linux 本機測試 S3 和 KMS

AWS Emulator Hands-On: Test S3 and KMS Locally on Linux

AI 導讀

作者在 Ubuntu 22.04 上實測 AWS Emulator 1.0.322,於本機測試 S3 與 KMS 操作及錯誤處理。多數 KMS 錯誤碼與 AWS 一致,但兩項 S3 與 KMS 整合情況不同於 AWS,且 IAM 政策評估並不等同 AWS。文章示範以 AWS CLI v2、boto3、pytest 和 GitHub Actions 建立本機及 CI 測試流程。

正文

In this blog post, we will see how to install the new AWS Emulator on a Linux VM, point the AWS CLI and boto3 at it, and test Amazon S3 and AWS KMS locally, including the KMS failure cases that usually only show up after you deploy.

Quick answer: AWS Emulator is a free, local emulator of the AWS APIs that AWS announced on 11 November 2026. You install it as a .deb or .rpm package on Linux (or run it in Docker on macOS and Windows), it serves HTTPS on 127.0.0.1:9297, and the AWS CLI and SDKs talk to it with a few environment variables. In my tests on Ubuntu, KMS encrypt, decrypt, encryption context, disabled keys, key usage, rotation, grants and S3 SSE-KMS all behaved like AWS. Two S3 plus KMS edge cases did not, and I show both below.

Tested on AWS Emulator 1.0.322 (release 2026.11.10), AWS CLI 2.40.1, Python 3.12, Ubuntu 22.04, on 12 November 2026.

What is AWS Emulator?

AWS Emulator is a local emulator for AWS APIs, built by AWS, that runs on your own machine and answers the same API calls the AWS CLI and SDKs send to the cloud. It is written in Rust, generated from the same AWS API models the SDKs use, and has no service fee.

A few things I like about the design:

  • It speaks real SigV4. Every request must be signed with the credentials the emulator generates on start. Its access key IDs start with EMULATOR, so you cannot confuse them with real keys.
  • One fake account. Everything lives in account 000000000000.
  • Unimplemented means 501. If an operation is not implemented yet, you get HTTP 501 instead of a fake success, so your test fails loudly.
  • Fidelity is measured in public. AWS publishes per-service fidelity scores, and the tests behind them are in the open aws-emulator-evaluation-suite repository. It has KMS checks such as kms/encryption-context-mismatch-rejected and kms/error-pending-deletion-encrypt.

Source code: github.com/aws/aws-emulator.

Announcement: Test your applications against AWS locally with AWS Emulator.

Why is testing AWS code locally so painful?

Before we install anything, here is the list I keep running into on real projects. If you have built anything on AWS, at least three of these will sound familiar.

  1. Slow feedback loop. Change code, package, deploy, wait, test, read CloudWatch logs, repeat. A one-line fix can cost ten minutes.
  2. Shared dev accounts. Two developers create my-test-bucket, one deletes the other's key, and nobody knows which stack owns what.
  3. Leftover resources and cost surprises. A test that crashes before cleanup leaves buckets, tables and KMS keys behind. KMS keys cost money every month until they are deleted, and deletion has a minimum 7 day waiting period.
  4. Real credentials in CI. Integration tests need access keys or OIDC roles in the pipeline, which means one more secret to rotate and one more thing that can leak.
  5. Mocks that lie. Hand-written mocks return whatever you told them to. They rarely return the exact error code AWS returns, so your error handling is never actually tested.
  6. Flaky network tests. Throttling, eventual consistency and Region outages turn a green test suite red for reasons that have nothing to do with your change.

Why is KMS the hardest part to test?

S3 is the usual starting point for local AWS testing, and it is the easy part. KMS is where I have lost hours. KMS bugs are almost always about state and context, and those are exactly what mocks skip.

KMS pain What happens in production
Encryption context mismatch Encrypt with {"tenant": "a"}, decrypt with {"tenant": "A"} or no context, and you get InvalidCiphertextException with an empty message.
Disabled key Someone disables a key during cleanup and every encrypt call starts failing with DisabledException.
Key pending deletion Reads of old data fail with KMSInvalidStateException for the whole waiting period.
Wrong key usage A SIGN_VERIFY key is passed to Encrypt, which fails with InvalidKeyUsageException.
Region and ARN mix-ups A key ARN from us-east-1 is used by a client in us-west-2, which fails with NotFoundException.
Envelope encryption GenerateDataKey, local AES, storing the encrypted data key next to the data: lots of moving parts, all easy to get subtly wrong.
S3 SSE-KMS Upload succeeds, but readers fail because they lack kms:Decrypt or the key is in the wrong state.

The good news: most of this can now be tested on a laptop.

How to install AWS Emulator on Ubuntu or any Linux

I used a fresh Ubuntu 22.04 VM. On Linux you install a native package. On macOS and Windows, AWS gives you a short Dockerfile in the docs and you run it in a container.

  1. Download and install the package.
# Debian / Ubuntu
curl -fL https://downloads.aws.com/aws-emulator/packages/aws-emulator/LTS/latest/aws-emulator_amd64.deb -o aws-emulator.deb
sudo dpkg -i aws-emulator.deb

# Amazon Linux / Fedora / RHEL
# sudo dnf install -y https://downloads.aws.com/aws-emulator/packages/aws-emulator/LTS/latest/aws-emulator-x86_64.rpm

aws-emulator -v

Tip: The Debian file name is aws-emulator_amd64.deb (underscore, amd64). I tried aws-emulator-x86_64.deb first by copying the RPM name, and the download returns HTTP 403, not 404, which looks like a permissions issue but is just the wrong file name.

  1. Install AWS CLI v2. This is the gotcha that got me.
aws --version   # Ubuntu's apt package gave me aws-cli/1.22.34, which is CLI v1

curl -s https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip -o awscliv2.zip
unzip -q awscliv2.zip && sudo ./aws/install
/usr/local/bin/aws --version   # aws-cli/2.40.1
AWS Emulator 1.0.322 and AWS CLI v2 versions on Ubuntu
AWS Emulator 1.0.322 and AWS CLI v2 versions on Ubuntu

Tip: With CLI v1, the emulator settings are silently ignored. My first aws sts get-caller-identity went to the real https://sts.amazonaws.com/ and failed with SSL: CERTIFICATE_VERIFY_FAILED. If you see a real AWS hostname in an error, check your CLI version before anything else. Same for old SDK versions: AWS_ENDPOINT_URL support needs a recent SDK.

AWS CLI v1 ignores the emulator endpoint and calls sts.amazonaws.com
AWS CLI v1 ignores the emulator endpoint and calls sts.amazonaws.com
  1. Start the emulator in its own terminal.
aws-emulator
# Serves HTTPS on 127.0.0.1:9297 and writes credentials, config and a CA to ~/.aws/emulator/9297/
# Telemetry is on by default. To opt out: EMULATOR_TELEMETRY=off aws-emulator
AWS Emulator startup log showing the endpoint, config file and CA fil
AWS Emulator startup log showing the endpoint, config file and CA fil
  1. In a second terminal, point your tools at it. I keep this in an env.sh file and source it.
export AWS_ENDPOINT_URL=https://127.0.0.1:9297
export AWS_SHARED_CREDENTIALS_FILE=~/.aws/emulator/9297/emulator_credentials
export AWS_CONFIG_FILE=~/.aws/emulator/9297/config
export AWS_CA_BUNDLE=~/.aws/emulator/9297/ca.pem       # so boto3 trusts the local certificate
export AWS_EC2_METADATA_DISABLED=true
export AWS_DISABLE_HOST_PREFIX_INJECTION=true
export AWS_REGION=us-east-1 AWS_DEFAULT_REGION=us-east-1
unset AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN AWS_PROFILE   # no real creds in this shell
  1. Confirm you are talking to the emulator, not your AWS account.
curl --cacert ~/.aws/emulator/9297/ca.pem https://127.0.0.1:9297/__admin/health
aws sts get-caller-identity
# "Account": "000000000000", "Arn": "arn:aws:iam::000000000000:user/emulator"
Emulator health check and caller identity in account 000000000000
Emulator health check and caller identity in account 000000000000

If you see 000000000000, you are safe to experiment.

How to test S3 locally with AWS Emulator

The plain S3 path is boring in a good way: the commands you already know just work.

aws s3 mb s3://local-demo
echo "hello from the emulator" > hello.txt
aws s3 cp hello.txt s3://local-demo/
aws s3 ls s3://local-demo/

The more interesting part is S3 with SSE-KMS, because that is where S3 and KMS meet.

KEY=$(aws kms create-key --query KeyMetadata.KeyId --output text)

# Upload with SSE-KMS using our customer managed key
aws s3 cp hello.txt s3://local-demo/hello.txt --sse aws:kms --sse-kms-key-id "$KEY"

# Confirm the object is encrypted with that key
aws s3api head-object --bucket local-demo --key hello.txt
# "ServerSideEncryption": "aws:kms",
# "SSEKMSKeyId": "06c0cfac-..."
S3 upload with SSE-KMS and head-object showing ServerSideEncryption aws:kms
S3 upload with SSE-KMS and head-object showing ServerSideEncryption aws:kms

Passing a key that does not exist fails the same way AWS does:

An error occurred (KMS.NotFoundException) when calling the PutObject operation:
Key 'arn:aws:kms:us-east-1:000000000000:key/1111...' does not exist

How to test KMS locally with AWS Emulator

Now the part I came for. Here is the core encrypt and decrypt flow with an encryption context.

KEY=$(aws kms create-key --query KeyMetadata.KeyId --output text)
aws kms create-alias --alias-name alias/app --target-key-id "$KEY"

echo -n "secret" > plain.txt

# Encrypt with an encryption context (this is bound to the ciphertext)
aws kms encrypt --key-id alias/app --plaintext fileb://plain.txt \
  --encryption-context app=demo \
  --query CiphertextBlob --output text | base64 -d > secret.bin

# Decrypt with the SAME context: works
aws kms decrypt --ciphertext-blob fileb://secret.bin \
  --encryption-context app=demo \
  --query Plaintext --output text | base64 -d

# Decrypt with a DIFFERENT context: fails, exactly like AWS
aws kms decrypt --ciphertext-blob fileb://secret.bin --encryption-context app=wrong
# InvalidCiphertextException
KMS encrypt and decrypt with encryption context, and the wrong-context failure
KMS encrypt and decrypt with encryption context, and the wrong-context failure

Then I went through the failure cases one by one. Every row below is a real run on the emulator.

Scenario Command Emulator result Same as AWS?
Decrypt with wrong encryption context kms decrypt --encryption-context app=wrong InvalidCiphertextException Yes
Encrypt with a disabled key kms disable-key then kms encrypt DisabledException ... is disabled. Yes
Encrypt with a SIGN_VERIFY key kms encrypt --key-id <ecc-or-rsa-sign-key> InvalidKeyUsageException ... key usage is SIGN_VERIFY which is not valid for Encrypt. Yes
Use key ID from another Region kms describe-key --region us-west-2 NotFoundException ... does not exist Yes
Decrypt after scheduling deletion kms schedule-key-deletion then decrypt KMSInvalidStateException Yes
Data key for envelope encryption kms generate-data-key --key-spec AES_256 Plaintext + encrypted data key Yes
Automatic and on-demand rotation enable-key-rotation, rotate-key-on-demand Enabled, 365 days, next date returned Yes
Sign and verify kms sign / kms verify with ECDSA_SHA_256 SignatureValid: true Yes
Grants kms create-grant --operations Decrypt Grant ID and token returned Yes
Lock yourself out with a key policy put-key-policy with deny kms:* MalformedPolicyDocumentException (lockout safety check) Yes
Explicit Deny kms:Decrypt in key policy put-key-policy then decrypt AccessDeniedException ... explicit deny in a resource-based policy Yes
KMS error cases: disabled key, wrong key usage and wrong Region
KMS error cases: disabled key, wrong key usage and wrong Region

Honestly, this is better than I expected for a launch day release. The error codes and most of the messages match what I am used to seeing from KMS, which means the except blocks in my code get exercised for real.

Tip: The emulator generates new credentials every time it starts, and state lives in that running process. Treat it like a fresh account per run and create everything your test needs inside the test.

Automate it with pytest, boto3 and GitHub Actions

Running CLI commands by hand is fine for exploring. For real value, the same checks should run on every pull request. I wrote a small envelope encryption helper and a pytest suite around it.

The helper does what most teams do with KMS and S3: ask KMS for a data key, encrypt locally with AES-256-GCM, and store the ciphertext plus the encrypted data key in S3.

# app/envelope.py (trimmed)
def encrypt_object(bucket, key, data, kms_key_id, context):
    kms = boto3.client("kms")
    material = kms.generate_data_key(KeyId=kms_key_id, KeySpec="AES_256", EncryptionContext=context)
    nonce = os.urandom(12)
    aad = json.dumps(context, sort_keys=True, separators=(",", ":")).encode()
    ciphertext = AESGCM(material["Plaintext"]).encrypt(nonce, data, aad)
    envelope = {
        "version": 1,
        "nonce": base64.b64encode(nonce).decode(),
        "encrypted_key": base64.b64encode(material["CiphertextBlob"]).decode(),
        "ciphertext": base64.b64encode(ciphertext).decode(),
    }
    boto3.client("s3").put_object(Bucket=bucket, Key=key, Body=json.dumps(envelope).encode())

Notice there is no endpoint_url anywhere in the application code. boto3 picks up AWS_ENDPOINT_URL from the environment, so the same code runs against the emulator in tests and against AWS in production.

The tests check the failure paths, not just the happy path:

# tests/test_envelope.py (trimmed)
def test_wrong_context(resources):
    r = resources
    encrypt_object(r.bucket, "message", b"secret", r.key, {"project": "blog"})
    with pytest.raises(ClientError) as error:
        decrypt_object(r.bucket, "message", {"project": "wrong"})
    assert error.value.response["Error"]["Code"] == "InvalidCiphertextException"


def test_pending_deletion(resources):
    r = resources
    encrypt_object(r.bucket, "message", b"secret", r.key, {"project": "blog"})
    r.kms.schedule_key_deletion(KeyId=r.key, PendingWindowInDays=7)
    with pytest.raises(ClientError) as error:
        decrypt_object(r.bucket, "message", {"project": "blog"})
    assert error.value.response["Error"]["Code"] == "KMSInvalidStateException"

Tip: My conftest.py fixture refuses to run unless AWS_ENDPOINT_URL is https://127.0.0.1:9297. That one line protects you from accidentally creating and scheduling deletion of keys in a real account.

source env.sh
pip install -r requirements.txt
pytest -v -rx
pytest results against AWS Emulator
pytest results against AWS Emulator

And the GitHub Actions job, so the suite runs on every push without any AWS credentials in the repo:

# .github/workflows/emulator-tests.yml
name: Emulator tests
on: [push, pull_request, workflow_dispatch]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: '3.12'
      - name: Install and start AWS Emulator
        run: |
          curl -fL https://downloads.aws.com/aws-emulator/packages/aws-emulator/LTS/latest/aws-emulator_amd64.deb -o /tmp/emulator.deb
          sudo dpkg -i /tmp/emulator.deb
          nohup aws-emulator > "$HOME/aws-emulator.log" 2>&1 &
          for i in {1..60}; do
            curl -fsS --cacert "$HOME/.aws/emulator/9297/ca.pem" https://127.0.0.1:9297/__admin/health && exit 0
            sleep 1
          done
          cat "$HOME/aws-emulator.log"; exit 1
      - name: Run tests
        run: |
          source ./env.sh
          python -m pip install -r requirements.txt
          python -m pytest -v -rx

The health endpoint is what makes this reliable. No sleep 10 and hoping for the best.

What AWS Emulator does not catch (yet)

This is the section I would read first if I were deciding whether to trust it.

1. S3 accepts an asymmetric KMS key for SSE-KMS. S3 only supports symmetric encryption KMS keys for SSE-KMS. On the emulator, PutObject with a SIGN_VERIFY RSA key returned HTTP 200 and ServerSideEncryption: aws:kms. On AWS this request is rejected.

2. S3 still serves SSE-KMS objects after the key is pending deletion. I uploaded an object with SSE-KMS, scheduled the key for deletion, then called GetObject. The emulator returned HTTP 200 and the original body. On AWS, a key in PendingDeletion cannot be used for decryption, so the read fails with KMS.KMSInvalidStateException. Interestingly, a direct kms decrypt with the same key does fail correctly. The gap is only in the S3 to KMS path.

I kept both as xfail tests in the demo project. When the emulator fixes them, they will show up as XPASS and I will know.

Known gaps captured as xfail tests
Known gaps captured as xfail tests

3. IAM is not evaluated the way AWS does it. The announcement is clear that the emulator does not evaluate IAM policies and resource-based policies like AWS does. In my run an explicit Deny in a key policy was honored, which is nice, but do not treat that as a security test. Missing kms:Decrypt on a Lambda role, a key policy that forgets a principal, a condition on kms:EncryptionContext: test those on AWS.

P.S: If IAM policy review is the part that worries you, I wrote about Cloudsplaining for AWS IAM security assessment a while back.

4. Single account, single Region view. Each emulator is one account, with no cross-account or cross-Region behavior. Multi-Region keys and cross-account key sharing stay on AWS.

5. Fidelity varies by service. Check the published fidelity score for every service you depend on before you build a test strategy around it.

AWS Emulator vs LocalStack vs moto vs real AWS

AWS Emulator LocalStack moto Real AWS (dev account)
Maintained by AWS LocalStack (third party) Open source community AWS
How it runs Native package on Linux, Docker on macOS/Windows Docker container Python library (in-process) or standalone server Cloud
Works with AWS CLI and any SDK Yes, via environment variables Yes, via endpoint configuration Best with Python; server mode for others Yes
Request signing Real SigV4 with emulator keys Accepts test credentials Not enforced Real SigV4 and IAM
Error shapes Built from AWS API models, fidelity scores published Varies by service Varies by service The truth
IAM evaluation Not like AWS Check their current docs and plans Not like AWS Yes
Cost No service fee Check their current plans Free Pay per use
Best for Local and CI integration tests, coding agents Teams already invested in its tooling Fast Python unit tests Final validation before prod

My take: if you are starting fresh today, try AWS Emulator first for S3, KMS and DynamoDB style integration tests. If you already have a working LocalStack or moto setup, run your existing suite against the emulator in a branch and compare before you switch anything.

Honest Pros and Cons

Pros

  • Install and first request took me less than five minutes on Ubuntu.
  • KMS error codes matched AWS for every common failure I tried.
  • Real SigV4 signing with EMULATOR keys, bound to localhost by default.
  • No AWS account or credentials needed in CI.
  • A public evaluation suite instead of a vague "supports 100+ services" claim.
  • Unimplemented operations fail with 501 instead of pretending to work.

Cons

  • The CLI v1 trap on Ubuntu, and older SDKs, will confuse people on day one.
  • Two S3 plus KMS edge cases differ from AWS (shown above).
  • Not a security test: IAM is not evaluated like AWS.
  • Embedded in-process mode is Rust only at launch.
  • Telemetry is on by default (easy to turn off with EMULATOR_TELEMETRY=off).
  • No ready-made Docker image; you build it from the Dockerfile in the docs.

FAQ

What is AWS Emulator?

AWS Emulator is a free, local emulator of AWS APIs from AWS. It runs on your machine, serves HTTPS on 127.0.0.1:9297, and works with the AWS CLI, AWS SDKs and coding agents through environment variables, so you can test AWS code without deploying.

Is AWS Emulator free?

Yes. AWS says it has no additional service fee. You only pay for AWS resources when you deploy to AWS.

How do I install AWS Emulator on Ubuntu?

Download aws-emulator_amd64.deb from https://downloads.aws.com/aws-emulator/packages/aws-emulator/LTS/latest/, install it with sudo dpkg -i, run aws-emulator, and set AWS_ENDPOINT_URL, AWS_SHARED_CREDENTIALS_FILE and AWS_CONFIG_FILE to the files it creates in ~/.aws/emulator/9297/. Use AWS CLI v2.

Why does the AWS CLI ignore the AWS Emulator endpoint?

You are probably on AWS CLI v1, which Ubuntu's apt package installs. CLI v1 does not read the emulator's endpoint_url setting and calls real AWS endpoints instead. Install AWS CLI v2.

Can I test AWS KMS locally with AWS Emulator?

Yes. In my tests, encrypt, decrypt, encryption context checks, GenerateDataKey, disabled keys, key usage errors, rotation, grants, sign and verify, and scheduled deletion all returned the same error codes as AWS.

Does AWS Emulator check IAM policies?

Not the way AWS does. AWS states that the emulator does not evaluate IAM and resource-based policies like AWS, so a request AWS would deny may succeed locally. Test permissions on AWS.

Is AWS Emulator a replacement for LocalStack?

It covers the same need: local AWS API testing. It is built by AWS from the official API models and publishes fidelity scores. Compare it against your current setup by running your existing test suite on both.

Final Words

I went in expecting another "works for S3, falls over on anything real" emulator. For KMS, it held up much better than that: the failure paths I care about returned the right errors, and my envelope encryption tests run in about a second with no AWS account. The S3 plus KMS edge cases and IAM are the places where I would still keep a small set of tests on real AWS.

If you want to try it yourself, the full demo project (install script, env.sh, CLI walkthrough, envelope helper, pytest suite and GitHub Actions workflow) is available below.

來源:DEV Community · dev.to