From e31841301d722295bb8e0e087ea58394e2768034 Mon Sep 17 00:00:00 2001 From: Don Droid <127677734+Randomname653@users.noreply.github.com> Date: Sun, 15 Nov 2026 09:17:28 +0100 Subject: [PATCH 1/6] LAN logos: the app's whole origin, and an icon link with a query - A LAN app's logo fetch stays on that app's origin - scheme, host AND port: one NAS answers for a dozen apps on one address, a redirect to another port is another app (the same-origin idea from Sentinel #356). - The endpoint policy judges the app's address once instead of every hop: it is for base URLs and refused an icon link with a query, so SoulSync (/static/pwa-icon-192.png?v=...) showed no logo since #353. Live: Radarr, Sonarr and SoulSync logos from the LAN all arrive. test_fresh_install +2 (another port refused; a query icon fetched). Co-Authored-By: Claude Opus 5.5 --- src/services/setup_icons.py | 22 +++++++++++++--------- tests/test_fresh_install.py | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 9 deletions(-) diff --git a/src/services/setup_icons.py b/src/services/setup_icons.py index 4738cb90..cab58325 100644 --- a/src/services/setup_icons.py +++ b/src/services/setup_icons.py @@ -88,8 +88,8 @@ def icon_candidates(html: str, base: str) -> list[str]: # each redirect hop (redirects are followed here, not by httpx). A public # site's fetches stay on https and on hosts that resolve to public internet # addresses only (github.com/Radarr.png lands on avatars.githubusercontent.com, -# netflix.com names a CDN). A LAN app's stay on that app's own host and pass -# the endpoint policy (code scanning 221/222, 2026-11-14). +# netflix.com names a CDN). A LAN app's stay on that app's own origin (host and +# port) and pass the endpoint policy (code scanning 221/222, 2026-11-14). _MAX_HOPS = 3 @@ -129,17 +129,21 @@ async def _public_ok(url: str) -> bool: def _lan_ok(lan_base: str): - """The check for a LAN app: its own host, and the endpoint policy.""" + """The check for a LAN app: its own origin (scheme, host AND port: a + NAS answers for a dozen apps on one address, one per port), and the + endpoint policy.""" + from src.services.endpoint_policy import same_origin from src.services.media_server.jellyfin_connect import _allowed - host = httpx.URL(lan_base).host + verdict: dict = {} async def ok(url: str) -> bool: - try: - if httpx.URL(url).host != host: - return False - except (httpx.InvalidURL, ValueError, TypeError): + if not same_origin(url, lan_base): return False - return await _allowed(url) + # The policy judges the app's address once: it is for base URLs and + # refused an icon link with a query (SoulSync's /static/pwa-icon-192.png?v=...). + if "ok" not in verdict: + verdict["ok"] = await _allowed(lan_base) + return verdict["ok"] return ok diff --git a/tests/test_fresh_install.py b/tests/test_fresh_install.py index 6894d09f..8db4d011 100644 --- a/tests/test_fresh_install.py +++ b/tests/test_fresh_install.py @@ -340,6 +340,42 @@ def _lan_app(req): check("a LAN app's logo never leaves that app's host (no foreign icon link, no redirect away)", got is None and _asked and all(u.startswith("http://192.168.0.10:7878/") for u in _asked), _asked) +# One NAS, many apps: another port on the same address is another app. +_asked.clear() + + +def _other_port(req): + _asked.append(str(req.url)) + if req.url.port == 7878 and req.url.path.startswith("/Content/"): + return httpx.Response(302, headers={"location": "http://192.168.0.10:8096/Content/x.png"}) + if req.url.port == 7878 and req.url.path == "/": + return httpx.Response(200, text='') + if req.url.port == 7878: + return httpx.Response(404) + return httpx.Response(200, content=b"other-app", headers={"content-type": "image/png"}) + + +_forget_logos() +got = asyncio.run(setup_icons.service_logo("radarr", "http://192.168.0.10:7878", + transport=httpx.MockTransport(_other_port))) +check("a LAN app's logo never comes from another port of the same machine (another app)", + got is None and all(":7878/" in u for u in _asked), _asked) + + +def _query_icon(req): + if req.url.path == "/": + return httpx.Response(200, text='') + if req.url.path == "/static/pwa-icon-192.png" and req.url.query: + return httpx.Response(200, content=b"pwa", headers={"content-type": "image/png"}) + return httpx.Response(404) + + +_forget_logos() +got = asyncio.run(setup_icons.service_logo("soulsync", "http://192.168.0.10:12279", + transport=httpx.MockTransport(_query_icon))) +check("an icon link with a query on the app's own origin is fetched (SoulSync's ?v=)", + got == (b"pwa", "image/png"), got) + # Kept in the data folder: a new run answers without the network; a month # old copy is fetched again, and still answers when the site does not. import os as _os # noqa: E402 From f5abf9952cc1713ac9f695381ace5260b8908d30 Mon Sep 17 00:00:00 2001 From: Don Droid <127677734+Randomname653@users.noreply.github.com> Date: Sun, 15 Nov 2026 09:26:15 +0100 Subject: [PATCH 2/6] Backups stay copyable for the app's group: 0640, not reset to 0600 at every start The start-up pass set every SQLite file under data/ to 0600, the backups included: the backup written at 22:47 could be copied off the NAS share until the 23:43 restart turned it 0600 (2026-11-14), and a manual chmod would be undone by the next start. Now: - _secure_db_files gives files under data/backups 0640 (BACKUP_MODE); - the nightly DB backup writes its snapshot 0640; - the cache snapshot is written 0640, its folders 0750. The live database, its sidecars, the caches, the vector store and .env stay 0600 (a live SQLite file is never copied; .env holds the tokens). tests/test_backup_perms.py (POSIX modes, checked in CI) and test_backup_retention +1 (a new snapshot is 0640). Co-Authored-By: Claude Opus 5.5 --- src/database/connection.py | 15 +++++- src/services/cache_snapshot.py | 13 ++++++ src/services/scheduler.py | 6 +++ tests/test_backup_perms.py | 84 ++++++++++++++++++++++++++++++++++ tests/test_backup_retention.py | 6 +++ 5 files changed, 122 insertions(+), 2 deletions(-) create mode 100644 tests/test_backup_perms.py diff --git a/src/database/connection.py b/src/database/connection.py index 66ed3f77..a4950236 100644 --- a/src/database/connection.py +++ b/src/database/connection.py @@ -694,8 +694,17 @@ def _rebuild_from_model(conn, table) -> None: conn.exec_driver_sql(f'DROP TABLE "{aside}"') +# Backups: the owner and the group may read them (0640), so the NAS user in +# the app's group can copy a snapshot off the share; the world still cannot. +# This pass used to set them to 0600 at every start - a backup written at +# 22:47 was copyable until the 23:43 restart (2026-11-14). The live database +# and .env stay 0600: a live SQLite file is never copied, and .env holds the +# tokens. +BACKUP_MODE = 0o640 + + def _secure_db_files() -> None: - """Ensure SQLite files in data/ and .env are 0600 (POSIX only).""" + """Ensure SQLite files in data/ and .env are 0600, backups 0640 (POSIX only).""" import os import stat import logging as _logging @@ -711,10 +720,12 @@ def _secure_db_files() -> None: if not DATA_DIR.exists(): return + backups = (DATA_DIR / "backups").resolve() for ext in ("*.db", "*.sqlite3", "*.sqlite3-wal", "*.sqlite3-shm", "*.db-wal", "*.db-shm"): for p in DATA_DIR.rglob(ext): try: - os.chmod(p, stat.S_IRUSR | stat.S_IWUSR) + in_backups = backups in p.resolve().parents + os.chmod(p, BACKUP_MODE if in_backups else stat.S_IRUSR | stat.S_IWUSR) except FileNotFoundError: pass # a -wal/-shm sidecar checkpointed away mid-scan except OSError as e: diff --git a/src/services/cache_snapshot.py b/src/services/cache_snapshot.py index 7f0a53ea..f8400fde 100644 --- a/src/services/cache_snapshot.py +++ b/src/services/cache_snapshot.py @@ -93,6 +93,18 @@ def _snapshot_chroma(src: Path, dst: Path) -> int: return n +def _group_readable(root: Path) -> None: + """Files 0640, folders 0750, like the DB backup beside them: copyable by + the app's group off a NAS share, not by the world (POSIX only).""" + from src.database.connection import BACKUP_MODE + try: + os.chmod(root, 0o750) + for p in root.rglob("*"): + os.chmod(p, 0o750 if p.is_dir() else BACKUP_MODE) + except OSError as e: + logger.debug("[backup] could not open the cache snapshot to the group: %s", e) + + async def snapshot_caches(bdir: str) -> str: """Write backups/caches; a one-line summary for the backup task. Never raises: the DB backup already succeeded and stands on its own.""" @@ -120,6 +132,7 @@ async def snapshot_caches(bdir: str) -> str: bad.append(p.name) (tmp / "cache" / p.name).unlink(missing_ok=True) files = await run_chroma(_snapshot_chroma, chroma, tmp / "chromadb") if chroma.is_dir() else 0 + _group_readable(tmp) shutil.rmtree(old, ignore_errors=True) if final.exists(): final.rename(old) diff --git a/src/services/scheduler.py b/src/services/scheduler.py index 0069c4d7..76c30006 100644 --- a/src/services/scheduler.py +++ b/src/services/scheduler.py @@ -1584,6 +1584,12 @@ async def job_db_backup(): try: ok = await asyncio.to_thread(_snapshot_sqlite, db_path, dest) + if ok: + from src.database.connection import BACKUP_MODE + try: + os.chmod(dest, BACKUP_MODE) # copyable by the app's group (NAS share) + except OSError as e: + logger.debug("[backup] could not set %s to 0640: %s", dest, e) if not ok: os.remove(dest) task_monitor.error(task, "snapshot failed integrity check — discarded") diff --git a/tests/test_backup_perms.py b/tests/test_backup_perms.py new file mode 100644 index 00000000..e0fa1a9e --- /dev/null +++ b/tests/test_backup_perms.py @@ -0,0 +1,84 @@ +"""Backups are copyable by the app's group; the live database and .env are not. + +The start-up pass (connection._secure_db_files) set every SQLite file under +data/ to 0600, the backups included: a backup written at 22:47 could be +copied off the NAS share until the 23:43 restart (2026-11-14). Backups and +the cache snapshot are 0640 (folders 0750) now; the live database, its +sidecars and .env stay 0600. POSIX only: on Windows chmod sets nothing but +the read-only bit, so the checks run where the modes exist (CI, the NAS). + + python tests/test_backup_perms.py +""" +from _harness import check, TMP # noqa: I001 - first: temp stores + +import asyncio +import os +import sqlite3 +import stat + +import src.paths as paths +from src.config import settings +from src.database import connection +from src.services import cache_snapshot as cs + +POSIX = os.name == "posix" + + +def mode(p): + return stat.S_IMODE(os.stat(p).st_mode) + + +root = TMP / "perms" +data = root / "data" +for d in (data / "backups" / "caches" / "cache", data / "chromadb", data / "cache"): + d.mkdir(parents=True, exist_ok=True) + + +def db(p): + c = sqlite3.connect(p) + c.execute("create table if not exists t (v)") + c.commit() + c.close() + os.chmod(p, 0o644) + + +for p in (data / "curatarr.db", data / "cache" / "enrichment.db", data / "chromadb" / "chroma.sqlite3", + data / "backups" / "curatarr_20261114_214712.db", data / "backups" / "caches" / "cache" / "lyrics.db"): + db(p) +env = root / ".env" +env.write_text("JWT_SECRET=x\n", encoding="utf-8") + +_data, _env = paths.DATA_DIR, paths.ENV_FILE +paths.DATA_DIR, paths.ENV_FILE = data, env +try: + connection._secure_db_files() +finally: + paths.DATA_DIR, paths.ENV_FILE = _data, _env + +if POSIX: + check("the live database, a cache and the vector store stay 0600", + {mode(data / "curatarr.db"), mode(data / "cache" / "enrichment.db"), + mode(data / "chromadb" / "chroma.sqlite3")} == {0o600}) + check(".env stays 0600", mode(env) == 0o600) + check("a backup and the cache snapshot are 0640: the group may copy them", + mode(data / "backups" / "curatarr_20261114_214712.db") == 0o640 + and mode(data / "backups" / "caches" / "cache" / "lyrics.db") == 0o640) +else: + check("(Windows: file modes are POSIX-only; the pass ran without error)", True) + +# The cache snapshot is written group-readable from the start. +src_cache = root / "live" / "cache" +src_cache.mkdir(parents=True) +db(src_cache / "enrichment.db") +settings.ENRICHMENT_CACHE = str(src_cache / "enrichment.db") +settings.CHROMADB_PATH = str(root / "live" / "chromadb") +bdir = root / "nas-backups" +bdir.mkdir() +msg = asyncio.run(cs.snapshot_caches(str(bdir))) +check("the cache snapshot is written", (bdir / "caches" / "cache" / "enrichment.db").exists(), msg) +if POSIX: + check("...its files 0640, its folders 0750", + mode(bdir / "caches" / "cache" / "enrichment.db") == 0o640 + and mode(bdir / "caches") == 0o750 and mode(bdir / "caches" / "cache") == 0o750) + +check.done() diff --git a/tests/test_backup_retention.py b/tests/test_backup_retention.py index db6bceaf..b691ee67 100644 --- a/tests/test_backup_retention.py +++ b/tests/test_backup_retention.py @@ -82,6 +82,12 @@ check("room for the snapshot plus as much again: backup taken", res is not False and any(not n.startswith("curatarr_2026010") for n in snaps)) check("rotation keeps seven", len(snaps) == 7) +import os as _os # noqa: E402 +import stat as _stat # noqa: E402 +if _os.name == "posix": + newest = max(bdir.glob("curatarr_*.db"), key=lambda p: p.stat().st_mtime) + check("a new snapshot is 0640: the app's group may copy it off a NAS share", + _stat.S_IMODE(newest.stat().st_mode) == 0o640, oct(_stat.S_IMODE(newest.stat().st_mode))) # Short at first, enough once the oldest made way: the backup still happens. calls = [] From f021f15aee0ff5f988c8ab3a34eaf338c539d564 Mon Sep 17 00:00:00 2001 From: Don Droid <127677734+Randomname653@users.noreply.github.com> Date: Sun, 15 Nov 2026 09:33:28 +0100 Subject: [PATCH 3/6] Music: one song played is one play - copies and double stamps Reading the owner's music library whole stored copies: Plex gives every copy of a track (album, remaster, compilation) the same lastViewedAt second while its history holds one play ('Lovely Day' three times at 00:46:51, one of them without genres), and a song stored from the listing and from the history landed twice, the two stamps 147 s apart (the 90-second same-play rule is for video). - plex_sync.drop_music_copies: per song and second one listing entry stays (the one with a genre), before the three-in-a-second mark rule counts. - _same_play_s: a song's same-play window is its length (a history event without a length: 6 minutes); video keeps 90 s. Used where a history event meets the listing and the stored plays. - A history event of another copy of a listed song is that same play. - Schema 4 migration: per song and second one row stays (with genres, a play rather than 'marked'), and a second row of a song inside the first one's length goes. On a copy of the owner's backup: music plays from Plex 48,258 -> 40,204, 'marked' 628 -> 105 (137 groups of only marked copies now count as the play they were); Spotify, films, shows and anime untouched. tests/test_music_copies.py (11 checks: sync, history match, migration); test_single_marks pins 'generation 3 or later'. Co-Authored-By: Claude Opus 5.5 --- src/database/connection.py | 38 +++++++++++- src/services/plex_sync.py | 54 ++++++++++++++++- tests/test_music_copies.py | 121 +++++++++++++++++++++++++++++++++++++ tests/test_single_marks.py | 4 +- 4 files changed, 212 insertions(+), 5 deletions(-) create mode 100644 tests/test_music_copies.py diff --git a/src/database/connection.py b/src/database/connection.py index 66ed3f77..5cadde35 100644 --- a/src/database/connection.py +++ b/src/database/connection.py @@ -214,7 +214,10 @@ def checkpoint_and_dispose() -> None: # plays imported from Plex's history without a length count as played (2026-10-25). # 3 = episodes marked as played one after another (seconds apart, no play event) # are source "marked" too (2026-10-30). -SCHEMA_VERSION = 3 +# 4 = music read whole from Plex once: copies of one song at one second are one +# play, and a play stored twice from the listing and the history is one +# (2026-11-15). +SCHEMA_VERSION = 4 def _migrate_columns() -> None: @@ -527,6 +530,39 @@ def _migrate_columns() -> None: " AND player IS NULL AND media_type IN ('movie', 'show', 'anime'))" " SELECT a.id FROM v a JOIN v b ON b.user_id = a.user_id AND b.t = a.t" " AND b.p != a.p AND b.s BETWEEN a.s - 60 AND a.s + 60)") + if schema_was < 4 and "watch_history" in tables: + # The first read of a music library stored every COPY of a + # song Plex marked at the play's second (the album, the + # remaster, a compilation): 962 rows on the owner's server, + # 628 of them parked as "marked" by the three-in-a-second + # rule. One per song and second stays - the one with genres, + # a play (not "marked") - the others go. + conn.exec_driver_sql( + "CREATE TEMP TABLE _copies AS SELECT id, " + " ROW_NUMBER() OVER (g ORDER BY COALESCE(genres, '') = '', source IS NOT NULL, id) AS rn, " + " COUNT(*) OVER g AS n, source " # g unordered: the whole group, not a running count + " FROM watch_history WHERE media_type = 'music' " + " AND (source IS NULL OR source = 'marked') " + " WINDOW g AS (PARTITION BY user_id, LOWER(COALESCE(series_title, '')), " + " LOWER(title), viewed_at)") + conn.exec_driver_sql( + "UPDATE watch_history SET source = NULL WHERE id IN " + "(SELECT id FROM _copies WHERE rn = 1 AND n > 1 AND source = 'marked')") + conn.exec_driver_sql( + "DELETE FROM watch_history WHERE id IN (SELECT id FROM _copies WHERE rn > 1)") + conn.exec_driver_sql("DROP TABLE _copies") + # One play stored twice: the listing stamps a song at one end, + # the history at the other (147 s apart for a 4-minute track), + # and the 90-second rule took them for two. A second row of the + # same song inside the first one's length is that same play. + conn.exec_driver_sql( + "DELETE FROM watch_history WHERE id IN (" + " WITH v AS (SELECT id, user_id, plex_item_id AS p," + " CAST(strftime('%s', viewed_at) AS INTEGER) AS s," + " COALESCE(duration_ms, 0) / 1000 AS d" + " FROM watch_history WHERE media_type = 'music' AND source IS NULL)" + " SELECT b.id FROM v a JOIN v b ON b.user_id = a.user_id AND b.p = a.p" + " AND b.s > a.s AND b.s - a.s < MAX(90, a.d))") # Record the schema generation this boot brought the file to. A # future one-shot backfill keys on it (``if user_version < N``) # rather than on whether its column happened to be added just now. diff --git a/src/services/plex_sync.py b/src/services/plex_sync.py index 05d10872..ecabdb4a 100644 --- a/src/services/plex_sync.py +++ b/src/services/plex_sync.py @@ -480,6 +480,11 @@ def _drop_dead() -> None: item["_anilist_id"] = gid[10:] elif gid.startswith("mal://"): item["_mal_id"] = gid[6:] + if category == "music": + copies = drop_music_copies(items) + if copies: + logger.info("Library %r: %d copies of songs played once (same song, same " + "second) left out", sec_title, copies) marked = mark_bulk_marked(items) if marked: logger.info("Library %r: %d item(s) marked as played in Plex (one second " @@ -855,7 +860,7 @@ def _template(rk: str): if entry.get("_history_extra"): vts = int(viewed_at_ts) - if any(abs(t - vts) <= _SAME_PLAY_S for t in near.get((user.id, rating_key), ())): + if any(abs(t - vts) <= _same_play_s(entry) for t in near.get((user.id, rating_key), ())): skipped += 1 continue if not entry.get("duration") or not entry.get("Genre"): @@ -1338,6 +1343,44 @@ def follow_libraries(section_keys: list) -> None: _MARKED_MIN = 3 +def _song_key(artist, title) -> tuple: + return ((artist or "").strip().lower(), (title or "").strip().lower()) + + +def drop_music_copies(items: list) -> int: + """One song played, every copy of it marked: Plex gives each copy of a + track in the library (the album, the remaster, a compilation) the same + lastViewedAt second, while its history holds one play. The owner's + first music read stored 962 such copies (2026-11-15: "Lovely Day" three + times at 00:46:51). Keep one per song and second - the one Plex knows + a genre for - and drop the others from ``items``; returns how many.""" + groups: dict = {} + for it in items: + ts = it.get("lastViewedAt") + if ts and not it.get("_in_progress"): + key = (*_song_key(it.get("grandparentTitle"), it.get("title")), int(ts)) + groups.setdefault(key, []).append(it) + drop = set() + for group in groups.values(): + if len(group) > 1: + keep = next((it for it in group if it.get("Genre")), group[0]) + drop.update(id(it) for it in group if it is not keep) + if drop: + items[:] = [it for it in items if id(it) not in drop] + return len(drop) + + +def _same_play_s(entry: dict) -> int: + """How far apart the listing's and the history's stamp of ONE play may + lie. Plex truncates seconds for video; for a song the two stamps are the + start and the end of it (147 s apart for a 4-minute track, measured on + the owner's server), so the window is the song's length.""" + if entry.get("type") == "track" or entry.get("_category") == "music": + # a history event carries no length: a song's typical one + return max(_SAME_PLAY_S, int(entry.get("duration") or 360_000) // 1000) + return _SAME_PLAY_S + + def mark_bulk_marked(items: list) -> int: """Flag the listed items whose lastViewedAt they share with at least ``_MARKED_MIN - 1`` others of the same library (``_marked``).""" @@ -1398,10 +1441,13 @@ def _owner_history_entries(events: list, lib_configs: dict, listing: list, Events older than ``backfill_before`` are marked ``_backfill``: recovered history, not news.""" listed: dict = {} + songs: dict = {} for e in listing: ts = e.get("lastViewedAt") or e.get("viewedAt") if e.get("ratingKey") and ts: listed.setdefault(str(e["ratingKey"]), []).append((int(ts), e)) + if e.get("_category") == "music": + songs.setdefault(_song_key(e.get("grandparentTitle"), e.get("title")), []).append((int(ts), e)) out: list = [] for ev in events: base = _member_entry(dict(zip(_HISTORY_EVENT_KEYS, ev)), lib_configs, 1) @@ -1409,8 +1455,12 @@ def _owner_history_entries(events: list, lib_configs: dict, listing: list, continue vts = base["viewedAt"] same = listed.get(base["ratingKey"], ()) - if any(abs(t - vts) <= _SAME_PLAY_S for t, _ in same): + if any(abs(t - vts) <= _same_play_s(e) for t, e in same): continue + if base["_category"] == "music" and any( + abs(t - vts) <= _same_play_s(e) + for t, e in songs.get(_song_key(base.get("grandparentTitle"), base.get("title")), ())): + continue # the play of another copy of this song, already listed if same: entry = {k: v for k, v in same[0][1].items() if k not in _LISTING_ONLY_KEYS} entry.update(lastViewedAt=vts, viewedAt=vts) diff --git a/tests/test_music_copies.py b/tests/test_music_copies.py new file mode 100644 index 00000000..99b7c685 --- /dev/null +++ b/tests/test_music_copies.py @@ -0,0 +1,121 @@ +"""One song played is one play (plex_sync + the schema 4 migration). + +Reading the owner's music library whole (2026-11-15) stored 962 copies of +songs played once: Plex gives every copy of a track (album, remaster, +compilation) the same lastViewedAt second, while its history holds one +play ("Lovely Day" three times at 00:46:51). And a song stored from the +listing and from the history landed twice, the two stamps 147 s apart - the +90-second same-play rule is for video. On a copy of the owner's backup the +migration took 8,577 such rows out of 400k and left Spotify and video alone. + + python tests/test_music_copies.py +""" +from _harness import check # noqa: I001 - first: temp stores + +from datetime import datetime, timedelta + +from sqlalchemy import text +from sqlalchemy.orm import sessionmaker + +import src.database.connection as conn_mod +import src.services.plex_sync as ps +from src.database.models import Base, User, WatchHistoryEntry as W + +# ── the sync keeps one copy per song and second ───────────────────────────── +T = 1794703611 +items = [ + {"ratingKey": "1007446", "lastViewedAt": T, "title": "Lovely Day", "grandparentTitle": "Bill Withers", + "Genre": [{"tag": "Soul"}], "_category": "music"}, + {"ratingKey": "1007354", "lastViewedAt": T, "title": "Lovely Day", "grandparentTitle": "Bill Withers", + "_category": "music"}, + {"ratingKey": "1007264", "lastViewedAt": T, "title": "lovely day ", "grandparentTitle": "BILL WITHERS", + "_category": "music"}, + {"ratingKey": "2001", "lastViewedAt": T, "title": "Another Song", "grandparentTitle": "Bill Withers", + "_category": "music"}, + {"ratingKey": "3001", "lastViewedAt": T + 400, "title": "Lovely Day", "grandparentTitle": "Bill Withers", + "_category": "music"}, +] +n = ps.drop_music_copies(items) +keys = [i["ratingKey"] for i in items] +check("three copies of one song at one second are one play, the one with a genre kept", + n == 2 and "1007446" in keys and "1007354" not in keys and "1007264" not in keys, keys) +check("another song at that second, and the same song later, stay", "2001" in keys and "3001" in keys) +check("...so the three-in-a-second mark rule no longer counts copies", + ps.mark_bulk_marked(items) == 0) + +# ── one play from the listing and the history is one ──────────────────────── +song = {"type": "track", "_category": "music", "duration": 251_133} +check("a song's same-play window is its length; video keeps 90 s; a history event without a length a song's", + ps._same_play_s(song) == 251 and ps._same_play_s({"type": "movie", "duration": 7_200_000}) == 90 + and ps._same_play_s({"type": "track"}) == 360) + +listing = [{"ratingKey": "1015214", "lastViewedAt": T, "title": "Cozy", "grandparentTitle": "Next", + "type": "track", "_category": "music", "duration": 251_133}, + {"ratingKey": "1007446", "lastViewedAt": T, "title": "Lovely Day", "grandparentTitle": "Bill Withers", + "type": "track", "_category": "music", "duration": 256_159}] +libs = {"14": ("music", "artist", "Music")} + + +def ev(rk, at, title, artist): + d = {"ratingKey": rk, "viewedAt": at, "type": "track", "title": title, "grandparentTitle": artist, + "librarySectionID": "14"} + return tuple(d.get(k) for k in ps._HISTORY_EVENT_KEYS) + + +extra = ps._owner_history_entries( + [ev("1015214", T + 147, "Cozy", "Next"), # the same play, its other end + ev("1007264", T + 30, "Lovely Day", "Bill Withers"), # the play, on another copy + ev("1015214", T + 2000, "Cozy", "Next")], libs, listing) # a second play, later +check("the history's stamp of a listed song, 147 s off, is the same play", + not any(e["viewedAt"] == T + 147 for e in extra), extra) +check("a play the history holds on another copy of a listed song is the same play", + not any(e["ratingKey"] == "1007264" for e in extra), extra) +check("a later play of the song is its own", [e["viewedAt"] for e in extra] == [T + 2000], extra) + +# ── the migration repairs what the first read stored ──────────────────────── +from _checks import memory_engine # noqa: E402 +eng = memory_engine() +conn_mod.engine = eng +Base.metadata.create_all(bind=eng) +with eng.begin() as c: + c.exec_driver_sql("PRAGMA user_version = 3") +S = sessionmaker(bind=eng) +db = S() +db.add(User(id=1, plex_user_id="1", plex_username="owner", is_admin=True)) +at = datetime(2026, 11, 15, 0, 46, 51) + + +def row(rk, title, artist, when, source=None, genres=None, dur=256_000, mt="music"): + db.add(W(user_id=1, plex_user_id="1", plex_item_id=rk, title=title, series_title=artist, media_type=mt, + viewed_at=when, source=source, genres=genres, duration_ms=dur, completed=True)) + + +row("1007446", "Lovely Day", "Bill Withers", at, "marked", "Soul") +row("1007354", "Lovely Day", "Bill Withers", at, "marked", "Soul") +row("1007264", "Lovely Day", "Bill Withers", at, None, None) +row("1015214", "Cozy", "Next", at + timedelta(minutes=10), None, "R&B", 251_133) +row("1015214", "Cozy", "Next", at + timedelta(minutes=10, seconds=147), None, "R&B", 251_133) +row("1015214", "Cozy", "Next", at + timedelta(minutes=30), None, "R&B", 251_133) # played again later +row("sp1", "Lovely Day", "Bill Withers", at, "spotify", "Soul") # Spotify: not a copy +row("e1", "Ep 1", "Show", at, "marked", mt="show") +row("e2", "Ep 2", "Show", at, "marked", mt="show") +db.commit() +db.close() +conn_mod._migrate_columns() +db = S() +lovely = db.query(W).filter(W.title == "Lovely Day", W.source.isnot("spotify") | W.source.is_(None)).all() +plex_lovely = [r for r in lovely if r.source != "spotify"] +check("the three copies are one row, with its genre, counted as a play", + len(plex_lovely) == 1 and plex_lovely[0].genres == "Soul" and plex_lovely[0].source is None, + [(r.plex_item_id, r.source, r.genres) for r in plex_lovely]) +cozy = sorted(r.viewed_at for r in db.query(W).filter(W.title == "Cozy").all()) +check("one play stored twice 147 s apart is one; the play twenty minutes later stays", + cozy == [at + timedelta(minutes=10), at + timedelta(minutes=30)], cozy) +check("Spotify plays and video marks are left alone", + db.query(W).filter(W.source == "spotify").count() == 1 + and db.query(W).filter(W.media_type == "show").count() == 2) +check("the migration runs once (schema generation 4)", + db.execute(text("PRAGMA user_version")).scalar() == conn_mod.SCHEMA_VERSION >= 4) +db.close() + +check.done() diff --git a/tests/test_single_marks.py b/tests/test_single_marks.py index 1ea3c167..5a8a5312 100644 --- a/tests/test_single_marks.py +++ b/tests/test_single_marks.py @@ -88,8 +88,8 @@ def row(key, series, at, **kw): check("the run of marks is marked; an evening's two episodes, plays with a player and one item " "played twice are not", marked == {f"gs{e}" for e in (8, 5, 7, 1, 3, 4)}) -check("the migration is generation 3", - db.execute(text("PRAGMA user_version")).scalar() == conn_mod.SCHEMA_VERSION == 3) +check("the migration brings the file to the current generation (3 or later)", + db.execute(text("PRAGMA user_version")).scalar() == conn_mod.SCHEMA_VERSION >= 3) db.close() # ── played time: a finished row keeps the minutes really watched ──────────── From 6a7ae49823bdbbd12cae11fd24debda96348e580 Mon Sep 17 00:00:00 2001 From: Don Droid <127677734+Randomname653@users.noreply.github.com> Date: Sun, 15 Nov 2026 09:37:26 +0100 Subject: [PATCH 4/6] Arr discovery: each redirect hop on the app's own origin, port included #362 followed an arr's login redirect by hand on the asked host; one NAS answers for a dozen apps, one per port. The probe now uses the LAN logo fetch's check (setup_icons._lan_ok): same scheme, host and port, the endpoint policy judging the app's address once. Live: Radarr, Sonarr and SoulSync found as before. Co-Authored-By: Claude Opus 5.5 --- src/services/arr_find.py | 18 +++++------------- 1 file changed, 5 insertions(+), 13 deletions(-) diff --git a/src/services/arr_find.py b/src/services/arr_find.py index e92a2cff..44dd9f43 100644 --- a/src/services/arr_find.py +++ b/src/services/arr_find.py @@ -53,19 +53,11 @@ def which_app(html: str) -> Optional[str]: async def _probe(client: httpx.AsyncClient, url: str) -> Optional[str]: # An app's login redirect is followed by hand, each hop on the asked - # host and its origin through the endpoint policy, as the wizard's logo - # fetch does: the policy judged the first address, the answer names the - # next. The origin, because the login hop carries a ?returnUrl= query. - from src.services.media_server.jellyfin_connect import _allowed - from src.services.setup_icons import _get - host = httpx.URL(url).host - - async def ok(hop: str) -> bool: - try: - u = httpx.URL(hop) - except (httpx.InvalidURL, ValueError, TypeError): - return False - return u.host == host and await _allowed(str(u.copy_with(path="/", query=None, fragment=None))) + # app's origin (host AND port: one NAS, an app per port) with the + # endpoint policy judging that address, as the wizard's LAN logo fetch + # does (setup_icons._lan_ok). + from src.services.setup_icons import _get, _lan_ok + ok = _lan_ok(url) r = await _get(client, f"{url}/", ok) if r is None or r.status_code >= 400: From 9f95151a3a3d311109bc0a35a92d2ae76664b6ff Mon Sep 17 00:00:00 2001 From: Don Droid <127677734+Randomname653@users.noreply.github.com> Date: Sun, 15 Nov 2026 09:37:48 +0100 Subject: [PATCH 5/6] CHANGELOG: Unreleased - music copies, backup permissions, LAN origins, the bots' three Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7d8c9baf..48f2fa7e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,25 @@ Condensed release history, newest first. ## Unreleased -Nothing yet. +**One song played is one play.** Plex gives every copy of a track in the library (the album, the +remaster, a compilation) the same "last played" second while its history holds one play, and a song +stored from the library listing and from the history landed twice when the two stamps lay more than +90 seconds apart (a song's two ends; the rule was made for video). Per song and second one copy is +kept now (the one with genres), a song's same-play window is its length, and a one-time repair takes +the copies out of what was stored: on the owner's server 8,577 rows of about 400,000, Spotify plays +and video untouched. The taste profile had counted them. + +**Backups stay copyable.** Every start set all SQLite files under `data/` to 0600, the backups +included, so a NAS user in the app's group could copy a backup only until the next restart. +Backups and the cache snapshot are 0640 now; the live database and `.env` stay 0600. + +**LAN apps keep to their own address, port included.** The setup's logo fetch and the arr +discovery follow a redirect only on the app's own scheme, host and port (one NAS, an app per port). +SoulSync's logo shows again: its icon link carries a `?v=` query, which the address check refused. + +**From the bots:** the setup wizard moves focus to the new step's heading, the arr discovery checks +each redirect hop, and the Wrap-Up's comebacks find a title's last earlier play through the title +indexes. --- From ce4ff43f010920945c02247e2044502f58762da6 Mon Sep 17 00:00:00 2001 From: Don Droid <127677734+Randomname653@users.noreply.github.com> Date: Sun, 15 Nov 2026 09:56:42 +0100 Subject: [PATCH 6/6] Backups: no tokens inside, 0600 by default, the cache snapshot opt-in Reworked after a look at how comparable self-hosted apps do it (Sonarr, Tautulli, Plex, Home Assistant, Immich, Jellyfin): they back up what cannot be rebuilt (database, config), skip caches, keep 0600, and Plex keeps its token out of its database backups. - scheduler._strip_secrets: the backup copy's users.plex_token (and the session tokens) are blanked with secure_delete on, the copy left one file and checked again. A restore asks each member to sign in once (the token is refreshed at every sign-in); the server's token lives in .env. - Modes: backups 0600/0700 like the database (connection.backup_modes); BACKUP_GROUP_READABLE=true makes them 0640/0750 for a NAS user in the app's group, and the start-up pass follows the setting instead of forcing 0600. The live database and .env stay 0600. - BACKUP_CACHES (default false): the cache and vector-store snapshot from 1.2.0 only when asked for; switched off, a snapshot already written is removed. The demo builder names both settings when they are missing. - Both settings env-only (.env.example documents them). tests/test_backup_perms.py reworked (tokens gone from the file bytes, live DB keeps them, modes per setting, cache snapshot off/on/removed); test_backup_retention expects 0600; test_cache_snapshot turns the option on. Co-Authored-By: Claude Opus 5.5 --- .env.example | 7 +++ CHANGELOG.md | 10 ++- docs/screenshots/README.md | 4 +- scripts/demo/build_demo.py | 8 ++- src/config.py | 9 +++ src/database/connection.py | 19 +++--- src/services/cache_snapshot.py | 34 ++++++---- src/services/scheduler.py | 42 +++++++++++-- tests/test_backup_perms.py | 112 +++++++++++++++++++++++---------- tests/test_backup_retention.py | 4 +- tests/test_cache_snapshot.py | 1 + 11 files changed, 184 insertions(+), 66 deletions(-) diff --git a/.env.example b/.env.example index 063161db..a582fb71 100644 --- a/.env.example +++ b/.env.example @@ -15,6 +15,13 @@ FIRST_RUN=true # Ask GitHub (anonymously, at most hourly) whether a newer build exists; # admins then see "Update available" under the sidebar. Sends no library data. UPDATE_CHECK=true +# The nightly DB backup (data/backups) keeps users' Plex tokens out and is +# 0600 like the database; true makes it 0640, readable by the app's group +# (a NAS user in that group copying backups off a share). +BACKUP_GROUP_READABLE=false +# Also keep one snapshot of the caches and the vector store with the nightly +# backup (~2 GB on a large library; they are rebuilt from their sources). +BACKUP_CACHES=false # ── Security (required) ──────────────────────────────────────────────────── # Long random string; the setup wizard generates one for you. diff --git a/CHANGELOG.md b/CHANGELOG.md index 48f2fa7e..0c858872 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,9 +14,13 @@ kept now (the one with genres), a song's same-play window is its length, and a o the copies out of what was stored: on the owner's server 8,577 rows of about 400,000, Spotify plays and video untouched. The taste profile had counted them. -**Backups stay copyable.** Every start set all SQLite files under `data/` to 0600, the backups -included, so a NAS user in the app's group could copy a backup only until the next restart. -Backups and the cache snapshot are 0640 now; the live database and `.env` stay 0600. +**Backups carry no tokens, and the cache snapshot is opt-in.** The nightly DB backup blanks the +users' Plex tokens in its copy (overwriting their bytes); a restore asks each member to sign in once, +the way Plex keeps its token out of its own database backups. Backups stay 0600 like the database; +`BACKUP_GROUP_READABLE=true` makes them 0640 for a NAS user in the app's group, and the start-up pass +no longer undoes that. The cache and vector-store snapshot from 1.2.0 is off by default now +(`BACKUP_CACHES=true` keeps it); switched off, the snapshot already written is removed. Like the +other self-hosted apps, the backup holds what cannot be rebuilt: the database. **LAN apps keep to their own address, port included.** The setup's logo fetch and the arr discovery follow a redirect only on the app's own scheme, host and port (one NAS, an app per port). diff --git a/docs/screenshots/README.md b/docs/screenshots/README.md index 7c9443b7..f60acb4b 100644 --- a/docs/screenshots/README.md +++ b/docs/screenshots/README.md @@ -26,7 +26,9 @@ python scripts/demo/build_demo.py --source as the database, and the nightly cache snapshot (`backups/caches`: the enrichment cache, music index, lyrics, anime maps and the vector store), both made with SQLite's backup API, so the demo has today's library and - today's schema. A running install's own files are never copied: they + today's schema. The source install needs `BACKUP_CACHES=true` in its + `.env` (the snapshot is off by default) and, to copy backups off a share, + `BACKUP_GROUP_READABLE=true`. A running install's own files are never copied: they are open, and a share refuses them. Each copied database is checked. 3. **Its own `.env`:** a fresh JWT secret; from your `.env` only the model names, Ollama, the metadata keys, and Radarr/Sonarr (read only, for the diff --git a/scripts/demo/build_demo.py b/scripts/demo/build_demo.py index 7fd28fd2..a0209025 100644 --- a/scripts/demo/build_demo.py +++ b/scripts/demo/build_demo.py @@ -9,6 +9,9 @@ backup API and integrity-checked) becomes the demo's database, so the demo always has today's library and today's schema, never an old copy that is missing columns. CURATARR_DEMO_SOURCE may hold it instead of --source. +The source install needs BACKUP_CACHES=true (the cache snapshot) and, to +read its backups over a share as a member of the app's group, +BACKUP_GROUP_READABLE=true in its .env. Stages, in order (--stages picks some): @@ -188,8 +191,9 @@ def stage_fetch(base: Path, source: str) -> None: # cannot be copied safely (a share refuses them outright). snap = src / "backups" / "caches" if not (snap / "cache").is_dir(): - sys.exit(f"no cache snapshot in {snap} - it is written with the nightly DB backup; run it now " - "as the admin: Activity -> Scheduled -> DB backup -> Run now") + sys.exit(f"no cache snapshot in {snap}: set BACKUP_CACHES=true (and BACKUP_GROUP_READABLE=true " + "to copy backups off a share) in the source install's .env, then run the backup as the " + "admin: Activity -> Scheduled -> DB backup -> Run now") for sub in ("cache", "chromadb"): if (snap / sub).is_dir(): say(f"fetch: {sub}/ from the cache snapshot ...") diff --git a/src/config.py b/src/config.py index 21442302..c657de51 100644 --- a/src/config.py +++ b/src/config.py @@ -376,6 +376,15 @@ def _blank_url_falls_back_to_default(cls, v, info): # Ask GitHub (anonymously, hourly) whether a newer build is published; # admins then see "Update available" under the sidebar (services/update_check.py). UPDATE_CHECK: bool = True + # The nightly DB backup (data/backups) holds no tokens: users' Plex tokens + # are blanked in the copy. Its files are 0600 like the live database; + # true makes them 0640, readable by the app's group - for a NAS user in + # that group who copies them off a share (scripts/demo/build_demo.py). + BACKUP_GROUP_READABLE: bool = False + # Also keep ONE snapshot of the caches and the vector store next to the + # DB backup (backups/caches, ~2 GB on a large library). They are rebuilt + # from their sources; only the demo builder reads them. + BACKUP_CACHES: bool = False # ── API surface hardening ──────────────────────────────────────────────── # Pass 97: Swagger / ReDoc are off by default. Curatarr binds to diff --git a/src/database/connection.py b/src/database/connection.py index afb48006..92d3cbbb 100644 --- a/src/database/connection.py +++ b/src/database/connection.py @@ -730,17 +730,18 @@ def _rebuild_from_model(conn, table) -> None: conn.exec_driver_sql(f'DROP TABLE "{aside}"') -# Backups: the owner and the group may read them (0640), so the NAS user in -# the app's group can copy a snapshot off the share; the world still cannot. -# This pass used to set them to 0600 at every start - a backup written at -# 22:47 was copyable until the 23:43 restart (2026-11-14). The live database -# and .env stay 0600: a live SQLite file is never copied, and .env holds the -# tokens. -BACKUP_MODE = 0o640 +def backup_modes() -> tuple: + """(file mode, folder mode) for what the nightly backup writes: 0600/0700 + like the database, or 0640/0750 when BACKUP_GROUP_READABLE opens them to + the app's group (a NAS user copying them off a share). The backups carry + no tokens (scheduler._strip_secrets); the live database and .env stay + 0600 either way.""" + return (0o640, 0o750) if settings.BACKUP_GROUP_READABLE else (0o600, 0o700) def _secure_db_files() -> None: - """Ensure SQLite files in data/ and .env are 0600, backups 0640 (POSIX only).""" + """Ensure SQLite files in data/ and .env are 0600; backups follow + backup_modes() (POSIX only).""" import os import stat import logging as _logging @@ -761,7 +762,7 @@ def _secure_db_files() -> None: for p in DATA_DIR.rglob(ext): try: in_backups = backups in p.resolve().parents - os.chmod(p, BACKUP_MODE if in_backups else stat.S_IRUSR | stat.S_IWUSR) + os.chmod(p, backup_modes()[0] if in_backups else stat.S_IRUSR | stat.S_IWUSR) except FileNotFoundError: pass # a -wal/-shm sidecar checkpointed away mid-scan except OSError as e: diff --git a/src/services/cache_snapshot.py b/src/services/cache_snapshot.py index f8400fde..4bc1f604 100644 --- a/src/services/cache_snapshot.py +++ b/src/services/cache_snapshot.py @@ -4,7 +4,8 @@ enrichment work lives beside it: the enrichment cache, the music index, the lyrics, the anime maps (data/cache/*.db) and the vector store (data/chromadb). Weeks of API calls and GPU time, with no restore point but -a hand-made copy. After the DB backup, this keeps ONE consistent snapshot of +a hand-made copy. With BACKUP_CACHES on (off by default: they are rebuilt +from their sources), the DB backup is followed by ONE consistent snapshot of them in backups/caches/ (the newest only: they are large and rebuilt from the same sources): @@ -93,21 +94,32 @@ def _snapshot_chroma(src: Path, dst: Path) -> int: return n -def _group_readable(root: Path) -> None: - """Files 0640, folders 0750, like the DB backup beside them: copyable by - the app's group off a NAS share, not by the world (POSIX only).""" - from src.database.connection import BACKUP_MODE +def _set_modes(root: Path) -> None: + """The DB backup's modes (connection.backup_modes): 0600/0700, or + 0640/0750 when BACKUP_GROUP_READABLE opens backups to the app's group.""" + from src.database.connection import backup_modes + fmode, dmode = backup_modes() try: - os.chmod(root, 0o750) + os.chmod(root, dmode) for p in root.rglob("*"): - os.chmod(p, 0o750 if p.is_dir() else BACKUP_MODE) + os.chmod(p, dmode if p.is_dir() else fmode) except OSError as e: - logger.debug("[backup] could not open the cache snapshot to the group: %s", e) + logger.debug("[backup] could not set the cache snapshot's modes: %s", e) async def snapshot_caches(bdir: str) -> str: - """Write backups/caches; a one-line summary for the backup task. Never - raises: the DB backup already succeeded and stands on its own.""" + """Write backups/caches when BACKUP_CACHES is on; a one-line summary for + the backup task ("" when off). Switched off, a snapshot left from before + is removed (it is ~2 GB). Never raises: the DB backup already succeeded + and stands on its own.""" + from src.config import settings + if not settings.BACKUP_CACHES: + old = Path(bdir) / DIR + if old.exists(): + shutil.rmtree(old, ignore_errors=True) + logger.info("[backup] cache snapshot removed (BACKUP_CACHES is off)") + return "caches: old snapshot removed (BACKUP_CACHES off)" + return "" from src.services.scheduler import _free_bytes from src.vector_store.chromadb_wrapper import run_chroma base = Path(bdir) @@ -132,7 +144,7 @@ async def snapshot_caches(bdir: str) -> str: bad.append(p.name) (tmp / "cache" / p.name).unlink(missing_ok=True) files = await run_chroma(_snapshot_chroma, chroma, tmp / "chromadb") if chroma.is_dir() else 0 - _group_readable(tmp) + _set_modes(tmp) shutil.rmtree(old, ignore_errors=True) if final.exists(): final.rename(old) diff --git a/src/services/scheduler.py b/src/services/scheduler.py index 76c30006..a7e3ad0a 100644 --- a/src/services/scheduler.py +++ b/src/services/scheduler.py @@ -1507,6 +1507,31 @@ def _snapshot_sqlite(db_path: str, dest: str) -> bool: chk.close() +# Secrets a backup must not carry. Users' Plex tokens are refreshed at every +# sign-in, so a restored database asks each member to sign in once; the +# server's own token lives in .env, never in the database. Plex keeps its +# token out of its database backups the same way. +_SECRET_COLUMNS = (("users", "plex_token"), ("sessions", "access_token"), ("sessions", "refresh_token")) + + +def _strip_secrets(dest: str) -> bool: + """Blank the token columns in a backup copy, overwriting the old bytes + (secure_delete), and leave it one file (out of WAL mode). True when the + copy still checks.""" + con = sqlite_connect(dest) + try: + con.execute("PRAGMA journal_mode=DELETE") + con.execute("PRAGMA secure_delete=ON") + tables = {t for (t,) in con.execute("SELECT name FROM sqlite_master WHERE type='table'")} + for table, col in _SECRET_COLUMNS: + if table in tables and col in {r[1] for r in con.execute(f'PRAGMA table_info("{table}")')}: # nosec B608 - literals above + con.execute(f'UPDATE "{table}" SET "{col}" = NULL WHERE "{col}" IS NOT NULL') # nosec B608 - literals above + con.commit() + return (con.execute("PRAGMA quick_check(1)").fetchone() or ["?"])[0] == "ok" + finally: + con.close() + + def _free_bytes(path: str) -> int: import shutil return shutil.disk_usage(path).free @@ -1585,11 +1610,13 @@ async def job_db_backup(): try: ok = await asyncio.to_thread(_snapshot_sqlite, db_path, dest) if ok: - from src.database.connection import BACKUP_MODE + ok = await asyncio.to_thread(_strip_secrets, dest) + if ok: + from src.database.connection import backup_modes try: - os.chmod(dest, BACKUP_MODE) # copyable by the app's group (NAS share) + os.chmod(dest, backup_modes()[0]) except OSError as e: - logger.debug("[backup] could not set %s to 0640: %s", dest, e) + logger.debug("[backup] could not set the mode of %s: %s", dest, e) if not ok: os.remove(dest) task_monitor.error(task, "snapshot failed integrity check — discarded") @@ -1602,10 +1629,13 @@ async def job_db_backup(): size_mb = os.path.getsize(dest) / (1024 * 1024) summary = f"{os.path.basename(dest)} ({size_mb:.1f}MB) · kept {min(len(snaps), KEEP)} · dropped {dropped}" - # The caches and the vector store beside it: one snapshot, the newest - # (services/cache_snapshot). Its failure never fails this backup. + # The caches and the vector store beside it, when the operator asked + # for them (BACKUP_CACHES): one snapshot, the newest. Its failure never + # fails this backup. from src.services.cache_snapshot import snapshot_caches - summary += " · " + await snapshot_caches(bdir) + cache_note = await snapshot_caches(bdir) + if cache_note: + summary += " · " + cache_note task_monitor.done(task, summary) logger.info("[scheduler] DB backup OK: %s", summary) except Exception as e: diff --git a/tests/test_backup_perms.py b/tests/test_backup_perms.py index e0fa1a9e..7165d4f8 100644 --- a/tests/test_backup_perms.py +++ b/tests/test_backup_perms.py @@ -1,11 +1,17 @@ -"""Backups are copyable by the app's group; the live database and .env are not. +"""What the nightly backup may carry, and who may read it. -The start-up pass (connection._secure_db_files) set every SQLite file under -data/ to 0600, the backups included: a backup written at 22:47 could be -copied off the NAS share until the 23:43 restart (2026-11-14). Backups and -the cache snapshot are 0640 (folders 0750) now; the live database, its -sidecars and .env stay 0600. POSIX only: on Windows chmod sets nothing but -the read-only bit, so the checks run where the modes exist (CI, the NAS). +* No tokens: users' Plex tokens are blanked in the backup copy, and their + bytes overwritten (secure_delete) - a restore asks each member to sign in + once, as Plex keeps its own token out of its database backups. +* 0600 like the live database, unless the operator sets + BACKUP_GROUP_READABLE (0640, folders 0750) to copy backups off a NAS + share. The start-up pass used to force every backup to 0600 whatever was + wanted; it now follows the same setting. The live database and .env stay + 0600 always. +* The cache snapshot only with BACKUP_CACHES; switched off, an old one goes. + +POSIX modes are checked where they exist (CI, the NAS); on Windows chmod +sets only the read-only bit. python tests/test_backup_perms.py """ @@ -20,14 +26,42 @@ from src.config import settings from src.database import connection from src.services import cache_snapshot as cs +from src.services import scheduler as sched POSIX = os.name == "posix" +TOKEN = "zQ7plexTokenAbc123xy" def mode(p): return stat.S_IMODE(os.stat(p).st_mode) +# ── tokens stay out of the backup ─────────────────────────────────────────── +src_db = TMP / "live.db" +c = sqlite3.connect(src_db) +c.execute("PRAGMA journal_mode=WAL") +c.execute("create table users (id integer primary key, plex_username text, plex_token text)") +c.execute("create table sessions (id integer primary key, access_token text, refresh_token text)") +c.execute("insert into users (plex_username, plex_token) values ('owner', ?), ('member', ?)", (TOKEN, TOKEN[::-1])) +c.commit() +c.close() +dest = TMP / "backup.db" +check("the backup copy is made and checks", sched._snapshot_sqlite(str(src_db), str(dest))) +check("...its tokens blanked and the copy still checks", sched._strip_secrets(str(dest))) +c = sqlite3.connect(f"file:{dest}?mode=ro", uri=True) +check("no user keeps a Plex token in the backup; the users themselves stay", + c.execute("select count(*) from users where plex_token is not null").fetchone()[0] == 0 + and c.execute("select count(*) from users").fetchone()[0] == 2) +c.close() +blob = dest.read_bytes() +check("the token's bytes are gone from the file, not just unlinked (secure_delete)", + TOKEN.encode() not in blob and TOKEN[::-1].encode() not in blob) +check("the backup is one file (no -wal beside it)", not (TMP / "backup.db-wal").exists()) +c = sqlite3.connect(f"file:{src_db}?mode=ro", uri=True) +check("the live database keeps its tokens", c.execute("select count(*) from users where plex_token is not null").fetchone()[0] == 2) +c.close() + +# ── modes ─────────────────────────────────────────────────────────────────── root = TMP / "perms" data = root / "data" for d in (data / "backups" / "caches" / "cache", data / "chromadb", data / "cache"): @@ -42,43 +76,57 @@ def db(p): os.chmod(p, 0o644) -for p in (data / "curatarr.db", data / "cache" / "enrichment.db", data / "chromadb" / "chroma.sqlite3", - data / "backups" / "curatarr_20261114_214712.db", data / "backups" / "caches" / "cache" / "lyrics.db"): +backup = data / "backups" / "curatarr_20261114_214712.db" +for p in (data / "curatarr.db", data / "cache" / "enrichment.db", backup, + data / "backups" / "caches" / "cache" / "lyrics.db"): db(p) env = root / ".env" env.write_text("JWT_SECRET=x\n", encoding="utf-8") -_data, _env = paths.DATA_DIR, paths.ENV_FILE -paths.DATA_DIR, paths.ENV_FILE = data, env -try: - connection._secure_db_files() -finally: - paths.DATA_DIR, paths.ENV_FILE = _data, _env +def secure(group_readable): + settings.BACKUP_GROUP_READABLE = group_readable + _data, _env = paths.DATA_DIR, paths.ENV_FILE + paths.DATA_DIR, paths.ENV_FILE = data, env + try: + connection._secure_db_files() + finally: + paths.DATA_DIR, paths.ENV_FILE = _data, _env + + +secure(False) if POSIX: - check("the live database, a cache and the vector store stay 0600", - {mode(data / "curatarr.db"), mode(data / "cache" / "enrichment.db"), - mode(data / "chromadb" / "chroma.sqlite3")} == {0o600}) - check(".env stays 0600", mode(env) == 0o600) - check("a backup and the cache snapshot are 0640: the group may copy them", - mode(data / "backups" / "curatarr_20261114_214712.db") == 0o640 - and mode(data / "backups" / "caches" / "cache" / "lyrics.db") == 0o640) -else: + check("by default backups are 0600 like the database", mode(backup) == 0o600) +secure(True) +if POSIX: + check("BACKUP_GROUP_READABLE: backups 0640, the cache snapshot too", + 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}) +if not POSIX: check("(Windows: file modes are POSIX-only; the pass ran without error)", True) -# The cache snapshot is written group-readable from the start. -src_cache = root / "live" / "cache" -src_cache.mkdir(parents=True) -db(src_cache / "enrichment.db") -settings.ENRICHMENT_CACHE = str(src_cache / "enrichment.db") +# ── the cache snapshot only when asked for ────────────────────────────────── +live = root / "live" / "cache" +live.mkdir(parents=True) +db(live / "enrichment.db") +settings.ENRICHMENT_CACHE = str(live / "enrichment.db") settings.CHROMADB_PATH = str(root / "live" / "chromadb") bdir = root / "nas-backups" bdir.mkdir() +settings.BACKUP_CACHES = False +check("BACKUP_CACHES off (the default): no cache snapshot, no summary", + asyncio.run(cs.snapshot_caches(str(bdir))) == "" and not (bdir / "caches").exists()) +settings.BACKUP_CACHES = True +settings.BACKUP_GROUP_READABLE = False msg = asyncio.run(cs.snapshot_caches(str(bdir))) -check("the cache snapshot is written", (bdir / "caches" / "cache" / "enrichment.db").exists(), msg) +check("BACKUP_CACHES on: the snapshot is written", (bdir / "caches" / "cache" / "enrichment.db").exists(), msg) if POSIX: - check("...its files 0640, its folders 0750", - mode(bdir / "caches" / "cache" / "enrichment.db") == 0o640 - and mode(bdir / "caches") == 0o750 and mode(bdir / "caches" / "cache") == 0o750) + check("...0600 and 0700 by default", + mode(bdir / "caches" / "cache" / "enrichment.db") == 0o600 and mode(bdir / "caches") == 0o700) +settings.BACKUP_CACHES = False +msg = asyncio.run(cs.snapshot_caches(str(bdir))) +check("switched off again: the old snapshot (~2 GB on a big library) is removed", + not (bdir / "caches").exists() and "removed" in msg, msg) check.done() diff --git a/tests/test_backup_retention.py b/tests/test_backup_retention.py index b691ee67..25ff1a17 100644 --- a/tests/test_backup_retention.py +++ b/tests/test_backup_retention.py @@ -86,8 +86,8 @@ import stat as _stat # noqa: E402 if _os.name == "posix": newest = max(bdir.glob("curatarr_*.db"), key=lambda p: p.stat().st_mtime) - check("a new snapshot is 0640: the app's group may copy it off a NAS share", - _stat.S_IMODE(newest.stat().st_mode) == 0o640, oct(_stat.S_IMODE(newest.stat().st_mode))) + check("a new snapshot is 0600 by default, like the database", + _stat.S_IMODE(newest.stat().st_mode) == 0o600, oct(_stat.S_IMODE(newest.stat().st_mode))) # Short at first, enough once the oldest made way: the backup still happens. calls = [] diff --git a/tests/test_cache_snapshot.py b/tests/test_cache_snapshot.py index 86c061f3..c54b4b54 100644 --- a/tests/test_cache_snapshot.py +++ b/tests/test_cache_snapshot.py @@ -39,6 +39,7 @@ def _db(path, rows, keep_open=False): (chroma / "seg-1" / "data_level0.bin").write_bytes(b"\x01" * 2048) (chroma / "stray.sqlite3-wal").write_bytes(b"junk") +settings.BACKUP_CACHES = True # opt-in; off is checked in test_backup_perms settings.ENRICHMENT_CACHE = str(cache / "enrichment.db") settings.CHROMADB_PATH = str(chroma)