Skip to content

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

feat(rds): delegate MySQL IAM login to broker (#1803)

Ian Oberst16bc7c2e6963
diff --git a/contrib/mysql-iam-plugin/README.md b/contrib/mysql-iam-plugin/README.md
index c4672696..2f2dd929 100644
--- a/contrib/mysql-iam-plugin/README.md
+++ b/contrib/mysql-iam-plugin/README.md
@@ -6,7 +6,89 @@ Aurora MySQL users declared with `AWSAuthenticationPlugin`.
The initial L0 implementation deliberately rejects every login, matching
MySQL's `mysql_no_login` behavior. It supports provider workflows that create,
alter, grant, revoke, inspect, and drop IAM-authenticated users without
-pretending that local IAM token validation exists.
+enabling direct IAM logins before the isolated proxy topology is provisioned.
+
+## Stage 7: inactive Python gatekeeper
+
+`ministack/core/mysqlproxy.py` implements the narrow MySQL connection adapter.
+It relays ordinary password authentication to MySQL and delegates IAM admission
+to a caller-supplied Python authorizer. No C++ HTTP callback or libcurl dependency
+is needed. The opt-in connection fixture uses the existing `rds_iam._decision`
+implementation with a resource capability and SDK-signed tokens; it does not
+duplicate SigV4 or IAM policy evaluation.
+
+`aws_auth_plugin.cc` is the single plugin implementation. Its minimal accepting
+path is enabled by `-DMINISTACK_IAM_PROXY_AUTH=1` only in the isolated live test
+fixture. This compile-time switch defaults to zero; it is not a runtime setting
+or a second AUTH flag. **Normal builds do not enable acceptance.**
+`Dockerfile.full` continues to build the default reject-all mode from that source.
+The accepting variant must never replace that artifact while MySQL is directly
+reachable. A caller inside the trusted backend namespace can bypass the proxy;
+the tests demonstrate both that bypass and denial from outside the namespace.
+
+MySQL selects the private `ministack_iam_gate_v1` client method for IAM accounts.
+The adapter rejects client claims of that method and translates the backend's
+auth switch to `mysql_clear_password`. Account creation and changes between IAM
+and password methods therefore require no cached user list. MySQL still owns
+account locks, SQL identity, grants, and password verification.
+
+The SSLRequest and subsequent login must declare identical capabilities and
+character sets. Usernames are restricted to 1–32 printable, non-space ASCII
+characters without single quotes, with handshake collation IDs 8, 33, 45, 46 or
+255. Other forms fail closed instead of risking a different identity after
+MySQL's charset conversion, quote removal or truncation. Broader username and
+encoding support is deferred; these restrictions also apply to password users.
+
+With `AUTH=true`, IAM admission requires frontend TLS before requesting a token
+and applies the existing token/policy decision. False or unset remains permissive
+for IAM credentials and transport. Valid resource capability, current binding,
+and resource IAM enablement remain required by the authorizer in either mode.
+Password users retain MySQL's password checks and account-specific SSL rules.
+
+### Validation and limits
+
+Offline handshake tests run in the normal Python test lane without image builds:
+
+```sh
+uv run --extra dev pytest tests/test_mysqlproxy.py tests/test_rds_iam.py tests/test_rds_iam_plugin.py -q
+```
+
+The opt-in live tests compile both modes of the original plugin and connect through the Python
+adapter to MySQL 8.0 and 8.4. They cover signed-token acceptance/rejection,
+password users, account changes, grants, TLS rules, method spoofing, disabled
+LOCAL INFILE, and backend isolation. They are not part of normal PR CI and do
+not rebuild plugin images there. On the existing ARM64 validation environment:
+
+```sh
+docker build -f Dockerfile.full --target plugin-build-80 -t ministack-spike-compiler80:local .
+docker build -f Dockerfile.full --target plugin-build -t ministack-iam-stage7-build:local .
+uv run --extra dev pytest contrib/mysql-iam-plugin/tests/test_connections.py -q
+```
+
+Requires Docker, OpenSSL, a native `mysql` client on PATH, and the repo's dev
+dependencies. The Python helper image is `ghcr.io/ministackorg/ministack:full`;
+local source is mounted read-only. Fixtures own and remove their containers,
+volumes and network; Compose is unnecessary. The native client covers cold-cache
+plaintext RSA authentication because the installed PyMySQL 1.2.3 cold RSA path
+returns no packet to its caller. PyMySQL covers TLS and warmed password logins.
+
+This is not yet a provisioned integration. The adapter only forwards QUERY,
+QUIT, INIT_DB and PING; reauthentication, prepared statements and compression
+are unsupported. Frames are capped at 1 MiB, socket operations at five seconds,
+and idle sessions at ten seconds. These bounds are not a whole-handshake
+deadline or a concurrency limit. Backend TLS is encrypted but its certificate
+is not verified. Host-specific account selection is unproven: fixtures use `%`
+accounts and MySQL sees the proxy's loopback address. Broader client compatibility
+and fragmentation/multi-statement behavior still need validation.
+
+Item 8 of #1744 must provide isolated backend networking, endpoint/resource and
+capability provisioning, lifecycle handling, TLS certificates, and tests through
+normal MiniStack provisioning before activating the accepting shim. It should
+expose a supported internal decision API rather than the fixture's private seam.
+The authorizer fixture creates local state; it is not production provisioning
+or validation against AWS. Token expiry affects new logins, not existing sessions.
+
+## Bundled compatibility artifact
The same C++ source is compiled separately against MySQL 8.0 and 8.4 headers.
MySQL checks the authentication-plugin interface version when the library is
diff --git a/contrib/mysql-iam-plugin/aws_auth_plugin.cc b/contrib/mysql-iam-plugin/aws_auth_plugin.cc
index 97b3d5d7..7c6bbb23 100644
--- a/contrib/mysql-iam-plugin/aws_auth_plugin.cc
+++ b/contrib/mysql-iam-plugin/aws_auth_plugin.cc
@@ -1,13 +1,17 @@
/*
- * MiniStack's L0 emulation of Aurora MySQL's AWSAuthenticationPlugin.
+ * MiniStack's Aurora MySQL AWSAuthenticationPlugin compatibility adapter.
*
- * This plugin intentionally rejects every authentication attempt. It exists
- * so local Aurora users can be created with the same authentication-plugin
- * name as AWS and retain that name in mysql.user. Token authentication is a
- * later fidelity level; accepting credentials here would be unsafe.
+ * Normal builds reject logins until isolated proxy provisioning is available.
+ * Only isolated connection tests currently enable the proxy-approved path.
+ * That path does not verify credentials: clients must not reach it directly.
*/
#include <stddef.h>
+#include <string.h>
+
+#ifndef MINISTACK_IAM_PROXY_AUTH
+#define MINISTACK_IAM_PROXY_AUTH 0
+#endif
// MYSQL_ABI_CHECK omits MySQL's internal compiler headers. Dynamic plugin
// declarations still need the public-symbol visibility wrapper they provide.
@@ -17,11 +21,24 @@
#include <mysql/plugin_auth.h>
-static int reject_authentication(MYSQL_PLUGIN_VIO *vio,
+static int authenticate(MYSQL_PLUGIN_VIO *vio,
MYSQL_SERVER_AUTH_INFO *info) {
+#if MINISTACK_IAM_PROXY_AUTH
+ if (!vio || !vio->read_packet || !info) return CR_ERROR;
+ unsigned char *packet = nullptr;
+ info->password_used = PASSWORD_USED_YES;
+ int size = vio->read_packet(vio, &packet);
+ if (size < 1 || !packet || packet[size - 1] != 0 || !info->user_name ||
+ info->user_name_length == 0 ||
+ strlen(info->authenticated_as) != info->user_name_length ||
+ memcmp(info->authenticated_as, info->user_name, info->user_name_length))
+ return CR_ERROR;
+ return CR_OK; // Python proxy owns IAM admission; isolation is mandatory.
+#else
(void)vio;
(void)info;
return CR_ERROR;
+#endif
}
static int generate_authentication_string(char *outbuf,
@@ -53,8 +70,12 @@ static int set_salt(const char *password, unsigned int password_len,
static struct st_mysql_auth aws_auth_handler = {
MYSQL_AUTHENTICATION_INTERFACE_VERSION,
+#if MINISTACK_IAM_PROXY_AUTH
+ "ministack_iam_gate_v1",
+#else
NULL,
- reject_authentication,
+#endif
+ authenticate,
generate_authentication_string,
validate_authentication_string,
set_salt,
@@ -67,7 +88,7 @@ mysql_declare_plugin(aws_auth_plugin) {
&aws_auth_handler,
"AWSAuthenticationPlugin",
"MiniStack",
- "Aurora IAM authentication compatibility plugin (reject-all L0)",
+ "Aurora IAM authentication compatibility plugin",
PLUGIN_LICENSE_GPL,
NULL,
NULL,
diff --git a/contrib/mysql-iam-plugin/tests/gatekeeper_server.py b/contrib/mysql-iam-plugin/tests/gatekeeper_server.py
new file mode 100644
index 00000000..f4923ae4
--- /dev/null
+++ b/contrib/mysql-iam-plugin/tests/gatekeeper_server.py
@@ -0,0 +1,16 @@
+"""Fixture launcher; deliberately not part of normal RDS provisioning."""
+import os
+import ssl
+
+from proof_authorization import bootstrap
+
+from ministack.core.mysqlproxy import Handler, Server
+
+if __name__ == "__main__":
+ with Server(("0.0.0.0", int(os.environ["SPIKE_PORT"])), Handler) as server:
+ server.authorize = bootstrap()
+ server.strict = os.environ.get("AUTH", "").lower() == "true"
+ server.tls = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
+ server.tls.minimum_version = ssl.TLSVersion.TLSv1_2
+ server.tls.load_cert_chain("/tls/cert.pem", "/tls/key.pem")
+ server.serve_forever()
diff --git a/contrib/mysql-iam-plugin/tests/proof_authorization.py b/contrib/mysql-iam-plugin/tests/proof_authorization.py
new file mode 100644
index 00000000..085c0390
--- /dev/null
+++ b/contrib/mysql-iam-plugin/tests/proof_authorization.py
@@ -0,0 +1,39 @@
+"""Fixture-only bootstrap of real MiniStack authorizer state, not provisioning."""
+import os
+
+from ministack.core import rds_iam
+from ministack.services import iam, rds
+
+ACCOUNT = "123456789012"
+REGION = "us-east-1"
+HOST = "database.spike.us-east-1.rds.amazonaws.com"
+KEY = "AKIASPIKELOCALTEST"
+
+
+def bootstrap():
+ iam._users.set_scoped(ACCOUNT, None, "spike", {
+ "UserName": "spike", "Arn": f"arn:aws:iam::{ACCOUNT}:user/spike",
+ })
+ iam._access_keys.set_scoped(ACCOUNT, None, KEY, {
+ "UserName": "spike", "Status": "Active", "SecretAccessKey": os.environ["SPIKE_SECRET"],
+ })
+ allowed = ["iam_user", "iam_locked", "dynamic_user"]
+ iam._user_inline_policies.set_scoped(ACCOUNT, None, "spike", {"connect": {
+ "Statement": [{"Effect": "Allow", "Action": "rds-db:connect", "Resource": [
+ f"arn:aws:rds-db:{REGION}:{ACCOUNT}:dbuser:db-SPIKE/{u}" for u in allowed
+ ]}],
+ }})
+ rds._instances.set_scoped(ACCOUNT, REGION, "spike", {
+ "Engine": "mysql", "DbiResourceId": "db-SPIKE",
+ "IAMDatabaseAuthenticationEnabled": True,
+ "Endpoint": {"Address": HOST, "Port": 3306},
+ })
+ cap = rds_iam.issue_capability(account_id=ACCOUNT, region=REGION,
+ resource_kind="instance", resource_identifier="spike")
+
+ def authorize(user, token, strict):
+ # Reuse the existing capability/current-resource/AUTH decision. A
+ # production refactor should expose this private seam as a public API.
+ return rds_iam._decision(cap.encode(), {"username": user, "token": token}, strict)
+
+ return authorize
diff --git a/contrib/mysql-iam-plugin/tests/test_connections.py b/contrib/mysql-iam-plugin/tests/test_connections.py
new file mode 100644
index 00000000..03127bf8
--- /dev/null
+++ b/contrib/mysql-iam-plugin/tests/test_connections.py
@@ -0,0 +1,349 @@
+"""Opt-in live tests: accepting shim + Python gate + real password users."""
+import datetime as dt
+import os
+import secrets
+import socket
+import ssl
+import subprocess
+import time
+from pathlib import Path
+from unittest.mock import patch
+
+import boto3
+import pymysql
+import pytest
+from proof_authorization import HOST, KEY, REGION
+
+SOURCE = Path(__file__).resolve().parent
+LABEL = "ministack.task=accepting-gate-spike"
+PYTHON_IMAGE = "ghcr.io/ministackorg/ministack:full"
+
+
+def signed(secret, *, user="iam_user", host=HOST, age=0):
+ client = boto3.client("rds", region_name=REGION, aws_access_key_id=KEY, aws_secret_access_key=secret)
+ now = dt.datetime.now(dt.timezone.utc) - dt.timedelta(seconds=age)
+ with patch("botocore.auth.get_current_datetime", return_value=now):
+ return client.generate_db_auth_token(DBHostname=host, Port=3306, DBUsername=user)
+
+
+def run(*args, **kwargs):
+ return subprocess.run(args, text=True, capture_output=True, check=True, **kwargs).stdout.strip()
+
+
[email protected](scope="module", params=["8.0", "8.4"])
+def setup(request, tmp_path_factory):
+ suffix = secrets.token_hex(4)
+ db = "accepting-spike-" + suffix
+ network = db + "-net"
+ containers = []
+ root, password, secret = [secrets.token_hex(16) for _ in range(3)]
+ token = signed(secret)
+ temp = tmp_path_factory.mktemp("accepting-shim")
+ compiler = "ministack-spike-compiler80:local" if request.param == "8.0" else "ministack-iam-stage7-build:local"
+ linked = run("docker", "run", "--rm", "--label", LABEL, "--entrypoint", "sh",
+ "-v", f"{SOURCE.parent}:/src:ro", "-v", f"{temp}:/out", compiler, "-c",
+ 'set -e; header=$(rpm -ql mysql-community-debugsource | grep "/include/mysql/plugin_auth.h$" | head -1); '
+ 'g++ -Wall -Wextra -Werror -shared -fPIC -DMYSQL_ABI_CHECK -DMYSQL_DYNAMIC_PLUGIN '
+ '-DMINISTACK_IAM_PROXY_AUTH=1 '
+ '-I"$(dirname "$(dirname "$header")")" /src/aws_auth_plugin.cc -o /out/accepting_shim.so; '
+ 'g++ -Wall -Wextra -Werror -shared -fPIC -DMYSQL_ABI_CHECK -DMYSQL_DYNAMIC_PLUGIN '
+ '-I"$(dirname "$(dirname "$header")")" /src/aws_auth_plugin.cc -o /out/rejecting_shim.so; '
+ 'ldd /out/accepting_shim.so; ldd /out/rejecting_shim.so')
+ assert "libcurl" not in linked
+ run("openssl", "req", "-x509", "-newkey", "rsa:2048", "-nodes", "-days", "1",
+ "-subj", "/CN=localhost", "-addext", "subjectAltName=IP:127.0.0.1",
+ "-keyout", str(temp / "key.pem"), "-out", str(temp / "cert.pem"))
+ context = ssl.create_default_context(cafile=str(temp / "cert.pem"))
+
+ def admin(sql):
+ return run("docker", "exec", "-i", "-e", "MYSQL_PWD=" + root, db,
+ "mysql", "-uroot", "-N", "-B", input=sql)
+
+ run("docker", "network", "create", "--label", LABEL, network)
+ try:
+ run("docker", "run", "-d", "--name", db, "--label", LABEL, "--network", network,
+ "-e", "MYSQL_ROOT_PASSWORD=" + root,
+ "-p", "127.0.0.1::13306", "-p", "127.0.0.1::13307",
+ # Deliberately publish the backend port too: loopback binding must
+ # defeat even this accidental forwarding rule.
+ "-p", "127.0.0.1::3306", "mysql:" + request.param, "--bind-address=127.0.0.1")
+ containers.append(db)
+ deadline = time.monotonic() + 120
+ while True:
+ try:
+ admin("SELECT 1")
+ # Entry-point temporary server also accepts socket connections;
+ # require the final TCP server before installing the plugin.
+ run("docker", "exec", "-e", "MYSQL_PWD=" + root, db, "mysql", "-h127.0.0.1", "-uroot", "-e", "SELECT 1")
+ break
+ except subprocess.CalledProcessError:
+ if time.monotonic() > deadline:
+ raise
+ time.sleep(1)
+ plugin_dir = admin("SELECT @@plugin_dir")
+ run("docker", "cp", str(temp / "accepting_shim.so"), f"{db}:{plugin_dir}accepting_shim.so")
+ run("docker", "cp", str(temp / "rejecting_shim.so"), f"{db}:{plugin_dir}rejecting_shim.so")
+ admin("INSTALL PLUGIN AWSAuthenticationPlugin SONAME 'accepting_shim.so';"
+ "CREATE DATABASE spike; CREATE TABLE spike.visible(id INT);"
+ "INSERT INTO spike.visible VALUES (7); CREATE TABLE spike.hidden(id INT);")
+ for user in ("iam_user", "iam_other", "iam_locked"):
+ admin(f"CREATE USER '{user}'@'%' IDENTIFIED WITH AWSAuthenticationPlugin;"
+ f"GRANT SELECT ON spike.visible TO '{user}'@'%';")
+ for user in ("password_user", "password_locked", "password_tls"):
+ admin(f"CREATE USER '{user}'@'%' IDENTIFIED WITH caching_sha2_password BY '{password}';"
+ f"GRANT SELECT ON spike.visible TO '{user}'@'%';")
+ admin("ALTER USER 'iam_locked'@'%' ACCOUNT LOCK;"
+ "ALTER USER 'password_locked'@'%' ACCOUNT LOCK;"
+ "ALTER USER 'password_tls'@'%' REQUIRE SSL;")
+ ports = {}
+ for strict, port in ((True, 13306), (False, 13307)):
+ proxy = db + ("-strict" if strict else "-permissive")
+ run("docker", "run", "-d", "--name", proxy, "--label", LABEL,
+ "--network", "container:" + db, "--entrypoint", "python",
+ "-v", f"{SOURCE}:/src:ro", "-v", f"{temp}:/tls:ro",
+ "-v", f"{SOURCE.parents[2]}:/repo:ro", "-e", "PYTHONPATH=/repo",
+ "-e", "SPIKE_PORT=" + str(port), "-e", "AUTH=" + str(strict).lower(),
+ "-e", "SPIKE_SECRET=" + secret,
+ PYTHON_IMAGE, "/src/gatekeeper_server.py")
+ containers.append(proxy)
+ ports[strict] = int(run("docker", "port", db, f"{port}/tcp").split(":")[-1])
+ deadline = time.monotonic() + 20
+ while True:
+ try:
+ with socket.create_connection(("127.0.0.1", ports[strict]), timeout=1) as sock:
+ if not sock.recv(1):
+ raise OSError("proxy not ready")
+ break
+ except OSError:
+ if time.monotonic() > deadline:
+ raise
+ time.sleep(0.2)
+ yield dict(db=db, network=network, ports=ports, tls=context, password=password,
+ token=token, secret=secret, admin=admin)
+ finally:
+ for name in reversed(containers):
+ run("docker", "rm", "-fv", name)
+ run("docker", "network", "rm", network)
+
+
+def connect(setup, *, user="iam_user", password=None, strict=True, tls=True, local_infile=False):
+ return pymysql.connect(host="127.0.0.1", port=setup["ports"][strict], user=user,
+ password=setup["token"] if password is None else password,
+ ssl=setup["tls"] if tls else None, ssl_disabled=not tls,
+ local_infile=local_infile, autocommit=True,
+ read_timeout=5, write_timeout=5, connect_timeout=5)
+
+
[email protected]("user", ["iam_user", "password_user"])
+def test_identity_grants_and_ddl(setup, user):
+ password = setup["token"] if user == "iam_user" else setup["password"]
+ with connect(setup, user=user, password=password) as conn, conn.cursor() as cur:
+ cur.execute("SELECT CURRENT_USER()")
+ assert cur.fetchone() == (user + "@%",)
+ cur.execute("SELECT id FROM spike.visible")
+ assert cur.fetchone() == (7,)
+ for sql in ("SELECT * FROM spike.hidden", "INSERT INTO spike.visible VALUES(8)"):
+ with pytest.raises(pymysql.MySQLError) as caught:
+ cur.execute(sql)
+ assert caught.value.args[0] == 1142
+ cur.execute("SHOW CREATE USER CURRENT_USER()")
+ expected = "AWSAuthenticationPlugin" if user == "iam_user" else "caching_sha2_password"
+ assert expected in cur.fetchone()[0]
+
+
[email protected]("options", [
+ {"password": "wrong"}, {"tls": False}, {"user": "iam_other"}, {"user": "unknown"},
+ {"user": "iam_locked"},
+])
+def test_iam_rejections(setup, options):
+ if options.get("user") == "iam_locked":
+ options = {**options, "password": signed(setup["secret"], user="iam_locked")}
+ with pytest.raises(pymysql.MySQLError):
+ connect(setup, **options)
+
+
[email protected]("strict", [True, False])
[email protected]("tls", [True, False])
+def test_password_login_unchanged(setup, strict, tls):
+ with connect(setup, user="password_user", password=setup["password"], strict=strict, tls=tls) as conn:
+ conn.ping(reconnect=False)
+ for user, password in (("password_user", "wrong"), ("password_locked", setup["password"])):
+ with pytest.raises(pymysql.MySQLError):
+ connect(setup, user=user, password=password, strict=strict, tls=tls)
+
+
+def test_password_account_tls_rule_preserved(setup):
+ with connect(setup, user="password_tls", password=setup["password"]) as conn:
+ conn.ping(reconnect=False)
+ with pytest.raises(pymysql.MySQLError):
+ connect(setup, user="password_tls", password=setup["password"], strict=False, tls=False)
+
+
+def test_iam_permissive_plaintext(setup):
+ with connect(setup, password="anything", strict=False, tls=False) as conn:
+ conn.ping(reconnect=False)
+
+
[email protected]("user", ["iam_user", "password_user"])
+def test_change_user_blocked(setup, user):
+ password = setup["token"] if user == "iam_user" else setup["password"]
+ with connect(setup, user=user, password=password) as conn:
+ conn._execute_command(17, b"iam_other\0")
+ with pytest.raises(pymysql.MySQLError):
+ conn._read_packet()
+
+
+def test_backend_isolation_and_trusted_bypass(setup):
+ port = int(run("docker", "port", setup["db"], "3306/tcp").split(":")[-1])
+ with pytest.raises(pymysql.MySQLError):
+ pymysql.connect(host="127.0.0.1", port=port, user="iam_user", password="anything",
+ connect_timeout=2, read_timeout=2)
+ # An ordinary container on the same bridge cannot reach MySQL's loopback.
+ result = subprocess.run(["docker", "run", "--rm", "--label", LABEL,
+ "--network", setup["network"], "--entrypoint", "python", PYTHON_IMAGE,
+ "-c", "import socket; socket.create_connection(('" + setup["db"] + "',3306),2)"],
+ capture_output=True, text=True)
+ assert result.returncode != 0 and "ConnectionRefusedError" in result.stderr
+ # Deliberate negative control: inside the trusted namespace the shim DOES
+ # accept arbitrary credentials. Isolation, not the shim, is the security gate.
+ output = run("docker", "run", "--rm", "--label", LABEL, "--network", "container:" + setup["db"],
+ "-v", f"{SOURCE}:/src:ro", "-v", f"{SOURCE.parents[2]}:/repo:ro",
+ "-e", "PYTHONPATH=/repo", "--entrypoint", "python", PYTHON_IMAGE, "/src/trusted_bypass.py")
+ assert output == "backend accepted unverified login"
+
+
[email protected]("case", ["expired", "bad-signature", "wrong-host", "policy-denied"])
+def test_real_iam_denials(setup, case):
+ args = {"secret": setup["secret"]}
+ user = "iam_user"
+ if case == "expired":
+ args["age"] = 1800
+ elif case == "bad-signature":
+ args["secret"] = "incorrect-secret"
+ elif case == "wrong-host":
+ args["host"] = "other.spike.us-east-1.rds.amazonaws.com"
+ else:
+ user = args["user"] = "iam_other"
+ with pytest.raises(pymysql.MySQLError):
+ connect(setup, user=user, password=signed(**args))
+
+
+def test_account_changes_need_no_cached_classification(setup):
+ admin = setup["admin"]
+ admin("CREATE USER 'dynamic_user'@'%' IDENTIFIED WITH AWSAuthenticationPlugin;")
+ try:
+ token = signed(setup["secret"], user="dynamic_user")
+ with connect(setup, user="dynamic_user", password=token) as conn:
+ conn.ping(reconnect=False)
+ admin("ALTER USER 'dynamic_user'@'%' IDENTIFIED WITH caching_sha2_password BY 'spike-password';")
+ with pytest.raises(pymysql.MySQLError):
+ connect(setup, user="dynamic_user", password=token)
+ with connect(setup, user="dynamic_user", password="spike-password") as conn:
+ conn.ping(reconnect=False)
+ admin("ALTER USER 'dynamic_user'@'%' IDENTIFIED WITH AWSAuthenticationPlugin;")
+ with pytest.raises(pymysql.MySQLError):
+ connect(setup, user="dynamic_user", password="spike-password")
+ with connect(setup, user="dynamic_user", password=token) as conn:
+ conn.ping(reconnect=False)
+ finally:
+ admin("DROP USER 'dynamic_user'@'%';")
+
+
+def test_client_cannot_claim_private_auth_method(setup):
+ from trusted_bypass import handshake
+
+ from ministack.core.mysqlproxy import read, send
+
+ # Permissive mode still must not permit the client to choose classification.
+ with socket.create_connection(("127.0.0.1", setup["ports"][False]), timeout=3) as sock:
+ read(sock)
+ send(sock, 1, handshake(b"ministack_iam_gate_v1"))
+ _, result = read(sock)
+ assert result[:1] == b"\xff"
+
+
+def test_cold_password_rsa_with_mysql_client(setup):
+ # PyMySQL 1.2.3's RSA full-auth path lacks a return packet; exercise this
+ # path with the native client instead, without warming the auth cache.
+ password = secrets.token_hex(16)
+ setup["admin"]("CREATE USER 'cold_user'@'%' IDENTIFIED WITH caching_sha2_password BY '" + password + "';")
+ try:
+ result = subprocess.run(["mysql", "--no-defaults", "--local-infile=0", "--host=127.0.0.1",
+ "--port=" + str(setup["ports"][True]), "--user=cold_user", "--ssl-mode=DISABLED",
+ "--get-server-public-key", "-N", "-e", "SELECT CURRENT_USER()"],
+ text=True, capture_output=True, env={**os.environ, "MYSQL_PWD": password})
+ assert result.returncode == 0, (result.stderr, run("docker", "logs", setup["db"] + "-strict"))
+ output = result.stdout.strip()
+ assert output == "cold_user@%"
+ finally:
+ setup["admin"]("DROP USER 'cold_user'@'%';")
+
+
+def test_local_infile_stays_disabled(setup):
+ admin = setup["admin"]
+ admin("CREATE USER 'file_user'@'%' IDENTIFIED BY 'spike-password';"
+ "GRANT INSERT ON spike.visible TO 'file_user'@'%'; SET GLOBAL local_infile=ON;")
+ try:
+ with connect(setup, user="file_user", password="spike-password", local_infile=True) as conn:
+ with conn.cursor() as cur, pytest.raises(pymysql.MySQLError) as caught:
+ cur.execute("LOAD DATA LOCAL INFILE '/nonexistent-spike-file' INTO TABLE spike.visible")
+ assert caught.value.args[0] == 3948 # LOCAL disabled by negotiated capability
+ finally:
+ admin("DROP USER 'file_user'@'%'; SET GLOBAL local_infile=OFF;")
+
+
[email protected]("strict", [True, False])
[email protected]("change", ["database", "auth-length", "charset"])
+def test_tls_handshake_mismatch_rejected(setup, strict, change):
+ from ministack.core.mysqlproxy import read, send
+
+ flags = (1 << 9) | (1 << 15) | (1 << 19) | (1 << 11)
+ header = flags.to_bytes(4, "little") + b"\0" * 4 + b"\x21" + b"\0" * 23
+ altered = bytearray(header)
+ if change == "charset":
+ altered[8] = 8
+ else:
+ altered[:4] = (flags | (1 << (3 if change == "database" else 21))).to_bytes(4, "little")
+ # With the database bit mismatch, MySQL sees the private method while an
+ # unchecked proxy would parse it as a database and accept the public method.
+ payload = bytes(altered) + b"iam_user\0\x01\0ministack_iam_gate_v1\0mysql_native_password\0"
+ with socket.create_connection(("127.0.0.1", setup["ports"][strict]), timeout=3) as raw:
+ read(raw)
+ send(raw, 1, header)
+ with setup["tls"].wrap_socket(raw, server_hostname="127.0.0.1") as conn:
+ send(conn, 2, payload)
+ _, packet = read(conn)
+ assert packet[:1] == b"\xff" # Never OK or a cleartext token request.
+
+
[email protected]("strict", [True, False])
[email protected]("name,charset", [("é".encode(), 8), (b"'iam_user'", 33)])
+def test_ambiguous_sql_identity_rejected(setup, strict, name, charset):
+ from ministack.core.mysqlproxy import read, send
+
+ setup["admin"]("SET NAMES utf8mb4; CREATE USER IF NOT EXISTS 'é'@'%' IDENTIFIED WITH AWSAuthenticationPlugin;")
+ try:
+ flags = (1 << 9) | (1 << 15) | (1 << 19) | (1 << 11)
+ header = flags.to_bytes(4, "little") + b"\0" * 4 + bytes([charset]) + b"\0" * 23
+ with socket.create_connection(("127.0.0.1", setup["ports"][strict]), timeout=3) as raw:
+ read(raw)
+ send(raw, 1, header)
+ with setup["tls"].wrap_socket(raw, server_hostname="127.0.0.1") as conn:
+ send(conn, 2, header + name + b"\0\0mysql_native_password\0")
+ _, packet = read(conn)
+ assert packet[:1] == b"\xff"
+ finally:
+ setup["admin"]("SET NAMES utf8mb4; DROP USER 'é'@'%';")
+
+
+def test_bundled_shim_stays_fail_closed(setup):
+ admin = setup["admin"]
+ admin("UNINSTALL PLUGIN AWSAuthenticationPlugin;"
+ "INSTALL PLUGIN AWSAuthenticationPlugin SONAME 'rejecting_shim.so';")
+ try:
+ for strict in (True, False):
+ with pytest.raises(pymysql.MySQLError):
+ connect(setup, strict=strict)
+ finally:
+ admin("UNINSTALL PLUGIN AWSAuthenticationPlugin;"
+ "INSTALL PLUGIN AWSAuthenticationPlugin SONAME 'accepting_shim.so';")
diff --git a/contrib/mysql-iam-plugin/tests/trusted_bypass.py b/contrib/mysql-iam-plugin/tests/trusted_bypass.py
new file mode 100644
index 00000000..aed54253
--- /dev/null
+++ b/contrib/mysql-iam-plugin/tests/trusted_bypass.py
@@ -0,0 +1,21 @@
+"""Negative control: only run inside the isolated MySQL network namespace."""
+import socket
+import struct
+
+from ministack.core.mysqlproxy import read, send
+
+
+def handshake(plugin=b"mysql_native_password"):
+ flags = (1 << 9) | (1 << 15) | (1 << 19)
+ return struct.pack("<IIB23x", flags, 1024 * 1024, 45) + b"iam_user\0\0" + plugin + b"\0"
+
+
+if __name__ == "__main__":
+ with socket.create_connection(("127.0.0.1", 3306), timeout=3) as sock:
+ read(sock)
+ send(sock, 1, handshake())
+ seq, packet = read(sock)
+ assert packet.startswith(b"\xfeministack_iam_gate_v1\0")
+ send(sock, seq + 1, b"anything\0")
+ assert read(sock)[1][:1] == b"\0"
+ print("backend accepted unverified login")
diff --git a/ministack/core/mysqlproxy.py b/ministack/core/mysqlproxy.py
new file mode 100644
index 00000000..3dc1881c
--- /dev/null
+++ b/ministack/core/mysqlproxy.py
@@ -0,0 +1,215 @@
+"""Inactive MySQL IAM adapter: relay password auth and gate IAM auth switches.
+
+Runs in MySQL's network namespace. MySQL listens on loopback only.
+No SQL/account rewriting. The caller supplies resource-bound authorization.
+Not provisioned by the runtime: backend isolation is mandatory before activation.
+"""
+import contextlib
+import select
+import socket
+import socketserver
+import ssl
+
+
+def exact(sock, n):
+ data = b""
+ while len(data) < n:
+ chunk = sock.recv(n - len(data))
+ if not chunk:
+ raise EOFError
+ data += chunk
+ return data
+
+
+def read(sock):
+ header = exact(sock, 4)
+ n = int.from_bytes(header[:3], "little")
+ if n > 1024 * 1024:
+ raise ValueError("adapter packet limit")
+ return header[3], exact(sock, n)
+
+
+def send(sock, seq, body):
+ sock.sendall(len(body).to_bytes(3, "little") + bytes([seq % 256]) + body)
+
+
+def deny(sock, seq):
+ send(sock, seq, b"\xff\x15\x04#28000IAM gate denied")
+
+
+def limited_greeting(packet):
+ # Do not advertise wire modes that this adapter cannot relay safely.
+ packet = bytearray(packet)
+ lower = packet.index(0, 1) + 14
+ upper = lower + 5
+ flags = int.from_bytes(packet[lower:lower + 2], "little")
+ flags |= int.from_bytes(packet[upper:upper + 2], "little") << 16
+ flags &= ~((1 << 5) | (1 << 26) | (1 << 7))
+ packet[lower:lower + 2] = (flags & 65535).to_bytes(2, "little")
+ packet[upper:upper + 2] = (flags >> 16).to_bytes(2, "little")
+ return bytes(packet)
+
+
+def validate_header(reply):
+ """Accept only the explicitly supported protocol and character sets."""
+ if len(reply) < 32:
+ raise ValueError("short handshake")
+ flags = int.from_bytes(reply[:4], "little")
+ if not flags & (1 << 19) or not flags & (1 << 9):
+ raise ValueError("plugin authentication and protocol 4.1 required")
+ if flags & ((1 << 5) | (1 << 26) | (1 << 7)):
+ raise ValueError("compression and local infile unsupported")
+ if not flags & (1 << 15):
+ raise ValueError("secure connection capability required")
+ # latin1, utf8mb3, and the tested utf8mb4 collations share ASCII identity.
+ if reply[8] not in (8, 33, 45, 46, 255):
+ raise ValueError("unsupported handshake charset")
+
+
+def client_identity(reply):
+ """Parse enough HandshakeResponse41 to reject private-plugin spoofing."""
+ validate_header(reply)
+ flags = int.from_bytes(reply[:4], "little")
+ end = reply.index(0, 32)
+ name = reply[32:end]
+ # MySQL normalizes quoted names and converts the declared charset. Until
+ # those forms are supported, restrict identity to unquoted printable ASCII
+ # and MySQL's 32-character limit, preventing conversion or truncation drift.
+ if not 1 <= len(name) <= 32 or any(c < 33 or c > 126 or c == 39 for c in name):
+ raise ValueError("invalid username")
+ username = name.decode("ascii")
+ pos = end + 1
+ if flags & (1 << 21):
+ size = reply[pos]
+ pos += 1
+ if size >= 251:
+ width = {252: 2, 253: 3, 254: 8}.get(size)
+ if width is None or pos + width > len(reply):
+ raise ValueError("invalid auth length")
+ size = int.from_bytes(reply[pos:pos + width], "little")
+ pos += width
+ pos += size
+ elif flags & (1 << 15):
+ pos += 1 + reply[pos]
+ else:
+ raise ValueError("secure connection capability required")
+ if flags & (1 << 3):
+ pos = reply.index(0, pos) + 1
+ plugin = reply[pos:reply.index(0, pos)]
+ # In particular, never forward the shim's private name from a client:
+ # it could suppress the backend auth switch on which the gate depends.
+ if plugin not in (b"mysql_native_password", b"caching_sha2_password"):
+ raise ValueError("unsupported client auth method")
+ return username
+
+
+class Handler(socketserver.BaseRequestHandler):
+ def handle(self):
+ front = self.request
+ back = None
+ seq = 0
+ phase = "handshake"
+ try:
+ front.settimeout(5)
+ back = socket.create_connection(("127.0.0.1", 3306), timeout=5)
+ seq, greeting = read(back)
+ send(front, seq, limited_greeting(greeting))
+ seq, reply = read(front)
+ secure = False
+ if len(reply) == 32 and int.from_bytes(reply[:4], "little") & 2048:
+ tls_header = reply
+ flags = int.from_bytes(reply[:4], "little") & ~(1 << 7)
+ reply = flags.to_bytes(4, "little") + reply[4:]
+ validate_header(reply)
+ send(back, seq, reply)
+ # Encryption only on the namespace-local backend leg; server
+ # identity verification is not implemented by this adapter.
+ back = ssl._create_unverified_context().wrap_socket(back)
+ front = self.server.tls.wrap_socket(front, server_side=True)
+ secure = True
+ seq, reply = read(front)
+ # MySQL retains the SSLRequest capabilities/charset. Do not
+ # parse a different packet layout or identity on this side.
+ if len(reply) < 32 or reply[:4] != tls_header[:4] or reply[8] != tls_header[8]:
+ raise ValueError("TLS handshake header mismatch")
+ # libmysqlclient can set LOCAL_FILES even when --local-infile=0.
+ # We never advertised it and must not enable it on the backend.
+ if len(reply) >= 4:
+ flags = int.from_bytes(reply[:4], "little") & ~(1 << 7)
+ reply = flags.to_bytes(4, "little") + reply[4:]
+ username = client_identity(reply)
+ phase = "authentication"
+ send(back, seq, reply)
+ # Only the trusted backend can select the private IAM method.
+ # No client assertion or cached list classifies the SQL account.
+ while True:
+ seq, packet = read(back)
+ if packet[:1] == b"\xff":
+ send(front, seq, packet)
+ return
+ if packet[:1] == b"\x00":
+ send(front, seq, packet)
+ break
+ is_iam = packet.startswith(b"\xfeministack_iam_gate_v1\0")
+ if is_iam and self.server.strict and not secure:
+ deny(front, seq)
+ return
+ if is_iam:
+ packet = b"\xfemysql_clear_password\0"
+ elif packet[:1] == b"\xfe" and packet[1:].split(b"\0", 1)[0] not in (
+ b"mysql_native_password", b"caching_sha2_password",
+ ):
+ raise ValueError("unsupported backend auth method")
+ send(front, seq, packet)
+ if packet == b"\x01\x03": # caching_sha2 fast-auth success; OK follows
+ continue
+ seq, response = read(front)
+ if is_iam:
+ if (len(response) > 65537 or not response.endswith(b"\0") or b"\0" in response[:-1]
+ or not self.server.authorize(username, response[:-1].decode(), self.server.strict)):
+ deny(front, seq + 1)
+ return
+ # Do not expose the frontend token to the accepting shim.
+ response = b"proxy-approved\0"
+ send(back, seq, response)
+ phase = "commands"
+ while True:
+ ready = [s for s in (front, back) if isinstance(s, ssl.SSLSocket) and s.pending()]
+ if not ready:
+ ready, _, _ = select.select([front, back], [], [], 10)
+ if not ready:
+ return
+ for source in ready:
+ if source is front:
+ seq, payload = read(front)
+ # Deliberate limited command set; reject CHANGE_USER,
+ # prepared statements, and LOCAL INFILE exchanges.
+ if seq != 0 or not payload or payload[0] not in (1, 2, 3, 14):
+ deny(front, 1)
+ return
+ send(back, seq, payload)
+ if payload[0] == 1:
+ return
+ else:
+ data = back.recv(65536)
+ if not data:
+ return
+ front.sendall(data)
+ except Exception as exc:
+ # Fail closed without logging usernames, tokens, or exception data.
+ known = {"short handshake", "plugin authentication and protocol 4.1 required",
+ "compression and local infile unsupported", "invalid username", "invalid auth length",
+ "secure connection capability required", "unsupported client auth method"}
+ reason = str(exc) if type(exc) is ValueError and str(exc) in known else type(exc).__name__
+ print("MySQL adapter rejection", phase, reason, flush=True)
+ with contextlib.suppress(OSError):
+ deny(front, seq + 1)
+ finally:
+ front.close()
+ if back:
+ back.close()
+
+
+class Server(socketserver.ThreadingTCPServer):
+ allow_reuse_address = True
+ daemon_threads = True
diff --git a/tests/test_mysqlproxy.py b/tests/test_mysqlproxy.py
new file mode 100644
index 00000000..dbce8a66
--- /dev/null
+++ b/tests/test_mysqlproxy.py
@@ -0,0 +1,64 @@
+"""Offline fail-closed checks for the adapter's explicitly limited handshake."""
+import socket
+
+import pytest
+
+from ministack.core.mysqlproxy import client_identity, read
+
+
+def handshake(plugin=b"mysql_native_password"):
+ flags = (1 << 9) | (1 << 15) | (1 << 19)
+ return (flags.to_bytes(4, "little") + b"\0" * 4 + b"\x21" + b"\0" * 23
+ + b"iam_user\0\0" + plugin + b"\0")
+
+
[email protected]("plugin", [b"mysql_native_password", b"caching_sha2_password"])
+def test_supported_client_identity(plugin):
+ assert client_identity(handshake(plugin)) == "iam_user"
+
+
[email protected]("payload", [
+ b"", b"\0" * 32, handshake()[:-1], handshake(b"ministack_iam_gate_v1"),
+ handshake(b"mysql_clear_password"), handshake(b"unknown"),
+])
+def test_malformed_or_spoofed_identity(payload):
+ with pytest.raises((ValueError, IndexError)):
+ client_identity(payload)
+
+
[email protected]("flag", [1 << 5, 1 << 26, 1 << 7])
+def test_unsupported_capabilities(flag):
+ payload = handshake()
+ payload = (int.from_bytes(payload[:4], "little") | flag).to_bytes(4, "little") + payload[4:]
+ with pytest.raises(ValueError):
+ client_identity(payload)
+
+
+def test_oversized_frame_rejected_before_reading_body():
+ left, right = socket.socketpair()
+ with left, right:
+ left.sendall((1024 * 1024 + 1).to_bytes(3, "little") + b"\0")
+ with pytest.raises(ValueError):
+ read(right)
+
+
[email protected]("name", [b"'iam_user'", "é".encode(), b"x" * 33, b"a b", b"a\n", b""])
+def test_ambiguous_username_rejected(name):
+ payload = handshake().replace(b"iam_user", name)
+ with pytest.raises(ValueError):
+ client_identity(payload)
+
+
[email protected]("charset", [0, 1, 28, 35, 54])
+def test_unsupported_charset_rejected(charset):
+ payload = bytearray(handshake())
+ payload[8] = charset
+ with pytest.raises(ValueError):
+ client_identity(payload)
+
+
[email protected]("charset", [8, 33, 45, 46, 255])
+def test_supported_charset_ascii_identity(charset):
+ payload = bytearray(handshake())
+ payload[8] = charset
+ assert client_identity(payload) == "iam_user"