Add MariaDB provisioning for hosting accounts #5
No files matched your search
@@ -84,6 +84,30 @@ 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
|
||||
|
||||
@@ -66,6 +66,11 @@ def main(argv=None):
|
||||
)
|
||||
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:
|
||||
@@ -77,6 +82,12 @@ def main(argv=None):
|
||||
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)
|
||||
|
||||
@@ -2,7 +2,7 @@ import hashlib
|
||||
import json
|
||||
import os
|
||||
import secrets
|
||||
from contextlib import closing
|
||||
from contextlib import closing, contextmanager
|
||||
from pathlib import Path
|
||||
|
||||
from .node_files import read_root_file, require_root_directory, write_new_file
|
||||
@@ -14,6 +14,18 @@ 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:
|
||||
@@ -21,10 +33,6 @@ def apply_database(database, socket):
|
||||
"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(
|
||||
@@ -41,18 +49,15 @@ def apply_database(database, socket):
|
||||
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."
|
||||
"Could not acquire the lock for this MariaDB database."
|
||||
)
|
||||
install_database(cursor, database, socket, record_path)
|
||||
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
|
||||
|
||||
return record_path
|
||||
|
||||
|
||||
def install_database(cursor, database, socket, record_path):
|
||||
name = database.name
|
||||
def read_resources(cursor, name):
|
||||
cursor.execute(
|
||||
"SELECT SCHEMA_COMMENT FROM information_schema.SCHEMATA WHERE SCHEMA_NAME = %s",
|
||||
(name,),
|
||||
@@ -62,7 +67,87 @@ def install_database(cursor, database, socket, record_path):
|
||||
"SELECT Host, plugin, authentication_string FROM mysql.user WHERE User = %s",
|
||||
(name,),
|
||||
)
|
||||
users = cursor.fetchall()
|
||||
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
|
||||
@@ -70,22 +155,8 @@ def install_database(cursor, database, socket, record_path):
|
||||
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."
|
||||
)
|
||||
ready = check_completion_marker(ready_path, record)
|
||||
check_resources(schema, users, comment, password_hash, require_complete=ready)
|
||||
|
||||
if schema is None:
|
||||
cursor.execute(
|
||||
@@ -98,43 +169,23 @@ def install_database(cursor, database, socket, record_path):
|
||||
(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,)
|
||||
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):
|
||||
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
|
||||
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 = {
|
||||
**identity,
|
||||
**credential_identity(database, socket),
|
||||
"password": secrets.token_urlsafe(32),
|
||||
"ownership": secrets.token_hex(16),
|
||||
}
|
||||
@@ -142,6 +193,69 @@ def reserve_credentials(database, socket, path, ready_path, schema, users):
|
||||
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()
|
||||
@@ -9,6 +9,7 @@ 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,
|
||||
)
|
||||
@@ -96,3 +97,84 @@ class DatabaseProvisioningTests(SimpleTestCase):
|
||||
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)
|
||||
Reference in new issue
Block a user