Skip to content

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

fix(sts): authorize GetAccessKeyInfo and answer the key's owning account (#1976)

iot-rocket4db686172c9d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 329cbedf..881dbf1f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,8 @@ Versioning follows [Semantic Versioning](https://semver.org/).
### Fixed
+- **STS — `GetAccessKeyInfo` answers the account that owns the key** — it returned the caller's account whatever `AccessKeyId` said; it now returns the owning account for keys the emulator knows (its root key, IAM access keys and STS sessions), the account encoded in any other `AKIA` or `ASIA` key id as AWS does, and a `ValidationError` for an id that encodes no account or breaks the parameter's length and pattern constraints. Contributed by @iot-rocket.
+- **STS — `GetAccessKeyInfo` is authorized like other actions** — under `AUTH=true` it was allowed like `GetCallerIdentity` and `GetSessionToken`, whatever the caller's policies said. It now needs an identity policy that allows it and no deny, and otherwise answers `AccessDenied`, as AWS does; the other two stay allowed. Contributed by @iot-rocket.
- **API Gateway v2 (WebSocket API) — `$connect` with `AWS_IAM`** — an unsigned handshake is refused with 403 `Missing Authentication Token`, and under `AUTH=true` the caller needs `execute-api:Invoke` on `arn:aws:execute-api:<region>:<account>:<api-id>/<stage>/$connect`. Contributed by @iot-rocket.
- **SNS — `CreateTopic` keeps its tags** — the handler read `Tag.member.N` where the API sends `Tags.member.N`, so tags given at creation were dropped. Contributed by @iot-rocket.
diff --git a/ministack/core/iam_evaluator.py b/ministack/core/iam_evaluator.py
index 73d00557..fef193d5 100644
--- a/ministack/core/iam_evaluator.py
+++ b/ministack/core/iam_evaluator.py
@@ -1083,7 +1083,6 @@ def resolve_principal(access_key_id: str,
_ALWAYS_ALLOWED_ACTIONS = frozenset({
"sts:GetCallerIdentity",
"sts:GetSessionToken",
- "sts:GetAccessKeyInfo",
})
diff --git a/ministack/services/sts.py b/ministack/services/sts.py
index 0241cafa..8abe59b4 100644
--- a/ministack/services/sts.py
+++ b/ministack/services/sts.py
@@ -12,12 +12,28 @@ import base64
import hashlib
import hmac
import json
+import os
+import re
import time
from urllib.parse import parse_qs
+from xml.sax.saxutils import escape
from ministack.core.arn import ArnParseError, parse_arn
-from ministack.core.iam_evaluator import CredentialResolutionError, resolve_credential
-from ministack.core.responses import error_response_json, get_account_id, get_region, json_response, new_uuid
+from ministack.core.iam_evaluator import (
+ AmbiguousAccessKeyError,
+ CredentialResolutionError,
+ find_iam_access_key_account,
+ is_root_access_key,
+ resolve_credential,
+)
+from ministack.core.responses import (
+ _account_from_sts_session,
+ error_response_json,
+ get_account_id,
+ get_region,
+ json_response,
+ new_uuid,
+)
from ministack.core.router import extract_access_key_id
# Shared helpers — IAM and STS are a natural pair; STS is stateless
@@ -97,6 +113,37 @@ def _credential_error_response(error: CredentialResolutionError):
return _error(403, code, error.message, ns="sts")
+def _access_key_id_problems(key_id: str | None) -> list[str]:
+ """The constraint violations AWS reports for a GetAccessKeyInfo AccessKeyId."""
+ if key_id is None:
+ return ["Value null at 'accessKeyId' failed to satisfy constraint: Member must not be null"]
+ constraints = [
+ ("Member must satisfy regular expression pattern: [\\w]*", not re.fullmatch(r"\w*", key_id, re.ASCII)),
+ ("Member must have length greater than or equal to 16", len(key_id) < 16),
+ ("Member must have length less than or equal to 128", len(key_id) > 128),
+ ]
+ return [f"Value '{escape(key_id)}' at 'accessKeyId' failed to satisfy constraint: {c}"
+ for c, failed in constraints if failed]
+
+
+def _access_key_account(key_id: str) -> str | None:
+ """The account owning a known key, else the account AWS decodes from an AKIA/ASIA id, else None."""
+ if is_root_access_key(key_id):
+ return os.environ.get("MINISTACK_ACCOUNT_ID", "000000000000")
+ try:
+ account = _account_from_sts_session(key_id) or find_iam_access_key_account(key_id)
+ except AmbiguousAccessKeyError:
+ account = None
+ if account:
+ return account
+ if key_id[:4] not in ("AKIA", "ASIA") or len(key_id) > 25:
+ return None
+ bits = 0
+ for char in key_id[4:14]:
+ bits = bits << 5 | max("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".find(char), 0)
+ return f"{bits >> 9 & (1 << 40) - 1:012d}" if bits >> 49 else None
+
+
def reset():
_sessions.clear()
@@ -364,11 +411,19 @@ async def handle_request(method, path, headers, body, query_params):
ns="sts")
if action == "GetAccessKeyInfo":
+ key_id = _p(params, "AccessKeyId", None)
+ problems = _access_key_id_problems(key_id)
+ if problems:
+ count = f"{len(problems)} validation error{'s' if len(problems) > 1 else ''} detected"
+ return _error(400, "ValidationError", f"{count}: " + "; ".join(problems), ns="sts")
+ account = _access_key_account(key_id)
+ if account is None:
+ return _error(400, "ValidationError", "Access key ID is not valid.", ns="sts")
if use_json:
- return json_response({"Account": get_account_id()})
+ return json_response({"Account": account})
return _xml(200, "GetAccessKeyInfoResponse",
f"<GetAccessKeyInfoResult>"
- f"<Account>{get_account_id()}</Account>"
+ f"<Account>{account}</Account>"
f"</GetAccessKeyInfoResult>",
ns="sts")
diff --git a/tests/test_sts.py b/tests/test_sts.py
index d1212943..da6da5a6 100644
--- a/tests/test_sts.py
+++ b/tests/test_sts.py
@@ -22,10 +22,78 @@ def test_sts_assume_role_returns_credentials(sts):
assert "Expiration" in creds
assert resp["AssumedRoleUser"]["Arn"]
-def test_sts_get_access_key_info(sts):
- resp = sts.get_access_key_info(AccessKeyId="test-key-do-not-use")
- assert "Account" in resp
- assert resp["Account"] == "000000000000"
[email protected]("key_id, account", [
+ ("AKIAZZZZZZZZZZZZZZZZ", "673894223475"), ("ASIAZZZZZZZZZZZZZZZZ", "673894223475"),
+ ("AKIA2222222222222222", "744830457525"), ("AKIAQAAAAAABAAAAAAAA", "000000000002"),
+ ("AKIA7777777777777777", "1099511627775"), ("AKIAZZZZZZZ0ZZZZZZZZ", "673894223425"),
+ ("AKIAQAAAAAAAAAAA", "000000000000"), ("AKIAQAAAAAAAAAAAAAAAAAAAB", "000000000000"),
+])
+def test_sts_get_access_key_info(sts, key_id, account):
+ """An unknown AKIA or ASIA key id answers the account encoded in the id."""
+ assert sts.get_access_key_info(AccessKeyId=key_id)["Account"] == account
+
+
[email protected]("key_id, message", [
+ ("AKIAIOSFODNN7EXAMPLE", "Access key ID is not valid."),
+ ("AKIA0123456789ABCDEF", "Access key ID is not valid."),
+ ("ABIAZZZZZZZZZZZZZZZZ", "Access key ID is not valid."),
+ ("AKIAQAAAAAAAAAAAAAAAAAAABB", "Access key ID is not valid."),
+ ("AKIAPAAAAAAAAAAAAAAA", "Access key ID is not valid."),
+ ("A" * 128, "Access key ID is not valid."),
+ (None, "1 validation error detected: Value null at 'accessKeyId' failed to satisfy constraint: "
+ "Member must not be null"),
+ ("abc", "1 validation error detected: Value 'abc' at 'accessKeyId' failed to satisfy constraint: "
+ "Member must have length greater than or equal to 16"),
+ ("a-b", "2 validation errors detected: Value 'a-b' at 'accessKeyId' failed to satisfy constraint: "
+ "Member must satisfy regular expression pattern: [\\w]*; Value 'a-b' at 'accessKeyId' failed to "
+ "satisfy constraint: Member must have length greater than or equal to 16"),
+ ("A" * 129, f"1 validation error detected: Value '{'A' * 129}' at 'accessKeyId' failed to satisfy "
+ "constraint: Member must have length less than or equal to 128"),
+])
+def test_sts_get_access_key_info_rejects_invalid_key_id(key_id, message):
+ """A malformed key id, or one that encodes no account, is a ValidationError."""
+ from conftest import make_client
+
+ client = make_client("sts", {"parameter_validation": False})
+ with pytest.raises(ClientError) as exc:
+ client.get_access_key_info(**({} if key_id is None else {"AccessKeyId": key_id}))
+ assert exc.value.response["Error"]["Code"] == "ValidationError"
+ assert exc.value.response["Error"]["Message"] == message
+
+
+def test_sts_get_access_key_info_returns_owning_account(sts):
+ """A key the emulator issued answers the account that owns it, not the caller's."""
+ import boto3
+
+ endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
+ other = {"endpoint_url": endpoint, "region_name": "us-east-1",
+ "aws_access_key_id": "111111111111", "aws_secret_access_key": "test"}
+ iam_other = boto3.client("iam", **other)
+ iam_other.create_user(UserName="key-info-owner")
+ user_key = iam_other.create_access_key(UserName="key-info-owner")["AccessKey"]["AccessKeyId"]
+ try:
+ session_key = boto3.client("sts", **other).get_session_token()["Credentials"]["AccessKeyId"]
+ assert sts.get_access_key_info(AccessKeyId=user_key)["Account"] == "111111111111"
+ assert sts.get_access_key_info(AccessKeyId=session_key)["Account"] == "111111111111"
+ finally:
+ iam_other.delete_access_key(UserName="key-info-owner", AccessKeyId=user_key)
+ iam_other.delete_user(UserName="key-info-owner")
+
+
+def test_sts_get_access_key_info_configured_root_key(monkeypatch):
+ """The configured root key answers the emulator's account, not an account decoded from the id."""
+ import asyncio
+
+ from ministack.services import sts as sts_svc
+
+ monkeypatch.setenv("AWS_ACCESS_KEY_ID", "AKIAROOTCONFIGURED1")
+ monkeypatch.setenv("MINISTACK_ACCOUNT_ID", "123456789012")
+ status, _, payload = asyncio.run(sts_svc.handle_request(
+ "POST", "/", {"content-type": "application/x-www-form-urlencoded"},
+ b"Action=GetAccessKeyInfo&Version=2011-06-15&AccessKeyId=AKIAROOTCONFIGURED1", {},
+ ))
+ assert status == 200
+ assert b"<Account>123456789012</Account>" in payload
def test_sts_get_caller_identity_full(sts):
resp = sts.get_caller_identity()
@@ -377,6 +445,62 @@ def test_sts_credential_rejections_require_auth(monkeypatch, auth_enabled, actio
sts_svc._sessions.pop(key, None)
[email protected]("auth_enabled", [False, True])
[email protected]("action", ["GetCallerIdentity", "GetSessionToken", "GetAccessKeyInfo"])
[email protected]("statement", [
+ None,
+ {"Effect": "Deny", "Action": "*", "Resource": "*"},
+ {"Effect": "Allow", "Action": "sts:GetAccessKeyInfo", "Resource": "*"},
+])
+def test_sts_policies_reach_only_get_access_key_info(monkeypatch, auth_enabled, action, statement):
+ """Under AUTH GetAccessKeyInfo needs an Allow; GetCallerIdentity and GetSessionToken always succeed."""
+ import asyncio
+
+ from ministack import app as app_mod
+ from ministack.core.responses import request_scope
+ from ministack.services import iam as iam_svc
+ from ministack.services import sts as sts_svc
+
+ account = "000000000000"
+ user_name = "sts-deny-all-user"
+ key = "AKIASTSDENYALLACTIVE"
+ monkeypatch.setattr(app_mod, "AUTH", auth_enabled)
+ previous = set(sts_svc._sessions)
+ with request_scope(account, "us-east-1"):
+ iam_svc._users.set_scoped(account, None, user_name, {
+ "UserName": user_name, "UserId": "AIDASTSDENYALLUSER", "Path": "/",
+ "Arn": f"arn:aws:iam::{account}:user/{user_name}", "AttachedPolicies": [],
+ })
+ if statement:
+ iam_svc._user_inline_policies[user_name] = {"p": {"Statement": [statement]}}
+ iam_svc._access_keys.set_scoped(account, None, key, {
+ "AccessKeyId": key, "SecretAccessKey": "secret", "Status": "Active", "UserName": user_name,
+ })
+ try:
+ status, _, payload = asyncio.run(app_mod._dispatch_service_request(
+ "POST", "/", {
+ "host": "sts.localhost",
+ "authorization": f"AWS4-HMAC-SHA256 Credential={key}/20260929/us-east-1/sts/aws4_request",
+ "content-type": "application/x-www-form-urlencoded",
+ }, f"Action={action}&Version=2011-06-15&AccessKeyId={key}".encode(), {}, "req-1",
+ ))
+ finally:
+ iam_svc._access_keys.pop_scoped(account, None, key, None)
+ iam_svc._user_inline_policies.pop(user_name, None)
+ iam_svc._users.pop_scoped(account, None, user_name, None)
+ for created in set(sts_svc._sessions) - previous:
+ sts_svc._sessions.pop(created, None)
+ if auth_enabled and action == "GetAccessKeyInfo" and statement is None:
+ assert status == 403
+ assert (b"is not authorized to perform: sts:GetAccessKeyInfo because no identity-based policy "
+ b"allows the sts:GetAccessKeyInfo action") in payload
+ elif auth_enabled and action == "GetAccessKeyInfo" and statement["Effect"] == "Deny":
+ assert status == 403
+ assert b"AccessDenied" in payload
+ else:
+ assert status == 200
+
+
def test_sts_assume_role_with_web_identity(sts, iam):
iam.create_role(
RoleName="test-oidc-role",