diff --git a/docs/guide/vaults.md b/docs/guide/vaults.md index 6c55b8f8..651910d4 100644 --- a/docs/guide/vaults.md +++ b/docs/guide/vaults.md @@ -83,7 +83,7 @@ Network-backed vaults (`HTTP` and `API`) accept an optional per-vault `timeout` vault_timeout: 10.0 # default, in seconds ``` -A `timeout` set inline on an individual vault always wins over this global value. The `SQLite` and `MySQL` backends do not take a `timeout` field. `MySQL` uses `vault_timeout` as its `connect_timeout` instead, and falls back to the pymysql default of 10 seconds when `vault_timeout` is `0`. To use a different connect timeout, set `connect_timeout` on the vault. +A `timeout` set inline on an individual vault always wins over this global value. The `SQLite` and `MySQL` backends do not take a `timeout` field. `MySQL` uses `vault_timeout` as its `connect_timeout`, `read_timeout` and `write_timeout` instead, and falls back to 10 seconds when `vault_timeout` is `0`. To use a different value, set that field on the vault. unshackle pushes content keys to all vaults at the same time, so one slow or unreachable vault costs only its own timeout and does not delay the others. @@ -146,7 +146,9 @@ key_vaults: | `username` | yes | Login user. | | `no_push` | no | If `true`, keys are read but never written. | -Any additional fields you provide (such as `password`, `port`, or `ssl`) are passed straight through to `pymysql.connect`, so you can use the full range of its connection options. +Any additional fields you provide (such as `password`, `port`, or `ssl`) are passed straight through to `pymysql.connect`, so you can use the full range of its connection options. The one exception is `autocommit`, which is always on. + +Each `MySQL` vault keeps one connection open for the whole run and shares it between threads. If the server is down, unshackle skips the vault for the rest of the run. !!! warning "Account security is on you, not on unshackle" unshackle enforces none of this. It is operational policy for a database that may be shared with a group. Never connect with the `root` account, not even for yourself. Give every account a password, and never let two users share a username/password. Restrict each account's access to only the `unshackle` database, and grant normal users only `SELECT` and `INSERT`. Reserve the `CREATE` grant for a single trusted user who bootstraps the service tables (see [`kv prepare`](#kv-prepare-pre-create-service-tables)); everyone else can insert new keys but should not be creating tables. diff --git a/docs/reference/configuration/vaults.md b/docs/reference/configuration/vaults.md index 2e478727..eede75d5 100644 --- a/docs/reference/configuration/vaults.md +++ b/docs/reference/configuration/vaults.md @@ -13,7 +13,7 @@ name) and a `name`, plus backend-specific keys. | `type` | Purpose | Required keys | Notes | |--------|---------|--------------|-------| | `SQLite` | Local SQLite database | `name`, `path` | Loaded **critically**; a failure aborts the run. | -| `MySQL` | Remote MySQL database | `name`, `host`, `database`, `username` | Extra keys (e.g. `password`, `port`) forwarded to pymysql. `connect_timeout` defaults to `vault_timeout`. | +| `MySQL` | Remote MySQL database | `name`, `host`, `database`, `username` | Extra keys (e.g. `password`, `port`) forwarded to pymysql. `connect_timeout`, `read_timeout` and `write_timeout` default to `vault_timeout`. `autocommit` is always on. | | `API` | RESTful JSON API | `name`, `uri`, `token` | Optional `headers` map is sent with every request. Honours `vault_timeout`. | | `HTTP` | HTTP API with modes | `name`, `host`, one of `password`/`api_key`, and `username` in query mode | `api_mode`: `query` (default), `json`, `decrypt_labs`. Honours `vault_timeout`. | @@ -55,7 +55,7 @@ key_vaults: Timeout in seconds for vault operations. Injected automatically into any backend whose constructor accepts a `timeout` parameter (a per-vault `timeout` still wins). The `MySQL` backend -uses it as the default `connect_timeout`. +uses it as the default `connect_timeout`, `read_timeout` and `write_timeout`. The `API` and `HTTP` backends send a request again up to 3 times when the vault answers `429 Too Many Requests`. They wait the `Retry-After` time, but never longer than this timeout. diff --git a/tests/core/test_mysql_vault.py b/tests/core/test_mysql_vault.py new file mode 100644 index 00000000..d667b06d --- /dev/null +++ b/tests/core/test_mysql_vault.py @@ -0,0 +1,189 @@ +"""The MySQL vault keeps one connection for every thread, quotes its table names and dedupes KIDs without case.""" + +from __future__ import annotations + +import re +import threading +from typing import Any + +import pymysql +import pytest + +from unshackle.core.vaults import Vaults +from unshackle.vaults import MySQL as mysql_module +from unshackle.vaults.MySQL import MySQL + +KID = "ab" * 16 +KEY = "a" * 32 + + +class FakeServer: + """Answers the statements the vault sends, holds its tables in memory and counts connections.""" + + def __init__(self) -> None: + self.tables: dict[str, list[tuple[str, str]]] = {"EXAMPLE": [(KID.upper(), KEY)]} + self.connects = 0 + self.kwargs: dict[str, Any] = {} + self.pings = 0 + self.active = 0 + self.overlaps = 0 + self.down = False + self.guard = threading.Lock() + + def connect(self, **kwargs: Any) -> FakeConnection: + self.connects += 1 + self.kwargs = kwargs + return FakeConnection(self, kwargs["db"]) + + +class FakeConnection: + def __init__(self, server: FakeServer, db: str) -> None: + self.server = server + self.db = db + + def ping(self, reconnect: bool = True) -> None: + self.server.pings += 1 + if self.server.down: + raise pymysql.err.OperationalError(2003, "Can't connect to MySQL server") + + def cursor(self) -> FakeCursor: + return FakeCursor(self) + + +class FakeCursor: + def __init__(self, connection: FakeConnection) -> None: + self.connection = connection + self.server = connection.server + self.rows: list[dict[str, Any]] = [] + with self.server.guard: + self.server.active += 1 + self.server.overlaps += self.server.active > 1 + + def __enter__(self) -> FakeCursor: + return self + + def __exit__(self, *exc: object) -> None: + with self.server.guard: + self.server.active -= 1 + + def execute(self, sql: str, args: Any = ()) -> None: + tables = self.server.tables + if sql == "SHOW GRANTS": + self.rows = [{"Grants": "GRANT ALL PRIVILEGES ON *.* TO `user`@`%`"}] + elif "UPPER(TABLE_NAME)" in sql: + self.rows = [{"TABLE_NAME": t} for t in tables if t.upper() == args[1].upper()] + elif "count(TABLE_NAME)" in sql: + self.rows = [{"count": int(args[1] in tables)}] + elif sql.strip().startswith("CREATE TABLE"): + match = re.search(r"EXISTS `(.+?)` \(", sql) + if not match: + raise pymysql.err.ProgrammingError(1064, "You have an error in your SQL syntax") + tables.setdefault(match.group(1), []) + elif sql.startswith("SELECT `id`, `key_`"): + self.rows = [{"id": 1, "key_": k} for kid, k in tables[table(sql)] if kid.lower() == args[0].lower()] + elif sql.startswith("SELECT `kid`, `key_`"): + self.rows = [{"kid": kid, "key_": key} for kid, key in tables[table(sql)]] + elif sql.startswith("SELECT kid FROM"): + wanted = {a.lower() for a in args} + self.rows = [{"kid": kid} for kid, _ in tables[table(sql)] if kid.lower() in wanted] + else: + raise AssertionError(f"unexpected statement {sql!r}") + + def executemany(self, sql: str, rows: Any) -> None: + stored = self.server.tables[table(sql)] + for kid, key in rows: + if (kid.lower(), key.lower()) in {(k.lower(), v.lower()) for k, v in stored}: + raise pymysql.err.IntegrityError(1062, "Duplicate entry") + stored.append((kid, key)) + + def fetchone(self) -> dict[str, Any] | None: + return self.rows[0] if self.rows else None + + def fetchall(self) -> list[dict[str, Any]]: + return self.rows + + +def table(sql: str) -> str: + match = re.search(r"FROM `(.+?)`|INTO `(.+?)`", sql) + assert match + return match.group(1) or match.group(2) + + +@pytest.fixture +def server(monkeypatch: pytest.MonkeyPatch) -> FakeServer: + fake = FakeServer() + monkeypatch.setattr(mysql_module.pymysql, "connect", fake.connect) + return fake + + +def make_vault() -> MySQL: + return MySQL("test", host="127.0.0.1", database="keys", username="user") + + +def test_every_thread_shares_one_connection_one_cursor_at_a_time(server: FakeServer) -> None: + vault = make_vault() + start = threading.Barrier(8) + found: list[str | None] = [] + + def look_up() -> None: + start.wait() + for _ in range(20): + found.append(vault.get_key(KID, "EXAMPLE")) + + threads = [threading.Thread(target=look_up) for _ in range(8)] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + + assert found == [KEY] * 160 + assert server.connects == 1 + assert server.kwargs["autocommit"] is True + assert server.kwargs["read_timeout"] and server.kwargs["write_timeout"] + assert server.overlaps == 0 + + +@pytest.mark.parametrize("service", ["9EXAMPLE", "EXAMPLE-OTHER"]) +def test_a_tag_that_is_not_a_bare_identifier_gets_a_table(server: FakeServer, service: str) -> None: + vault = make_vault() + assert vault.add_keys(service, {KID: KEY}) == 1 + assert vault.get_key(KID, service) == KEY + + +def test_add_keys_skips_a_kid_stored_in_another_case(server: FakeServer) -> None: + vault = make_vault() + assert vault.add_keys("EXAMPLE", {KID: KEY, "cd" * 16: "b" * 32, "CD" * 16: "B" * 32}) == 1 + assert server.tables["EXAMPLE"] == [(KID.upper(), KEY), ("CD" * 16, "B" * 32)] + + +def test_an_idle_connection_is_pinged_before_use(server: FakeServer, monkeypatch: pytest.MonkeyPatch) -> None: + vault = make_vault() + vault.get_key(KID, "EXAMPLE") + assert server.pings == 0 + monkeypatch.setattr(mysql_module.ConnectionFactory, "PING_AFTER", -1.0) + vault.get_key(KID, "EXAMPLE") + assert server.pings == 2 + + +def test_a_server_that_goes_down_is_skipped_for_the_rest_of_the_run( + server: FakeServer, monkeypatch: pytest.MonkeyPatch +) -> None: + vaults = Vaults("EXAMPLE") + vaults.vaults.append(make_vault()) + monkeypatch.setattr(mysql_module.ConnectionFactory, "PING_AFTER", -1.0) + server.down = True + assert vaults.get_key(KID) == (None, None) + assert vaults.live() == [] + server.down = False + assert vaults.vaults[0].get_key(KID, "EXAMPLE") == KEY + + +def test_get_keys_frees_the_connection_before_it_yields(server: FakeServer) -> None: + vault = make_vault() + rows = vault.get_keys("EXAMPLE") + assert next(rows) == (KID.upper(), KEY) + found: list[str | None] = [] + thread = threading.Thread(target=lambda: found.append(vault.get_key(KID, "EXAMPLE"))) + thread.start() + thread.join(timeout=10) + assert found == [KEY] diff --git a/tests/core/test_vault_table_case.py b/tests/core/test_vault_table_case.py index efb7b1fd..456ce1f4 100644 --- a/tests/core/test_vault_table_case.py +++ b/tests/core/test_vault_table_case.py @@ -206,3 +206,25 @@ def test_lookups_work_from_another_thread(vault: SQLite) -> None: thread.start() thread.join() assert found == [KEY] + + +@pytest.mark.parametrize("service", ["9EXAMPLE", "EXAMPLE-OTHER"]) +def test_a_tag_that_is_not_a_bare_identifier_gets_a_table(tmp_path: Path, service: str) -> None: + v = SQLite("test", tmp_path / "kv.db") + assert v.add_keys(service, {KID: KEY}) == 1 + assert v.add_key(service, "0" * 31 + "2", "b" * 32) + assert v.get_key(KID, service) == KEY + assert tables(v.path) == sorted([service, "sqlite_sequence"]) + + +def test_add_keys_skips_a_kid_stored_in_another_case(tmp_path: Path) -> None: + v = SQLite("test", tmp_path / "kv.db") + v.add_key("SVCA", "AB" * 16, KEY) + batch = {"ab" * 16: KEY, "cd" * 16: "b" * 32, "CD" * 16: "B" * 32, "EF" * 16: "c" * 32, "ef" * 16: "d" * 32} + assert v.add_keys("SVCA", batch) == 3 + assert sorted(v.get_keys("SVCA")) == [ + ("AB" * 16, KEY), + ("CD" * 16, "B" * 32), + ("EF" * 16, "c" * 32), + ("ef" * 16, "d" * 32), + ] diff --git a/unshackle/vaults/MySQL.py b/unshackle/vaults/MySQL.py index 34231d69..53fc961e 100644 --- a/unshackle/vaults/MySQL.py +++ b/unshackle/vaults/MySQL.py @@ -1,7 +1,9 @@ from __future__ import annotations import threading +import time from collections.abc import Iterator +from contextlib import contextmanager from typing import Any from uuid import UUID @@ -24,7 +26,9 @@ class MySQL(Vault): """ super().__init__(name, no_push) self.slug = f"{host}:{database}:{username}" - kwargs.setdefault("connect_timeout", config.vault_timeout or 10) + for timeout in ("connect_timeout", "read_timeout", "write_timeout"): + kwargs.setdefault(timeout, config.vault_timeout or 10) + kwargs["autocommit"] = True self.conn_factory = ConnectionFactory( dict(host=host, db=database, user=username, cursorclass=DictCursor, **kwargs) ) @@ -41,36 +45,27 @@ class MySQL(Vault): if not table: return None - conn = self.conn_factory.get() - cursor = conn.cursor() - - try: + with self.conn_factory.cursor() as cursor: cursor.execute( f"SELECT `id`, `key_` FROM `{table}` WHERE `kid`=%s AND `key_`!=%s", (kid, "0" * 32), ) cek = cursor.fetchone() - return cek["key_"] if cek else None - finally: - cursor.close() + return cek["key_"] if cek else None def get_keys(self, service: str) -> Iterator[tuple[str, str]]: table = self.resolve_table(service) if not table: return None - conn = self.conn_factory.get() - cursor = conn.cursor() - - try: + with self.conn_factory.cursor() as cursor: cursor.execute( f"SELECT `kid`, `key_` FROM `{table}` WHERE `key_`!=%s", ("0" * 32,), ) - for row in cursor.fetchall(): - yield row["kid"], row["key_"] - finally: - cursor.close() + rows = cursor.fetchall() + for row in rows: + yield row["kid"], row["key_"] def add_key(self, service: str, kid: UUID | str, key: str) -> bool: if is_null_key(key): @@ -90,24 +85,16 @@ class MySQL(Vault): if isinstance(kid, UUID): kid = kid.hex - conn = self.conn_factory.get() - cursor = conn.cursor() - - try: + with self.conn_factory.cursor() as cursor: cursor.execute( f"SELECT `id` FROM `{service}` WHERE `kid`=%s AND `key_`=%s", (kid, key), ) - if cursor.fetchone(): - return True - cursor.execute( - f"INSERT INTO `{service}` (kid, key_) VALUES (%s, %s)", - (kid, key), - ) - finally: - conn.commit() - cursor.close() - + if not cursor.fetchone(): + cursor.execute( + f"INSERT INTO `{service}` (kid, key_) VALUES (%s, %s)", + (kid, key), + ) return True def add_keys(self, service: str, kid_keys: dict[UUID | str, str]) -> int: @@ -137,43 +124,36 @@ class MySQL(Vault): if not kid_keys: return 0 - conn = self.conn_factory.get() - cursor = conn.cursor() - - try: + with self.conn_factory.cursor() as cursor: existing_kids: set[str] = set() kid_list = list(kid_keys) for i in range(0, len(kid_list), 10000): batch = kid_list[i : i + 10000] placeholders = ",".join(["%s"] * len(batch)) cursor.execute(f"SELECT kid FROM `{service}` WHERE kid IN ({placeholders})", batch) - existing_kids.update(row["kid"] for row in cursor.fetchall()) - - new_keys = {kid: key for kid, key in kid_keys.items() if kid not in existing_kids} + existing_kids.update(row["kid"].lower() for row in cursor.fetchall()) + new_keys = { + (str(kid).lower(), key.lower()): (kid, key) + for kid, key in kid_keys.items() + if str(kid).lower() not in existing_kids + } if not new_keys: return 0 cursor.executemany( f"INSERT INTO `{service}` (kid, key_) VALUES (%s, %s)", - new_keys.items(), + new_keys.values(), ) - return len(new_keys) - finally: - conn.commit() - cursor.close() + return len(new_keys) def get_services(self) -> Iterator[str]: - conn = self.conn_factory.get() - cursor = conn.cursor() - - try: + with self.conn_factory.cursor() as cursor: cursor.execute("SHOW TABLES") - for table in cursor.fetchall(): - # each entry has a key named `Tables_in_` - yield list(table.values())[0] - finally: - cursor.close() + tables = cursor.fetchall() + for table in tables: + # each entry has a key named `Tables_in_` + yield list(table.values())[0] def resolve_table(self, name: str) -> str | None: """ @@ -182,18 +162,13 @@ class MySQL(Vault): The UPPER() comparison is explicit so the result does not depend on the server's `lower_case_table_names` setting. Where both spellings exist, exact case wins. """ - conn = self.conn_factory.get() - cursor = conn.cursor() - - try: + with self.conn_factory.cursor() as cursor: cursor.execute( "SELECT TABLE_NAME FROM information_schema.TABLES" " WHERE TABLE_SCHEMA=%s AND UPPER(TABLE_NAME)=UPPER(%s)", - (conn.db, name), + (cursor.connection.db, name), ) names = [list(row.values())[0] for row in cursor.fetchall()] - finally: - cursor.close() if name in names: return name @@ -201,19 +176,14 @@ class MySQL(Vault): def has_table(self, name: str) -> bool: """Return True if the Vault has a Table with the specified name.""" - conn = self.conn_factory.get() - cursor = conn.cursor() - - try: + with self.conn_factory.cursor() as cursor: cursor.execute( "SELECT count(TABLE_NAME) FROM information_schema.TABLES WHERE TABLE_SCHEMA=%s AND TABLE_NAME=%s", - (conn.db, name), + (cursor.connection.db, name), ) row = cursor.fetchone() - assert row is not None # COUNT() always returns one row - return list(row.values())[0] == 1 - finally: - cursor.close() + assert row is not None # COUNT() always returns one row + return list(row.values())[0] == 1 def create_table(self, name: str) -> None: """Make a Table with the specified name if it does not exist yet.""" @@ -223,13 +193,10 @@ class MySQL(Vault): if not self.has_permission("CREATE"): raise PermissionError(f"MySQL vault {self.slug} has no CREATE permission.") - conn = self.conn_factory.get() - cursor = conn.cursor() - - try: + with self.conn_factory.cursor() as cursor: cursor.execute( f""" - CREATE TABLE IF NOT EXISTS {name} ( + CREATE TABLE IF NOT EXISTS `{name}` ( id int AUTO_INCREMENT PRIMARY KEY, kid VARCHAR(64) NOT NULL, key_ VARCHAR(64) NOT NULL, @@ -237,30 +204,20 @@ class MySQL(Vault): ); """ ) - finally: - conn.commit() - cursor.close() def get_permissions(self) -> list: """Get and parse Grants to a more usable list tuple array.""" - conn = self.conn_factory.get() - cursor = conn.cursor() - - try: + with self.conn_factory.cursor() as cursor: cursor.execute("SHOW GRANTS") grants = [next(iter(x.values())) for x in cursor.fetchall()] - grants = [tuple(x[6:].split(" TO ")[0].split(" ON ")) for x in list(grants)] - grants = [ - ( - list(map(str.strip, perms.replace("ALL PRIVILEGES", "*").split(","))), - location.replace("`", "").split("."), - ) - for perms, location in grants - ] - return grants - finally: - conn.commit() - cursor.close() + grants = [tuple(x[6:].split(" TO ")[0].split(" ON ")) for x in grants] + return [ + ( + list(map(str.strip, perms.replace("ALL PRIVILEGES", "*").split(","))), + location.replace("`", "").split("."), + ) + for perms, location in grants + ] def has_permission(self, operation: str, database: str | None = None, table: str | None = None) -> bool: """Return True if the current connection has a specific permission.""" @@ -273,14 +230,33 @@ class MySQL(Vault): class ConnectionFactory: + """One connection per vault, shared by every thread, because a vault lookup runs on a new thread each time. + + A pymysql connection is not thread-safe, so each cursor holds the lock until it closes. The cursor pings a + connection idle for PING_AFTER seconds first, since a NAT or VPN can drop it silently. A failed connect raises + ConnectionError, so Vaults skips the vault for the rest of the run. + """ + + PING_AFTER = 10.0 + def __init__(self, con: dict) -> None: self._con = con - self._store = threading.local() + self._conn: pymysql.Connection[DictCursor] | None = None + self._lock = threading.RLock() + self._used = 0.0 - def create_connection(self) -> pymysql.Connection[DictCursor]: - return pymysql.connect(**self._con) - - def get(self) -> pymysql.Connection[DictCursor]: - if not hasattr(self._store, "conn"): - self._store.conn = self.create_connection() - return self._store.conn + @contextmanager + def cursor(self) -> Iterator[DictCursor]: + with self._lock: + try: + if self._conn is None: + self._conn = pymysql.connect(**self._con) + elif time.monotonic() - self._used > self.PING_AFTER: + self._conn.ping(reconnect=True) + except pymysql.err.OperationalError as e: + raise ConnectionError(str(e)) from e + try: + with self._conn.cursor() as cursor: + yield cursor + finally: + self._used = time.monotonic() diff --git a/unshackle/vaults/SQLite.py b/unshackle/vaults/SQLite.py index c53fe266..9853bc96 100644 --- a/unshackle/vaults/SQLite.py +++ b/unshackle/vaults/SQLite.py @@ -132,7 +132,7 @@ class SQLite(Vault): placeholders = ",".join(["?"] * len(batch)) try: cursor.execute(f"SELECT kid FROM `{service}` WHERE kid IN ({placeholders})", batch) - existing_kids.update(row[0] for row in cursor.fetchall()) + existing_kids.update(row[0].lower() for row in cursor.fetchall()) i += batch_size except sqlite3.OperationalError as e: if "too many SQL variables" in str(e) and batch_size > 500: @@ -140,14 +140,17 @@ class SQLite(Vault): continue raise - new_keys = {kid: key for kid, key in kid_keys.items() if kid not in existing_kids} - + new_keys = { + (str(kid).lower(), key.lower()): (kid, key) + for kid, key in kid_keys.items() + if str(kid).lower() not in existing_kids + } if not new_keys: return 0 cursor.executemany( f"INSERT INTO `{service}` (kid, key_) VALUES (?, ?)", - new_keys.items(), + new_keys.values(), ) return len(new_keys) finally: @@ -266,7 +269,7 @@ class SQLite(Vault): try: cursor.execute( f""" - CREATE TABLE IF NOT EXISTS {name} ( + CREATE TABLE IF NOT EXISTS `{name}` ( "id" INTEGER NOT NULL UNIQUE, "kid" TEXT NOT NULL COLLATE NOCASE, "key_" TEXT NOT NULL COLLATE NOCASE,