bdbackup 0.6.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
bdbackup/validation.py ADDED
@@ -0,0 +1,400 @@
1
+ """Read-only preflight checks and actionable permission/grant guidance."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import inspect
6
+ import os
7
+ import re
8
+ import shlex
9
+ import shutil
10
+ import subprocess
11
+ from collections import defaultdict
12
+ from pathlib import Path
13
+
14
+ from bdbackup import retention
15
+ from bdbackup.config import Config, Job, build_backend
16
+ from bdbackup.filebackup import FileBackup
17
+ from bdbackup.mysql import MySQLBackup, XtraBackup
18
+ from bdbackup.mysql.helpers import mysql_cnf_file
19
+ from bdbackup.scheduling import os_user
20
+
21
+
22
+ class Report:
23
+ def __init__(self):
24
+ self.lines: list[str] = []
25
+ self.ok = True
26
+
27
+ def add(self, status: str, message: str) -> None:
28
+ self.lines.append(f"[{status}] {message}")
29
+ if status == "FAIL":
30
+ self.ok = False
31
+
32
+
33
+ def _safe_error(exc: Exception, job: Job) -> str:
34
+ message = str(exc)
35
+ password = job.params.get("password")
36
+ if isinstance(password, str) and password:
37
+ message = message.replace(password, "<redacted>")
38
+ return " ".join(message.splitlines())
39
+
40
+
41
+ def _access(path: Path, mode: int) -> bool:
42
+ return os.access(path, mode, effective_ids=True)
43
+
44
+
45
+ def _directory(report: Report, path: Path, label: str, *, write=False, create=False) -> None:
46
+ path = path.expanduser().absolute()
47
+ required = "read/write/search" if write else "read/search"
48
+ if not path.exists():
49
+ parent = path.parent
50
+ while not parent.exists() and parent != parent.parent:
51
+ parent = parent.parent
52
+ creatable = create and parent.is_dir() and _access(parent, os.W_OK | os.X_OK)
53
+ report.add(
54
+ "OK" if creatable else "FAIL",
55
+ f"{label}: {path} does not exist; "
56
+ + ("can be created automatically." if creatable else "directory is required."),
57
+ )
58
+ report.lines.append(f" Required directory: mkdir -p -- {shlex.quote(str(path))}")
59
+ report.lines.append(f" OS user {os_user()} needs {required} permissions on {path}.")
60
+ return
61
+ mode = os.R_OK | os.X_OK | (os.W_OK if write else 0)
62
+ if not path.is_dir() or not _access(path, mode):
63
+ report.add("FAIL", f"{label}: OS user {os_user()} needs {required} on directory {path}.")
64
+ else:
65
+ report.add("OK", f"{label}: {path} ({required} as OS user {os_user()}).")
66
+
67
+
68
+ def _file(report: Report, path: Path, label: str, *, write=False) -> None:
69
+ mode = os.R_OK | (os.W_OK if write else 0)
70
+ if not path.is_file() or not _access(path, mode):
71
+ report.add(
72
+ "FAIL",
73
+ f"{label}: OS user {os_user()} needs "
74
+ f"{'read/write' if write else 'read'} access to file {path}.",
75
+ )
76
+ else:
77
+ report.add("OK", f"{label}: {path} is accessible.")
78
+
79
+
80
+ def _binary(report: Report, name: str) -> None:
81
+ found = shutil.which(name)
82
+ if found:
83
+ report.add("OK", f"Executable: {found}")
84
+ else:
85
+ report.add("FAIL", f"Required executable {name!r} is missing or not executable in PATH.")
86
+
87
+
88
+ def _settings(job: Job) -> None:
89
+ integer_options = {"parallel", "compress_threads", "retention_days", "throttle", "jobs", "port"}
90
+ boolean_options = {"encrypt", "follow_symlinks"}
91
+ string_options = {"user", "password", "host", "binary", "compress", "database", "format"}
92
+ list_options = {"options", "exclude", "exclude_pattern", "exclude_templates"}
93
+ for name, value in job.params.items():
94
+ if name in integer_options and (type(value) is not int or value < 1):
95
+ raise ValueError(f"{name} must be an integer >= 1")
96
+ if name == "port" and value > 65535:
97
+ raise ValueError("port must be <= 65535")
98
+ if name in boolean_options and not isinstance(value, bool):
99
+ raise ValueError(f"{name} must be true or false")
100
+ if name in string_options and not isinstance(value, str):
101
+ raise ValueError(f"{name} must be a string")
102
+ if name in list_options and (
103
+ not isinstance(value, list) or any(not isinstance(v, str) for v in value)
104
+ ):
105
+ raise ValueError(f"{name} must be an array of strings")
106
+
107
+
108
+ def _identifier(value: str) -> str:
109
+ return "`" + value.replace("`", "``") + "`"
110
+
111
+
112
+ def _account(user: str, host: str) -> str:
113
+ def quote(value):
114
+ return "'" + value.replace("\\", "\\\\").replace("'", "''") + "'"
115
+
116
+ return f"{quote(user)}@{quote(host)}"
117
+
118
+
119
+ def _scope(database: str, table: str) -> str:
120
+ return ".".join("*" if value == "*" else _identifier(value) for value in (database, table))
121
+
122
+
123
+ def _has_grant(grants: list[str], privilege: str, database="*", table="*") -> bool:
124
+ # ALL PRIVILEGES covers static privileges, not dynamic BACKUP_ADMIN/SHOW_ROUTINE.
125
+ scopes = {_scope(database, table), _scope(database, "*"), "*.*"}
126
+ for grant in grants:
127
+ match = re.match(r"^GRANT (.+?) ON (.+?) TO ", grant, flags=re.IGNORECASE)
128
+ if not match:
129
+ continue
130
+ names, scope = match.groups()
131
+ if scope not in scopes:
132
+ continue
133
+ privileges = {name.strip().upper() for name in names.split(",")}
134
+ if privilege in privileges or (
135
+ "ALL PRIVILEGES" in privileges and privilege not in {"BACKUP_ADMIN", "SHOW_ROUTINE"}
136
+ ):
137
+ return True
138
+ return False
139
+
140
+
141
+ def _requirements(backend, version: str) -> list[tuple[str, str, str]]:
142
+ if isinstance(backend, XtraBackup):
143
+ names = ["RELOAD", "REPLICATION CLIENT", "PROCESS", "LOCK TABLES"]
144
+ if backend.is_mariadb:
145
+ names[1] = "BINLOG MONITOR"
146
+ elif not version or not version.startswith("5."):
147
+ names.insert(1, "BACKUP_ADMIN")
148
+ requirements = [(name, "*", "*") for name in names]
149
+ if "BACKUP_ADMIN" in names:
150
+ requirements.extend(
151
+ ("SELECT", "performance_schema", table)
152
+ for table in (
153
+ "log_status",
154
+ "keyring_component_status",
155
+ "replication_group_members",
156
+ )
157
+ )
158
+ return requirements
159
+ database = backend.database or "*"
160
+ names = ["SELECT", "SHOW VIEW"]
161
+ options = backend.options
162
+ for name, flag in (("TRIGGER", "triggers"), ("EVENT", "events")):
163
+ if f"--skip-{flag}" not in options:
164
+ names.append(name)
165
+ if "--skip-single-transaction" in options or "--lock-tables" in options:
166
+ names.append("LOCK TABLES")
167
+ requirements = [(name, database, "*") for name in names]
168
+ if "--no-tablespaces" not in options:
169
+ requirements.append(("PROCESS", "*", "*"))
170
+ return requirements
171
+
172
+
173
+ def _grant_help(report: Report, backend, account: str, requirements) -> None:
174
+ report.lines.append(f" SQL for a database administrator (not executed), account {account}:")
175
+ grouped = defaultdict(list)
176
+ for privilege, database, table in requirements:
177
+ grouped[(database, table)].append(privilege)
178
+ for (database, table), privileges in grouped.items():
179
+ report.lines.append(
180
+ f" GRANT {', '.join(privileges)} ON {_scope(database, table)} TO {account};"
181
+ )
182
+ if isinstance(backend, XtraBackup) and not backend.is_mariadb:
183
+ report.lines.append(" Optional, for importing individual tables:")
184
+ report.lines.append(f" GRANT CREATE TABLESPACE ON *.* TO {account};")
185
+ report.lines.append(
186
+ " If the account does not exist, create it with your chosen authentication "
187
+ "method first; no password is printed here."
188
+ )
189
+
190
+
191
+ def _mysql(report: Report, backend) -> None:
192
+ physical = isinstance(backend, XtraBackup)
193
+ host = "localhost" if physical else backend.host
194
+ account = _account(backend.user, "localhost" if host == "localhost" else "<client-host>")
195
+ client = shutil.which("mariadb" if physical and backend.is_mariadb else "mysql")
196
+ if not client:
197
+ client = shutil.which("mysql" if physical and backend.is_mariadb else "mariadb")
198
+ requirements = _requirements(backend, "")
199
+ if not client:
200
+ report.add("FAIL", "Install mysql/mariadb client to check login and SHOW GRANTS.")
201
+ _grant_help(report, backend, account, requirements)
202
+ return
203
+ connection = {} if physical else {"host": backend.host, "port": backend.port}
204
+ try:
205
+ with mysql_cnf_file(user=backend.user, password=backend.password, **connection) as defaults:
206
+ result = subprocess.run( # noqa: S603
207
+ [
208
+ client,
209
+ f"--defaults-extra-file={defaults}",
210
+ "--batch",
211
+ "--raw",
212
+ "--skip-column-names",
213
+ "--connect-timeout=5",
214
+ "--execute=SELECT CURRENT_USER(), VERSION(), @@datadir; SHOW GRANTS;",
215
+ ],
216
+ capture_output=True,
217
+ text=True,
218
+ timeout=15,
219
+ )
220
+ if result.returncode:
221
+ report.add(
222
+ "FAIL",
223
+ f"MySQL login/grant query failed for user {backend.user!r} "
224
+ f"(client exit {result.returncode}); check credentials and connection defaults.",
225
+ )
226
+ _grant_help(report, backend, account, requirements)
227
+ return
228
+ lines = result.stdout.splitlines()
229
+ identity, version, datadir = lines[0].split("\t", 2)
230
+ user, matched_host = identity.rsplit("@", 1)
231
+ account = _account(user, matched_host)
232
+ report.add("OK", f"MySQL authenticated as {account}; server {version}.")
233
+ grants = lines[1:]
234
+ requirements = _requirements(backend, version)
235
+ missing = [entry for entry in requirements if not _has_grant(grants, *entry)]
236
+ if missing:
237
+ report.add(
238
+ "FAIL",
239
+ "Required grants not confirmed: "
240
+ + ", ".join(
241
+ f"{privilege} ON {_scope(db, table)}" for privilege, db, table in missing
242
+ ),
243
+ )
244
+ _grant_help(report, backend, account, missing)
245
+ else:
246
+ report.add("OK", "Required direct MySQL grants are present.")
247
+ if any(g.upper().startswith("REVOKE ") for g in grants):
248
+ report.add(
249
+ "FAIL",
250
+ "Partial revokes require manual privilege review; "
251
+ "effective access cannot be confirmed.",
252
+ )
253
+ if any(g.upper().startswith("GRANT ") and " ON " not in g.upper() for g in grants):
254
+ report.add(
255
+ "INFO",
256
+ "Role grants are not expanded; review active roles if grants "
257
+ "above could not be confirmed.",
258
+ )
259
+ if physical:
260
+ if backend.is_mariadb != ("mariadb" in version.lower()):
261
+ report.add("FAIL", "Backup binary family does not match the MySQL/MariaDB server.")
262
+ _directory(report, Path(datadir), "MySQL datadir")
263
+ report.add(
264
+ "INFO",
265
+ "Datadir check covers directory access; external tablespaces, "
266
+ "individual data files and server/binary version compatibility need review.",
267
+ )
268
+ else:
269
+ report.add(
270
+ "INFO",
271
+ "mysqldump options, routine visibility and GTID settings may require "
272
+ "additional grants (SHOW_ROUTINE or global SELECT, RELOAD/FLUSH_TABLES).",
273
+ )
274
+ except (OSError, ValueError, IndexError, subprocess.TimeoutExpired) as exc:
275
+ report.add("FAIL", f"Cannot validate MySQL login/grants ({type(exc).__name__}).")
276
+ _grant_help(report, backend, account, requirements)
277
+
278
+
279
+ def _retention(report: Report, job: Job) -> None:
280
+ params = dict(job.params)
281
+ if "apply" in params:
282
+ params["apply_changes"] = params.pop("apply")
283
+ if "pick" in params:
284
+ params["pick_mode"] = params.pop("pick")
285
+ bound = inspect.signature(retention.run_job).bind(**params)
286
+ bound.apply_defaults()
287
+ values = bound.arguments
288
+ for key, minimum in (
289
+ ("daily", 1),
290
+ ("weekly", 0),
291
+ ("monthly", 0),
292
+ ("incr_days", 0),
293
+ ("log_days", 0),
294
+ ("min_keep_fulls", 1),
295
+ ):
296
+ if type(values[key]) is not int or values[key] < minimum:
297
+ raise ValueError(f"{key} must be an integer >= {minimum}")
298
+ if values["pick_mode"] not in {"first", "last"}:
299
+ raise ValueError("pick must be first or last")
300
+ if not isinstance(values["apply_changes"], bool):
301
+ raise ValueError("apply must be true or false")
302
+ for key in ("full_dir", "incr_dir", "log_dir"):
303
+ if values[key] is not None:
304
+ _directory(report, Path(values[key]), key, write=values["apply_changes"])
305
+ report.add("INFO", "Retention mode: " + ("APPLY" if values["apply_changes"] else "DRY RUN"))
306
+ report.add("INFO", "Retention settings/access checked; no deletion scan or deletion performed.")
307
+
308
+
309
+ def validate_config(config: Config, jobs: list[Job]) -> tuple[list[str], bool]:
310
+ report = Report()
311
+ report.lines.append(
312
+ f"Validation as OS user {os_user()}; no backup, prune or GRANT is executed."
313
+ )
314
+ if config.history:
315
+ db = config.history.database
316
+ _directory(report, db.parent, "SQLite history directory", write=True, create=True)
317
+ if db.exists():
318
+ _file(report, db, "SQLite history", write=True)
319
+ _directory(report, config.history.restore_root, "Recovery root", write=True, create=True)
320
+ for job in jobs:
321
+ report.lines.append(f"\nJob {job.name!r} ({job.type})")
322
+ try:
323
+ if job.type == "retention":
324
+ _retention(report, job)
325
+ continue
326
+ if job.type not in {"file", "xtrabackup", "mysqldump"}:
327
+ report.add("FAIL", f"Preflight checks are not implemented for engine {job.type!r}.")
328
+ continue
329
+ # Report destinations even if another constructor setting is invalid.
330
+ destination = job.params.get("backup_root", job.params.get("out_dir"))
331
+ if destination is not None:
332
+ _directory(report, Path(destination), "Backup destination", write=True, create=True)
333
+ _settings(job)
334
+ backend = build_backend(job)
335
+ if isinstance(backend, FileBackup):
336
+ _directory(
337
+ report,
338
+ backend.tar_filename.parent,
339
+ "Archive destination",
340
+ write=True,
341
+ create=True,
342
+ )
343
+ if config.history and backend.tar_filename.resolve() in {
344
+ Path(str(config.history.database) + suffix)
345
+ for suffix in ("", "-wal", "-shm", "-journal")
346
+ }:
347
+ report.add(
348
+ "FAIL", "Archive destination conflicts with the SQLite history file."
349
+ )
350
+ if not backend.backup_paths:
351
+ report.add("FAIL", "File job needs a nonempty template_filename path list.")
352
+ count = 0
353
+ for source, _ in backend._walk():
354
+ count += 1
355
+ if source.is_symlink() and not backend.follow_symlinks:
356
+ continue
357
+ mode = os.R_OK | (os.X_OK if source.is_dir() else 0)
358
+ if not _access(source, mode):
359
+ report.add(
360
+ "FAIL", f"OS user {os_user()} cannot read/search source {source}."
361
+ )
362
+ if count:
363
+ report.add("OK", f"Checked access to {count} selected source entries.")
364
+ elif backend.backup_paths:
365
+ report.add("FAIL", "No source entries selected after exclusions.")
366
+ elif isinstance(backend, (MySQLBackup, XtraBackup)):
367
+ if not isinstance(backend.user, str) or not backend.user.strip():
368
+ raise ValueError("MySQL user must be a nonempty string")
369
+ if isinstance(backend, MySQLBackup):
370
+ _binary(report, "mysqldump")
371
+ if not backend.database and "--all-databases" not in backend.options:
372
+ report.add("FAIL", "Set database or include --all-databases in options.")
373
+ if destination is None:
374
+ _directory(
375
+ report, backend.out_dir, "Backup destination", write=True, create=True
376
+ )
377
+ else:
378
+ _binary(report, backend.binary)
379
+ if config.history and config.history.restore_root.is_relative_to(
380
+ backend.backup_root
381
+ ):
382
+ report.add("FAIL", "Recovery root must be outside this job's backup root.")
383
+ if backend.compress not in {"", "zstd", "lz4", "quicklz"}:
384
+ report.add("FAIL", "compress must be empty, zstd, lz4 or quicklz.")
385
+ if backend.compress:
386
+ _binary(
387
+ report, {"quicklz": "qpress"}.get(backend.compress, backend.compress)
388
+ )
389
+ if backend.encrypt:
390
+ report.add(
391
+ "OK",
392
+ f"AES256 key file is readable and 32 bytes: {backend.encrypt_key_file}",
393
+ )
394
+ _mysql(report, backend)
395
+ except Exception as exc:
396
+ report.add("FAIL", f"Invalid settings or inaccessible path: {_safe_error(exc, job)}")
397
+ report.lines.append(
398
+ "\nValidation passed." if report.ok else "\nValidation failed; see requirements above."
399
+ )
400
+ return report.lines, report.ok