Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions src/database/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -741,7 +741,8 @@ def backup_modes() -> tuple:

def _secure_db_files() -> None:
"""Ensure SQLite files in data/ and .env are 0600; backups follow
backup_modes() (POSIX only)."""
backup_modes() (POSIX only) - except a media-server switch's restore
point (backups/rebind-*/), a full copy with the tokens, which stays 0600."""
import os
import stat
import logging as _logging
Expand All @@ -761,8 +762,10 @@ def _secure_db_files() -> None:
for ext in ("*.db", "*.sqlite3", "*.sqlite3-wal", "*.sqlite3-shm", "*.db-wal", "*.db-shm"):
for p in DATA_DIR.rglob(ext):
try:
in_backups = backups in p.resolve().parents
os.chmod(p, backup_modes()[0] if in_backups else stat.S_IRUSR | stat.S_IWUSR)
rp = p.resolve()
stripped = (backups in rp.parents
and not rp.relative_to(backups).parts[0].startswith("rebind-"))
os.chmod(p, backup_modes()[0] if stripped else stat.S_IRUSR | stat.S_IWUSR)
except FileNotFoundError:
pass # a -wal/-shm sidecar checkpointed away mid-scan
except OSError as e:
Expand Down
6 changes: 5 additions & 1 deletion src/services/media_server/rebind.py
Original file line number Diff line number Diff line change
Expand Up @@ -472,10 +472,14 @@ async def apply_plan(plan: Plan, *, target_adapter, chroma=None, backup_root: Op
if (m := running_manifest(root)) is not None:
raise RuntimeError(f"an unfinished rebind is on record ({m}) - finish it with --undo first")
folder = root / f"rebind-{datetime.utcnow():%Y%m%d-%H%M%S}"
folder.mkdir()
# The restore point is the whole database, members' Plex tokens included
# (the nightly copy blanks them, this one must restore as it was): 0600
# in a 0700 folder like the live database, not the umask's 0644.
folder.mkdir(mode=0o700)
snap = str(folder / "curatarr.db")
if not await run_read(scheduler._snapshot_sqlite, _db_path(), snap):
raise RuntimeError("the database backup failed its integrity check - nothing was changed")
os.chmod(snap, 0o600)
pairs = dict(plan.items)
users = {sid: tid for _, (sid, tid, _) in plan.users.items()}
libs = {s: t for s, (t, _) in plan.libraries.items()}
Expand Down
7 changes: 6 additions & 1 deletion tests/test_backup_perms.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,11 @@ def db(p):


backup = data / "backups" / "curatarr_20261114_214712.db"
# A media-server switch's restore point: the whole database, tokens and all.
(data / "backups" / "rebind-20261110-120000").mkdir()
switch_copy = data / "backups" / "rebind-20261110-120000" / "curatarr.db"
for p in (data / "curatarr.db", data / "cache" / "enrichment.db", backup,
data / "backups" / "caches" / "cache" / "lyrics.db"):
data / "backups" / "caches" / "cache" / "lyrics.db", switch_copy):
db(p)
env = root / ".env"
env.write_text("JWT_SECRET=x\n", encoding="utf-8")
Expand All @@ -103,6 +106,8 @@ def secure(group_readable):
mode(backup) == 0o640 and mode(data / "backups" / "caches" / "cache" / "lyrics.db") == 0o640)
check("...while the live database, a cache and .env stay 0600",
{mode(data / "curatarr.db"), mode(data / "cache" / "enrichment.db"), mode(env)} == {0o600})
check("...and so does a switch's restore point: its tokens are not blanked",
mode(switch_copy) == 0o600, oct(mode(switch_copy)))
if not POSIX:
check("(Windows: file modes are POSIX-only; the pass ran without error)", True)

Expand Down
9 changes: 9 additions & 0 deletions tests/test_rebind.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@

import asyncio
import json
import os
import stat
import tempfile
from pathlib import Path

Expand Down Expand Up @@ -197,6 +199,13 @@ def rekey_facets(self, pairs):
check("setting flipped, backup kept, manifest completed",
flips == ["jellyfin"] and Path(m["backup"]).exists() and m["status"] == "completed"
and m["settings"] == "plex-was-blank")
if os.name == "posix":
# The restore point keeps every member's Plex token: 0600 in a 0700
# folder like the live database, whatever the umask or BACKUP_GROUP_READABLE.
snap = Path(m["backup"])
check("the backup is 0600 in a 0700 folder (it carries the tokens)",
stat.S_IMODE(snap.stat().st_mode) == 0o600 and stat.S_IMODE(snap.parent.stat().st_mode) == 0o700,
(oct(snap.stat().st_mode), oct(snap.parent.stat().st_mode)))
with conn_mod.engine.connect() as c:
mem = dict(c.execute(text("SELECT canonical_key, jellyfin_id FROM server_id_map WHERE entity_type='user'")).fetchall())
check("users filed in the id memory", mem == {"user:1": JANE, "user:2": SAM})
Expand Down
Loading