Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.
Python awsaws-emulatoraws-localaws-sdkdevtoolsdockerdynamodbec2emulatorlambdalocalstacklocalstack-alternativeministackmock-awsopen-sourcepythons3sqsterraform
Add Aurora MySQL compatibility objects (#1364)
Ian Oberst7938db5be7f0
diff --git a/Dockerfile.full b/Dockerfile.fullindex c9d21074..55ba2b87 100644--- a/Dockerfile.full+++ b/Dockerfile.full@@ -28,6 +28,63 @@ RUN rm -rf /usr/local/lib/python3.13/site-packages/awscli/examples \&& rm -rf /usr/local/lib/python3.13/site-packages/_duckdb-stubs \&& rm -rf /usr/local/lib/python3.13/site-packages/adbc_driver_duckdb+# Compile the IAM-auth compatibility plugin against each supported MySQL+# series. The compiler and headers remain isolated in these build stages.+FROM mysql:8.0 AS plugin-build-80+USER root+RUN mysql_version="$(rpm -q --qf '%{VERSION}-%{RELEASE}' mysql-community-server-minimal)" \+ && sed -i 's#/docker/#/#' /etc/yum.repos.d/mysql-community-minimal.repo \+ && microdnf install -y gcc-c++ "mysql-community-debugsource-${mysql_version}" \+ && microdnf clean all+ARG TARGETARCH+COPY contrib/mysql-iam-plugin/aws_auth_plugin.cc /tmp/aws_auth_plugin.cc+RUN arch="${TARGETARCH}"; \+ if [ -z "${arch}" ]; then \+ case "$(uname -m)" in \+ x86_64) arch=amd64 ;; \+ aarch64) arch=arm64 ;; \+ *) echo "unsupported build architecture: $(uname -m)" >&2; exit 1 ;; \+ esac; \+ fi; \+ header="$(rpm -ql mysql-community-debugsource | grep '/include/mysql/plugin_auth.h$' | head -1)"; \+ include_dir="$(dirname "$(dirname "${header}")")"; \+ mkdir -p "/opt/ministack/mysql-plugins/8.0/${arch}"; \+ g++ -O2 -Wall -Wextra -Werror -fPIC -shared \+ -DMYSQL_ABI_CHECK -DMYSQL_DYNAMIC_PLUGIN \+ -I"${include_dir}" \+ -o "/opt/ministack/mysql-plugins/8.0/${arch}/aws_auth_plugin.so" \+ /tmp/aws_auth_plugin.cc; \+ nm -D "/opt/ministack/mysql-plugins/8.0/${arch}/aws_auth_plugin.so" \+ | grep -q ' _mysql_plugin_interface_version_$'++FROM mysql:8.4 AS plugin-build+USER root+RUN mysql_version="$(rpm -q --qf '%{VERSION}-%{RELEASE}' mysql-community-server-minimal)" \+ && sed -i 's#/docker/#/#' /etc/yum.repos.d/mysql-community-minimal.repo \+ && microdnf install -y gcc-c++ "mysql-community-debugsource-${mysql_version}" \+ && microdnf clean all+ARG TARGETARCH+COPY contrib/mysql-iam-plugin/aws_auth_plugin.cc /tmp/aws_auth_plugin.cc+RUN arch="${TARGETARCH}"; \+ if [ -z "${arch}" ]; then \+ case "$(uname -m)" in \+ x86_64) arch=amd64 ;; \+ aarch64) arch=arm64 ;; \+ *) echo "unsupported build architecture: $(uname -m)" >&2; exit 1 ;; \+ esac; \+ fi; \+ header="$(rpm -ql mysql-community-debugsource | grep '/include/mysql/plugin_auth.h$' | head -1)"; \+ include_dir="$(dirname "$(dirname "${header}")")"; \+ mkdir -p "/opt/ministack/mysql-plugins/8.4/${arch}"; \+ g++ -O2 -Wall -Wextra -Werror -fPIC -shared \+ -DMYSQL_ABI_CHECK -DMYSQL_DYNAMIC_PLUGIN \+ -I"${include_dir}" \+ -o "/opt/ministack/mysql-plugins/8.4/${arch}/aws_auth_plugin.so" \+ /tmp/aws_auth_plugin.cc; \+ nm -D "/opt/ministack/mysql-plugins/8.4/${arch}/aws_auth_plugin.so" \+ | grep -q ' _mysql_plugin_interface_version_$'+COPY --from=plugin-build-80 /opt/ministack/mysql-plugins/8.0 /opt/ministack/mysql-plugins/8.0+FROM python:3.13-slimLABEL maintainer="MiniStack" \@@ -56,6 +113,7 @@ COPY bin/awslocal /usr/local/bin/awslocalRUN chmod +x /usr/local/bin/awslocalCOPY ministack/ ministack/+COPY --from=plugin-build /opt/ministack/mysql-plugins /opt/ministack/mysql-pluginsRUN groupadd -r ministack && useradd -r -g ministack ministackRUN mkdir -p /tmp/ministack-data/s3 && chown -R ministack:ministack /tmp/ministack-datadiff --git a/README.md b/README.mdindex d8aefb3a..c14c69b1 100644--- a/README.md+++ b/README.md@@ -647,7 +647,7 @@ Each `CreateCluster` returns an `ACTIVE` cluster with an endpoint. Set `DSQL_STR**The proxy fails like real DSQL**: SQL that DSQL rejects fails here too (`serial` columns, foreign keys, `CREATE EXTENSION`, `TRUNCATE`, temp tables, `ALTER COLUMN TYPE`, `SET NOT NULL`, materialized views, partitioned tables, non-btree/partial/expression indexes, ...), plain `CREATE INDEX` on a non-empty table is refused (`use CREATE INDEX ASYNC instead`), `CREATE INDEX ASYNC` and `ALTER TABLE ASYNC ... VALIDATE CONSTRAINT` return a `job_id`, `sys.jobs` / `sys.wait_for_job` are emulated, CHECK constraints via ALTER TABLE require `NOT VALID`, `ALTER TABLE ... DROP COLUMN` works (several columns in one statement included) except on a primary key column, identity columns are bigint-only (CACHE 1 or ≥ 65536), index limits are enforced (8 columns/index, 24/table), transactions allow only one DDL statement with no DDL+DML mixing, `SELECT ... FOR UPDATE` requires a single table with equality predicates on the key, a transaction that outlives another session's DDL fails once with `40001` (OC001) and succeeds on retry, and the transaction limits (3,000 rows / 10 MiB / 5 min) are enforced.-`GetCluster` returns an `endpoint` of the form `localhost:<port>` (ports allocated from `DSQL_BASE_PORT`, default `25432`). Any user/password is accepted — IAM auth tokens from `generate_db_connect_auth_token` work but aren't validated. Connect with e.g. `psql "postgresql://admin:anything@localhost:25432/postgres"` (no TLS — use `sslmode=disable`/`prefer`; with psycopg2 use `autocommit=True`).+`GetCluster` returns an `endpoint` of the form `localhost:<port>` (ports allocated from `DSQL_BASE_PORT`, default `25432`). Any user/password is accepted — IAM auth tokens from `generate_db_connect_auth_token` work but aren't validated. Connect with e.g. `psql "postgresql://admin@localhost:25432/postgres"` and enter any test password when prompted (no TLS — use `sslmode=disable`/`prefer`; with psycopg2 use `autocommit=True`).**Both wire protocols are validated**: the simple protocol (psql, psycopg2) and the extended `Parse`/`Bind`/`Execute` protocol used by pgjdbc, pgx, asyncpg, psycopg3 and every ORM built on prepared statements. Transaction state is read from the backend's `ReadyForQuery` status byte rather than inferred from statement text, so `BEGIN`/`COMMIT` sent over either protocol keeps the transaction rules accurate. A statement the proxy rejects inside a transaction aborts that block exactly as a real error would — later statements fail with `25P02` and `COMMIT` reports `ROLLBACK`.diff --git a/contrib/mysql-iam-plugin/README.md b/contrib/mysql-iam-plugin/README.mdnew file mode 100644index 00000000..8e2388e1--- /dev/null+++ b/contrib/mysql-iam-plugin/README.md@@ -0,0 +1,114 @@+# MiniStack MySQL IAM authentication plugin++This directory contains MiniStack's server-side compatibility plugin for+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.++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+loaded, so artifacts must stay separated by series and architecture:++```text+<root>/<series>/<arch>/aws_auth_plugin.so+```++Supported v1 combinations are MySQL 8.0 and 8.4 on `amd64` and `arm64`.+Rebuild and test the artifacts when the corresponding MySQL image tag moves;+within-series server plugin ABI stability is not an explicit MySQL guarantee.+The official runtime images expose only a minimal repository. Installing+`mysql-community-devel` from the full repository conflicts with files already+owned by `mysql-community-server-minimal`, and it does not contain the server+plugin header. The build therefore installs the exact-version+`mysql-community-debugsource` package from the image's series repository and+compiles with its server headers. Generated `mysql_version.h` and the unused+server-internal headers are excluded with MySQL's `MYSQL_ABI_CHECK` compile+mode. `MYSQL_DYNAMIC_PLUGIN` emits the three loader-facing symbols instead of+the built-in-plugin symbol names, and the image build asserts that the interface+version symbol is exported. MySQL's interface version check remains the+load-time ABI guard.++Build the 8.0 and 8.4 artifacts for the host architecture with Docker from the+repository root:++```bash+contrib/mysql-iam-plugin/build.sh+```++This writes to `build/mysql-plugins` by default. The full Docker image places+the same tree at `/opt/ministack/mysql-plugins`, the fixed runtime lookup path.+Delivery and installation happen automatically when a matching bundled+artifact exists and are silent when it is absent.++Artifact series selection uses the tag of the same resolved MySQL image that+the RDS container launch uses. Accepted version prefixes such as Aurora MySQL+`8` therefore follow the current fallback image (`mysql:8.4`) automatically.+If a custom resolved image has no recognized series tag, MiniStack warns and+leaves the plugin artifact absent while still attempting the compatibility+procedures independently.++| Engine class | Launch image source | Compatibility series | Disposition |+|---|---|---|---|+| `aurora-mysql` | Aurora version map, then `DEFAULT_AURORA_MYSQL_IMAGE` | Parsed from the selected MySQL image tag | 8.0/8.4 plugin artifacts when present; predefined S3 roles on 8.x; procedures/config always attempted. |+| `mysql` | Same MySQL version map and fallback as the launch path | Parsed from the selected MySQL image tag | Same ABI-matched artifact rule; predefined S3 roles skipped; procedures/config always attempted. |+| `mariadb` | The launch path's `mariadb:latest` selection | None | Plugin and Aurora roles skipped; RDS procedures/config still attempted independently. |++## MySQL-ready path design++The lifecycle hook runs after authenticated readiness and outside RDS store+locks. Cluster paths revalidate their container ID/epoch after the hook before+publishing readiness. It installs the local Aurora compatibility procedures on+every MySQL compute node, then installs the auth plugin when its artifact is+available. Replication cannot begin before either installation attempt.++| Compute path | Container transition | Compatibility disposition |+|---|---|---|+| First Aurora member | `_start_cluster_shared_container` (`containers.run`) then `_create_db_instance` readiness worker | Hooked before `_configure_or_defer_mysql_replication`; applies to writers and secondaries. |+| New standalone RDS instance | `_create_db_instance` (`containers.run`) readiness worker | Hooked after authenticated readiness. |+| Persisted Aurora cluster | `restore_state` through `_start_cluster_shared_container` (`containers.run`) | Hooked after authenticated readiness and before replication reconfiguration. |+| Persisted standalone instance | `restore_state` through `_start_rds_container_for_instance` (`containers.run`) | Hooked after an authenticated readiness wait. |+| Stopped Aurora cluster | `_restart_cluster_shared_container` (`container.start`) or recreate fallback, then `_start_db_cluster` readiness worker | Hooked after authenticated readiness; object-existence guards preserve grants across restart. |+| CloudFormation DBCluster/DBInstance | `cloudformation/provisioners.py` writes metadata only | No hook: this path explicitly does not create or adopt database compute. |+| Read-replica and snapshot-restore stubs | Metadata-only records | No hook: no MySQL server transitions to ready. |++The same hook creates `mysql.rds_kill`, `mysql.rds_kill_query`,+`mysql.rds_show_configuration`, and `mysql.rds_set_configuration` with binary+logging disabled for the session. The provider's Square and Cash user sets are+the source of all four procedure grants. A validation-lane sweep of every+deployed control-plane ASL definition in both regions found no `rds_%` routine+reference; the only lexical match was the unrelated `rds_managed` identifier.+The kill procedures use a root-privileged definer and real `KILL CONNECTION` /+`KILL QUERY` statements. The configuration pair models only the+binlog-retention-hours round-trip.++For Aurora MySQL 8.x, the hook also creates the two predefined roles referenced+by the Cash user set: `AWS_SELECT_S3_ACCESS` and `AWS_LOAD_S3_ACCESS`. They+intentionally carry no privileges because MiniStack does not model Aurora's S3+import/export data plane; their fidelity contract is existence so grants and+reconciliation match Aurora. The deployed-ASL sweep found no `AWS_%`+identifiers, so it adds no role beyond the two provider-source roles.+Provider-created service roles+are runtime resources and require no MiniStack fixture. Standalone MySQL never+receives these Aurora-only roles, and Aurora MySQL 5.7 skips them because its S3+integration uses privileges instead. Their configuration table and four+procedures are still installed independently. An error creating+one compatibility object is logged and does not suppress the remaining+objects.++When a stopped cluster is recreated on its retained data volume, `mysql.plugin`+can contain the prior registration even though the fresh container failed to+load the absent library at boot. The hook copies the artifact first, attempts+`UNINSTALL PLUGIN`, removes only the stale `AWSAuthenticationPlugin` row when+MySQL rejects that unload for a boot-failed plugin, reinstalls, and verifies the+plugin is `ACTIVE` before reporting success. The maintenance session disables+binary logging at entry so every current and future plugin-metadata statement+remains compute-local and cannot alter a global-cluster secondary.++Residuals: the full image carries the artifacts; the slim image remains+artifact-free and therefore auto-off. The existing global-replication live+fixture now asserts that an IAM user created on the primary reaches the+secondary without breaking replication whenever artifacts are present. Each+MySQL image-tag update must rebuild and reload-test its series artifact.diff --git a/contrib/mysql-iam-plugin/aws_auth_plugin.cc b/contrib/mysql-iam-plugin/aws_auth_plugin.ccnew file mode 100644index 00000000..97b3d5d7--- /dev/null+++ b/contrib/mysql-iam-plugin/aws_auth_plugin.cc@@ -0,0 +1,80 @@+/*+ * MiniStack's L0 emulation of Aurora MySQL's AWSAuthenticationPlugin.+ *+ * 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.+ */++#include <stddef.h>++// MYSQL_ABI_CHECK omits MySQL's internal compiler headers. Dynamic plugin+// declarations still need the public-symbol visibility wrapper they provide.+#ifndef MY_ATTRIBUTE+#define MY_ATTRIBUTE(attributes) __attribute__(attributes)+#endif++#include <mysql/plugin_auth.h>++static int reject_authentication(MYSQL_PLUGIN_VIO *vio,+ MYSQL_SERVER_AUTH_INFO *info) {+ (void)vio;+ (void)info;+ return CR_ERROR;+}++static int generate_authentication_string(char *outbuf,+ unsigned int *outbuflen,+ const char *inbuf,+ unsigned int inbuflen) {+ (void)outbuf;+ (void)inbuf;+ (void)inbuflen;+ *outbuflen = 0;+ return 0;+}++static int validate_authentication_string(char *const inbuf,+ unsigned int buflen) {+ (void)inbuf;+ (void)buflen;+ return 0;+}++static int set_salt(const char *password, unsigned int password_len,+ unsigned char *salt, unsigned char *salt_len) {+ (void)password;+ (void)password_len;+ (void)salt;+ *salt_len = 0;+ return 0;+}++static struct st_mysql_auth aws_auth_handler = {+ MYSQL_AUTHENTICATION_INTERFACE_VERSION,+ NULL,+ reject_authentication,+ generate_authentication_string,+ validate_authentication_string,+ set_salt,+ AUTH_FLAG_PRIVILEGED_USER_FOR_PASSWORD_CHANGE,+ NULL,+};++mysql_declare_plugin(aws_auth_plugin) {+ MYSQL_AUTHENTICATION_PLUGIN,+ &aws_auth_handler,+ "AWSAuthenticationPlugin",+ "MiniStack",+ "Aurora IAM authentication compatibility plugin (reject-all L0)",+ PLUGIN_LICENSE_GPL,+ NULL,+ NULL,+ NULL,+ 0x0100,+ NULL,+ NULL,+ NULL,+ 0,+} mysql_declare_plugin_end;diff --git a/contrib/mysql-iam-plugin/build.sh b/contrib/mysql-iam-plugin/build.shnew file mode 100755index 00000000..41ba4561--- /dev/null+++ b/contrib/mysql-iam-plugin/build.sh@@ -0,0 +1,19 @@+#!/usr/bin/env bash+set -euo pipefail++repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"+output_dir="${1:-${repo_root}/build/mysql-plugins}"+image_tag="ministack-mysql-iam-plugin-build:local"++docker build \+ --file "${repo_root}/Dockerfile.full" \+ --target plugin-build \+ --tag "${image_tag}" \+ "${repo_root}"++container_id="$(docker create "${image_tag}")"+trap 'docker rm -f "${container_id}" >/dev/null 2>&1 || true' EXIT+mkdir -p "${output_dir}"+docker cp "${container_id}:/opt/ministack/mysql-plugins/." "${output_dir}/"++printf 'MySQL IAM plugin artifacts copied to %s\n' "${output_dir}"diff --git a/ministack/services/rds.py b/ministack/services/rds.pyindex aded9d73..a5c2fb54 100644--- a/ministack/services/rds.py+++ b/ministack/services/rds.py@@ -57,6 +57,13 @@ from ministack.core.responses import (new_uuid,)from ministack.services import secretsmanager+from ministack.services.rds_iam_plugin import (+ ensure_iam_auth_plugin,+ iam_auth_plugin_enabled,+)+from ministack.services.rds_mysql_compat import (+ ensure_rds_compatibility_procedures,+)logger = logging.getLogger("rds")@@ -629,6 +636,7 @@ def restore_state(data):if pending_rotationelse cluster.get("_MasterUserPassword", "password"))+ root_password = readiness_passwordreadiness_user = cluster.get("MasterUsername", "admin")if _mysql_replication_secondary(cluster):# A fresh secondary volume has only the image's local@@ -653,6 +661,21 @@ def restore_state(data):else cluster.get("DatabaseName") or "mydb",_container_alive,)+ if authenticated_ready and _is_mysql_engine(+ cluster.get("Engine", ""),+ ):+ _ensure_mysql_compatibility(+ container_id,+ result.get("readiness_host")+ or cluster["_shared_endpoint"]["Address"],+ result.get("readiness_port")+ or cluster["_shared_endpoint"]["Port"],+ root_password,+ cluster.get("EngineVersion")+ or _default_engine_version(cluster.get("Engine", "")),+ cluster_id,+ engine=cluster.get("Engine", "aurora-mysql"),+ )with _shared_container_lock:current_cluster = _clusters.get(cluster_id)if (@@ -1343,6 +1366,23 @@ def _start_rds_container_for_instance(db_id, instance):passinstance["_internal_address"] = internal_hostinstance["_internal_port"] = internal_port+ if _is_mysql_engine(engine):+ _ensure_mysql_compatibility(+ container.id,+ internal_host or "127.0.0.1",+ internal_port or host_port,+ master_pass,+ engine_version,+ db_id,+ engine=engine,+ database_name=db_name,+ wait_for_ready=True,+ )+ if (+ _instances.get(db_id) is not instance+ or instance.get("_docker_container_id") != container.id+ ):+ returninstance["DBInstanceStatus"] = "available"logger.info("RDS: respawned container %s for instance %s",container_name, db_id)@@ -1566,6 +1606,94 @@ def _mysql_admin_connection(cluster):)+def _mysql_endpoint_admin_connection(host, port, password):+ import pymysql++ return pymysql.connect(+ host=host,+ port=int(port),+ user="root",+ password=password,+ autocommit=True,+ connect_timeout=3,+ )+++def _ensure_mysql_compatibility(+ container_id,+ host,+ port,+ root_password,+ engine_version,+ resource_id,+ engine="aurora-mysql",+ database_name=None,+ wait_for_ready=False,+):+ """Best-effort fidelity hook shared by every MySQL-ready path."""+ _mysql_image, engine_series = _mysql_runtime_for_engine(+ engine,+ engine_version,+ )+ plugin_enabled = bool(engine_series) and iam_auth_plugin_enabled(+ engine_series,+ )+ container = None+ if wait_for_ready or plugin_enabled:+ docker_client = _get_docker()+ if docker_client and container_id:+ try:+ container = docker_client.containers.get(container_id)+ except Exception as e:+ logger.warning(+ "RDS: failed to inspect MySQL container for %s: %s",+ resource_id,+ e,+ )++ def _connection():+ if wait_for_ready:+ if container is None:+ raise RuntimeError("MySQL container is unavailable")++ def _container_alive():+ try:+ container.reload()+ return container.status not in (+ "exited", "dead", "removing",+ )+ except Exception:+ return False++ if not _wait_for_database_ready(+ host,+ port,+ engine,+ "root",+ root_password,+ database_name,+ _container_alive,+ ):+ raise RuntimeError("container exited before plugin installation")+ return _mysql_endpoint_admin_connection(host, port, root_password)++ procedures_ready = ensure_rds_compatibility_procedures(+ _connection,+ resource_id,+ engine,+ engine_series,+ )+ plugin_ready = False+ if plugin_enabled and container is not None:+ plugin_ready = ensure_iam_auth_plugin(+ container,+ _connection,+ engine_series,+ resource_id,+ )+ return procedures_ready, plugin_ready++def _mysql_replication_connection(cluster):return _mysql_cluster_connection(cluster,@@ -2889,6 +3017,7 @@ def _create_db_instance_impl(p):def _bg_finalize_ready(db_id=db_id, cluster_id=cluster_id, engine=engine,+ engine_version=engine_version,master_user=master_user, master_pass=master_pass,readiness_master_pass=readiness_master_pass,db_name=db_name, ready_host=ready_host, ready_port=ready_port,@@ -2917,6 +3046,7 @@ def _create_db_instance_impl(p):return Falsereadiness_cluster = _clusters.get(cluster_id) if cluster_id else Nonereadiness_user = master_user+ root_password = readiness_master_passif readiness_cluster and _mysql_replication_secondary(readiness_cluster):readiness_user = "root"if readiness_cluster.get("_mysql_control_user_ready"):@@ -2931,6 +3061,16 @@ def _create_db_instance_impl(p):ready_host, ready_port, engine, readiness_user,readiness_master_pass, readiness_db_name, _container_alive,)+ if database_ready and _is_mysql_engine(engine):+ _ensure_mysql_compatibility(+ container_id,+ ready_host,+ ready_port,+ root_password,+ engine_version,+ cluster_id or db_id,+ engine=engine,+ )cluster = readiness_clusterif cluster:with _shared_container_lock:@@ -4738,6 +4878,7 @@ def _start_db_cluster(p):pending_rotation = cluster.get("_pending_master_password_rotation")if pending_rotation:readiness_pass = pending_rotation["old_password"]+ root_password = readiness_passif _mysql_replication_secondary(cluster):readiness_user = "root"if cluster.get("_mysql_control_user_ready"):@@ -4748,6 +4889,17 @@ def _start_db_cluster(p):ready_host, ready_port, engine, readiness_user,readiness_pass, readiness_db, _container_alive,)+ if database_ready and _is_mysql_engine(engine):+ _ensure_mysql_compatibility(+ container_id,+ ready_host,+ ready_port,+ root_password,+ cluster.get("EngineVersion")+ or _default_engine_version(engine),+ cluster_id,+ engine=engine,+ )with _shared_container_lock:if (cluster.get("_shared_container_epoch") != container_epoch@@ -6111,8 +6263,32 @@ def _mysql_community_major_minor(engine_version):def _mysql_image_for_version(engine_version):+ return _mysql_runtime_for_version(engine_version)[0]+++def _mysql_runtime_for_engine(engine, engine_version):+ """Return the actual MySQL-family image and plugin-compatible series."""+ if engine == "mariadb":+ return "mariadb:latest", None+ return _mysql_runtime_for_version(engine_version)+++def _mysql_runtime_for_version(engine_version):+ """Return the selected image and the known series encoded in its tag."""major_minor = _mysql_community_major_minor(engine_version)- return AURORA_MYSQL_IMAGE_MAP.get(major_minor, DEFAULT_AURORA_MYSQL_IMAGE)+ image = AURORA_MYSQL_IMAGE_MAP.get(+ major_minor,+ DEFAULT_AURORA_MYSQL_IMAGE,+ )+ _repository, separator, tag = image.rpartition(":")+ if not separator or tag not in AURORA_MYSQL_IMAGE_MAP:+ logger.warning(+ "RDS: cannot derive a supported MySQL series from selected image "+ "%r; IAM auth plugin artifacts will remain disabled",+ image,+ )+ return image, None+ return image, tagdef _default_port(engine):@@ -6152,18 +6328,10 @@ def _docker_image_for_engine(engine, engine_version, user, password, db_name):5432,data_path,)- if "mysql" in engine or "aurora-mysql" in engine:- return (- apply_image_prefix(_mysql_image_for_version(engine_version)),- {"MYSQL_ROOT_PASSWORD": password, "MYSQL_ROOT_HOST": "%",- "MYSQL_DATABASE": db_name,- "MYSQL_USER": user, "MYSQL_PASSWORD": password},- 3306,- "/var/lib/mysql",- )- if "mariadb" in engine:+ if _is_mysql_engine(engine):+ image, _series = _mysql_runtime_for_engine(engine, engine_version)return (- apply_image_prefix("mariadb:latest"),+ apply_image_prefix(image),{"MYSQL_ROOT_PASSWORD": password, "MYSQL_ROOT_HOST": "%","MYSQL_DATABASE": db_name,"MYSQL_USER": user, "MYSQL_PASSWORD": password},diff --git a/ministack/services/rds_iam_plugin.py b/ministack/services/rds_iam_plugin.pynew file mode 100644index 00000000..65a55494--- /dev/null+++ b/ministack/services/rds_iam_plugin.py@@ -0,0 +1,152 @@+"""Best-effort delivery of MiniStack's Aurora MySQL IAM auth plugin."""++import io+import logging+import tarfile+from pathlib import Path++logger = logging.getLogger("rds")++PLUGIN_NAME = "AWSAuthenticationPlugin"+PLUGIN_FILE = "aws_auth_plugin.so"+DEFAULT_ARTIFACT_ROOT = "/opt/ministack/mysql-plugins"+++def iam_auth_plugin_enabled(engine_series=None):+ """Return whether a bundled artifact root merits Docker I/O."""+ root = Path(DEFAULT_ARTIFACT_ROOT)+ if engine_series:+ root = root / engine_series+ return root.is_dir()+++def _container_arch(container):+ image = getattr(container, "image", None)+ attrs = getattr(image, "attrs", {}) if image is not None else {}+ arch = str(attrs.get("Architecture", "")).lower()+ aliases = {+ "x86_64": "amd64",+ "aarch64": "arm64",+ "arm64/v8": "arm64",+ }+ return aliases.get(arch, arch)+++def _artifact_path(engine_series, container):+ root = Path(DEFAULT_ARTIFACT_ROOT)+ arch = _container_arch(container)+ if not engine_series or not arch:+ return None+ artifact = root / engine_series / arch / PLUGIN_FILE+ return artifact if artifact.is_file() else None+++def _archive(artifact):+ payload = artifact.read_bytes()+ stream = io.BytesIO()+ with tarfile.open(fileobj=stream, mode="w") as archive:+ member = tarfile.TarInfo(PLUGIN_FILE)+ member.mode = 0o755+ member.size = len(payload)+ archive.addfile(member, io.BytesIO(payload))+ return stream.getvalue()+++def ensure_iam_auth_plugin(+ container,+ connection_factory,+ engine_series,+ resource_id,+):+ """Install the matching artifact, returning True only when it is loaded.++ Missing artifacts preserve stock behavior silently.+ Once an artifact is selected, every failure is reported once and swallowed+ so plugin fidelity can never fail RDS provisioning.+ """+ artifact = _artifact_path(engine_series, container)+ if artifact is None:+ return False++ connection = None+ cursor = None+ try:+ connection = connection_factory()+ if connection is None:+ raise RuntimeError("admin connection is unavailable")+ cursor = connection.cursor()+ cursor.execute("SET SESSION sql_log_bin = 0")+ cursor.execute(+ "SELECT PLUGIN_NAME FROM INFORMATION_SCHEMA.PLUGINS "+ "WHERE PLUGIN_NAME = %s AND PLUGIN_STATUS = 'ACTIVE'",+ (PLUGIN_NAME,),+ )+ if cursor.fetchone():+ return True++ cursor.execute(+ "SELECT name, dl FROM mysql.plugin WHERE name = %s",+ (PLUGIN_NAME,),+ )+ stale_registration = cursor.fetchone()++ cursor.execute("SELECT @@plugin_dir")+ plugin_dir_row = cursor.fetchone()+ if not plugin_dir_row or not plugin_dir_row[0]:+ raise RuntimeError("MySQL returned an empty plugin_dir")+ if not container.put_archive(plugin_dir_row[0], _archive(artifact)):+ raise RuntimeError("Docker rejected the plugin archive")++ if stale_registration:+ try:+ cursor.execute(f"UNINSTALL PLUGIN {PLUGIN_NAME}")+ except Exception as e:+ logger.warning(+ "RDS: failed to uninstall stale %s registration for "+ "%s; removing mysql.plugin row: %s",+ PLUGIN_NAME,+ resource_id,+ e,+ )+ cursor.execute(+ "DELETE FROM mysql.plugin WHERE name = %s",+ (PLUGIN_NAME,),+ )++ cursor.execute(+ f"INSTALL PLUGIN {PLUGIN_NAME} SONAME '{PLUGIN_FILE}'"+ )+ cursor.execute(+ "SELECT PLUGIN_NAME FROM INFORMATION_SCHEMA.PLUGINS "+ "WHERE PLUGIN_NAME = %s AND PLUGIN_STATUS = 'ACTIVE'",+ (PLUGIN_NAME,),+ )+ if not cursor.fetchone():+ raise RuntimeError("plugin did not become ACTIVE after installation")+ logger.info(+ "RDS: installed %s for %s (MySQL %s, %s)",+ PLUGIN_NAME,+ resource_id,+ engine_series,+ _container_arch(container),+ )+ return True+ except Exception as e:+ logger.warning(+ "RDS: failed to install %s for %s: %s",+ PLUGIN_NAME,+ resource_id,+ e,+ )+ return False+ finally:+ if cursor is not None:+ try:+ cursor.close()+ except Exception:+ pass+ if connection is not None:+ try:+ connection.close()+ except Exception:+ passdiff --git a/ministack/services/rds_mysql_compat.py b/ministack/services/rds_mysql_compat.pynew file mode 100644index 00000000..b086f8d3--- /dev/null+++ b/ministack/services/rds_mysql_compat.py@@ -0,0 +1,180 @@+"""Aurora MySQL compatibility objects installed on MiniStack compute."""++import logging++logger = logging.getLogger("rds")++_PREDEFINED_ROLES = (+ "AWS_SELECT_S3_ACCESS",+ "AWS_LOAD_S3_ACCESS",+)++_CONFIG_TABLE_SQL = """+CREATE TABLE IF NOT EXISTS mysql.ministack_rds_configuration (+ name VARCHAR(128) NOT NULL PRIMARY KEY,+ value VARCHAR(128) NOT NULL,+ description VARCHAR(255) NOT NULL+)+"""++_CONFIG_DEFAULT_SQL = """+INSERT IGNORE INTO mysql.ministack_rds_configuration+ (name, value, description)+VALUES+ ('binlog retention hours', '0',+ 'Number of hours that binary logs are retained')+"""++_PROCEDURES = {+ "rds_kill": """+CREATE DEFINER = 'root'@'%' PROCEDURE mysql.rds_kill(IN thread_id BIGINT UNSIGNED)+SQL SECURITY DEFINER+KILL CONNECTION thread_id+""",+ "rds_kill_query": """+CREATE DEFINER = 'root'@'%' PROCEDURE mysql.rds_kill_query(IN thread_id BIGINT UNSIGNED)+SQL SECURITY DEFINER+KILL QUERY thread_id+""",+ "rds_show_configuration": """+CREATE DEFINER = 'root'@'%' PROCEDURE mysql.rds_show_configuration()+SQL SECURITY DEFINER+SELECT name, value, description+FROM mysql.ministack_rds_configuration+ORDER BY name+""",+ "rds_set_configuration": """+CREATE DEFINER = 'root'@'%' PROCEDURE mysql.rds_set_configuration(+ IN configuration_name VARCHAR(128),+ IN configuration_value VARCHAR(128)+)+SQL SECURITY DEFINER+BEGIN+ IF LOWER(configuration_name) <> 'binlog retention hours' THEN+ SIGNAL SQLSTATE '45000'+ SET MESSAGE_TEXT = 'Unsupported RDS configuration';+ END IF;+ INSERT INTO mysql.ministack_rds_configuration+ (name, value, description)+ VALUES+ ('binlog retention hours', configuration_value,+ 'Number of hours that binary logs are retained')+ ON DUPLICATE KEY UPDATE value = VALUES(value);+END+""",+}+++def _execute_object(cursor, statement, object_name, resource_id):+ try:+ cursor.execute(statement)+ return True+ except Exception as e:+ logger.warning(+ "RDS: failed to ensure Aurora compatibility object %s for %s: %s",+ object_name,+ resource_id,+ e,+ )+ return False+++def _supports_predefined_roles(engine, engine_series):+ if engine != "aurora-mysql":+ return False+ try:+ major = int(str(engine_series).split(".", 1)[0])+ except (TypeError, ValueError):+ return False+ return major >= 8+++def ensure_rds_compatibility_procedures(+ connection_factory,+ resource_id,+ engine,+ engine_series,+):+ """Create the Aurora procedures needed by provider user-set grants.++ The session disables binary logging so each MySQL compute node owns its+ local DEFINER objects. Failures are loud but never fail RDS provisioning.+ """+ connection = None+ cursor = None+ try:+ connection = connection_factory()+ if connection is None:+ raise RuntimeError("admin connection is unavailable")+ cursor = connection.cursor()+ cursor.execute("SET SESSION sql_log_bin = 0")+ all_ready = _execute_object(+ cursor,+ _CONFIG_TABLE_SQL,+ "mysql.ministack_rds_configuration table",+ resource_id,+ )+ all_ready = _execute_object(+ cursor,+ _CONFIG_DEFAULT_SQL,+ "binlog retention hours default",+ resource_id,+ ) and all_ready+ if _supports_predefined_roles(engine, engine_series):+ for role in _PREDEFINED_ROLES:+ all_ready = _execute_object(+ cursor,+ f"CREATE ROLE IF NOT EXISTS `{role}`@'%'",+ f"`{role}`@'%' role",+ resource_id,+ ) and all_ready++ existing = set()+ try:+ cursor.execute(+ "SELECT ROUTINE_NAME FROM INFORMATION_SCHEMA.ROUTINES "+ "WHERE ROUTINE_SCHEMA = 'mysql' "+ "AND ROUTINE_TYPE = 'PROCEDURE' "+ "AND ROUTINE_NAME IN (%s, %s, %s, %s)",+ tuple(_PROCEDURES),+ )+ existing = {row[0].lower() for row in cursor.fetchall()}+ except Exception as e:+ logger.warning(+ "RDS: failed to inspect Aurora compatibility procedures "+ "for %s; attempting each procedure independently: %s",+ resource_id,+ e,+ )+ all_ready = False+ for name, statement in _PROCEDURES.items():+ if name not in existing:+ all_ready = _execute_object(+ cursor,+ statement,+ f"mysql.{name} procedure",+ resource_id,+ ) and all_ready+ logger.info(+ "RDS: ensured Aurora compatibility objects for %s",+ resource_id,+ )+ return all_ready+ except Exception as e:+ logger.warning(+ "RDS: failed to ensure Aurora compatibility objects for %s: %s",+ resource_id,+ e,+ )+ return False+ finally:+ if cursor is not None:+ try:+ cursor.close()+ except Exception:+ pass+ if connection is not None:+ try:+ connection.close()+ except Exception:+ passdiff --git a/tests/test_rds.py b/tests/test_rds.pyindex 94674395..daa84e86 100644--- a/tests/test_rds.py+++ b/tests/test_rds.py@@ -4,6 +4,7 @@ import ioimport jsonimport osimport sys+import threadingimport timeimport typesimport uuid@@ -2160,6 +2161,7 @@ def test_rds_stop_start_cluster_compute_lifecycle(monkeypatch):self.status = "exited"container = FakeContainer()+ readiness_actions = []class FakeContainers:def run(self, **_kwargs):@@ -2184,7 +2186,14 @@ def test_rds_stop_start_cluster_compute_lifecycle(monkeypatch):monkeypatch.setattr(m, "_is_host_port_free", lambda _port: True)monkeypatch.setattr(m, "_wait_for_database_ready", lambda *_args: True)monkeypatch.setattr(- m, "_grant_mysql_master_user_privileges", lambda *_args: None,+ m,+ "_ensure_mysql_compatibility",+ lambda *_args, **_kwargs: readiness_actions.append("plugin") or True,+ )+ monkeypatch.setattr(+ m,+ "_grant_mysql_master_user_privileges",+ lambda *_args: readiness_actions.append("grant"),)def _wait_for_member_status(db_id, expected, timeout=2):@@ -2216,6 +2225,7 @@ def test_rds_stop_start_cluster_compute_lifecycle(monkeypatch):_wait_for_member_status("stopstart-writer", "available")cluster = m._clusters.get("stopstart-cluster")assert cluster["Status"] == "available"+ assert readiness_actions == ["plugin", "grant"]m._stop_db_cluster({"DBClusterIdentifier": "stopstart-cluster"})assert container.status == "exited"@@ -2235,6 +2245,9 @@ def test_rds_stop_start_cluster_compute_lifecycle(monkeypatch):time.sleep(0.01)assert cluster["Status"] == "available"assert cluster["_shared_container_ready"] is True+ assert readiness_actions == [+ "plugin", "grant", "plugin", "grant",+ ]finally:m._instances.clear()m._clusters.clear()@@ -3876,7 +3889,11 @@ def test_docker_image_for_engine_aurora_postgres_18_uses_new_layout():def test_mysql_image_for_version_maps_aurora_tracks():- from ministack.services.rds import _mysql_image_for_version+ from ministack.services.rds import (+ _mysql_image_for_version,+ _mysql_runtime_for_engine,+ _mysql_runtime_for_version,+ )assert _mysql_image_for_version("8.4.mysql_aurora.8.4.7") == "mysql:8.4"assert _mysql_image_for_version("8.0.mysql_aurora.3.12.0") == "mysql:8.0"@@ -3885,6 +3902,41 @@ def test_mysql_image_for_version_maps_aurora_tracks():assert _mysql_image_for_version("8.4.7") == "mysql:8.4"assert _mysql_image_for_version("9.0.mysql_aurora.9.0.1") == "mysql:8.4"assert _mysql_image_for_version("not-a-version") == "mysql:8.4"+ assert _mysql_runtime_for_version("8") == ("mysql:8.4", "8.4")+ assert _mysql_runtime_for_engine("aurora-mysql", "8") == (+ "mysql:8.4",+ "8.4",+ )+ assert _mysql_runtime_for_engine("mysql", "8.0.33") == (+ "mysql:8.0",+ "8.0",+ )+ assert _mysql_runtime_for_engine("mysql", "5.7.44") == (+ "mysql:5.7",+ "5.7",+ )+ assert _mysql_runtime_for_engine("mariadb", "10.6.14") == (+ "mariadb:latest",+ None,+ )+++def test_mysql_runtime_unknown_image_tag_disables_plugin(monkeypatch, caplog):+ from ministack.services import rds as rds_service++ monkeypatch.setattr(+ rds_service,+ "DEFAULT_AURORA_MYSQL_IMAGE",+ "registry.example/ministack-mysql:custom",+ )++ with caplog.at_level("WARNING", logger="rds"):+ assert rds_service._mysql_runtime_for_version("8") == (+ "registry.example/ministack-mysql:custom",+ None,+ )++ assert "IAM auth plugin artifacts will remain disabled" in caplog.textdef test_docker_image_for_engine_mysql_uses_versioned_images():@@ -6766,19 +6818,22 @@ def _aurora_connect(endpoint, user="admin", password=PASSWORD, database=DATABASE@contextlib.contextmanager-def _live_cluster(rds):+def _live_cluster(rds, engine_version=None):suffix = uuid.uuid4().hex[:10]cluster_id = f"shared-{suffix}"writer_id = f"{cluster_id}-writer"reader_id = f"{cluster_id}-reader"try:- rds.create_db_cluster(- DBClusterIdentifier=cluster_id,- Engine="aurora-mysql",- MasterUsername="admin",- MasterUserPassword=PASSWORD,- DatabaseName=DATABASE,- )+ create_cluster = {+ "DBClusterIdentifier": cluster_id,+ "Engine": "aurora-mysql",+ "MasterUsername": "admin",+ "MasterUserPassword": PASSWORD,+ "DatabaseName": DATABASE,+ }+ if engine_version:+ create_cluster["EngineVersion"] = engine_version+ rds.create_db_cluster(**create_cluster)for db_id in (writer_id, reader_id):rds.create_db_instance(DBInstanceIdentifier=db_id,@@ -6841,6 +6896,257 @@ def test_aurora_user_and_grant_are_visible_through_reader(rds):assert cursor.fetchone() == (0,)+ not os.environ.get("DOCKER_NETWORK"),+ reason="DOCKER_NETWORK not set -- live Aurora",+)+ "engine_version",+ [+ "8.0.mysql_aurora.3.10.3",+ "8.4.mysql_aurora.8.4.7",+ "8",+ ],+)+def test_aurora_mysql_iam_plugin_ddl_and_reject_all(rds, engine_version):+ with _live_cluster(rds, engine_version=engine_version) as (+ _cid, _wid, _rid, writer, _reader, _cluster,+ ):+ user = f"iam_{uuid.uuid4().hex[:8]}"+ with _aurora_connect(writer["Endpoint"]) as conn:+ with conn.cursor() as cursor:+ cursor.execute(+ "SELECT COUNT(*) FROM INFORMATION_SCHEMA.PLUGINS "+ "WHERE PLUGIN_NAME = 'AWSAuthenticationPlugin'"+ )+ if cursor.fetchone()[0] == 0:+ pytest.skip(+ "matching AWSAuthenticationPlugin artifact is absent"+ )+ cursor.execute(+ f"CREATE USER IF NOT EXISTS '{user}'@'%' "+ "IDENTIFIED WITH AWSAuthenticationPlugin AS 'RDS' "+ "REQUIRE SSL WITH MAX_USER_CONNECTIONS 8 "+ "ATTRIBUTE '{\"k\":\"v\"}'"+ )+ cursor.execute(+ "SELECT plugin, authentication_string FROM mysql.user "+ "WHERE User = %s AND Host = '%'",+ (user,),+ )+ assert cursor.fetchone() == ("AWSAuthenticationPlugin", "RDS")+ cursor.execute(f"GRANT SELECT ON `{DATABASE}`.* TO `{user}`@'%'")+ cursor.execute(f"REVOKE SELECT ON `{DATABASE}`.* FROM `{user}`@'%'")+ cursor.execute(+ f"ALTER USER `{user}`@'%' WITH MAX_USER_CONNECTIONS 9"+ )++ import pymysql++ with pytest.raises(pymysql.err.OperationalError):+ _aurora_connect(+ writer["Endpoint"],+ user=user,+ password="not-a-token",+ )++ with _aurora_connect(writer["Endpoint"]) as conn:+ with conn.cursor() as cursor:+ cursor.execute(f"DROP USER `{user}`@'%'")+++ not os.environ.get("DOCKER_NETWORK"),+ reason="DOCKER_NETWORK not set -- live Aurora",+)+def test_aurora_mysql_rds_compatibility_procedures(rds):+ import pymysql++ with _live_cluster(+ rds,+ engine_version="8.0.mysql_aurora.3.10.3",+ ) as (_cid, _wid, _rid, writer, _reader, _cluster):+ user = f"proc_{uuid.uuid4().hex[:8]}"+ user_password = "ProcedureTest123!"+ procedure_names = (+ "rds_kill",+ "rds_kill_query",+ "rds_show_configuration",+ "rds_set_configuration",+ )+ predefined_roles = (+ "AWS_SELECT_S3_ACCESS",+ "AWS_LOAD_S3_ACCESS",+ )+ with _aurora_connect(writer["Endpoint"]) as admin:+ with admin.cursor() as cursor:+ cursor.execute(+ f"CREATE USER `{user}`@'%' IDENTIFIED BY %s",+ (user_password,),+ )+ for procedure_name in procedure_names:+ cursor.execute(+ "GRANT EXECUTE ON PROCEDURE "+ f"mysql.{procedure_name} TO `{user}`@'%'"+ )+ for role in predefined_roles:+ cursor.execute(+ f"GRANT `{role}`@'%' TO `{user}`@'%'"+ )+ cursor.execute(f"SHOW GRANTS FOR `{user}`@'%'")+ grants = "\n".join(row[0] for row in cursor.fetchall())+ for role in predefined_roles:+ assert f"`{role}`@`%`" in grants++ def connect_user():+ return _aurora_connect(+ writer["Endpoint"],+ user=user,+ password=user_password,+ )++ with connect_user() as caller:+ with caller.cursor() as cursor:+ cursor.execute(+ "CALL mysql.rds_set_configuration(%s, %s)",+ ("binlog retention hours", 24),+ )+ cursor.execute("CALL mysql.rds_show_configuration()")+ assert cursor.fetchone() == (+ "binlog retention hours",+ "24",+ "Number of hours that binary logs are retained",+ )++ with connect_user() as target, connect_user() as killer:+ with target.cursor() as cursor:+ cursor.execute("SELECT CONNECTION_ID()")+ target_id = cursor.fetchone()[0]+ query_result = {}++ def run_sleep():+ try:+ with target.cursor() as cursor:+ cursor.execute("SELECT SLEEP(30)")+ query_result["row"] = cursor.fetchone()+ except Exception as e:+ query_result["error"] = e++ sleeper = threading.Thread(target=run_sleep, daemon=True)+ sleeper.start()+ time.sleep(0.2)+ with killer.cursor() as cursor:+ cursor.execute("CALL mysql.rds_kill_query(%s)", (target_id,))+ sleeper.join(timeout=5)+ assert not sleeper.is_alive()+ assert isinstance(query_result.get("error"), pymysql.MySQLError)+ with target.cursor() as cursor:+ cursor.execute("SELECT 1")+ assert cursor.fetchone() == (1,)++ victim = connect_user()+ try:+ with victim.cursor() as cursor:+ cursor.execute("SELECT CONNECTION_ID()")+ victim_id = cursor.fetchone()[0]+ with connect_user() as killer:+ with killer.cursor() as cursor:+ cursor.execute("CALL mysql.rds_kill(%s)", (victim_id,))+ with pytest.raises(pymysql.MySQLError):+ victim.ping(reconnect=False)+ finally:+ victim.close()+++ not os.environ.get("DOCKER_NETWORK"),+ reason="DOCKER_NETWORK not set -- live Aurora",+)+def test_aurora_mysql_iam_plugin_survives_compute_replacement(rds):+ import docker++ with _live_cluster(+ rds,+ engine_version="8.0.mysql_aurora.3.10.3",+ ) as (cluster_id, writer_id, _rid, writer, _reader, _cluster):+ with _aurora_connect(writer["Endpoint"]) as conn:+ with conn.cursor() as cursor:+ cursor.execute(+ "SELECT COUNT(*) FROM INFORMATION_SCHEMA.PLUGINS "+ "WHERE PLUGIN_NAME = 'AWSAuthenticationPlugin'"+ )+ if cursor.fetchone()[0] == 0:+ pytest.skip(+ "matching AWSAuthenticationPlugin artifact is absent"+ )++ rds.stop_db_cluster(DBClusterIdentifier=cluster_id)+ containers = docker.from_env().containers.list(+ all=True,+ filters={+ "label": ["ministack=rds", f"cluster_id={cluster_id}"],+ },+ )+ assert len(containers) == 1+ containers[0].remove()+ rds.start_db_cluster(DBClusterIdentifier=cluster_id)+ restarted_writer = _wait_for_instance(rds, writer_id)++ with _aurora_connect(restarted_writer["Endpoint"]) as conn:+ with conn.cursor() as cursor:+ cursor.execute(+ "SELECT COUNT(*) FROM INFORMATION_SCHEMA.PLUGINS "+ "WHERE PLUGIN_NAME = 'AWSAuthenticationPlugin'"+ )+ assert cursor.fetchone()[0] == 1+ user = f"iam_recycled_{uuid.uuid4().hex[:8]}"+ cursor.execute(+ f"CREATE USER `{user}`@'%' "+ "IDENTIFIED WITH AWSAuthenticationPlugin AS 'RDS'"+ )+ cursor.execute(+ "SELECT plugin FROM mysql.user "+ "WHERE User = %s AND Host = '%'",+ (user,),+ )+ assert cursor.fetchone() == ("AWSAuthenticationPlugin",)+ cursor.execute(f"DROP USER `{user}`@'%'")+++ not os.environ.get("DOCKER_NETWORK"),+ reason="DOCKER_NETWORK not set -- live Aurora",+)+ os.environ.get("MINISTACK_MYSQL_IAM_EXPECT_STOCK") != "absent",+ reason="dedicated artifact-absent server lane not requested",+)+def test_aurora_mysql_iam_plugin_stock_behavior_when_unavailable(rds):+ import pymysql++ with _live_cluster(+ rds,+ engine_version="8.0.mysql_aurora.3.10.3",+ ) as (_cid, _wid, _rid, writer, _reader, _cluster):+ with _aurora_connect(writer["Endpoint"]) as conn:+ with conn.cursor() as cursor:+ cursor.execute(+ "SELECT COUNT(*) FROM INFORMATION_SCHEMA.PLUGINS "+ "WHERE PLUGIN_NAME = 'AWSAuthenticationPlugin'"+ )+ assert cursor.fetchone()[0] == 0+ with pytest.raises(pymysql.err.OperationalError) as error:+ cursor.execute(+ "CREATE USER 'iam_unavailable'@'%' "+ "IDENTIFIED WITH AWSAuthenticationPlugin AS 'RDS'"+ )+ assert getattr(error.value, "args", [None])[0] == 1524++@pytest.mark.skipif(not os.environ.get("DOCKER_NETWORK"), reason="DOCKER_NETWORK not set -- live Aurora")def test_aurora_cluster_uses_one_backing_container(rds):import docker@@ -7854,6 +8160,7 @@ def test_rds_restore_respawns_persisted_headless_secondary_applier(monkeypatch):started = []readiness_credentials = []configured = threading.Event()+ readiness_actions = []class FakeContainer:status = "running"@@ -7893,6 +8200,7 @@ def test_rds_restore_respawns_persisted_headless_secondary_applier(monkeypatch):def configure(cluster_id, cluster):assert cluster_id == "secondary"assert cluster["_mysql_headless_applier_required"] is True+ readiness_actions.append("replication")configured.set()m._instances.clear()@@ -7902,6 +8210,11 @@ def test_rds_restore_respawns_persisted_headless_secondary_applier(monkeypatch):monkeypatch.setattr(m, "_get_docker", lambda: FakeDocker())monkeypatch.setattr(m, "_start_cluster_shared_container", start_cluster)monkeypatch.setattr(m, "_wait_for_database_ready", wait_for_ready)+ monkeypatch.setattr(+ m,+ "_ensure_mysql_compatibility",+ lambda *_args, **_kwargs: readiness_actions.append("plugin") or True,+ )monkeypatch.setattr(m, "_configure_or_defer_mysql_replication", configure)m.restore_state({@@ -7915,6 +8228,7 @@ def test_rds_restore_respawns_persisted_headless_secondary_applier(monkeypatch):assert readiness_credentials == [(m._MYSQL_CONTROL_USER, m._MYSQL_CONTROL_PASSWORD, None),]+ assert readiness_actions == ["plugin", "replication"]restored = m._clusters.get_scoped(account_id,"us-west-2",@@ -8577,6 +8891,40 @@ def test_aurora_mysql_global_replication_replays_and_streams_rows():assert replica_status["Last_IO_Error"] == ""assert replica_status["Last_SQL_Error"] == ""+ plugin_counts = []+ for endpoint in (+ primary_instance["Endpoint"],+ secondary_instance["Endpoint"],+ ):+ with _aurora_connect(endpoint) as conn:+ with conn.cursor() as cursor:+ cursor.execute(+ "SELECT COUNT(*) FROM INFORMATION_SCHEMA.PLUGINS "+ "WHERE PLUGIN_NAME = 'AWSAuthenticationPlugin'"+ )+ plugin_counts.append(cursor.fetchone()[0])+ if any(plugin_counts):+ assert plugin_counts == [1, 1]+ iam_user = f"iam_repl_{suffix}"+ with _aurora_connect(primary_instance["Endpoint"]) as conn:+ with conn.cursor() as cursor:+ cursor.execute(+ f"CREATE USER '{iam_user}'@'%' "+ "IDENTIFIED WITH AWSAuthenticationPlugin AS 'RDS'"+ )+ _wait_for_gtid(+ primary_instance["Endpoint"],+ secondary_instance["Endpoint"],+ )+ with _aurora_connect(secondary_instance["Endpoint"]) as conn:+ with conn.cursor() as cursor:+ cursor.execute(+ "SELECT plugin FROM mysql.user "+ "WHERE User = %s AND Host = '%'",+ (iam_user,),+ )+ assert cursor.fetchone() == ("AWSAuthenticationPlugin",)+_wait_for_gtid(primary_instance["Endpoint"],secondary_instance["Endpoint"],diff --git a/tests/test_rds_iam_plugin.py b/tests/test_rds_iam_plugin.pynew file mode 100644index 00000000..ecf97086--- /dev/null+++ b/tests/test_rds_iam_plugin.py@@ -0,0 +1,331 @@+import io+import logging+import tarfile+import types++from ministack.services import rds as rds_service+from ministack.services import rds_iam_plugin as plugin+++class FakeCursor:+ def __init__(self, rows):+ self.rows = iter(rows)+ self.executed = []+ self.closed = False++ def execute(self, statement, params=None):+ self.executed.append((statement, params))++ def fetchone(self):+ return next(self.rows)++ def close(self):+ self.closed = True+++class FakeConnection:+ def __init__(self, rows):+ self.cursor_value = FakeCursor(rows)+ self.closed = False++ def cursor(self):+ return self.cursor_value++ def close(self):+ self.closed = True+++class FakeContainer:+ def __init__(self, arch="amd64", put_result=True):+ self.image = types.SimpleNamespace(attrs={"Architecture": arch})+ self.put_result = put_result+ self.archives = []++ def put_archive(self, path, data):+ self.archives.append((path, data))+ return self.put_result+++def _write_artifact(tmp_path, series="8.0", arch="amd64"):+ artifact = tmp_path / series / arch / plugin.PLUGIN_FILE+ artifact.parent.mkdir(parents=True)+ artifact.write_bytes(b"plugin-payload")+ return artifact+++def test_rds_iam_plugin_absent_is_silent_and_does_not_connect(+ monkeypatch, tmp_path, caplog,+):+ monkeypatch.setattr(plugin, "DEFAULT_ARTIFACT_ROOT", str(tmp_path))+ connections = []++ with caplog.at_level(logging.WARNING, logger="rds"):+ installed = plugin.ensure_iam_auth_plugin(+ FakeContainer(),+ lambda: connections.append(True),+ "8.0",+ "db-1",+ )++ assert installed is False+ assert connections == []+ assert caplog.records == []+++def test_rds_iam_plugin_unsupported_series_avoids_docker_work(+ monkeypatch, tmp_path,+):+ _write_artifact(tmp_path, series="8.0")+ monkeypatch.setattr(plugin, "DEFAULT_ARTIFACT_ROOT", str(tmp_path))++ assert plugin.iam_auth_plugin_enabled("8.0") is True+ assert plugin.iam_auth_plugin_enabled("5.7") is False+++def test_rds_iam_plugin_installs_matching_series_and_arch(monkeypatch, tmp_path):+ _write_artifact(tmp_path, series="8.4", arch="arm64")+ monkeypatch.setattr(plugin, "DEFAULT_ARTIFACT_ROOT", str(tmp_path))+ container = FakeContainer(arch="aarch64")+ connection = FakeConnection(+ [None, None, ("/usr/lib64/mysql/plugin",), (plugin.PLUGIN_NAME,)]+ )++ installed = plugin.ensure_iam_auth_plugin(+ container,+ lambda: connection,+ "8.4",+ "cluster-1",+ )++ assert installed is True+ assert connection.closed is True+ assert connection.cursor_value.closed is True+ assert connection.cursor_value.executed == [+ ("SET SESSION sql_log_bin = 0", None),+ (+ "SELECT PLUGIN_NAME FROM INFORMATION_SCHEMA.PLUGINS "+ "WHERE PLUGIN_NAME = %s AND PLUGIN_STATUS = 'ACTIVE'",+ (plugin.PLUGIN_NAME,),+ ),+ (+ "SELECT name, dl FROM mysql.plugin WHERE name = %s",+ (plugin.PLUGIN_NAME,),+ ),+ ("SELECT @@plugin_dir", None),+ (+ "INSTALL PLUGIN AWSAuthenticationPlugin "+ "SONAME 'aws_auth_plugin.so'",+ None,+ ),+ (+ "SELECT PLUGIN_NAME FROM INFORMATION_SCHEMA.PLUGINS "+ "WHERE PLUGIN_NAME = %s AND PLUGIN_STATUS = 'ACTIVE'",+ (plugin.PLUGIN_NAME,),+ ),+ ]+ assert len(container.archives) == 1+ archive_path, archive_data = container.archives[0]+ assert archive_path == "/usr/lib64/mysql/plugin"+ with tarfile.open(fileobj=io.BytesIO(archive_data), mode="r:") as archive:+ member = archive.getmember(plugin.PLUGIN_FILE)+ assert member.mode == 0o755+ assert archive.extractfile(member).read() == b"plugin-payload"+++def test_rds_iam_plugin_is_idempotent(monkeypatch, tmp_path):+ _write_artifact(tmp_path)+ monkeypatch.setattr(plugin, "DEFAULT_ARTIFACT_ROOT", str(tmp_path))+ container = FakeContainer()+ connection = FakeConnection([("AWSAuthenticationPlugin",)])++ installed = plugin.ensure_iam_auth_plugin(+ container,+ lambda: connection,+ "8.0",+ "db-1",+ )++ assert installed is True+ assert container.archives == []+ assert connection.cursor_value.executed == [+ ("SET SESSION sql_log_bin = 0", None),+ (+ "SELECT PLUGIN_NAME FROM INFORMATION_SCHEMA.PLUGINS "+ "WHERE PLUGIN_NAME = %s AND PLUGIN_STATUS = 'ACTIVE'",+ (plugin.PLUGIN_NAME,),+ ),+ ]+++def test_rds_iam_plugin_recovers_boot_failed_registration(+ monkeypatch, tmp_path, caplog,+):+ _write_artifact(tmp_path)+ monkeypatch.setattr(plugin, "DEFAULT_ARTIFACT_ROOT", str(tmp_path))+ container = FakeContainer()+ connection = FakeConnection(+ [+ None,+ (plugin.PLUGIN_NAME, plugin.PLUGIN_FILE),+ ("/usr/lib64/mysql/plugin",),+ (plugin.PLUGIN_NAME,),+ ]+ )+ original_execute = connection.cursor_value.execute++ def execute(statement, params=None):+ original_execute(statement, params)+ if statement == f"UNINSTALL PLUGIN {plugin.PLUGIN_NAME}":+ raise RuntimeError("plugin is registered but not loaded")++ connection.cursor_value.execute = execute++ with caplog.at_level(logging.WARNING, logger="rds"):+ assert plugin.ensure_iam_auth_plugin(+ container,+ lambda: connection,+ "8.0",+ "db-1",+ ) is True++ statements = connection.cursor_value.executed+ assert statements[0] == ("SET SESSION sql_log_bin = 0", None)+ assert statements.index(+ (f"UNINSTALL PLUGIN {plugin.PLUGIN_NAME}", None)+ ) < statements.index(+ ("DELETE FROM mysql.plugin WHERE name = %s", (plugin.PLUGIN_NAME,))+ )+ assert statements.index(+ ("DELETE FROM mysql.plugin WHERE name = %s", (plugin.PLUGIN_NAME,))+ ) < statements.index(+ (+ "INSTALL PLUGIN AWSAuthenticationPlugin "+ "SONAME 'aws_auth_plugin.so'",+ None,+ )+ )+ assert "removing mysql.plugin row" in caplog.text+++def test_rds_iam_plugin_failure_warns_once_and_does_not_escape(+ monkeypatch, tmp_path, caplog,+):+ _write_artifact(tmp_path)+ monkeypatch.setattr(plugin, "DEFAULT_ARTIFACT_ROOT", str(tmp_path))+ container = FakeContainer(put_result=False)+ connection = FakeConnection(+ [None, None, ("/usr/lib64/mysql/plugin",)]+ )++ with caplog.at_level(logging.WARNING, logger="rds"):+ installed = plugin.ensure_iam_auth_plugin(+ container,+ lambda: connection,+ "8.0",+ "db-1",+ )++ assert installed is False+ warnings = [+ record for record in caplog.records+ if "failed to install AWSAuthenticationPlugin" in record.message+ ]+ assert len(warnings) == 1+++def test_mysql_compatibility_wait_resolves_container_before_procedures(+ monkeypatch, tmp_path,+):+ monkeypatch.setattr(plugin, "DEFAULT_ARTIFACT_ROOT", str(tmp_path))+ connection = object()+ calls = []++ class ReadyContainer:+ status = "running"++ def reload(self):+ calls.append("reload")++ container = ReadyContainer()++ class Containers:+ def get(self, container_id):+ calls.append(("get", container_id))+ return container++ docker_client = types.SimpleNamespace(containers=Containers())++ def wait_for_ready(*args):+ calls.append("wait")+ assert args[-1]() is True+ return True++ def ensure_procedures(+ connection_factory, resource_id, engine, engine_series,+ ):+ calls.append(("procedures", resource_id))+ assert engine == "aurora-mysql"+ assert engine_series == "8.0"+ assert connection_factory() is connection+ return True++ monkeypatch.setattr(rds_service, "_get_docker", lambda: docker_client)+ monkeypatch.setattr(rds_service, "_wait_for_database_ready", wait_for_ready)+ monkeypatch.setattr(+ rds_service,+ "_mysql_endpoint_admin_connection",+ lambda *_args: connection,+ )+ monkeypatch.setattr(+ rds_service,+ "ensure_rds_compatibility_procedures",+ ensure_procedures,+ )++ assert rds_service._ensure_mysql_compatibility(+ "container-1",+ "127.0.0.1",+ 3306,+ "password",+ "8.0.mysql_aurora.3.10.3",+ "db-1",+ wait_for_ready=True,+ ) == (True, False)+ assert calls == [+ ("get", "container-1"),+ ("procedures", "db-1"),+ "wait",+ "reload",+ ]+++def test_mariadb_compatibility_skips_plugin_and_roles(monkeypatch):+ calls = []++ def enabled(engine_series):+ calls.append(("plugin-enabled", engine_series))+ return True++ def ensure_procedures(+ _connection_factory, resource_id, engine, engine_series,+ ):+ calls.append(("procedures", resource_id, engine, engine_series))+ return True++ monkeypatch.setattr(rds_service, "iam_auth_plugin_enabled", enabled)+ monkeypatch.setattr(+ rds_service,+ "ensure_rds_compatibility_procedures",+ ensure_procedures,+ )++ assert rds_service._ensure_mysql_compatibility(+ None,+ "127.0.0.1",+ 3306,+ "password",+ "10.6.14",+ "db-1",+ engine="mariadb",+ ) == (True, False)+ assert calls == [("procedures", "db-1", "mariadb", None)]diff --git a/tests/test_rds_mysql_compat.py b/tests/test_rds_mysql_compat.pynew file mode 100644index 00000000..b03ba66d--- /dev/null+++ b/tests/test_rds_mysql_compat.py@@ -0,0 +1,162 @@+import logging++from ministack.services import rds_mysql_compat as compat+++class FakeCursor:+ def __init__(self, routines=()):+ self.routines = routines+ self.executed = []+ self.closed = False++ def execute(self, statement, params=None):+ self.executed.append((statement, params))++ def fetchall(self):+ return [(name,) for name in self.routines]++ def close(self):+ self.closed = True+++class FailingObjectCursor(FakeCursor):+ def execute(self, statement, params=None):+ super().execute(statement, params)+ if statement == compat._CONFIG_TABLE_SQL:+ raise RuntimeError("table failed")+++class FakeConnection:+ def __init__(self, routines=()):+ self.cursor_value = FakeCursor(routines)+ self.closed = False++ def cursor(self):+ return self.cursor_value++ def close(self):+ self.closed = True+++def test_rds_compatibility_procedures_create_complete_family():+ connection = FakeConnection()++ assert compat.ensure_rds_compatibility_procedures(+ lambda: connection,+ "cluster-1",+ "aurora-mysql",+ "8.0",+ ) is True++ statements = [statement for statement, _params in connection.cursor_value.executed]+ assert statements[0] == "SET SESSION sql_log_bin = 0"+ assert statements[1] == compat._CONFIG_TABLE_SQL+ assert statements[2] == compat._CONFIG_DEFAULT_SQL+ assert statements[3:5] == [+ f"CREATE ROLE IF NOT EXISTS `{role}`@'%'"+ for role in compat._PREDEFINED_ROLES+ ]+ assert statements[5].startswith("SELECT ROUTINE_NAME")+ assert statements[6:] == list(compat._PROCEDURES.values())+ assert connection.cursor_value.closed is True+ assert connection.closed is True+++def test_rds_compatibility_procedures_are_idempotent():+ connection = FakeConnection(compat._PROCEDURES)++ assert compat.ensure_rds_compatibility_procedures(+ lambda: connection,+ "cluster-1",+ "aurora-mysql",+ "8.4",+ ) is True++ statements = [statement for statement, _params in connection.cursor_value.executed]+ assert statements[:3] == [+ "SET SESSION sql_log_bin = 0",+ compat._CONFIG_TABLE_SQL,+ compat._CONFIG_DEFAULT_SQL,+ ]+ assert statements[3:5] == [+ f"CREATE ROLE IF NOT EXISTS `{role}`@'%'"+ for role in compat._PREDEFINED_ROLES+ ]+ assert len(statements) == 6+ assert statements[5].startswith("SELECT ROUTINE_NAME")+++def test_rds_compatibility_procedure_failure_warns_and_does_not_escape(caplog):+ def fail_connection():+ raise RuntimeError("database unavailable")++ with caplog.at_level(logging.WARNING, logger="rds"):+ assert compat.ensure_rds_compatibility_procedures(+ fail_connection,+ "cluster-1",+ "aurora-mysql",+ "8.0",+ ) is False++ assert len(caplog.records) == 1+ assert "failed to ensure Aurora compatibility objects" in caplog.text+++def test_rds_compatibility_procedures_skip_roles_before_mysql_8():+ connection = FakeConnection()++ assert compat.ensure_rds_compatibility_procedures(+ lambda: connection,+ "cluster-1",+ "aurora-mysql",+ "5.7",+ ) is True++ statements = [statement for statement, _params in connection.cursor_value.executed]+ assert not any(statement.startswith("CREATE ROLE") for statement in statements)+ assert statements[:3] == [+ "SET SESSION sql_log_bin = 0",+ compat._CONFIG_TABLE_SQL,+ compat._CONFIG_DEFAULT_SQL,+ ]+ assert statements[3].startswith("SELECT ROUTINE_NAME")+ assert statements[4:] == list(compat._PROCEDURES.values())+++def test_rds_compatibility_procedures_skip_roles_for_standalone_mysql_8():+ connection = FakeConnection()++ assert compat.ensure_rds_compatibility_procedures(+ lambda: connection,+ "instance-1",+ "mysql",+ "8.4",+ ) is True++ statements = [statement for statement, _params in connection.cursor_value.executed]+ assert not any(statement.startswith("CREATE ROLE") for statement in statements)+ assert statements[:3] == [+ "SET SESSION sql_log_bin = 0",+ compat._CONFIG_TABLE_SQL,+ compat._CONFIG_DEFAULT_SQL,+ ]+ assert statements[3].startswith("SELECT ROUTINE_NAME")+ assert statements[4:] == list(compat._PROCEDURES.values())+++def test_rds_compatibility_object_failure_does_not_abort_later_objects(caplog):+ connection = FakeConnection()+ connection.cursor_value = FailingObjectCursor()++ with caplog.at_level(logging.WARNING, logger="rds"):+ assert compat.ensure_rds_compatibility_procedures(+ lambda: connection,+ "cluster-1",+ "aurora-mysql",+ "8.0",+ ) is False++ statements = [statement for statement, _params in connection.cursor_value.executed]+ assert compat._CONFIG_DEFAULT_SQL in statements+ assert statements[-4:] == list(compat._PROCEDURES.values())+ assert "mysql.ministack_rds_configuration table" in caplog.text