Support local MariaDB provisioning over a restricted Unix socket

This commit is contained in:
parkel committed 2026-11-21 01:21:07 +01:00
1 parent cdc82bac67
commit 091193baa0
8 files changed
+142 -26

No files matched your search

@@ -0,0 +1,14 @@
[Unit]
Description=Coulobre local MariaDB provisioning socket
[Socket]
ListenStream=/run/coulobre-database-apply.sock
SocketUser=root
SocketGroup=coulobre-db-provisioning
SocketMode=0660
Accept=yes
MaxConnections=4
RemoveOnStop=true
[Install]
WantedBy=sockets.target
@@ -0,0 +1,21 @@
[Unit]
Description=Coulobre local MariaDB provisioning request
After=mariadb.service
CollectMode=inactive-or-failed
[Service]
Type=exec
User=root
WorkingDirectory=/opt/coulobre
StateDirectory=coulobre/database-node
StateDirectoryMode=0700
UMask=0077
ExecStart=/opt/coulobre/bin/coulobre-database-node apply-request
StandardInput=socket
StandardOutput=socket
StandardError=journal
RuntimeMaxSec=3min
NoNewPrivileges=true
PrivateTmp=true
ProtectHome=true
ProtectSystem=strict
+22
View File
@@ -142,6 +142,28 @@ message when the installation needs attention.
Exit code `1` indicates an invalid manifest or an unavailable check, for example Exit code `1` indicates an invalid manifest or an unavailable check, for example
when the MariaDB administrative connection fails. when the MariaDB administrative connection fails.
### Enable local database provisioning
On a MariaDB node using `/run/mysqld/mysqld.sock`, install the matching Coulobre
package with its `mariadb` extra in a root-owned virtual environment at
`/opt/coulobre`. Enable the local provisioning socket.
```sh
getent group coulobre-db-provisioning >/dev/null || sudo groupadd --system coulobre-db-provisioning
sudo install -m 0644 deploy/systemd/coulobre-database-apply.socket \
deploy/systemd/coulobre-database-apply@.service /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl enable --now coulobre-database-apply.socket
```
Grant the socket group only to the service identity responsible for database
provisioning. Send one version 1 MariaDB database manifest as UTF-8 JSON to
`/run/coulobre-database-apply.sock`. The limit is 4 KiB. Close the writing half
of the socket and read the JSON reply to EOF. For a valid manifest, the reply
includes its identity, a state of `configured` or `failed`, and a diagnostic
on failure.
MariaDB passwords stay in the root-only credentials files on the node.
## Render a BIND9 zone ## Render a BIND9 zone
Open a hosting account and select **Add DNS zone** to configure a zone for Open a hosting account and select **Add DNS zone** to configure a zone for
+15
View File
@@ -4,6 +4,8 @@ import re
from dataclasses import dataclass from dataclasses import dataclass
from pathlib import Path from pathlib import Path
from .node_requests import serve_apply_request
MANIFEST_VERSION = 1 MANIFEST_VERSION = 1
MANIFEST_KIND = "mariadb_database" MANIFEST_KIND = "mariadb_database"
DEFAULT_SOCKET = Path("/run/mysqld/mysqld.sock") DEFAULT_SOCKET = Path("/run/mysqld/mysqld.sock")
@@ -66,6 +68,10 @@ def main(argv=None):
) )
apply.add_argument("manifest", type=Path) apply.add_argument("manifest", type=Path)
apply.add_argument("--socket", type=Path, default=DEFAULT_SOCKET) apply.add_argument("--socket", type=Path, default=DEFAULT_SOCKET)
commands.add_parser(
"apply-request",
help="Apply one MariaDB manifest from standard input and report JSON.",
)
status = commands.add_parser( status = commands.add_parser(
"status", help="Check a database and its local login on MariaDB." "status", help="Check a database and its local login on MariaDB."
) )
@@ -73,6 +79,15 @@ def main(argv=None):
status.add_argument("--socket", type=Path, default=DEFAULT_SOCKET) status.add_argument("--socket", type=Path, default=DEFAULT_SOCKET)
args = parser.parse_args(argv) args = parser.parse_args(argv)
if args.command == "apply-request":
from .database_node_apply import apply_database
return serve_apply_request(
MANIFEST_VERSION,
DatabaseSpec.from_manifest,
lambda database: apply_database(database, DEFAULT_SOCKET),
)
try: try:
payload = json.loads(args.manifest.read_text(encoding="utf-8")) payload = json.loads(args.manifest.read_text(encoding="utf-8"))
database = DatabaseSpec.from_manifest(payload) database = DatabaseSpec.from_manifest(payload)
@@ -1,12 +1,15 @@
import json import json
import stat import stat
from contextlib import redirect_stdout
from io import BytesIO, StringIO
from pathlib import Path from pathlib import Path
from tempfile import TemporaryDirectory from tempfile import TemporaryDirectory
from types import SimpleNamespace
from unittest.mock import Mock, patch from unittest.mock import Mock, patch
from django.test import SimpleTestCase from django.test import SimpleTestCase
from coulobre.database_node import DatabaseSpec from coulobre.database_node import DEFAULT_SOCKET, DatabaseSpec, main
from coulobre.database_node_apply import ( from coulobre.database_node_apply import (
MANAGED_COMMENT_PREFIX, MANAGED_COMMENT_PREFIX,
check_database, check_database,
@@ -15,6 +18,42 @@ from coulobre.database_node_apply import (
) )
class DatabaseApplyRequestTests(SimpleTestCase):
def setUp(self):
self.database = DatabaseSpec(42, "site_db")
self.apply = self.enterContext(
patch(
"coulobre.database_node_apply.apply_database",
return_value=Path("/private/credentials.json"),
)
)
def request(self, manifest):
data = BytesIO(json.dumps(manifest).encode())
output = StringIO()
with (
patch("sys.stdin", SimpleNamespace(buffer=data)),
redirect_stdout(output),
):
code = main(["apply-request"])
return code, json.loads(output.getvalue())
def test_request_uses_the_local_socket_and_reports_only_manifest_identity(self):
manifest = self.database.manifest()
code, reply = self.request(manifest)
self.apply.assert_called_once_with(self.database, DEFAULT_SOCKET)
self.assertEqual(code, 0)
self.assertEqual(reply, manifest | {"state": "configured", "problem": None})
def test_request_rejects_a_socket_supplied_by_the_client(self):
code, reply = self.request(
self.database.manifest() | {"socket": "/tmp/custom.sock"}
)
self.assertEqual(code, 1)
self.assertEqual(reply["state"], "failed")
self.apply.assert_not_called()
class DatabaseProvisioningTests(SimpleTestCase): class DatabaseProvisioningTests(SimpleTestCase):
def setUp(self): def setUp(self):
root = Path(self.enterContext(TemporaryDirectory())) root = Path(self.enterContext(TemporaryDirectory()))
@@ -6,7 +6,8 @@ from unittest.mock import patch
from django.test import SimpleTestCase from django.test import SimpleTestCase
from coulobre.web_node import MAX_REQUEST_BYTES, WebSite, main from coulobre.node_requests import MAX_REQUEST_BYTES
from coulobre.web_node import WebSite, main
class WebSiteManifestTests(SimpleTestCase): class WebSiteManifestTests(SimpleTestCase):
+24
View File
@@ -0,0 +1,24 @@
import json
import sys
MAX_REQUEST_BYTES = 4096
def serve_apply_request(manifest_version, parse_manifest, apply):
report = {"version": manifest_version}
try:
body = sys.stdin.buffer.read(MAX_REQUEST_BYTES + 1)
if len(body) > MAX_REQUEST_BYTES:
raise ValueError(f"The manifest exceeds {MAX_REQUEST_BYTES} bytes.")
try:
payload = json.loads(body.decode("utf-8"))
except (ValueError, RecursionError):
raise ValueError("Expected a UTF-8 JSON manifest.") from None
spec = parse_manifest(payload)
report = spec.manifest()
apply(spec)
except (OSError, ValueError) as error:
print(json.dumps({**report, "state": "failed", "problem": str(error)}))
return 1
print(json.dumps({**report, "state": "configured", "problem": None}))
return 0
+4 -24
View File
@@ -8,9 +8,9 @@ from string import Template
from .directadmin import DOCUMENT_ROOTS from .directadmin import DOCUMENT_ROOTS
from .domain_names import canonical_domain from .domain_names import canonical_domain
from .node_requests import serve_apply_request
MANIFEST_VERSION = 1 MANIFEST_VERSION = 1
MAX_REQUEST_BYTES = 4096
CONFIGURATIONS = {"apache": "apache-vhost.conf", "php-fpm": "php-fpm-pool.conf"} CONFIGURATIONS = {"apache": "apache-vhost.conf", "php-fpm": "php-fpm-pool.conf"}
@@ -67,28 +67,6 @@ class WebSite:
) )
def apply_request():
from .web_node_apply import apply_site
report = {"version": MANIFEST_VERSION}
try:
body = sys.stdin.buffer.read(MAX_REQUEST_BYTES + 1)
if len(body) > MAX_REQUEST_BYTES:
raise ValueError(f"The manifest exceeds {MAX_REQUEST_BYTES} bytes.")
try:
payload = json.loads(body.decode("utf-8"))
except (ValueError, RecursionError):
raise ValueError("Expected a UTF-8 JSON manifest.") from None
site = WebSite.from_manifest(payload)
report = site.manifest()
apply_site(site)
except (OSError, ValueError) as error:
print(json.dumps({**report, "state": "failed", "problem": str(error)}))
return 1
print(json.dumps({**report, "state": "configured", "problem": None}))
return 0
def main(argv=None): def main(argv=None):
parser = argparse.ArgumentParser(prog="coulobre-web-node") parser = argparse.ArgumentParser(prog="coulobre-web-node")
commands = parser.add_subparsers(dest="command", required=True) commands = parser.add_subparsers(dest="command", required=True)
@@ -117,7 +95,9 @@ def main(argv=None):
args = parser.parse_args(argv) args = parser.parse_args(argv)
if args.command == "apply-request": if args.command == "apply-request":
return apply_request() from .web_node_apply import apply_site
return serve_apply_request(MANIFEST_VERSION, WebSite.from_manifest, apply_site)
try: try:
payload = json.loads(args.manifest.read_text(encoding="utf-8")) payload = json.loads(args.manifest.read_text(encoding="utf-8"))