Qualify pinned database identity and restricted MySQL backup profile
ABSDEV Framework CI / framework-ci (push) Successful in 24s
ABSDEV Framework CI / framework-ci (push) Successful in 24s
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
"""Pinned live database identity for backup and runtime preflight."""
|
||||
|
||||
import io
|
||||
import re
|
||||
|
||||
from core.database import DatabaseError
|
||||
|
||||
|
||||
class DatabaseIdentityProbe:
|
||||
"""Check a trusted server pin and the exact authenticated account."""
|
||||
|
||||
def __init__(self, adapter, runner, *, server_id, account=None):
|
||||
self.adapter = adapter
|
||||
self.runner = runner
|
||||
database = adapter.database
|
||||
self.driver = database["driver"]
|
||||
self.database = database["name"]
|
||||
username = database["username"]
|
||||
if self.driver == "mysql":
|
||||
valid_account = (
|
||||
isinstance(account, str)
|
||||
and account.startswith(username + "@")
|
||||
and re.fullmatch(r"[A-Za-z0-9_.:%-]+", account[len(username) + 1:]) is not None
|
||||
)
|
||||
else:
|
||||
account = username if account is None else account
|
||||
valid_account = account == username
|
||||
pattern = (r"[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}"
|
||||
if self.driver == "mysql" else r"[1-9][0-9]{0,19}")
|
||||
if (not callable(runner) or not valid_account or not isinstance(server_id, str)
|
||||
or re.fullmatch(pattern, server_id) is None):
|
||||
raise DatabaseError("Invalid pinned database identity")
|
||||
self.expected = (self.database, account, server_id)
|
||||
|
||||
def observe(self):
|
||||
output = io.BytesIO()
|
||||
self.runner(self.adapter.live_identity_command(), output)
|
||||
try:
|
||||
row = output.getvalue().decode("utf-8").removesuffix("\n").removesuffix("\r")
|
||||
except UnicodeError as error:
|
||||
raise DatabaseError("Invalid live database identity output") from error
|
||||
separator = "\t" if self.driver == "mysql" else "|"
|
||||
if tuple(row.split(separator)) != self.expected:
|
||||
raise DatabaseError("Live database identity differs from the configured pin")
|
||||
return row
|
||||
|
||||
def __call__(self):
|
||||
self.observe()
|
||||
return True
|
||||
Reference in New Issue
Block a user