Phase 21: Database identity and access
This commit is contained in:
@@ -143,6 +143,7 @@ class BackupEvidence:
|
|||||||
backup["driver"] in (
|
backup["driver"] in (
|
||||||
"mysql",
|
"mysql",
|
||||||
"postgresql",
|
"postgresql",
|
||||||
|
"sqlite",
|
||||||
),
|
),
|
||||||
"Invalid database driver",
|
"Invalid database driver",
|
||||||
)
|
)
|
||||||
@@ -171,6 +172,7 @@ class BackupEvidence:
|
|||||||
filename = {
|
filename = {
|
||||||
"mysql": "database.sql",
|
"mysql": "database.sql",
|
||||||
"postgresql": "database.dump",
|
"postgresql": "database.dump",
|
||||||
|
"sqlite": "database.sqlite",
|
||||||
}[backup["driver"]]
|
}[backup["driver"]]
|
||||||
|
|
||||||
require(
|
require(
|
||||||
|
|||||||
@@ -0,0 +1,95 @@
|
|||||||
|
"""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
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
import sqlite3
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from contextlib import closing
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from core.dev3.database import DatabaseIdentityError, SandboxDatabase
|
||||||
|
|
||||||
|
|
||||||
|
class DatabaseTests(unittest.TestCase):
|
||||||
|
def test_read_scope_backup_and_replacement(self):
|
||||||
|
with tempfile.TemporaryDirectory() as directory:
|
||||||
|
db = SandboxDatabase(Path(directory).resolve())
|
||||||
|
with closing(sqlite3.connect(db.path)) as writer:
|
||||||
|
writer.execute("CREATE TABLE fixture (id INT)")
|
||||||
|
writer.execute("INSERT INTO fixture VALUES (3)")
|
||||||
|
writer.commit()
|
||||||
|
with db.reader() as reader:
|
||||||
|
self.assertEqual(reader.execute("SELECT * FROM fixture").fetchall(), [(3,)])
|
||||||
|
for sql in ("DELETE FROM fixture", "ATTACH DATABASE ':memory:' AS extra"):
|
||||||
|
with self.assertRaises(sqlite3.DatabaseError):
|
||||||
|
reader.execute(sql)
|
||||||
|
backup = db.create()
|
||||||
|
self.assertEqual(db.verify(backup)["driver"], "sqlite")
|
||||||
|
db.path.rename(db.path.with_suffix(".old"))
|
||||||
|
db.path.touch(mode=0o600)
|
||||||
|
with self.assertRaises(DatabaseIdentityError):
|
||||||
|
db.check()
|
||||||
Reference in New Issue
Block a user