diff --git a/docs/development.md b/docs/development.md index 907f516..aa8d7ef 100644 --- a/docs/development.md +++ b/docs/development.md @@ -45,6 +45,69 @@ and node deployment files. The local database defaults to `db.sqlite3`. Set `COULOBRE_SQLITE_PATH` to use a different file. Keep `COULOBRE_DEBUG` for local development. +## Request a MariaDB database + +Open a hosting account and select **Request database**. Choose a short suffix +such as `wordpress`. The panel derives the full database name from the account +ID and suffix, so two accounts can each request a database named `wordpress`. + +The account page shows the requested databases. Operators can download a +versioned deployment manifest containing the account ID and suffix. Resellers +can view the requested database names on their own assigned accounts. The +manifest describes the database to provision on a MariaDB node. + +Use the installed node command to validate the manifest and display the derived +database and login names. + +```sh +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. + +### Check a database installation + +Run the following command on the MariaDB node with the same manifest and socket +used for installation. + +```sh +sudo /opt/coulobre/bin/coulobre-database-node status coulobre-database-1.json +``` + +The read-only check verifies the local registry, the database ownership marker +and the application's direct MariaDB grants. It then connects over the local +socket with the stored application credentials and selects the database. The +JSON report includes the database and login names, the state, and a diagnostic +message when the installation needs attention. + +| State | Exit code | Meaning | +| --- | --- | --- | +| `configured` | 0 | All checks passed. | +| `not_installed` | 2 | The registry, database, and login are absent. | +| `needs_attention` | 2 | An installation is incomplete or differs from the expected configuration. | + +Exit code `1` indicates an invalid manifest or an unavailable check, for example +when the MariaDB administrative connection fails. + ## Request an Apache configuration preview Start RabbitMQ and set `COULOBRE_BROKER_URL` to its AMQP URL. The development diff --git a/pyproject.toml b/pyproject.toml index 77c8fcc..2be9202 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -16,6 +16,7 @@ dependencies = [ ] [project.scripts] +coulobre-database-node = "coulobre.database_node:main" coulobre-web-node = "coulobre.web_node:main" [project.optional-dependencies] diff --git a/src/coulobre/database_node.py b/src/coulobre/database_node.py new file mode 100644 index 0000000..e390386 --- /dev/null +++ b/src/coulobre/database_node.py @@ -0,0 +1,98 @@ +import argparse +import json +import re +from dataclasses import dataclass +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." +) + + +@dataclass(frozen=True) +class DatabaseSpec: + account_id: int + suffix: str + + def __post_init__(self): + if type(self.account_id) is not int or not 1 <= self.account_id <= 2**63 - 1: + raise ValueError("The account ID must be a positive 64-bit integer.") + if not isinstance(self.suffix, str) or not re.fullmatch( + DATABASE_SUFFIX_PATTERN, self.suffix + ): + raise ValueError(INVALID_SUFFIX) + + @property + def name(self): + return f"coulobre_{self.account_id}_{self.suffix}" + + def manifest(self): + return { + "version": MANIFEST_VERSION, + "kind": MANIFEST_KIND, + "account_id": self.account_id, + "suffix": self.suffix, + } + + @classmethod + def from_manifest(cls, data): + if not isinstance(data, dict) or data.keys() != { + "version", + "kind", + "account_id", + "suffix", + }: + raise ValueError("Expected a MariaDB database manifest.") + if type(data["version"]) is not int or data["version"] != MANIFEST_VERSION: + raise ValueError("Unsupported database manifest version.") + if data["kind"] != MANIFEST_KIND: + raise ValueError("Expected a MariaDB database manifest.") + return cls(data["account_id"], data["suffix"]) + + +def main(argv=None): + parser = argparse.ArgumentParser(prog="coulobre-database-node") + commands = parser.add_subparsers(dest="command", required=True) + inspect = commands.add_parser( + "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) + status = commands.add_parser( + "status", help="Check a database and its local login on MariaDB." + ) + status.add_argument("manifest", type=Path) + status.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}") + elif args.command == "status": + from .database_node_apply import database_status + + report = database_status(database, args.socket) + print(json.dumps(report, indent=2)) + return 0 if report["state"] == "configured" else 2 + 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") + + return 0 diff --git a/src/coulobre/database_node_apply.py b/src/coulobre/database_node_apply.py new file mode 100644 index 0000000..05c3f0b --- /dev/null +++ b/src/coulobre/database_node_apply.py @@ -0,0 +1,261 @@ +import hashlib +import json +import os +import secrets +from contextlib import closing, contextmanager +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.") + + 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" + with locked_cursor(database, socket) as (_, cursor): + install_database(cursor, database, socket, record_path) + return record_path + + +@contextmanager +def locked_cursor(database, socket): + try: + import MySQLdb + except ImportError: + raise ValueError( + "Install Coulobre Panel with its mariadb extra on the node." + ) from None + + 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 acquire the lock for this MariaDB database." + ) + yield MySQLdb, cursor + 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 + + +def read_resources(cursor, 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,), + ) + return schema, cursor.fetchall() + + +def database_status(database, socket): + if os.geteuid() != 0: + raise ValueError("Run status as root on the MariaDB node.") + + socket = socket.resolve() + record_path = STATE_DIRECTORY / f"{database.name}.json" + with locked_cursor(database, socket) as (driver, cursor): + try: + state = check_database(driver, cursor, database, socket, record_path) + problem = None + except (OSError, ValueError) as error: + state = "needs_attention" + problem = str(error) + return { + "database": database.name, + "user": database.name, + "state": state, + "problem": problem, + } + + +def check_database(driver, cursor, database, socket, record_path): + name = database.name + schema, users = read_resources(cursor, name) + ready_path = record_path.with_suffix(".ready") + try: + require_root_directory(record_path.parent) + except FileNotFoundError: + pass + if not os.path.lexists(record_path): + if os.path.lexists(ready_path) or schema is not None or users: + raise ValueError( + "The database, login, or completion marker has no local credentials record." + ) + return "not_installed" + + record = load_credentials(database, socket, record_path) + if not check_completion_marker(ready_path, record): + raise ValueError("The database installation is incomplete.") + password_hash = native_password_hash(record["password"]) + check_resources( + schema, + users, + MANAGED_COMMENT_PREFIX + record["ownership"], + password_hash, + require_complete=True, + ) + cursor.execute("SHOW GRANTS FOR %s@'localhost'", (name,)) + grantee = f"`{name}`@`localhost`" + expected_grants = { + (f"GRANT USAGE ON *.* TO {grantee} IDENTIFIED BY PASSWORD '{password_hash}'",), + (f"GRANT ALL PRIVILEGES ON {grant_scope(name)} TO {grantee}",), + } + if set(cursor.fetchall()) != expected_grants: + raise ValueError("The MariaDB login has unexpected grants.") + try: + with closing( + driver.connect( + host="localhost", + user=name, + passwd=record["password"], + db=name, + unix_socket=str(socket), + connect_timeout=5, + charset="utf8mb4", + ) + ): + pass + except driver.Error: + raise ValueError( + "The stored application credentials cannot open the managed database." + ) from None + return "configured" + + +def install_database(cursor, database, socket, record_path): + name = database.name + schema, users = read_resources(cursor, name) + 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 = check_completion_marker(ready_path, record) + check_resources(schema, users, comment, password_hash, require_complete=ready) + + 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), + ) + + cursor.execute( + f"GRANT ALL PRIVILEGES ON {grant_scope(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): + if os.path.lexists(path): + return load_credentials(database, socket, path) + + 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 = { + **credential_identity(database, socket), + "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 credential_identity(database, socket): + return { + "database": database.name, + "user": database.name, + "host": "localhost", + "socket": str(socket), + } + + +def load_credentials(database, socket, path): + try: + record = json.loads(read_root_file(path, mode=0o600)) + except (json.JSONDecodeError, UnicodeDecodeError): + raise ValueError("The local credentials record is unreadable.") from None + identity = credential_identity(database, socket) + 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 record["password"].isascii() + 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 + + +def check_completion_marker(path, record): + if not os.path.lexists(path): + return False + try: + marker = read_root_file(path, mode=0o600).strip() + except UnicodeDecodeError: + raise ValueError("The database completion marker is unreadable.") from None + if marker != record["ownership"]: + raise ValueError( + "The database completion marker conflicts with its credentials record." + ) + return True + + +def check_resources(schema, users, comment, password_hash, *, require_complete): + if require_complete and (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." + ) + + +def grant_scope(name): + # A database-level GRANT treats underscores as wildcards, even in backticks. + escaped_name = name.replace("_", r"\_") + return f"`{escaped_name}`.*" + + +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/migrations/0006_hostingdatabase.py b/src/coulobre/hosting/migrations/0006_hostingdatabase.py new file mode 100644 index 0000000..d630161 --- /dev/null +++ b/src/coulobre/hosting/migrations/0006_hostingdatabase.py @@ -0,0 +1,59 @@ +# Generated by Django 5.2.19 on 2026-11-19 21:37 + +import django.core.validators +import django.db.models.deletion +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("hosting", "0005_reseller_account_limit_reseller_hosting_plans"), + ] + + operations = [ + migrations.CreateModel( + name="HostingDatabase", + fields=[ + ( + "id", + models.BigAutoField( + auto_created=True, + primary_key=True, + serialize=False, + verbose_name="ID", + ), + ), + ( + "suffix", + models.CharField( + help_text="Use 1 to 24 lowercase letters, digits, or underscores. Start with a letter.", + max_length=24, + validators=[ + django.core.validators.RegexValidator( + "\\A[a-z][a-z0-9_]{0,23}\\Z", + "Use 1 to 24 lowercase letters, digits, or underscores. Start with a letter.", + ) + ], + verbose_name="database suffix", + ), + ), + ( + "account", + models.ForeignKey( + on_delete=django.db.models.deletion.PROTECT, + related_name="databases", + to="hosting.hostingaccount", + ), + ), + ], + options={ + "ordering": ("suffix",), + "constraints": [ + models.UniqueConstraint( + fields=("account", "suffix"), + name="hosting_database_account_suffix_unique", + ) + ], + }, + ), + ] diff --git a/src/coulobre/hosting/models.py b/src/coulobre/hosting/models.py index 9336f68..7cd8cbb 100644 --- a/src/coulobre/hosting/models.py +++ b/src/coulobre/hosting/models.py @@ -1,7 +1,10 @@ from django.conf import settings +from django.core.validators import RegexValidator from django.db import models from django.urls import reverse +from coulobre.database_node import DATABASE_SUFFIX_PATTERN, INVALID_SUFFIX, DatabaseSpec + from .fields import DomainNameField @@ -51,6 +54,34 @@ class HostingAccount(models.Model): return str(self.primary_domain) +class HostingDatabase(models.Model): + account = models.ForeignKey( + HostingAccount, on_delete=models.PROTECT, related_name="databases" + ) + suffix = models.CharField( + "database suffix", + max_length=24, + validators=[RegexValidator(DATABASE_SUFFIX_PATTERN, INVALID_SUFFIX)], + help_text=INVALID_SUFFIX, + ) + + class Meta: + ordering = ("suffix",) + constraints = [ + models.UniqueConstraint( + fields=("account", "suffix"), + name="hosting_database_account_suffix_unique", + ) + ] + + @property + def spec(self): + return DatabaseSpec(self.account_id, self.suffix) + + def __str__(self): + return self.spec.name + + class WebProvisioningPlan(models.Model): account = models.ForeignKey(HostingAccount, on_delete=models.CASCADE) primary_domain = DomainNameField(max_length=253) diff --git a/src/coulobre/hosting/static/hosting/panel.css b/src/coulobre/hosting/static/hosting/panel.css index 986d254..14e5bfa 100644 --- a/src/coulobre/hosting/static/hosting/panel.css +++ b/src/coulobre/hosting/static/hosting/panel.css @@ -237,6 +237,10 @@ h2 { box-shadow: 0 2px 5px #1a2e2010; } +.main > section.surface + section.surface { + margin-top: 1.5rem; +} + .button { display: inline-flex; min-height: 2.55rem; diff --git a/src/coulobre/hosting/templates/hosting/account_detail.html b/src/coulobre/hosting/templates/hosting/account_detail.html index 248e494..e210b86 100644 --- a/src/coulobre/hosting/templates/hosting/account_detail.html +++ b/src/coulobre/hosting/templates/hosting/account_detail.html @@ -35,4 +35,33 @@ {% include "hosting/plan_table.html" %} {% endif %} + {% if is_reseller or perms.hosting.view_hostingdatabase %} +
+
+

MariaDB database requests

+ {% if not is_reseller and perms.hosting.add_hostingdatabase %} + Request database + {% endif %} +
+ {% if databases %} +
+ + {% if not is_reseller %}{% endif %} + + {% for database in databases %} + + + {% if not is_reseller %} + + {% endif %} + + {% endfor %} + +
DatabaseDeployment
{{ database }}Download manifest
+
+ {% else %} +

No databases requested yet.

+ {% endif %} +
+ {% endif %} {% endblock %} diff --git a/src/coulobre/hosting/templates/hosting/base.html b/src/coulobre/hosting/templates/hosting/base.html index 4b8b73a..efde25d 100644 --- a/src/coulobre/hosting/templates/hosting/base.html +++ b/src/coulobre/hosting/templates/hosting/base.html @@ -18,7 +18,7 @@