mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-27 11:25:08 +00:00
fix(vaults): quote table names, dedupe kids without case, and reuse one mysql connection
This commit is contained in:
@@ -83,7 +83,7 @@ Network-backed vaults (`HTTP` and `API`) accept an optional per-vault `timeout`
|
|||||||
vault_timeout: 10.0 # default, in seconds
|
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.
|
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. |
|
| `username` | yes | Login user. |
|
||||||
| `no_push` | no | If `true`, keys are read but never written. |
|
| `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"
|
!!! 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.
|
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.
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ name) and a `name`, plus backend-specific keys.
|
|||||||
| `type` | Purpose | Required keys | Notes |
|
| `type` | Purpose | Required keys | Notes |
|
||||||
|--------|---------|--------------|-------|
|
|--------|---------|--------------|-------|
|
||||||
| `SQLite` | Local SQLite database | `name`, `path` | Loaded **critically**; a failure aborts the run. |
|
| `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`. |
|
| `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`. |
|
| `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
|
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
|
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
|
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.
|
`429 Too Many Requests`. They wait the `Retry-After` time, but never longer than this timeout.
|
||||||
|
|||||||
@@ -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]
|
||||||
@@ -206,3 +206,25 @@ def test_lookups_work_from_another_thread(vault: SQLite) -> None:
|
|||||||
thread.start()
|
thread.start()
|
||||||
thread.join()
|
thread.join()
|
||||||
assert found == [KEY]
|
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),
|
||||||
|
]
|
||||||
|
|||||||
+58
-82
@@ -1,7 +1,9 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import threading
|
import threading
|
||||||
|
import time
|
||||||
from collections.abc import Iterator
|
from collections.abc import Iterator
|
||||||
|
from contextlib import contextmanager
|
||||||
from typing import Any
|
from typing import Any
|
||||||
from uuid import UUID
|
from uuid import UUID
|
||||||
|
|
||||||
@@ -24,7 +26,9 @@ class MySQL(Vault):
|
|||||||
"""
|
"""
|
||||||
super().__init__(name, no_push)
|
super().__init__(name, no_push)
|
||||||
self.slug = f"{host}:{database}:{username}"
|
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(
|
self.conn_factory = ConnectionFactory(
|
||||||
dict(host=host, db=database, user=username, cursorclass=DictCursor, **kwargs)
|
dict(host=host, db=database, user=username, cursorclass=DictCursor, **kwargs)
|
||||||
)
|
)
|
||||||
@@ -41,36 +45,27 @@ class MySQL(Vault):
|
|||||||
if not table:
|
if not table:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
conn = self.conn_factory.get()
|
with self.conn_factory.cursor() as cursor:
|
||||||
cursor = conn.cursor()
|
|
||||||
|
|
||||||
try:
|
|
||||||
cursor.execute(
|
cursor.execute(
|
||||||
f"SELECT `id`, `key_` FROM `{table}` WHERE `kid`=%s AND `key_`!=%s",
|
f"SELECT `id`, `key_` FROM `{table}` WHERE `kid`=%s AND `key_`!=%s",
|
||||||
(kid, "0" * 32),
|
(kid, "0" * 32),
|
||||||
)
|
)
|
||||||
cek = cursor.fetchone()
|
cek = cursor.fetchone()
|
||||||
return cek["key_"] if cek else None
|
return cek["key_"] if cek else None
|
||||||
finally:
|
|
||||||
cursor.close()
|
|
||||||
|
|
||||||
def get_keys(self, service: str) -> Iterator[tuple[str, str]]:
|
def get_keys(self, service: str) -> Iterator[tuple[str, str]]:
|
||||||
table = self.resolve_table(service)
|
table = self.resolve_table(service)
|
||||||
if not table:
|
if not table:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
conn = self.conn_factory.get()
|
with self.conn_factory.cursor() as cursor:
|
||||||
cursor = conn.cursor()
|
|
||||||
|
|
||||||
try:
|
|
||||||
cursor.execute(
|
cursor.execute(
|
||||||
f"SELECT `kid`, `key_` FROM `{table}` WHERE `key_`!=%s",
|
f"SELECT `kid`, `key_` FROM `{table}` WHERE `key_`!=%s",
|
||||||
("0" * 32,),
|
("0" * 32,),
|
||||||
)
|
)
|
||||||
for row in cursor.fetchall():
|
rows = cursor.fetchall()
|
||||||
|
for row in rows:
|
||||||
yield row["kid"], row["key_"]
|
yield row["kid"], row["key_"]
|
||||||
finally:
|
|
||||||
cursor.close()
|
|
||||||
|
|
||||||
def add_key(self, service: str, kid: UUID | str, key: str) -> bool:
|
def add_key(self, service: str, kid: UUID | str, key: str) -> bool:
|
||||||
if is_null_key(key):
|
if is_null_key(key):
|
||||||
@@ -90,24 +85,16 @@ class MySQL(Vault):
|
|||||||
if isinstance(kid, UUID):
|
if isinstance(kid, UUID):
|
||||||
kid = kid.hex
|
kid = kid.hex
|
||||||
|
|
||||||
conn = self.conn_factory.get()
|
with self.conn_factory.cursor() as cursor:
|
||||||
cursor = conn.cursor()
|
|
||||||
|
|
||||||
try:
|
|
||||||
cursor.execute(
|
cursor.execute(
|
||||||
f"SELECT `id` FROM `{service}` WHERE `kid`=%s AND `key_`=%s",
|
f"SELECT `id` FROM `{service}` WHERE `kid`=%s AND `key_`=%s",
|
||||||
(kid, key),
|
(kid, key),
|
||||||
)
|
)
|
||||||
if cursor.fetchone():
|
if not cursor.fetchone():
|
||||||
return True
|
|
||||||
cursor.execute(
|
cursor.execute(
|
||||||
f"INSERT INTO `{service}` (kid, key_) VALUES (%s, %s)",
|
f"INSERT INTO `{service}` (kid, key_) VALUES (%s, %s)",
|
||||||
(kid, key),
|
(kid, key),
|
||||||
)
|
)
|
||||||
finally:
|
|
||||||
conn.commit()
|
|
||||||
cursor.close()
|
|
||||||
|
|
||||||
return True
|
return True
|
||||||
|
|
||||||
def add_keys(self, service: str, kid_keys: dict[UUID | str, str]) -> int:
|
def add_keys(self, service: str, kid_keys: dict[UUID | str, str]) -> int:
|
||||||
@@ -137,43 +124,36 @@ class MySQL(Vault):
|
|||||||
if not kid_keys:
|
if not kid_keys:
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
conn = self.conn_factory.get()
|
with self.conn_factory.cursor() as cursor:
|
||||||
cursor = conn.cursor()
|
|
||||||
|
|
||||||
try:
|
|
||||||
existing_kids: set[str] = set()
|
existing_kids: set[str] = set()
|
||||||
kid_list = list(kid_keys)
|
kid_list = list(kid_keys)
|
||||||
for i in range(0, len(kid_list), 10000):
|
for i in range(0, len(kid_list), 10000):
|
||||||
batch = kid_list[i : i + 10000]
|
batch = kid_list[i : i + 10000]
|
||||||
placeholders = ",".join(["%s"] * len(batch))
|
placeholders = ",".join(["%s"] * len(batch))
|
||||||
cursor.execute(f"SELECT kid FROM `{service}` WHERE kid IN ({placeholders})", batch)
|
cursor.execute(f"SELECT kid FROM `{service}` WHERE kid IN ({placeholders})", batch)
|
||||||
existing_kids.update(row["kid"] for row in cursor.fetchall())
|
existing_kids.update(row["kid"].lower() for row in cursor.fetchall())
|
||||||
|
|
||||||
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:
|
if not new_keys:
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
cursor.executemany(
|
cursor.executemany(
|
||||||
f"INSERT INTO `{service}` (kid, key_) VALUES (%s, %s)",
|
f"INSERT INTO `{service}` (kid, key_) VALUES (%s, %s)",
|
||||||
new_keys.items(),
|
new_keys.values(),
|
||||||
)
|
)
|
||||||
return len(new_keys)
|
return len(new_keys)
|
||||||
finally:
|
|
||||||
conn.commit()
|
|
||||||
cursor.close()
|
|
||||||
|
|
||||||
def get_services(self) -> Iterator[str]:
|
def get_services(self) -> Iterator[str]:
|
||||||
conn = self.conn_factory.get()
|
with self.conn_factory.cursor() as cursor:
|
||||||
cursor = conn.cursor()
|
|
||||||
|
|
||||||
try:
|
|
||||||
cursor.execute("SHOW TABLES")
|
cursor.execute("SHOW TABLES")
|
||||||
for table in cursor.fetchall():
|
tables = cursor.fetchall()
|
||||||
|
for table in tables:
|
||||||
# each entry has a key named `Tables_in_<db name>`
|
# each entry has a key named `Tables_in_<db name>`
|
||||||
yield list(table.values())[0]
|
yield list(table.values())[0]
|
||||||
finally:
|
|
||||||
cursor.close()
|
|
||||||
|
|
||||||
def resolve_table(self, name: str) -> str | None:
|
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
|
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.
|
`lower_case_table_names` setting. Where both spellings exist, exact case wins.
|
||||||
"""
|
"""
|
||||||
conn = self.conn_factory.get()
|
with self.conn_factory.cursor() as cursor:
|
||||||
cursor = conn.cursor()
|
|
||||||
|
|
||||||
try:
|
|
||||||
cursor.execute(
|
cursor.execute(
|
||||||
"SELECT TABLE_NAME FROM information_schema.TABLES"
|
"SELECT TABLE_NAME FROM information_schema.TABLES"
|
||||||
" WHERE TABLE_SCHEMA=%s AND UPPER(TABLE_NAME)=UPPER(%s)",
|
" 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()]
|
names = [list(row.values())[0] for row in cursor.fetchall()]
|
||||||
finally:
|
|
||||||
cursor.close()
|
|
||||||
|
|
||||||
if name in names:
|
if name in names:
|
||||||
return name
|
return name
|
||||||
@@ -201,19 +176,14 @@ class MySQL(Vault):
|
|||||||
|
|
||||||
def has_table(self, name: str) -> bool:
|
def has_table(self, name: str) -> bool:
|
||||||
"""Return True if the Vault has a Table with the specified name."""
|
"""Return True if the Vault has a Table with the specified name."""
|
||||||
conn = self.conn_factory.get()
|
with self.conn_factory.cursor() as cursor:
|
||||||
cursor = conn.cursor()
|
|
||||||
|
|
||||||
try:
|
|
||||||
cursor.execute(
|
cursor.execute(
|
||||||
"SELECT count(TABLE_NAME) FROM information_schema.TABLES WHERE TABLE_SCHEMA=%s AND TABLE_NAME=%s",
|
"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()
|
row = cursor.fetchone()
|
||||||
assert row is not None # COUNT() always returns one row
|
assert row is not None # COUNT() always returns one row
|
||||||
return list(row.values())[0] == 1
|
return list(row.values())[0] == 1
|
||||||
finally:
|
|
||||||
cursor.close()
|
|
||||||
|
|
||||||
def create_table(self, name: str) -> None:
|
def create_table(self, name: str) -> None:
|
||||||
"""Make a Table with the specified name if it does not exist yet."""
|
"""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"):
|
if not self.has_permission("CREATE"):
|
||||||
raise PermissionError(f"MySQL vault {self.slug} has no CREATE permission.")
|
raise PermissionError(f"MySQL vault {self.slug} has no CREATE permission.")
|
||||||
|
|
||||||
conn = self.conn_factory.get()
|
with self.conn_factory.cursor() as cursor:
|
||||||
cursor = conn.cursor()
|
|
||||||
|
|
||||||
try:
|
|
||||||
cursor.execute(
|
cursor.execute(
|
||||||
f"""
|
f"""
|
||||||
CREATE TABLE IF NOT EXISTS {name} (
|
CREATE TABLE IF NOT EXISTS `{name}` (
|
||||||
id int AUTO_INCREMENT PRIMARY KEY,
|
id int AUTO_INCREMENT PRIMARY KEY,
|
||||||
kid VARCHAR(64) NOT NULL,
|
kid VARCHAR(64) NOT NULL,
|
||||||
key_ 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:
|
def get_permissions(self) -> list:
|
||||||
"""Get and parse Grants to a more usable list tuple array."""
|
"""Get and parse Grants to a more usable list tuple array."""
|
||||||
conn = self.conn_factory.get()
|
with self.conn_factory.cursor() as cursor:
|
||||||
cursor = conn.cursor()
|
|
||||||
|
|
||||||
try:
|
|
||||||
cursor.execute("SHOW GRANTS")
|
cursor.execute("SHOW GRANTS")
|
||||||
grants = [next(iter(x.values())) for x in cursor.fetchall()]
|
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 = [tuple(x[6:].split(" TO ")[0].split(" ON ")) for x in grants]
|
||||||
grants = [
|
return [
|
||||||
(
|
(
|
||||||
list(map(str.strip, perms.replace("ALL PRIVILEGES", "*").split(","))),
|
list(map(str.strip, perms.replace("ALL PRIVILEGES", "*").split(","))),
|
||||||
location.replace("`", "").split("."),
|
location.replace("`", "").split("."),
|
||||||
)
|
)
|
||||||
for perms, location in grants
|
for perms, location in grants
|
||||||
]
|
]
|
||||||
return grants
|
|
||||||
finally:
|
|
||||||
conn.commit()
|
|
||||||
cursor.close()
|
|
||||||
|
|
||||||
def has_permission(self, operation: str, database: str | None = None, table: str | None = None) -> bool:
|
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."""
|
"""Return True if the current connection has a specific permission."""
|
||||||
@@ -273,14 +230,33 @@ class MySQL(Vault):
|
|||||||
|
|
||||||
|
|
||||||
class ConnectionFactory:
|
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:
|
def __init__(self, con: dict) -> None:
|
||||||
self._con = con
|
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]:
|
@contextmanager
|
||||||
return pymysql.connect(**self._con)
|
def cursor(self) -> Iterator[DictCursor]:
|
||||||
|
with self._lock:
|
||||||
def get(self) -> pymysql.Connection[DictCursor]:
|
try:
|
||||||
if not hasattr(self._store, "conn"):
|
if self._conn is None:
|
||||||
self._store.conn = self.create_connection()
|
self._conn = pymysql.connect(**self._con)
|
||||||
return self._store.conn
|
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()
|
||||||
|
|||||||
@@ -132,7 +132,7 @@ class SQLite(Vault):
|
|||||||
placeholders = ",".join(["?"] * len(batch))
|
placeholders = ",".join(["?"] * len(batch))
|
||||||
try:
|
try:
|
||||||
cursor.execute(f"SELECT kid FROM `{service}` WHERE kid IN ({placeholders})", batch)
|
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
|
i += batch_size
|
||||||
except sqlite3.OperationalError as e:
|
except sqlite3.OperationalError as e:
|
||||||
if "too many SQL variables" in str(e) and batch_size > 500:
|
if "too many SQL variables" in str(e) and batch_size > 500:
|
||||||
@@ -140,14 +140,17 @@ class SQLite(Vault):
|
|||||||
continue
|
continue
|
||||||
raise
|
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:
|
if not new_keys:
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
cursor.executemany(
|
cursor.executemany(
|
||||||
f"INSERT INTO `{service}` (kid, key_) VALUES (?, ?)",
|
f"INSERT INTO `{service}` (kid, key_) VALUES (?, ?)",
|
||||||
new_keys.items(),
|
new_keys.values(),
|
||||||
)
|
)
|
||||||
return len(new_keys)
|
return len(new_keys)
|
||||||
finally:
|
finally:
|
||||||
@@ -266,7 +269,7 @@ class SQLite(Vault):
|
|||||||
try:
|
try:
|
||||||
cursor.execute(
|
cursor.execute(
|
||||||
f"""
|
f"""
|
||||||
CREATE TABLE IF NOT EXISTS {name} (
|
CREATE TABLE IF NOT EXISTS `{name}` (
|
||||||
"id" INTEGER NOT NULL UNIQUE,
|
"id" INTEGER NOT NULL UNIQUE,
|
||||||
"kid" TEXT NOT NULL COLLATE NOCASE,
|
"kid" TEXT NOT NULL COLLATE NOCASE,
|
||||||
"key_" TEXT NOT NULL COLLATE NOCASE,
|
"key_" TEXT NOT NULL COLLATE NOCASE,
|
||||||
|
|||||||
Reference in New Issue
Block a user