diff --git a/docs/development.md b/docs/development.md index 802cc5f..0f42b51 100644 --- a/docs/development.md +++ b/docs/development.md @@ -63,6 +63,27 @@ database and login names. coulobre-database-node inspect coulobre-database-1.json ``` +### Apply a database manifest + +Use a local MariaDB server with Unix socket authentication for +`root@localhost`. Install Coulobre with the `mariadb` extra in a root-owned +virtual environment and apply the downloaded manifest on that server. + +```sh +sudo /opt/coulobre/bin/coulobre-database-node apply coulobre-database-1.json +``` + +The default socket is `/run/mysqld/mysqld.sock`. Use `--socket` for a different +local socket. The command creates a UTF-8 database and one login at +`localhost` with privileges on that exact database. + +The command reports the path to a root-only credentials file under +`/var/lib/coulobre/database-node/`. Use those credentials when configuring the +application. Reapplying a manifest preserves the existing password and can +complete an interrupted first installation. Coulobre uses its local registry +and a database ownership marker to distinguish managed databases from existing +resources. + ## Request an Apache configuration preview Start RabbitMQ and set `COULOBRE_BROKER_URL` to its AMQP URL. The development diff --git a/src/coulobre/database_node.py b/src/coulobre/database_node.py index 756a8a1..b4d512c 100644 --- a/src/coulobre/database_node.py +++ b/src/coulobre/database_node.py @@ -6,6 +6,7 @@ from pathlib import Path MANIFEST_VERSION = 1 MANIFEST_KIND = "mariadb_database" +DEFAULT_SOCKET = Path("/run/mysqld/mysqld.sock") DATABASE_SUFFIX_PATTERN = r"\A[a-z][a-z0-9_]{0,23}\Z" INVALID_SUFFIX = ( "Use 1 to 24 lowercase letters, digits, or underscores. Start with a letter." @@ -60,13 +61,27 @@ def main(argv=None): "inspect", help="Inspect a database deployment manifest." ) inspect.add_argument("manifest", type=Path) + apply = commands.add_parser( + "apply", help="Create a database and local login on MariaDB." + ) + apply.add_argument("manifest", type=Path) + apply.add_argument("--socket", type=Path, default=DEFAULT_SOCKET) args = parser.parse_args(argv) try: payload = json.loads(args.manifest.read_text(encoding="utf-8")) database = DatabaseSpec.from_manifest(payload) + if args.command == "apply": + from .database_node_apply import apply_database + + credentials = apply_database(database, args.socket) + print(f"Applied MariaDB database {database.name}.") + print(f"Credentials file {credentials}") + else: + print( + json.dumps({"database": database.name, "user": database.name}, indent=2) + ) except (OSError, ValueError) as error: parser.exit(1, f"coulobre-database-node: {error}\n") - print(json.dumps({"database": database.name, "user": database.name}, indent=2)) return 0 diff --git a/src/coulobre/database_node_apply.py b/src/coulobre/database_node_apply.py new file mode 100644 index 0000000..440f115 --- /dev/null +++ b/src/coulobre/database_node_apply.py @@ -0,0 +1,147 @@ +import hashlib +import json +import os +import secrets +from contextlib import closing +from pathlib import Path + +from .node_files import read_root_file, require_root_directory, write_new_file + +STATE_DIRECTORY = Path("/var/lib/coulobre/database-node") +MANAGED_COMMENT_PREFIX = "Coulobre managed database " + + +def apply_database(database, socket): + if os.geteuid() != 0: + raise ValueError("Run apply as root on the MariaDB node.") + try: + import MySQLdb + except ImportError: + raise ValueError( + "Install Coulobre Panel with its mariadb extra on the node." + ) from None + + socket = socket.resolve() + require_root_directory(STATE_DIRECTORY.parent, create_mode=0o750) + require_root_directory(STATE_DIRECTORY, create_mode=0o700) + record_path = STATE_DIRECTORY / f"{database.name}.json" + try: + with ( + closing( + MySQLdb.connect( + host="localhost", + user="root", + unix_socket=str(socket), + connect_timeout=5, + charset="utf8mb4", + ) + ) as connection, + closing(connection.cursor()) as cursor, + ): + cursor.execute("SELECT GET_LOCK(%s, 10)", (f"coulobre:{database.name}",)) + if cursor.fetchone() != (1,): + raise ValueError( + "Could not lock this MariaDB database for provisioning." + ) + install_database(cursor, database, socket, record_path) + except MySQLdb.Error as error: + code = error.args[0] if error.args and type(error.args[0]) is int else "unknown" + raise ValueError(f"MariaDB rejected the operation (error {code}).") from None + + return record_path + + +def install_database(cursor, database, socket, record_path): + name = database.name + cursor.execute( + "SELECT SCHEMA_COMMENT FROM information_schema.SCHEMATA WHERE SCHEMA_NAME = %s", + (name,), + ) + schema = cursor.fetchone() + cursor.execute( + "SELECT Host, plugin, authentication_string FROM mysql.user WHERE User = %s", + (name,), + ) + users = cursor.fetchall() + ready_path = record_path.with_suffix(".ready") + record = reserve_credentials( + database, socket, record_path, ready_path, schema, users + ) + comment = MANAGED_COMMENT_PREFIX + record["ownership"] + password_hash = native_password_hash(record["password"]) + + ready = os.path.lexists(ready_path) + if ready: + if read_root_file(ready_path, mode=0o600).strip() != record["ownership"]: + raise ValueError( + "The database completion marker conflicts with its credentials record." + ) + if schema is None or not users: + raise ValueError( + "The managed database or login is missing. Restore it before reapplying." + ) + if schema is not None and schema != (comment,): + raise ValueError("The existing database has a different ownership marker.") + if users and users != (("localhost", "mysql_native_password", password_hash),): + raise ValueError( + "The existing MariaDB login differs from its managed credentials." + ) + + if schema is None: + cursor.execute( + f"CREATE DATABASE `{name}` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci COMMENT %s", + (comment,), + ) + if not users: + cursor.execute( + "CREATE USER %s@'localhost' IDENTIFIED VIA mysql_native_password USING %s", + (name, password_hash), + ) + + # A database-level GRANT treats underscores as wildcards, even in backticks. + grant_name = name.replace("_", r"\_") + cursor.execute( + f"GRANT ALL PRIVILEGES ON `{grant_name}`.* TO %s@'localhost'", (name,) + ) + if not ready: + write_new_file(ready_path, record["ownership"] + "\n", mode=0o600) + + +def reserve_credentials(database, socket, path, ready_path, schema, users): + identity = { + "database": database.name, + "user": database.name, + "host": "localhost", + "socket": str(socket), + } + if os.path.lexists(path): + record = json.loads(read_root_file(path, mode=0o600)) + if ( + not isinstance(record, dict) + or any(record.get(key) != value for key, value in identity.items()) + or not isinstance(record.get("password"), str) + or not record["password"] + or not isinstance(record.get("ownership"), str) + or not record["ownership"] + ): + raise ValueError( + "The local credentials record conflicts with the manifest or socket." + ) + return record + + if os.path.lexists(ready_path) or schema is not None or users: + raise ValueError( + "The database name or login already exists outside Coulobre's registry." + ) + record = { + **identity, + "password": secrets.token_urlsafe(32), + "ownership": secrets.token_hex(16), + } + write_new_file(path, json.dumps(record, indent=2) + "\n", mode=0o600) + return record + + +def native_password_hash(password): + first = hashlib.sha1(password.encode("utf-8")).digest() + return "*" + hashlib.sha1(first).hexdigest().upper() diff --git a/src/coulobre/hosting/test_database_node_apply.py b/src/coulobre/hosting/test_database_node_apply.py new file mode 100644 index 0000000..4700c41 --- /dev/null +++ b/src/coulobre/hosting/test_database_node_apply.py @@ -0,0 +1,98 @@ +import json +import stat +from pathlib import Path +from tempfile import TemporaryDirectory +from unittest.mock import Mock, patch + +from django.test import SimpleTestCase + +from coulobre.database_node import DatabaseSpec +from coulobre.database_node_apply import ( + MANAGED_COMMENT_PREFIX, + install_database, + native_password_hash, +) + + +class DatabaseProvisioningTests(SimpleTestCase): + def setUp(self): + root = Path(self.enterContext(TemporaryDirectory())) + self.database = DatabaseSpec(42, "site_db") + self.socket = root / "mariadb.sock" + self.record = root / f"{self.database.name}.json" + self.ready = self.record.with_suffix(".ready") + self.cursor = Mock() + self.cursor.fetchone.return_value = None + self.cursor.fetchall.return_value = () + self.enterContext( + patch( + "coulobre.database_node_apply.read_root_file", + side_effect=lambda path, *, mode: path.read_text(encoding="utf-8"), + ) + ) + + def apply(self): + install_database(self.cursor, self.database, self.socket, self.record) + + def test_creates_private_credentials_and_grants_only_the_exact_database(self): + self.apply() + + credentials = json.loads(self.record.read_text()) + self.assertEqual(stat.S_IMODE(self.record.stat().st_mode), 0o600) + self.assertEqual(stat.S_IMODE(self.ready.stat().st_mode), 0o600) + self.assertEqual(credentials["user"], self.database.name) + self.assertEqual(self.ready.read_text().strip(), credentials["ownership"]) + self.cursor.execute.assert_any_call( + r"GRANT ALL PRIVILEGES ON `coulobre\_42\_site\_db`.* TO %s@'localhost'", + (self.database.name,), + ) + self.cursor.execute.assert_any_call( + "CREATE USER %s@'localhost' IDENTIFIED VIA mysql_native_password USING %s", + (self.database.name, native_password_hash(credentials["password"])), + ) + + def test_interrupted_creation_reuses_the_reserved_password(self): + def fail_create_user(query, params): + if query.startswith("CREATE USER"): + raise RuntimeError("Interrupted after schema creation") + + self.cursor.execute.side_effect = fail_create_user + with self.assertRaises(RuntimeError): + self.apply() + + saved = self.record.read_bytes() + record = json.loads(saved) + self.assertFalse(self.ready.exists()) + self.cursor.reset_mock() + self.cursor.execute.side_effect = None + self.cursor.fetchone.return_value = ( + MANAGED_COMMENT_PREFIX + record["ownership"], + ) + self.apply() + + self.assertEqual(self.record.read_bytes(), saved) + self.assertTrue(self.ready.is_file()) + self.assertFalse( + any( + call.args[0].startswith("CREATE DATABASE") + for call in self.cursor.execute.call_args_list + ) + ) + + def test_existing_unmanaged_database_is_rejected_without_creating_credentials(self): + self.cursor.fetchone.return_value = ("Existing database",) + + with self.assertRaisesRegex(ValueError, "outside Coulobre's registry"): + self.apply() + + self.assertFalse(self.record.exists()) + self.assertEqual(self.cursor.execute.call_count, 2) + + def test_completed_deployment_with_missing_resource_requires_recovery(self): + self.apply() + self.cursor.reset_mock() + + with self.assertRaisesRegex(ValueError, "database or login is missing"): + self.apply() + + self.assertEqual(self.cursor.execute.call_count, 2) diff --git a/src/coulobre/node_files.py b/src/coulobre/node_files.py new file mode 100644 index 0000000..bc8894b --- /dev/null +++ b/src/coulobre/node_files.py @@ -0,0 +1,35 @@ +import os +import stat +from tempfile import NamedTemporaryFile + + +def require_root_directory(path, *, create_mode=None): + for parent in reversed(path.parents): + check_root_directory(parent) + if create_mode is not None: + path.mkdir(mode=create_mode, exist_ok=True) + check_root_directory(path) + + +def check_root_directory(path): + info = path.lstat() + if not stat.S_ISDIR(info.st_mode) or info.st_uid != 0 or info.st_mode & 0o022: + raise ValueError(f"Expected a root-controlled directory at {path}.") + + +def read_root_file(path, *, mode=None): + info = path.lstat() + if not stat.S_ISREG(info.st_mode) or info.st_uid != 0 or info.st_mode & 0o022: + raise ValueError(f"Expected a root-controlled file at {path}.") + if mode is not None and stat.S_IMODE(info.st_mode) != mode: + raise ValueError(f"Expected permissions {mode:04o} on {path}.") + return path.read_text(encoding="utf-8") + + +def write_new_file(path, content, *, mode): + with NamedTemporaryFile(mode="w", encoding="utf-8", dir=path.parent) as staged: + staged.write(content) + staged.flush() + os.fchmod(staged.fileno(), mode) + os.fsync(staged.fileno()) + os.link(staged.name, path) diff --git a/src/coulobre/web_node_apply.py b/src/coulobre/web_node_apply.py index 24ccc7e..f861ba3 100644 --- a/src/coulobre/web_node_apply.py +++ b/src/coulobre/web_node_apply.py @@ -8,7 +8,8 @@ import subprocess import time from dataclasses import dataclass from pathlib import Path -from tempfile import NamedTemporaryFile + +from .node_files import read_root_file, require_root_directory, write_new_file STATE_DIRECTORY = Path("/var/lib/coulobre/web-node") WEB_ROOT = Path("/srv/coulobre/web") @@ -56,20 +57,6 @@ def apply_site(site): install_site(site) -def require_root_directory(path, *, create_mode=None): - for parent in reversed(path.parents): - check_root_directory(parent) - if create_mode is not None: - path.mkdir(mode=create_mode, exist_ok=True) - check_root_directory(path) - - -def check_root_directory(path): - info = path.lstat() - if not stat.S_ISDIR(info.st_mode) or info.st_uid != 0 or info.st_mode & 0o022: - raise ValueError(f"Expected a root-controlled directory at {path}.") - - def install_site(site): user = site.configuration()["service_user"] paths = SitePaths.for_site(site) @@ -238,21 +225,6 @@ def check_public_directory(path, uid, gid): raise ValueError(f"Unexpected ownership or mode for {path}.") -def read_root_file(path): - info = path.lstat() - if not stat.S_ISREG(info.st_mode) or info.st_uid != 0 or info.st_mode & 0o022: - raise ValueError(f"Expected a root-controlled file at {path}.") - return path.read_text(encoding="utf-8") - - -def write_new_file(path, content, *, mode): - with NamedTemporaryFile(mode="w", encoding="utf-8", dir=path.parent) as staged: - staged.write(content) - staged.flush() - os.fchmod(staged.fileno(), mode) - os.link(staged.name, path) - - def install_configurations(site, apache, enabled, pool, socket): created = [] reload_attempts = []