Harden backup manifest metadata and database identity validation
ABSDEV Framework CI / framework-ci (push) Successful in 22s
ABSDEV Framework CI / framework-ci (push) Successful in 22s
This commit is contained in:
+64
-3
@@ -28,6 +28,45 @@ def require(condition, message):
|
||||
raise BackupError(message)
|
||||
|
||||
|
||||
def unique_json_object(pairs):
|
||||
|
||||
result = {}
|
||||
|
||||
for key, value in pairs:
|
||||
|
||||
require(
|
||||
key not in result,
|
||||
"Duplicate backup manifest field",
|
||||
)
|
||||
|
||||
result[key] = value
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def validate_timestamp(value):
|
||||
|
||||
require(
|
||||
isinstance(value, str)
|
||||
and bool(value)
|
||||
and "T" in value,
|
||||
"Invalid backup timestamp",
|
||||
)
|
||||
|
||||
try:
|
||||
parsed = datetime.fromisoformat(value)
|
||||
except ValueError as error:
|
||||
raise BackupError(
|
||||
"Invalid backup timestamp"
|
||||
) from error
|
||||
|
||||
require(
|
||||
parsed.tzinfo is not None
|
||||
and parsed.utcoffset() is not None,
|
||||
"Backup timestamp requires timezone",
|
||||
)
|
||||
|
||||
|
||||
def sync_directory(path):
|
||||
|
||||
fd = os.open(
|
||||
@@ -149,8 +188,18 @@ class BackupEngine:
|
||||
|
||||
raw = output.getvalue().decode("utf-8").strip()
|
||||
|
||||
return self.validate_identity(raw)
|
||||
|
||||
def validate_identity(self, raw):
|
||||
|
||||
require(
|
||||
raw and "\n" not in raw,
|
||||
isinstance(raw, str)
|
||||
and bool(raw.strip())
|
||||
and raw == raw.strip()
|
||||
and all(
|
||||
char == chr(9) or char.isprintable()
|
||||
for char in raw
|
||||
),
|
||||
"Invalid database identity output",
|
||||
)
|
||||
|
||||
@@ -187,7 +236,7 @@ class BackupEngine:
|
||||
if driver == "mysql":
|
||||
|
||||
require(
|
||||
bool(parts[2]),
|
||||
bool(parts[2].strip()),
|
||||
"Missing database server identity",
|
||||
)
|
||||
|
||||
@@ -369,7 +418,10 @@ class BackupEngine:
|
||||
|
||||
with os.fdopen(fd, "r", encoding="utf-8") as handle:
|
||||
|
||||
manifest = json.load(handle)
|
||||
manifest = json.load(
|
||||
handle,
|
||||
object_pairs_hook=unique_json_object,
|
||||
)
|
||||
|
||||
fields = {
|
||||
"format_version",
|
||||
@@ -401,6 +453,15 @@ class BackupEngine:
|
||||
"filename": self.filename,
|
||||
}
|
||||
|
||||
require(
|
||||
type(manifest["format_version"]) is int,
|
||||
"Invalid backup format version",
|
||||
)
|
||||
|
||||
validate_timestamp(manifest["created_at"])
|
||||
|
||||
self.validate_identity(manifest["identity"])
|
||||
|
||||
for key, value in expected.items():
|
||||
|
||||
require(
|
||||
|
||||
Reference in New Issue
Block a user