Files
absdev-deployment/core/dev3/database.py

96 lines
3.7 KiB
Python

"""Identity-bound SQLite access for the disposable Laravel environment."""
import contextlib
import os
import sqlite3
import stat
import uuid
from pathlib import Path
from core.backup import checksum, sync_directory
class DatabaseIdentityError(RuntimeError):
pass
class SandboxDatabase:
def __init__(self, root):
self.root = Path(root)
info = self.root.stat()
if (self.root.resolve() != self.root or info.st_uid != os.getuid()
or stat.S_IMODE(info.st_mode) != 0o700):
raise DatabaseIdentityError("Database directory is not private")
self.path = self.root / "app.sqlite"
with self.path.open("xb"):
pass
self.path.chmod(0o600)
self.identity = self._identity()
self.manifests = {}
def _identity(self):
info = self.path.lstat()
if (not stat.S_ISREG(info.st_mode) or info.st_nlink != 1
or info.st_uid != os.getuid() or stat.S_IMODE(info.st_mode) != 0o600):
raise DatabaseIdentityError("Unsafe database file")
return (info.st_dev, info.st_ino)
@contextlib.contextmanager
def reader(self):
if self._identity() != self.identity:
raise DatabaseIdentityError("Database identity changed")
with contextlib.closing(sqlite3.connect(self.path.as_uri() + "?mode=ro", uri=True)) as db:
db.set_authorizer(self._authorize)
if self._identity() != self.identity:
raise DatabaseIdentityError("Database identity changed during open")
yield db
@staticmethod
def _authorize(action, first, second, database, source):
return sqlite3.SQLITE_OK if action in {
sqlite3.SQLITE_SELECT, sqlite3.SQLITE_READ, sqlite3.SQLITE_FUNCTION,
} else sqlite3.SQLITE_DENY
def check(self):
with self.reader() as db:
return db.execute("SELECT 1").fetchone() == (1,)
def create(self):
identifier = uuid.uuid4().hex
backup = self.root / identifier
backup.mkdir(mode=0o700)
target = backup / "database.sqlite"
with target.open("xb"):
pass
target.chmod(0o600)
with self.reader() as source:
with contextlib.closing(sqlite3.connect(target)) as destination:
source.backup(destination)
with target.open("rb") as handle:
os.fsync(handle.fileno())
manifest = self.verify(identifier)
self.manifests[identifier] = manifest
sync_directory(backup)
sync_directory(self.root)
return identifier
def verify(self, identifier):
if len(identifier) != 32 or uuid.UUID(hex=identifier).hex != identifier:
raise DatabaseIdentityError("Invalid backup identifier")
path = self.root / identifier / "database.sqlite"
if path.resolve() != path or not path.is_file():
raise DatabaseIdentityError("Unsafe backup file")
with contextlib.closing(sqlite3.connect(path.as_uri() + "?mode=ro", uri=True)) as db:
if db.execute("PRAGMA integrity_check").fetchall() != [("ok",)]:
raise DatabaseIdentityError("Backup integrity check failed")
digest, size = checksum(path)
result = {
"backup_id": identifier, "driver": "sqlite", "database": "acceptance",
"username": "local_fixture", "container": "local_fixture",
"identity": ":".join(map(str, self.identity)), "filename": path.name,
"sha256": digest, "bytes": size,
}
if identifier in self.manifests and result != self.manifests[identifier]:
raise DatabaseIdentityError("Backup contents changed")
return result