Skip to content

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

feat(rds): add internal IAM authentication broker (#1789)

Ian Oberste6d7cf4bd49c
diff --git a/ministack/app.py b/ministack/app.py
index 95334689..da19e02f 100644
--- a/ministack/app.py
+++ b/ministack/app.py
@@ -2490,6 +2490,16 @@ async def app(scope, receive, send):
if scope["type"] != "http":
return
+ # Credential-bearing broker requests bypass generic body decoding, routing
+ # and tenant inference. The capability, not a client claim, selects RDS.
+ if scope["path"] == "/_ministack/rds/iam-auth":
+ from ministack.core import rds_iam_broker
+
+ async with _get_reset_lock():
+ pass
+ await rds_iam_broker.handle(scope, receive, send, auth_enabled=AUTH)
+ return
+
method = scope["method"]
path = scope["path"]
query_string = scope.get("query_string", b"").decode("utf-8")
diff --git a/ministack/core/rds_iam_broker.py b/ministack/core/rds_iam_broker.py
new file mode 100644
index 00000000..5b3f37dc
--- /dev/null
+++ b/ministack/core/rds_iam_broker.py
@@ -0,0 +1,186 @@
+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT
+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE).
+"""Internal stage-6 broker (#1744). Capability provisioning is stage 8.
+
+Capabilities are process-local, never persisted, and never issued over HTTP.
+AUTH controls IAM enforcement, not capability protection or resource enablement.
+No plugin/container calls this endpoint yet.
+"""
+
+import asyncio
+import hashlib
+import json
+import secrets
+import threading
+from dataclasses import dataclass
+
+from ministack.core.rds_iam import AuthorizedRdsConnection, authorize_rds_iam_token
+
+PATH = "/_ministack/rds/iam-auth"
+MAX_BODY = 70 * 1024
+BODY_TIMEOUT = 5
+_lock = threading.RLock()
+_bindings = {}
+
+
+@dataclass(frozen=True, repr=False)
+class _Binding:
+ account_id: str
+ region: str
+ resource_kind: str
+ resource_identifier: str
+ reader_endpoint: bool
+ target: dict
+ owner: dict
+ resource_id: str
+
+
+def _resources(account_id, region, resource_kind, resource_identifier):
+ from ministack.services import rds
+
+ store = rds._instances if resource_kind == "instance" else rds._clusters
+ target = store.get_scoped(account_id, region, resource_identifier)
+ if not target or target.get("Engine") not in ("mysql", "aurora", "aurora-mysql"):
+ return None, None
+ owner = target
+ if resource_kind == "instance" and target.get("DBClusterIdentifier"):
+ owner = rds._clusters.get_scoped(account_id, region, target["DBClusterIdentifier"])
+ if not owner or owner.get("Engine") not in ("aurora", "aurora-mysql"):
+ return None, None
+ elif target.get("Engine") != "mysql" and resource_kind == "instance":
+ return None, None
+ if resource_kind == "cluster" and target.get("Engine") == "mysql":
+ return None, None
+ return target, owner
+
+
+def _resource_id(target, owner, kind):
+ return owner.get("DbClusterResourceId" if kind == "cluster" or owner is not target else "DbiResourceId")
+
+
+def issue_capability(*, account_id, region, resource_kind, resource_identifier, reader_endpoint=False):
+ """Trusted in-process API; rotates the capability for this endpoint binding.
+
+ No production callers until container wiring. Call again after restart or
+ resource replacement; old capabilities cannot authorize recreated resources.
+ """
+ if (resource_kind not in ("instance", "cluster") or not account_id or not region
+ or type(reader_endpoint) is not bool or (reader_endpoint and resource_kind != "cluster")):
+ raise ValueError("Invalid RDS target")
+ with _lock:
+ target, owner = _resources(account_id, region, resource_kind, resource_identifier)
+ resource_id = _resource_id(target, owner, resource_kind) if owner is not None else None
+ if not resource_id:
+ raise ValueError("Invalid RDS target")
+ for digest, binding in list(_bindings.items()):
+ if (binding.account_id, binding.region, binding.resource_kind, binding.resource_identifier,
+ binding.reader_endpoint) == (account_id, region, resource_kind, resource_identifier, reader_endpoint):
+ del _bindings[digest]
+ capability = secrets.token_hex(32)
+ _bindings[hashlib.sha256(capability.encode()).digest()] = _Binding(
+ account_id, region, resource_kind, resource_identifier, reader_endpoint, target, owner, resource_id,
+ )
+ return capability
+
+
+def revoke_capability(capability):
+ with _lock:
+ _bindings.pop(hashlib.sha256(capability.encode()).digest(), None)
+
+
+def reset():
+ with _lock:
+ _bindings.clear()
+
+
+def _binding_current(binding):
+ target, owner = _resources(binding.account_id, binding.region, binding.resource_kind,
+ binding.resource_identifier)
+ return (target is binding.target and owner is binding.owner
+ and _resource_id(target, owner, binding.resource_kind) == binding.resource_id
+ and owner.get("IAMDatabaseAuthenticationEnabled") is True)
+
+
+def _decision(capability, payload, auth_enabled):
+ with _lock:
+ binding = _bindings.get(hashlib.sha256(capability).digest())
+ if binding is None:
+ return False
+ if not _binding_current(binding):
+ return False
+ if not auth_enabled:
+ return True
+ result = authorize_rds_iam_token(
+ payload["token"], account_id=binding.account_id, region=binding.region,
+ resource_kind=binding.resource_kind, resource_identifier=binding.resource_identifier,
+ reader_endpoint=binding.reader_endpoint, db_user=payload["username"],
+ )
+ # RDS lifecycle workers do not hold the broker lock. Authorization
+ # looks up state independently, so discard its result if the resource
+ # or its owner was replaced or disabled while that lookup ran.
+ return isinstance(result, AuthorizedRdsConnection) and _binding_current(binding)
+
+
+def _unique_object(pairs):
+ result = {}
+ for key, value in pairs:
+ if key in result:
+ raise ValueError("Duplicate field")
+ result[key] = value
+ return result
+
+
+async def _read_body(receive):
+ body = bytearray()
+ while True:
+ message = await receive()
+ if message["type"] != "http.request":
+ raise ValueError("Disconnected")
+ chunk = message.get("body", b"")
+ if len(body) + len(chunk) > MAX_BODY:
+ raise ValueError("Oversized request")
+ body.extend(chunk)
+ if not message.get("more_body", False):
+ return bytes(body)
+
+
+async def handle(scope, receive, send, *, auth_enabled):
+ """POST {username, token}, with X-Ministack-RDS-Capability header.
+
+ Transport/schema failures never grant access, even in permissive mode.
+ Do not log request data or exception details on this credential-bearing path.
+ """
+ status, allowed = 403, False
+ try:
+ headers = {}
+ for name, value in scope.get("headers", []):
+ name = name.lower()
+ if name in headers:
+ raise ValueError("Duplicate header")
+ headers[name] = value
+ capability = headers.get(b"x-ministack-rds-capability", b"")
+ if (scope["method"] != "POST" or scope.get("query_string")
+ or len(capability) != 64 or any(c not in b"0123456789abcdef" for c in capability)
+ or headers.get(b"content-type", b"").split(b";", 1)[0].strip().lower() != b"application/json"
+ or b"content-encoding" in headers):
+ raise ValueError("Invalid request")
+ with _lock:
+ if hashlib.sha256(capability).digest() not in _bindings:
+ raise ValueError("Invalid capability")
+ body = await asyncio.wait_for(_read_body(receive), timeout=BODY_TIMEOUT)
+ payload = json.loads(body.decode("utf-8"), object_pairs_hook=_unique_object)
+ if (not isinstance(payload, dict) or payload.keys() != {"username", "token"}
+ or not isinstance(payload["username"], str) or not 1 <= len(payload["username"]) <= 256
+ or "\x00" in payload["username"] or not isinstance(payload["token"], str)
+ or len(payload["token"]) > 65536):
+ raise ValueError("Invalid payload")
+ allowed = _decision(capability, payload, auth_enabled)
+ status = 200 if allowed else 403
+ except Exception:
+ # Even unexpected verifier failures must not leak tokens through logs
+ # or turn a failed request into an allow response.
+ pass
+ await send({"type": "http.response.start", "status": status, "headers": [
+ (b"content-type", b"application/json"), (b"cache-control", b"no-store"),
+ ]})
+ await send({"type": "http.response.body", "body": b'{"allowed":true}' if allowed else b'{"allowed":false}'})
diff --git a/ministack/services/rds.py b/ministack/services/rds.py
index e1ca52b5..dc1e4fc9 100644
--- a/ministack/services/rds.py
+++ b/ministack/services/rds.py
@@ -11095,6 +11095,9 @@ _ACTION_MAP = {
def reset():
+ from ministack.core import rds_iam_broker
+
+ rds_iam_broker.reset()
# Serialize teardown with warm-boot shared-container startup. Otherwise a
# restore worker can pass its membership check after reset has enumerated
# resources, then create a container after the stores are cleared.
diff --git a/tests/test_rds_iam_broker.py b/tests/test_rds_iam_broker.py
new file mode 100644
index 00000000..fd4b0a94
--- /dev/null
+++ b/tests/test_rds_iam_broker.py
@@ -0,0 +1,274 @@
+# Copyright (c) 2026 MiniStack Contributors. SPDX-License-Identifier: MIT
+# Copies or substantial portions, including AI-assisted ports or rewrites, must retain this notice (see LICENSE).
+"""Offline ASGI broker tests; no database or Docker resources required."""
+
+import asyncio
+import importlib
+import json
+
+import pytest
+from test_rds_iam import ACCOUNT, AUTHZ_HOST, AUTHZ_KEY, AUTHZ_SECRET, REGION, _authz_policy
+from test_rds_iam import AUTHZ_ARGS as ARGS
+from test_rds_iam import AUTHZ_USER as USER
+from test_rds_iam import _authz_token as token
+
+from ministack.core import rds_iam_broker as broker
+from ministack.core.responses import AccountRegionScopedDict, AccountScopedDict, get_account_id, get_region
+from ministack.services import iam, rds, sts
+
+app_module = importlib.import_module("ministack.app")
+
+
+def state(monkeypatch):
+ """Isolate the broker's resource and IAM state using the shared token inputs."""
+ for name in ("_users", "_access_keys", "_user_inline_policies", "_roles", "_groups",
+ "_group_inline_policies", "_policies"):
+ monkeypatch.setattr(iam, name, AccountScopedDict())
+ monkeypatch.setattr(rds, "_instances", AccountRegionScopedDict())
+ monkeypatch.setattr(rds, "_clusters", AccountRegionScopedDict())
+ monkeypatch.setattr(sts, "_sessions", {})
+ monkeypatch.setenv("AWS_ACCESS_KEY_ID", "test")
+ monkeypatch.setenv("AWS_SECRET_ACCESS_KEY", "root-secret")
+ monkeypatch.delenv("AWS_SESSION_TOKEN", raising=False)
+ iam._users.set_scoped(ACCOUNT, None, "alice", {
+ "UserName": "alice", "Arn": f"arn:aws:iam::{ACCOUNT}:user/alice",
+ })
+ iam._access_keys.set_scoped(ACCOUNT, None, AUTHZ_KEY, {
+ "UserName": "alice", "Status": "Active", "SecretAccessKey": AUTHZ_SECRET,
+ })
+ iam._user_inline_policies.set_scoped(ACCOUNT, None, "alice", {"connect": _authz_policy()})
+ instance = dict(Engine="mysql", DbiResourceId="db-TEST", IAMDatabaseAuthenticationEnabled=True,
+ Endpoint={"Address": AUTHZ_HOST, "Port": 3306})
+ rds._instances.set_scoped(ACCOUNT, REGION, "database", instance)
+ return instance
+
+
[email protected](autouse=True)
+def clean_broker():
+ broker.reset()
+ yield
+ broker.reset()
+
+
+def capability():
+ return broker.issue_capability(**{k: v for k, v in ARGS.items() if k != "db_user"})
+
+
+def request(cap, *, payload=None, body=None, headers=None, method="POST", query=b"", chunks=None):
+ if body is None:
+ body = json.dumps(payload if payload is not None else {"username": USER, "token": token()}).encode()
+ messages = iter(chunks or [{"type": "http.request", "body": body}])
+ sent = []
+
+ async def receive():
+ return next(messages)
+
+ async def send(message):
+ sent.append(message)
+
+ scope = {"type": "http", "method": method, "path": broker.PATH, "query_string": query,
+ "headers": headers if headers is not None else [
+ (b"content-type", b"application/json"), (b"x-ministack-rds-capability", cap.encode()),
+ ]}
+ asyncio.run(app_module.app(scope, receive, send))
+ return sent[0]["status"], json.loads(sent[1]["body"])
+
+
[email protected]("auth", [False, True])
[email protected]("enabled", [False, True])
[email protected]("valid_token", [False, True])
+def test_auth_and_enablement_matrix(state, monkeypatch, auth, enabled, valid_token):
+ monkeypatch.setattr(app_module, "AUTH", auth)
+ state["IAMDatabaseAuthenticationEnabled"] = enabled
+ before = get_account_id(), get_region()
+ result = request(capability(), payload={"username": USER, "token": token() if valid_token else ""})
+ allowed = enabled and (not auth or valid_token)
+ assert result == (200 if allowed else 403, {"allowed": allowed})
+ assert (get_account_id(), get_region()) == before
+
+
+def test_permissive_never_calls_authorizer(state, monkeypatch):
+ monkeypatch.setattr(app_module, "AUTH", False)
+
+ def unexpected(*args, **kwargs):
+ pytest.fail("Permissive mode called IAM authorizer")
+
+ monkeypatch.setattr(broker, "authorize_rds_iam_token", unexpected)
+ assert request(capability(), payload={"username": USER, "token": "not-a-token"})[0] == 200
+
+
[email protected]("auth", [False, True])
+def test_missing_invalid_rotated_revoked_capabilities(state, monkeypatch, auth):
+ monkeypatch.setattr(app_module, "AUTH", auth)
+ old = capability()
+ new = capability()
+ for cap in ("", "f" * 64, old):
+ assert request(cap)[0] == 403
+ assert request(new)[0] == 200
+ broker.revoke_capability(new)
+ assert request(new)[0] == 403
+
+
[email protected]("change", ["replace", "delete", "id", "reset"])
+def test_stale_binding_cannot_authorize(state, monkeypatch, change):
+ monkeypatch.setattr(app_module, "AUTH", False)
+ cap = capability()
+ if change == "replace":
+ rds._instances.set_scoped(ACCOUNT, REGION, "database", dict(state))
+ elif change == "delete":
+ rds._instances.pop_scoped(ACCOUNT, REGION, "database")
+ elif change == "id":
+ state["DbiResourceId"] = "db-NEW"
+ else:
+ broker.reset()
+ assert request(cap)[0] == 403
+
+
[email protected]("body", [b"null", b"[]", b"{", b'{}', b'\xff',
+ b'{"username":"x","username":"y","token":""}',
+ b'{"username":"x","token":"","account_id":"123456789012"}',
+ b'{"username":"","token":""}', b'{"username":"x","token":null}',
+ b'{"username":"x","token":"","resource_identifier":"other"}'])
+def test_malformed_payloads_denied_in_permissive_mode(state, monkeypatch, body):
+ monkeypatch.setattr(app_module, "AUTH", False)
+ assert request(capability(), body=body) == (403, {"allowed": False})
+
+
+def test_chunked_body_limit_and_disconnect(state, monkeypatch):
+ monkeypatch.setattr(app_module, "AUTH", False)
+ cap = capability()
+ assert request(cap, chunks=[{"type": "http.request", "body": b" " * broker.MAX_BODY, "more_body": True},
+ {"type": "http.request", "body": b"x"}])[0] == 403
+ assert request(cap, chunks=[{"type": "http.disconnect"}])[0] == 403
+ assert request(cap, chunks=[{"type": "http.request", "body": b'{"username":"x",', "more_body": True},
+ {"type": "http.request", "body": b'"token":""}'}])[0] == 200
+
+
[email protected]("kind", ["query", "get", "duplicate", "gzip"])
+def test_transport_constraints(state, monkeypatch, kind):
+ monkeypatch.setattr(app_module, "AUTH", False)
+ cap = capability()
+ headers = [(b"content-type", b"application/json"), (b"x-ministack-rds-capability", cap.encode())]
+ if kind == "duplicate":
+ headers.append(headers[-1])
+ if kind == "gzip":
+ headers.append((b"content-encoding", b"gzip"))
+ assert request(cap, headers=headers, query=b"token=secret" if kind == "query" else b"",
+ method="GET" if kind == "get" else "POST")[0] == 403
+
+
+def test_timeout(state, monkeypatch):
+ monkeypatch.setattr(broker, "BODY_TIMEOUT", 0.001)
+ sent = []
+
+ async def receive():
+ await asyncio.sleep(1)
+
+ async def send(message):
+ sent.append(message)
+
+ asyncio.run(broker.handle({"method": "POST", "headers": [
+ (b"content-type", b"application/json"), (b"x-ministack-rds-capability", capability().encode()),
+ ]}, receive, send, auth_enabled=False))
+ assert sent[0]["status"] == 403
+
+
+def test_authorizer_failure_does_not_log_secrets(state, monkeypatch, caplog):
+ monkeypatch.setattr(app_module, "AUTH", True)
+ cap = capability()
+
+ def broken(*args, **kwargs):
+ raise RuntimeError("secret-token " + cap)
+
+ monkeypatch.setattr(broker, "authorize_rds_iam_token", broken)
+ assert request(cap, payload={"username": USER, "token": "secret-token"}) == (403, {"allowed": False})
+ assert cap not in caplog.text
+ assert "secret-token" not in caplog.text
+
+
+def test_aurora_parent_flag_and_replacement(state, monkeypatch):
+ monkeypatch.setattr(app_module, "AUTH", False)
+ state.update(Engine="aurora-mysql", DBClusterIdentifier="cluster")
+ owner = {"Engine": "aurora-mysql", "DbClusterResourceId": "cluster-TEST",
+ "IAMDatabaseAuthenticationEnabled": False}
+ rds._clusters.set_scoped(ACCOUNT, REGION, "cluster", owner)
+ cap = capability()
+ assert request(cap)[0] == 403
+ owner["IAMDatabaseAuthenticationEnabled"] = True
+ assert request(cap)[0] == 200
+ rds._clusters.set_scoped(ACCOUNT, REGION, "cluster", dict(owner))
+ assert request(cap)[0] == 403
+
+
[email protected]("auth", [False, True])
+def test_policy_denial_only_enforced_when_auth_enabled(state, monkeypatch, auth):
+ monkeypatch.setattr(app_module, "AUTH", auth)
+ iam._user_inline_policies.set_scoped(ACCOUNT, None, "alice", {})
+ assert request(capability())[0] == (403 if auth else 200)
+
+
+def test_capability_selects_resource_even_with_identical_endpoint(state, monkeypatch):
+ monkeypatch.setattr(app_module, "AUTH", True)
+ rds._instances.set_scoped(ACCOUNT, REGION, "other", {**state, "DbiResourceId": "db-OTHER"})
+ cap = broker.issue_capability(account_id=ACCOUNT, region=REGION, resource_kind="instance",
+ resource_identifier="other")
+ assert request(cap)[0] == 403 # Token's user policy grants only db-TEST.
+
+
+def test_revocation_during_body_read_fails_closed(state, monkeypatch):
+ monkeypatch.setattr(app_module, "AUTH", False)
+ cap = capability()
+ sent = []
+
+ async def receive():
+ broker.revoke_capability(cap)
+ return {"type": "http.request", "body": b'{"username":"x","token":""}'}
+
+ async def send(message):
+ sent.append(message)
+
+ asyncio.run(broker.handle({"method": "POST", "headers": [
+ (b"content-type", b"application/json"), (b"x-ministack-rds-capability", cap.encode()),
+ ]}, receive, send, auth_enabled=False))
+ assert sent[0]["status"] == 403
+
+
[email protected]("aurora", [False, True])
[email protected]("change", ["target", "owner", "id", "disable", "delete"])
+def test_binding_changed_during_authorization_fails_closed(state, monkeypatch, aurora, change):
+ monkeypatch.setattr(app_module, "AUTH", True)
+ owner = state
+ if aurora:
+ state.update(Engine="aurora-mysql", DBClusterIdentifier="cluster")
+ owner = {"Engine": "aurora-mysql", "DbClusterResourceId": "cluster-TEST",
+ "IAMDatabaseAuthenticationEnabled": True}
+ rds._clusters.set_scoped(ACCOUNT, REGION, "cluster", owner)
+ cap = capability()
+ authorize = broker.authorize_rds_iam_token
+ decisions = []
+
+ def mutate_then_authorize(*args, **kwargs):
+ if change == "target":
+ rds._instances.set_scoped(ACCOUNT, REGION, "database", dict(state))
+ elif change == "owner":
+ store, identifier = (rds._clusters, "cluster") if aurora else (rds._instances, "database")
+ store.set_scoped(ACCOUNT, REGION, identifier, dict(owner))
+ elif change == "id":
+ owner["DbClusterResourceId" if aurora else "DbiResourceId"] = "cluster-NEW" if aurora else "db-NEW"
+ # For replacement/id mutations, the real authorizer can allow the new
+ # resource. For disable/delete, mutate just after a real allow result.
+ result = authorize(*args, **kwargs)
+ decisions.append(result)
+ if change == "disable":
+ owner["IAMDatabaseAuthenticationEnabled"] = False
+ elif change == "delete":
+ rds._instances.pop_scoped(ACCOUNT, REGION, "database")
+ return result
+
+ monkeypatch.setattr(broker, "authorize_rds_iam_token", mutate_then_authorize)
+ assert request(cap, payload={"username": USER, "token": token(key="test", secret="root-secret")}) == (
+ 403, {"allowed": False},
+ )
+ assert len(decisions) == 1
+ assert isinstance(decisions[0], broker.AuthorizedRdsConnection)