Merge pull request 'Add MariaDB provisioning for hosting accounts' (#5) from feature/hosting-databases into main
Reviewed-on: #5
This commit was merged in pull request #5.
This commit is contained in:
commit
5cd2614758
16 files changed
+967
-38
No files matched your search
@@ -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
|
||||
|
||||
@@ -16,6 +16,7 @@ dependencies = [
|
||||
]
|
||||
|
||||
[project.scripts]
|
||||
coulobre-database-node = "coulobre.database_node:main"
|
||||
coulobre-web-node = "coulobre.web_node:main"
|
||||
|
||||
[project.optional-dependencies]
|
||||
|
||||
@@ -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
|
||||
@@ -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()
|
||||
@@ -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",
|
||||
)
|
||||
],
|
||||
},
|
||||
),
|
||||
]
|
||||
@@ -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)
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -35,4 +35,33 @@
|
||||
{% include "hosting/plan_table.html" %}
|
||||
</section>
|
||||
{% endif %}
|
||||
{% if is_reseller or perms.hosting.view_hostingdatabase %}
|
||||
<section class="surface" aria-labelledby="databases-heading">
|
||||
<header class="section-heading">
|
||||
<h2 id="databases-heading">MariaDB database requests</h2>
|
||||
{% if not is_reseller and perms.hosting.add_hostingdatabase %}
|
||||
<a class="button primary" href="{% url 'panel:database_create' account.pk %}">Request database</a>
|
||||
{% endif %}
|
||||
</header>
|
||||
{% if databases %}
|
||||
<div class="table-scroll">
|
||||
<table>
|
||||
<thead><tr><th scope="col">Database</th>{% if not is_reseller %}<th scope="col">Deployment</th>{% endif %}</tr></thead>
|
||||
<tbody>
|
||||
{% for database in databases %}
|
||||
<tr>
|
||||
<td class="domain">{{ database }}</td>
|
||||
{% if not is_reseller %}
|
||||
<td><a class="record-link" href="{% url 'panel:database_manifest' database.pk %}" aria-label="Download manifest for {{ database }}">Download manifest</a></td>
|
||||
{% endif %}
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% else %}
|
||||
<p class="empty">No databases requested yet.</p>
|
||||
{% endif %}
|
||||
</section>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
@@ -18,7 +18,7 @@
|
||||
<nav class="navigation" aria-label="Main navigation">
|
||||
{% with current=request.resolver_match.url_name %}
|
||||
{% if is_reseller or perms.hosting.view_hostingaccount %}
|
||||
<a href="{% url 'panel:accounts' %}"{% if current == 'accounts' or current == 'account' or current == 'account_create' or current == 'account_edit' %} aria-current="page"{% endif %}>
|
||||
<a href="{% url 'panel:accounts' %}"{% if current == 'accounts' or current == 'account' or current == 'account_create' or current == 'account_edit' or current == 'database_create' %} aria-current="page"{% endif %}>
|
||||
<span class="nav-icon nav-icon-accounts" aria-hidden="true"></span>
|
||||
Hosting accounts
|
||||
</a>
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
{% extends "hosting/base.html" %}
|
||||
{% block title %}Request MariaDB database · Coulobre Panel{% endblock %}
|
||||
{% block content %}
|
||||
<a class="back-link" href="{{ account.get_absolute_url }}">← {{ account.name }}</a>
|
||||
<header class="page-heading"><h1>Request MariaDB database</h1></header>
|
||||
<section class="surface editor-surface">
|
||||
<form method="post" class="editor">
|
||||
{% csrf_token %}
|
||||
{{ form.as_div }}
|
||||
<div class="form-actions">
|
||||
<button class="button primary" type="submit">Request database</button>
|
||||
<a class="button secondary" href="{{ account.get_absolute_url }}">Cancel</a>
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,180 @@
|
||||
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,
|
||||
check_database,
|
||||
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)
|
||||
|
||||
def set_configured_resources(self):
|
||||
self.apply()
|
||||
credentials = json.loads(self.record.read_text())
|
||||
password_hash = native_password_hash(credentials["password"])
|
||||
self.cursor.fetchone.return_value = (
|
||||
MANAGED_COMMENT_PREFIX + credentials["ownership"],
|
||||
)
|
||||
grantee = "`coulobre_42_site_db`@`localhost`"
|
||||
self.grants = (
|
||||
(
|
||||
f"GRANT USAGE ON *.* TO {grantee} IDENTIFIED BY PASSWORD '{password_hash}'",
|
||||
),
|
||||
(rf"GRANT ALL PRIVILEGES ON `coulobre\_42\_site\_db`.* TO {grantee}",),
|
||||
)
|
||||
self.cursor.fetchall.side_effect = [
|
||||
(("localhost", "mysql_native_password", password_hash),),
|
||||
self.grants,
|
||||
]
|
||||
return credentials
|
||||
|
||||
def check_status(self, driver):
|
||||
with patch("coulobre.database_node_apply.require_root_directory"):
|
||||
return check_database(
|
||||
driver, self.cursor, self.database, self.socket, self.record
|
||||
)
|
||||
|
||||
def test_absent_database_has_no_local_state_or_application_connection(self):
|
||||
driver = Mock()
|
||||
|
||||
self.assertEqual(self.check_status(driver), "not_installed")
|
||||
|
||||
self.assertFalse(self.record.exists())
|
||||
self.assertFalse(self.ready.exists())
|
||||
driver.connect.assert_not_called()
|
||||
|
||||
def test_configured_database_is_opened_with_the_saved_application_login(self):
|
||||
driver = Mock()
|
||||
credentials = self.set_configured_resources()
|
||||
|
||||
self.assertEqual(self.check_status(driver), "configured")
|
||||
|
||||
driver.connect.assert_called_once_with(
|
||||
host="localhost",
|
||||
user=self.database.name,
|
||||
passwd=credentials["password"],
|
||||
db=self.database.name,
|
||||
unix_socket=str(self.socket),
|
||||
connect_timeout=5,
|
||||
charset="utf8mb4",
|
||||
)
|
||||
driver.connect.return_value.close.assert_called_once()
|
||||
|
||||
def test_status_rejects_database_grants_with_unescaped_wildcards(self):
|
||||
driver = Mock()
|
||||
credentials = self.set_configured_resources()
|
||||
password_hash = native_password_hash(credentials["password"])
|
||||
wildcard_grant = self.grants[1][0].replace(r"\_", "_")
|
||||
self.cursor.fetchall.side_effect = [
|
||||
(("localhost", "mysql_native_password", password_hash),),
|
||||
(self.grants[0], (wildcard_grant,)),
|
||||
]
|
||||
|
||||
with self.assertRaisesRegex(ValueError, "unexpected grants"):
|
||||
self.check_status(driver)
|
||||
|
||||
driver.connect.assert_not_called()
|
||||
|
||||
def test_status_omits_driver_details_when_application_login_fails(self):
|
||||
class DriverError(Exception):
|
||||
pass
|
||||
|
||||
credentials = self.set_configured_resources()
|
||||
driver = Mock(Error=DriverError)
|
||||
driver.connect.side_effect = DriverError(1045, credentials["password"])
|
||||
|
||||
with self.assertRaisesRegex(
|
||||
ValueError,
|
||||
"^The stored application credentials cannot open the managed database\\.$",
|
||||
):
|
||||
self.check_status(driver)
|
||||
@@ -0,0 +1,123 @@
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.db.models.deletion import ProtectedError
|
||||
from django.test import SimpleTestCase, TestCase
|
||||
from django.urls import reverse
|
||||
|
||||
from coulobre.database_node import DatabaseSpec
|
||||
|
||||
from .models import HostingAccount, HostingDatabase, Reseller
|
||||
|
||||
|
||||
class DatabaseRequestTests(TestCase):
|
||||
@classmethod
|
||||
def setUpTestData(cls):
|
||||
users = get_user_model().objects
|
||||
cls.operator = users.create_superuser("operator")
|
||||
cls.user = users.create_user("reseller")
|
||||
reseller = Reseller.objects.create(user=cls.user)
|
||||
cls.account = HostingAccount.objects.create(
|
||||
name="Account A", primary_domain="account-a.example", reseller=reseller
|
||||
)
|
||||
cls.other_account = HostingAccount.objects.create(
|
||||
name="Account B", primary_domain="account-b.example"
|
||||
)
|
||||
|
||||
def setUp(self):
|
||||
self.client.force_login(self.operator)
|
||||
self.request_url = reverse("panel:database_create", args=[self.account.pk])
|
||||
|
||||
def test_operator_can_request_a_database_and_download_its_manifest(self):
|
||||
response = self.client.post(self.request_url, {"suffix": "wordpress"})
|
||||
self.assertRedirects(response, self.account.get_absolute_url())
|
||||
database = HostingDatabase.objects.get()
|
||||
self.assertEqual(database.account, self.account)
|
||||
name = f"coulobre_{self.account.pk}_wordpress"
|
||||
self.assertContains(self.client.get(self.account.get_absolute_url()), name)
|
||||
|
||||
manifest = self.client.get(
|
||||
reverse("panel:database_manifest", args=[database.pk])
|
||||
)
|
||||
self.assertEqual(manifest.status_code, 200)
|
||||
self.assertEqual(manifest["Cache-Control"], "private, no-store")
|
||||
self.assertIn("attachment", manifest["Content-Disposition"])
|
||||
self.assertEqual(
|
||||
manifest.json(),
|
||||
{
|
||||
"version": 1,
|
||||
"kind": "mariadb_database",
|
||||
"account_id": self.account.pk,
|
||||
"suffix": "wordpress",
|
||||
},
|
||||
)
|
||||
self.assertEqual(DatabaseSpec.from_manifest(manifest.json()).name, name)
|
||||
|
||||
def test_duplicate_suffix_is_scoped_to_the_owning_account(self):
|
||||
HostingDatabase.objects.create(account=self.account, suffix="wordpress")
|
||||
duplicate = self.client.post(self.request_url, {"suffix": "wordpress"})
|
||||
self.assertContains(
|
||||
duplicate, "This account already has a database with that suffix."
|
||||
)
|
||||
|
||||
other_url = reverse("panel:database_create", args=[self.other_account.pk])
|
||||
self.assertRedirects(
|
||||
self.client.post(other_url, {"suffix": "wordpress"}),
|
||||
self.other_account.get_absolute_url(),
|
||||
)
|
||||
self.assertEqual(
|
||||
len({str(database) for database in HostingDatabase.objects.all()}), 2
|
||||
)
|
||||
|
||||
def test_request_rejects_invalid_suffixes(self):
|
||||
for suffix in ("UPPER", "bad-name", "3db", "mysql`", "a" * 25):
|
||||
with self.subTest(suffix=suffix):
|
||||
response = self.client.post(self.request_url, {"suffix": suffix})
|
||||
self.assertIn("suffix", response.context["form"].errors)
|
||||
self.assertFalse(HostingDatabase.objects.exists())
|
||||
|
||||
def test_reseller_view_is_scoped_and_node_actions_require_an_operator(self):
|
||||
owned = HostingDatabase.objects.create(account=self.account, suffix="wordpress")
|
||||
HostingDatabase.objects.create(account=self.other_account, suffix="othersite")
|
||||
self.client.force_login(self.user)
|
||||
account = self.client.get(self.account.get_absolute_url())
|
||||
self.assertContains(account, str(owned))
|
||||
self.assertNotContains(account, "othersite")
|
||||
self.assertNotContains(account, "Download manifest")
|
||||
self.assertNotContains(account, "Request database")
|
||||
self.assertEqual(
|
||||
self.client.get(self.other_account.get_absolute_url()).status_code, 404
|
||||
)
|
||||
self.assertEqual(
|
||||
self.client.post(self.request_url, {"suffix": "another"}).status_code, 403
|
||||
)
|
||||
self.assertEqual(
|
||||
self.client.get(
|
||||
reverse("panel:database_manifest", args=[owned.pk])
|
||||
).status_code,
|
||||
403,
|
||||
)
|
||||
|
||||
def test_account_deletion_protects_database_requests(self):
|
||||
HostingDatabase.objects.create(account=self.account, suffix="wordpress")
|
||||
with self.assertRaises(ProtectedError):
|
||||
self.account.delete()
|
||||
|
||||
|
||||
class DatabaseManifestTests(SimpleTestCase):
|
||||
def test_manifest_validates_identity_and_suffix_at_the_node_boundary(self):
|
||||
manifest = DatabaseSpec(42, "example_db").manifest()
|
||||
self.assertEqual(
|
||||
DatabaseSpec.from_manifest(manifest).name, "coulobre_42_example_db"
|
||||
)
|
||||
for changes in (
|
||||
{"kind": "unknown"},
|
||||
{"version": True},
|
||||
{"version": 2},
|
||||
{"account_id": True},
|
||||
{"account_id": 2**63},
|
||||
{"account_id": -1},
|
||||
{"suffix": "schema`"},
|
||||
{"suffix": None},
|
||||
{"password": "unused"},
|
||||
):
|
||||
with self.subTest(changes=changes), self.assertRaises(ValueError):
|
||||
DatabaseSpec.from_manifest(manifest | changes)
|
||||
@@ -19,6 +19,16 @@ urlpatterns = [
|
||||
path("accounts/new/", views.AccountCreate.as_view(), name="account_create"),
|
||||
path("accounts/<int:pk>/", views.AccountDetail.as_view(), name="account"),
|
||||
path("accounts/<int:pk>/edit/", views.AccountEdit.as_view(), name="account_edit"),
|
||||
path(
|
||||
"accounts/<int:pk>/databases/new/",
|
||||
views.DatabaseCreate.as_view(),
|
||||
name="database_create",
|
||||
),
|
||||
path(
|
||||
"databases/<int:pk>/manifest/",
|
||||
views.DownloadDatabaseManifest.as_view(),
|
||||
name="database_manifest",
|
||||
),
|
||||
path(
|
||||
"accounts/<int:pk>/plans/", views.RequestWebPlan.as_view(), name="request_plan"
|
||||
),
|
||||
|
||||
@@ -1,16 +1,17 @@
|
||||
from django.contrib.auth.mixins import PermissionRequiredMixin
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.db import IntegrityError
|
||||
from django.db import IntegrityError, transaction
|
||||
from django.db.models import Q
|
||||
from django.http import HttpResponse
|
||||
from django.shortcuts import redirect
|
||||
from django.http import HttpResponse, JsonResponse
|
||||
from django.shortcuts import get_object_or_404, redirect
|
||||
from django.urls import reverse_lazy
|
||||
from django.utils.functional import cached_property
|
||||
from django.views import View
|
||||
from django.views.generic import CreateView, DetailView, ListView, UpdateView
|
||||
from django.views.generic.detail import SingleObjectMixin
|
||||
|
||||
from .access import OperatorOnlyMixin, ResellerScopeMixin, reseller_for_user
|
||||
from .models import HostingAccount, HostingPlan, WebProvisioningPlan
|
||||
from .models import HostingAccount, HostingDatabase, HostingPlan, WebProvisioningPlan
|
||||
from .reseller_accounts import create_reseller_account
|
||||
from .web_node import build_web_smoke_bundle, serialize_deployment_manifest
|
||||
|
||||
@@ -19,6 +20,7 @@ CHANGE_ACCOUNTS = "hosting.change_hostingaccount"
|
||||
VIEW_PLANS = "hosting.view_webprovisioningplan"
|
||||
VIEW_HOSTING_PLANS = "hosting.view_hostingplan"
|
||||
VIEW_RESELLERS = "hosting.view_reseller"
|
||||
VIEW_DATABASES = "hosting.view_hostingdatabase"
|
||||
|
||||
|
||||
class AccountList(ResellerScopeMixin, PermissionRequiredMixin, ListView):
|
||||
@@ -140,15 +142,60 @@ class AccountDetail(ResellerScopeMixin, PermissionRequiredMixin, DetailView):
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
context = super().get_context_data(**kwargs)
|
||||
if reseller_for_user(
|
||||
self.request.user
|
||||
) is not None or self.request.user.has_perm(VIEW_PLANS):
|
||||
user = self.request.user
|
||||
reseller = reseller_for_user(user)
|
||||
if reseller is not None or user.has_perm(VIEW_PLANS):
|
||||
context["plans"] = self.object.webprovisioningplan_set.order_by(
|
||||
"-requested_at", "-pk"
|
||||
)[:10]
|
||||
if reseller is not None or user.has_perm(VIEW_DATABASES):
|
||||
context["databases"] = self.object.databases.all()
|
||||
return context
|
||||
|
||||
|
||||
class DatabaseCreate(OperatorOnlyMixin, PermissionRequiredMixin, CreateView):
|
||||
model = HostingDatabase
|
||||
fields = ("suffix",)
|
||||
template_name = "hosting/database_form.html"
|
||||
permission_required = (VIEW_ACCOUNTS, VIEW_DATABASES, "hosting.add_hostingdatabase")
|
||||
|
||||
@cached_property
|
||||
def account(self):
|
||||
return get_object_or_404(HostingAccount, pk=self.kwargs["pk"])
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
return super().get_context_data(account=self.account, **kwargs)
|
||||
|
||||
def form_valid(self, form):
|
||||
self.object = form.save(commit=False)
|
||||
self.object.account = self.account
|
||||
try:
|
||||
with transaction.atomic():
|
||||
self.object.save()
|
||||
except IntegrityError:
|
||||
if not self.account.databases.filter(suffix=self.object.suffix).exists():
|
||||
raise
|
||||
form.add_error(
|
||||
"suffix", "This account already has a database with that suffix."
|
||||
)
|
||||
return self.form_invalid(form)
|
||||
return redirect(self.account)
|
||||
|
||||
|
||||
class DownloadDatabaseManifest(OperatorOnlyMixin, PermissionRequiredMixin, View):
|
||||
permission_required = (VIEW_ACCOUNTS, VIEW_DATABASES)
|
||||
|
||||
def get(self, request, pk):
|
||||
database = get_object_or_404(HostingDatabase, pk=pk)
|
||||
return JsonResponse(
|
||||
database.spec.manifest(),
|
||||
headers={
|
||||
"Cache-Control": "private, no-store",
|
||||
"Content-Disposition": f'attachment; filename="coulobre-database-{database.pk}.json"',
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
class HostingPlanList(OperatorOnlyMixin, PermissionRequiredMixin, ListView):
|
||||
model = HostingPlan
|
||||
permission_required = VIEW_HOSTING_PLANS
|
||||
|
||||
@@ -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)
|
||||
@@ -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 = []
|
||||
|
||||
Reference in new issue
Block a user