Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

fix(s3) presigned urls temp cred (#1447)

Nahuel Nucera3e7ad4db865c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b2b9d4c3..c9e3b7a8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,6 +14,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
- **CloudFormation — API Gateway (v1) API keys and usage plans** — `AWS::ApiGateway::ApiKey`, `AWS::ApiGateway::UsagePlan`, and `AWS::ApiGateway::UsagePlanKey` failed stack creation with `Unsupported resource type`, even though the runtime `CreateApiKey` / `CreateUsagePlan` APIs were already served. The three resource types now provision through those same stores: an `ApiKey` supports a pinned `Value`, `Enabled`, and `StageKeys`, updates `Name` / `Description` / `Enabled` in place, and exposes both `Ref` and `Fn::GetAtt APIKeyId` as the key id; a `UsagePlan` maps `Throttle` / `Quota` / `ApiStages` and returns its id via `Ref` and `Fn::GetAtt Id`; a `UsagePlanKey` associates a key with a plan and is torn down from the plan on delete. This unblocks CDK `RestApi` / `ApiKey` constructs and Terraform `aws_api_gateway_api_key` deployed through CloudFormation. Contributed by @ryan-bennett.
- **AWS IoT Jobs — control plane and device data plane** — `CreateJob` fell through to `Unsupported IoT path` and the `iot-jobs-data` endpoint did not exist, so device OTA loops could not be rehearsed locally. The `iot` service now serves the nine job operations and a new `iot-jobs-data` service the four device ones (incl. the `$next` sentinel), sharing one store and the AWS execution state machine. A `documentSource` job gets a placeholder, not the S3 object. Contributed by @iot-rocket.
### Fixed
+- **S3 — presigned SigV4 URLs verify for virtual-hosted addressing and temporary credentials** — two bugs made valid presigned `GET`/`PUT` URLs fail `403 SignatureDoesNotMatch`: a virtual-hosted (`{bucket}.host`) URL was rewritten to path-style before the signature was recomputed, so it no longer matched the bucket-less URI the client signed; and a URL signed with STS temporary credentials was always verified against the static server secret, never the unique secret STS issued. Verification now runs against the original signed URI, and STS records each issued secret so the verifier resolves the one a credential actually signed with (long-term keys still fall back to `AWS_SECRET_ACCESS_KEY`). Tampered and wrong-secret URLs are still rejected. Reported by @mayankgupta57.
- **Step Functions — `arn:aws:states:::events:putEvents` actually publishes the event** — the optimized EventBridge integration fell through to the task passthrough, so the state reported `SUCCEEDED` while nothing reached any rule target. It now calls EventBridge `PutEvents` and returns its response (`Entries` / `FailedEntryCount`). Reported by @iwasakar.
- **Aurora DSQL — `SELECT ... FOR UPDATE` is no longer refused for its predicate** — strict mode enforced a rule Aurora DSQL does not (any more): a locking read had to be a single table with an equality on every primary key column, or it was rejected with `0A000` "locking clause such as FOR UPDATE can be applied only on tables with equality predicates on the key". The check compared the WHERE clause's column against the key name as raw SQL text, so `WHERE "id" = $1` did not match key column `id` — and every mainstream ORM (Drizzle, Prisma, TypeORM, SQLAlchemy) quotes its identifiers, so in practice every locking read from an ORM failed, with a message that blamed the user's schema. Measured against a live cluster (eu-central-1, 2026-08-18, `server_version` 16.15), DSQL restricts the lock *strength*, not the predicate: `FOR UPDATE` locks whatever the query selects — no `WHERE` clause, a non-key column, an inequality, `IN`/`OR`, a join, or a table with no primary key all succeed, as do `NOWAIT`, `SKIP LOCKED` and `OF` — while `FOR NO KEY UPDATE`, `FOR SHARE` and `FOR KEY SHARE` are refused with `0A000` "locking clauses other than FOR UPDATE/FOR KEY SHARE are not supported", inside a CTE or subquery included. The predicate rule is gone and the lock-strength rule takes its place, so the emulator stops failing correct code and starts failing the code DSQL actually fails. The new rule is token-based (`FOR SHARE` inside a string literal is text, not a clause) and needs no catalog probe, so a locking read no longer costs a round-trip before it is forwarded.
- **Aurora DSQL — quoted identifiers are normalized the way the server stores them** — `ALTER TABLE ... DROP COLUMN` compared the column against the primary key case-insensitively after stripping quotes, so `DROP COLUMN "ID"` was read as key column `id` and refused, while the primary-key probe dropped the quotes from its relation name — `"myschema".t` became `myschema".t` and resolved to nothing, and a table created as `"MyTable"` case-folded to `mytable` and was not found, silently disabling the rule. Identifiers are now folded as PostgreSQL folds them (bare to lower case, quoted verbatim, `""` unescaped) and the relation is requoted part by part before the lookup, so schema-qualified and mixed-case names resolve.
diff --git a/ministack/app.py b/ministack/app.py
index 4623d96d..7d79a0f1 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -1474,7 +1474,11 @@ async def _handle_s3_vhost_request(host: str, path: str, method: str, headers: d
vhost_path = "/" + bucket + path if path != "/" else "/" + bucket + "/"
try:
- return await _get_module("s3").handle_request(method, vhost_path, headers, body, query_params)
+ # Pass the original (pre-rewrite) URI as signed_path so a presigned
+ # virtual-hosted URL, which signed the canonical URI without the bucket,
+ # verifies against what the client actually signed.
+ return await _get_module("s3").handle_request(
+ method, vhost_path, headers, body, query_params, signed_path=path)
except Exception as e:
logger.exception("Error handling virtual-hosted S3 request: %s", e)
from xml.sax.saxutils import escape as _xml_esc
diff --git a/ministack/services/s3.py b/ministack/services/s3.py
index acaf8f0b..4d3cca20 100644
--- a/ministack/services/s3.py
+++ b/ministack/services/s3.py
@@ -1096,6 +1096,25 @@ def _sigv4_signing_key(secret: str, date_stamp: str, region: str, service: str)
return _h(k_service, "aws4_request")
+def _resolve_presign_secret(access_key_id):
+ """The secret a presigned URL was signed with.
+
+ STS temporary credentials are signed with the unique secret STS issued (not
+ the server's static one), so a presigned URL from an AssumeRole / session
+ token would never recompute against ``AWS_SECRET_ACCESS_KEY``. STS records
+ each issued secret by access key id; resolve it here, falling back to the
+ static server secret for a long-term (non-session) credential.
+ """
+ try:
+ from ministack.services import sts
+ session = sts._sessions.get(access_key_id)
+ if session and session.get("SecretAccessKey"):
+ return session["SecretAccessKey"]
+ except Exception:
+ pass
+ return os.environ.get("AWS_SECRET_ACCESS_KEY", "test")
+
+
def _verify_presigned_sigv4(method, path, headers, query_params):
"""Verify a SigV4 presigned S3 URL. Returns an error tuple for a bad
signature, or None when the request is not a SigV4 presigned URL (header-
@@ -1186,7 +1205,7 @@ def _verify_presigned_sigv4(method, path, headers, query_params):
hashlib.sha256(canonical_request.encode("utf-8")).hexdigest(),
])
- secret = os.environ.get("AWS_SECRET_ACCESS_KEY", "test")
+ secret = _resolve_presign_secret(_akid)
signing_key = _sigv4_signing_key(secret, date_stamp, region, service)
computed = hmac.new(signing_key, string_to_sign.encode("utf-8"),
hashlib.sha256).hexdigest()
@@ -1197,11 +1216,18 @@ def _verify_presigned_sigv4(method, path, headers, query_params):
async def handle_request(
- method: str, path: str, headers: dict, body: bytes, query_params: dict
+ method: str, path: str, headers: dict, body: bytes, query_params: dict,
+ signed_path: str | None = None,
) -> tuple:
bucket, key = _parse_bucket_key(path, headers)
- sig_error = _verify_presigned_sigv4(method, path, headers, query_params)
+ # A virtual-hosted request is rewritten to path-style before it reaches here
+ # (``/{bucket}{path}``), but the client signed the canonical URI it actually
+ # sent (``{path}``, no bucket) against the vhost Host header. ``signed_path``
+ # carries that original URI so the presigned signature recomputes correctly;
+ # path-style requests pass None and verify against ``path`` as before.
+ sig_error = _verify_presigned_sigv4(
+ method, signed_path if signed_path is not None else path, headers, query_params)
if sig_error is not None:
status, resp_headers, resp_body = sig_error
resp_headers.setdefault("x-amz-request-id", new_uuid())
diff --git a/ministack/services/sts.py b/ministack/services/sts.py
index caf5218e..165f7489 100644
--- a/ministack/services/sts.py
+++ b/ministack/services/sts.py
@@ -112,6 +112,7 @@ async def handle_request(method, path, headers, body, query_params):
session_token = _gen_session_token()
role_id = "AROA" + new_uuid().replace("-", "")[:17].upper()
_sessions[access_key] = {"Arn": assumed_arn, "UserId": f"{role_id}:{session_name}"}
+ _sessions[access_key]["SecretAccessKey"] = secret_key
if use_json:
return json_response({
"Credentials": {"AccessKeyId": access_key, "SecretAccessKey": secret_key, "SessionToken": session_token, "Expiration": int(time.time() + duration)},
@@ -146,6 +147,7 @@ async def handle_request(method, path, headers, body, query_params):
session_token = _gen_session_token()
role_id = "AROA" + new_uuid().replace("-", "")[:17].upper()
_sessions[access_key] = {"Arn": assumed_arn, "UserId": f"{role_id}:{session}"}
+ _sessions[access_key]["SecretAccessKey"] = secret_key
provider = _p(params, "ProviderId") or "sts.amazonaws.com"
if use_json:
return json_response({
@@ -179,6 +181,9 @@ async def handle_request(method, path, headers, body, query_params):
access_key = _gen_session_access_key()
secret_key = _gen_secret()
session_token = _gen_session_token()
+ # Record the secret so a presigned URL signed with these temporary
+ # credentials can be verified against the key it was actually signed with.
+ _sessions[access_key] = {"SecretAccessKey": secret_key}
if use_json:
return json_response({
"Credentials": {"AccessKeyId": access_key, "SecretAccessKey": secret_key, "SessionToken": session_token, "Expiration": int(time.time() + duration)},
diff --git a/tests/conftest.py b/tests/conftest.py
index 2ec15b5e..51fac482 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -176,6 +176,11 @@ _SERIAL_TESTS = {
# `{prefix}.jobs.iot.{region}` Host and a tight 5s timeout, so cross-file
# xdist pressure on the shared event loop makes it time out at random.
"tests/test_iot_jobs.py::test_iot_jobs_advertised_endpoint_host_reaches_the_data_plane",
+ # ECS service task-spawn: with a Docker daemon present (CI has one) a task
+ # whose container fails to start/exits under parallel container churn is set
+ # STOPPED, so list_tasks (RUNNING-only) sees fewer than desiredCount. Passes
+ # serially; run it in the serial phase.
+ "tests/test_ecs.py::test_ecs_service_spawns_tasks",
# WS/MQTT-broker tests (MQTT-over-WebSocket connect/publish/subscribe,
# device shadows over MQTT, fleet-index connectivity). They drive the
# single-event-loop broker over real WebSocket connections with tight
diff --git a/tests/test_s3.py b/tests/test_s3.py
index c368324d..475e9641 100644
--- a/tests/test_s3.py
+++ b/tests/test_s3.py
@@ -3710,6 +3710,42 @@ def test_s3_presigned_url_signature_is_verified():
assert status(urllib.request.Request(u, method="GET")) == 200
+def test_s3_presigned_url_virtual_hosted_style_is_verified():
+ """A virtual-hosted-style presigned URL signs the bucket-less canonical URI
+ against the `{bucket}.host` Host header. MiniStack rewrites vhost → path-style
+ internally, but verification must run against the URI the client actually
+ signed, not the rewritten one (#1441)."""
+ import urllib.error
+ import urllib.request
+ from urllib.parse import urlparse
+
+ import boto3
+ from botocore.config import Config
+
+ ep = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566").rstrip("/")
+ cli = boto3.client(
+ "s3", endpoint_url=ep, region_name="us-east-1",
+ aws_access_key_id="test", aws_secret_access_key="test",
+ config=Config(signature_version="s3v4", s3={"addressing_style": "virtual"}),
+ )
+ bucket = "presign-vhost-bkt"
+ cli.create_bucket(Bucket=bucket)
+
+ u = cli.generate_presigned_url(
+ "put_object", Params={"Bucket": bucket, "Key": "up.txt"}, ExpiresIn=300)
+ parsed = urlparse(u)
+ # The vhost host won't resolve; send to the endpoint with the bucket-less
+ # path and the signed Host header, exactly as a fronting proxy would.
+ target = ep + parsed.path + "?" + parsed.query
+ req = urllib.request.Request(
+ target, data=b"x", method="PUT", headers={"Host": parsed.netloc})
+ try:
+ code = urllib.request.urlopen(req).status
+ except urllib.error.HTTPError as exc:
+ code = exc.code
+ assert code in (200, 204), f"vhost presigned PUT rejected with {code}"
+
+
def test_s3_eventbridge_notification_on_delete(s3, sqs, eb):
"""S3 delete_object should send EventBridge event when EventBridgeConfiguration is enabled."""
bucket = "s3-eb-del-bkt"