Compare commits

67 Commits
Author SHA1 Message Date
admin b3ab7fbd1a controller v0.354.0: released — the changelog line and the report (release 4)
gates / gates (push) Successful in 42s
Claude-Session: https://claude.ai/code/session_0159rPz1ZhFKsS53msqPYxtS
2026-11-20 08:44:09 +01:00
admin 440711b4e4 controller v0.354.0: the CHANGELOG heading for release 4 (MinAgent 0.158.1, unchanged); not released until the test box has run it
gates / gates (push) Successful in 35s
Claude-Session: https://claude.ai/code/session_0159rPz1ZhFKsS53msqPYxtS
2026-11-19 09:39:50 +01:00
admin 10df99b89f The remove dialog shows the older sentence about the nightly snapshots only where no end date is shown (felhom.eu decision 316, R-1374)
gates / gates (push) Successful in 45s
Household-facing, built and NOT published. No string changed; layout.html only.
The 144 i18n_parity fixtures are patched on the dialog's lines only.

Claude-Session: https://claude.ai/code/session_0159rPz1ZhFKsS53msqPYxtS
2026-11-15 16:39:13 +01:00
admin c5acb91a44 Review fix 5: the box sends its end records only to a hub that says it reads them (version skew)
gates / gates (push) Successful in 32s
A new box with an older hub sent `ended` in the window request; that hub reads
4 KiB of it, decided the window on a wrong count, and the weekly clean-up
stalled.

- The box sends `ended` only when the hub's last window answer said
  accepts_ended (kept in settings, re-read from every answer, so a rolled-back
  hub stops getting them after one answer). Otherwise the request is the one
  every hub always got, and the ordinary clean-up runs.
- One request carries at most 5000 snapshot ids.

Tests seen red before the fix; 6 mutations seen red (felhom.eu
documentation/audits/build-release-4-2026-11-15/A/redproof-review-5.txt).

Claude-Session: https://claude.ai/code/session_0159rPz1ZhFKsS53msqPYxtS
2026-11-15 15:05:38 +01:00
admin c7e4ec9b5e Review fix 3: every install deletes the off-site end record — one point, SaveAppConfig (D72)
A `.fab` import installed the app and its end record survived; the restore
that installs from a unit had the same hole. Only DeployStack deleted it.

- stacks.SaveAppConfig, the only writer of an installed app's app.yaml, calls
  noteAppInstalled when the record says deployed (a hook per stacks directory,
  registered by SetMigrationDeps). A source pin lists every place that sets
  Deployed or writes an app.yaml; a new writer fails it.
- The living check is stacks.Manager.IsLivingApp (wired in main.go): the
  protected list, the manager's list (deployed, being deployed, protected) and
  the app's record on disk — an installed app the manager does not list is
  living. Tested by behaviour.

Tests seen red before the fix; 8 mutations seen red (felhom.eu
documentation/audits/build-release-4-2026-11-15/A/redproof-review-3.txt).

Claude-Session: https://claude.ai/code/session_0159rPz1ZhFKsS53msqPYxtS
2026-11-15 14:42:07 +01:00
admin 3928c3db28 Review fix 2: a take-back or an install during the clean-up window keeps the copies (D72)
The due end records and the candidates were read once, before the hub was
asked, and never again before the forget. A „Mégis megtartom” or an install
while the hub answered still deleted the copies.

The window now reads the records again immediately before the forget and takes
out every id whose record is gone, changed or no longer due. From that look
until the forget has ended, a take-back is answered „not marked, or already
deleted”, never „kept”. Not covered: an install during the forget itself.

Tests seen red on f628cb5, then green; mutations in felhom.eu
documentation/audits/build-release-4-2026-11-15/A/redproof-review-2.txt.

Claude-Session: https://claude.ai/code/session_0159rPz1ZhFKsS53msqPYxtS
2026-11-15 14:27:09 +01:00
admin f628cb5082 The off-site copies of a removed app end 30 days after „delete backup data” — the box's half (felhom.eu R-1374 part 1; D72, D84)
gates / gates (push) Successful in 41s
Built, not released; no box has run it. felhom.eu `07-backup-architecture.md` §8.2f.
It does nothing without a hub that knows it: an older hub agrees to no id.

- The record: settings `offsite_ends` {app, removed_at, ends_at}. One writer
  (backup.StartOffsiteEnd), called by a removal only with „delete backup data”
  and by „Törlés 30 nap múlva” on the restore page. A second press changes
  nothing. No record, no deletion. Only on the hub-provisioned tier.
- The date is on the remove dialog before the press; the restore page shows
  „Törlésre kijelölve …” with „Mégis megtartom”, and one history line per
  carried-out end. An install of the same app deletes the record.
- The weekly window: after the guard has passed the policy's plan under the cap
  as before, it adds the snapshots whose app tags are ALL due records, that the
  hub agreed to and the box named in the same request; the result names them
  apart (removed_for_ended_apps). `_shares`, the box's own stacks and an
  installed app are never due.
- The report carries the pending records; the household gets one mail per
  press (offsite_end_scheduled), in both languages.

MinAgent unchanged (0.158.1). 143 parity fixtures gained the dialog's one new
script line (patched, not regenerated); one new parity case.
Tests TestD72_*, TestD84_*; 56 mutations seen red
(felhom.eu documentation/audits/build-release-4-2026-11-15/A/redproof-ctrl-*.txt).

Claude-Session: https://claude.ai/code/session_0159rPz1ZhFKsS53msqPYxtS
2026-11-15 14:09:47 +01:00
admin 591195fadd controller v0.353.0: released — the changelog line and the report
gates / gates (push) Successful in 37s
Claude-Session: https://claude.ai/code/session_0159rPz1ZhFKsS53msqPYxtS
2026-11-15 12:11:14 +01:00
admin ae07ed46cd controller v0.353.0: the changelog heading (MinAgent 0.158.1, unchanged)
gates / gates (push) Successful in 35s
Claude-Session: https://claude.ai/code/session_0159rPz1ZhFKsS53msqPYxtS
2026-11-15 10:43:37 +01:00
admin ee3b05edd0 controller (unreleased): only certificates of the household's current domain are reported (review)
gates / gates (push) Successful in 38s
Claude-Session: https://claude.ai/code/session_0159rPz1ZhFKsS53msqPYxtS
2026-11-14 19:09:21 +01:00
admin 7daf3d24a7 controller (unreleased): the report carries the web certificate's end date (felhom.eu R-1379, D77)
gates / gates (push) Successful in 34s
Names and end dates only, read from Traefik's store; no key material leaves the box.

Claude-Session: https://claude.ai/code/session_0159rPz1ZhFKsS53msqPYxtS
2026-11-14 18:14:24 +01:00
admin fdc0e29400 controller README: the boot pass and the agent's boot key (R-1395)
gates / gates (push) Successful in 36s
Claude-Session: https://claude.ai/code/session_0159rPz1ZhFKsS53msqPYxtS
2026-11-14 17:43:33 +01:00
admin fcf73479c2 controller (unreleased): HSTS is one year (R-1050, decision 249)
gates / gates (push) Successful in 35s
One day since 2026-10-15; no https trouble found in the registers, the operator's mailbox or the hub's log. Still no
includeSubDomains, no preload. The release must be built on or after 2026-11-15.

Claude-Session: https://claude.ai/code/session_0159rPz1ZhFKsS53msqPYxtS
2026-11-14 17:34:50 +01:00
admin 95ed6314cc controller (unreleased): a step of the host's clock is not a new boot (R-1395)
The boot pass decides through guestBootVerdict and prefers the agent's new guest_boot_key (kernel boot_id), which a
clock step cannot move. An agent that sends no key gets the old rule. The move to the key recreates nothing.

Claude-Session: https://claude.ai/code/session_0159rPz1ZhFKsS53msqPYxtS
2026-11-14 17:34:13 +01:00
admin df0990f3aa CHANGELOG: v0.352.1 RELEASED (floors, box walk, golden)
gates / gates (push) Successful in 41s
2026-11-14 11:33:14 +01:00
admin 8747744b48 v0.352.1: Go 1.27.4 (GO-2026-6859, felhom.eu R-1391)
gates / gates (push) Successful in 35s
2026-11-14 10:15:08 +01:00
admin a9189c9dc4 v0.352.0 released: global floor 0.352.0 / MinAgent 0.158.1 after rc.1 on 9202 and walk green on three boxes
gates / gates (push) Successful in 35s
Notes only: CHANGELOG heading and box proof, REPORT, CONTEXT. No code change.

Claude-Session: https://claude.ai/code/session_0159rPz1ZhFKsS53msqPYxtS
2026-11-10 16:37:30 +01:00
admin 3dbb68c163 v0.352.0 (unreleased): one fill warning per filesystem (R-1371) — the release heading
gates / gates (push) Successful in 33s
Claude-Session: https://claude.ai/code/session_0159rPz1ZhFKsS53msqPYxtS
2026-11-10 15:50:58 +01:00
admin 844f19f11e fill watch: one warning per filesystem (R-1371) — committed, not released
gates / gates (push) Successful in 31s
On a box whose guest has one data volume the two built-in fill targets, "/"
(the controller's overlay on the Docker data volume) and /mnt/sys_drive, are one
filesystem. The target list was de-duplicated by path only, so one fill would
send two warnings under two names.

fillTargets now keeps one target per filesystem; the first stays (app area,
system area, drives). The identity is system.FilesystemKey, not st_dev alone:
inside the container "/" is an overlay with its own device number, so an
overlay path takes the device of a Docker-kept file on the data-root
(/etc/hostname, /etc/hosts, /etc/resolv.conf). Measured read-only on demo-hp
9201/9202 and the N100 on 2026-11-10.

Tests: TestR1371_* (3), TestFilesystemKey_* (2). Red seen three times.
No version, no image, no floor: it waits for a release session.

Claude-Session: https://claude.ai/code/session_0159rPz1ZhFKsS53msqPYxtS
2026-11-10 14:18:36 +01:00
adminandClaude Opus 5.5 da060d7e7f v0.351.0 released: global floor 0.351.0 / MinAgent 0.158.1 after rc.1 on Tester 1 and walk green on three boxes
gates / gates (push) Successful in 31s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0159rPz1ZhFKsS53msqPYxtS
2026-11-09 13:19:37 +01:00
adminandClaude Opus 5.5 27360d6abe v0.351.0 (unreleased): old -rc controller images and old infra images are deleted (decision 56 amended, decision 285)
gates / gates (push) Successful in 31s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0159rPz1ZhFKsS53msqPYxtS
2026-11-09 10:23:06 +01:00
admin 64b99b74e3 REPORT + CONTEXT: v0.350.0 the global floor; Traefik v3.7.17 proven by behaviour on 9202
gates / gates (push) Successful in 34s
2026-11-03 10:29:37 +01:00
admin 5c336d828c v0.350.0 CHANGELOG heading (MinAgent 0.158.1, unchanged) — the release build's commit; the Traefik load test's figures
gates / gates (push) Successful in 31s
2026-11-03 08:02:35 +01:00
admin 13e34d4ed4 REPORT: 2026-11-02 night, commit only (Traefik pin, R-1347, R-1348, R-1339, R-1351, R-1323)
gates / gates (push) Successful in 30s
2026-11-03 04:13:24 +01:00
admin 37644458c7 R-1348: the mail of an interrupted put-back names a restore, not an off-site run (seen on the live proof); changelog: R-1347, R-1348 proven live on 9202. Commit only.
gates / gates (push) Successful in 32s
2026-11-03 01:12:19 +01:00
admin c4b6844d34 Traefik v3.7.17 (GHSA-xv5x-242w-7hf7); R-1347 a restore forgets the update-held flag; R-1348 a failed put-back at start-up mails; R-1339, R-1351, R-1323 truthful start-up lines and one lock over FileBrowser's compose. Commit only.
gates / gates (push) Successful in 29s
2026-11-02 23:14:16 +01:00
admin a90b62323f REPORT + CONTEXT: v0.349.0 the global floor; busy file, household line, R-1350 proven live
gates / gates (push) Successful in 31s
2026-10-29 20:24:36 +01:00
admin 94049a7200 v0.349.0 CHANGELOG heading (MinAgent 0.158.1, unchanged) — the release build's commit
gates / gates (push) Successful in 31s
2026-10-29 19:18:56 +01:00
admin b69e90bdad D65 = A: the busy file the agent reads before an operator reboot, and the household's 'Felhom support restarted your box' line; R-1350: a hold clear records the wanted stop so no app_start_failed follows it
gates / gates (push) Successful in 32s
2026-10-29 16:24:40 +01:00
admin a28db2d17f REPORT + CONTEXT: v0.348.0 the global floor; clear_hold proven on the release build
gates / gates (push) Successful in 31s
2026-10-29 15:11:17 +01:00
admin 2a0a17a760 v0.348.0: CHANGELOG heading — the release build's commit
gates / gates (push) Successful in 31s
2026-10-29 14:35:30 +01:00
admin 99fac06aa7 R-1340 second producer: a restore_mixed hold's Why() names the cause from its record (found live on rc.1: the hub's Held apps line said off-site/database for a local restore with no database) — test red first
gates / gates (push) Successful in 30s
2026-10-29 14:35:07 +01:00
admin 6077ac0083 R-1343 fallback: the box command's own settings.json edit (no controller running) goes through the same clear door, so a waiting put-back is dropped from the marker there too — test red first
gates / gates (push) Successful in 30s
2026-10-29 12:59:41 +01:00
admin 5b3b541602 clear_hold (D64 = B) + the box command through the running controller (R-1343), R-1340, R-1341 — tests red first; commit only
gates / gates (push) Successful in 31s
- clear_hold: a fifth verb in the closed operator-action list; lifts a hold of any reason in the RUNNING
  controller (memory + settings.json together), forgets the update's held flag, drops a waiting put-back
  from the app-stop marker (copy kept). Refused on a bad name or no hold. No new event type.
- --clear-restore-hold asks the running controller over <data dir>/ctl/hold.sock (unix, 0600, peer uid
  checked, no TCP); edits settings.json only when no controller answers, and says so (in-guest restart).
- R-1340: the operator's HELD STOPPED mail is built from the hold record (restore kind, mixed cause,
  failed put-back step, database replay or not, kept copy) — never the option-C database story by default.
- R-1341: the OOM WARN line once per new kill (container, start time, kill count); event unchanged.
2026-10-29 12:49:46 +01:00
admin c7bb776e00 REPORT: R-1342 after the release (fixed on main 652a690, not released)
gates / gates (push) Successful in 28s
2026-10-29 11:16:36 +01:00
admin 652a690e5d R-1342: a restore copy under the stable-start watch is not deletable (D62 gap); an app removed during the watch raises no alarm — tests red first; commit only
gates / gates (push) Successful in 31s
2026-10-29 11:16:13 +01:00
admin 6c72e3ff34 v0.347.0 RELEASED (the global floor, MinAgent 0.158.1): CHANGELOG heading, CONTEXT, REPORT
gates / gates (push) Successful in 33s
2026-10-29 10:48:22 +01:00
admin fd75c7c717 v0.347.0: CHANGELOG heading (D62, R-1256 all proven live, R-1254 controller half, R-528, 404) — the release build's commit
gates / gates (push) Successful in 30s
2026-10-29 09:55:42 +01:00
admin e3fce09d96 D62: restore copies kept 30 days, listed with their date, deletable by hand (typed name, never a needed copy, operator event); D63: a test-build-only fault switch for the R-1256 H4/H5 live proofs — tests red first
gates / gates (push) Successful in 33s
2026-10-29 08:50:59 +01:00
admin a815b37fbd Night 2026-10-28 docs: REPORT (H5 + H8 live on 9202, teardown), README (restore edges, host OOM count — unreleased), CONTEXT, CHANGELOG live line
gates / gates (push) Successful in 29s
2026-10-29 05:14:05 +01:00
admin 20c5877056 An action on a name that is no app answers 404, not 'settings cannot be saved' (found walking capability map B2 on 9202)
gates / gates (push) Successful in 27s
Test TestAnActionOnANameThatIsNoAppIsA404 red first. Commit only.
2026-10-28 23:56:36 +01:00
admin eed23e7594 R-528: the 30-s OOM scan also reads the host's per-container kernel counter (agent GET /guest/oom-kills)
gates / gates (push) Successful in 32s
A count above 0 in a running container's current run fires the existing app_oom line (source cgroup/docker in the
details), whatever Docker's OOMKilled says. Old agent: 404 back-off; no agent: Docker's flag only.
Tests TestR528_* red first / red-proved. Commit only.
2026-10-28 23:22:46 +01:00
admin e33cffaee1 R-1254 (controller half): escrow claim/confirm outwait the agent (60 s); an unknown confirm outcome promises nothing
gates / gates (push) Successful in 28s
504 from the agent (it cannot learn which package the hub holds) or a failed call -> api.escrow.confirm_store_unknown
(hu+en); only 502 keeps 'your previous code still works'. Tests TestR1254_* red before the fix. Commit only.
2026-10-28 22:59:52 +01:00
admin 342a394bff R-1256: four restore edges (review round 2 HUNT-1 H4/H5/H6/H8) — each test seen failing first
gates / gates (push) Successful in 31s
H4: a failed definition write in the off-site restore writes the live definition back before the start;
    a failed write-back holds the app (restore_mixed).
H5: a put-back whose stop fails pours nothing, keeps the copy and holds the app (off-site, local, power-cut);
    a failed definition write-back keeps the copy (D20); a failed 'volume rm -f' fails that volume (no merge).
H6: TryBeginRestoreOp/RestoreBusy: check every operation and record the restore in one step under m.mu;
    every web handler and the kept loads begin through it; install-time kept load asks about the mirror too.
H8: SweepUnusedRestoreCopies every 6 h: removes a copy only with no hold, no marker naming it, no restore
    running, and older than 14 days.

Commit only; rides the next controller release.
2026-10-28 22:24:16 +01:00
admin ed3927f03a REPORT: controller v0.346.0 released; R-1250 fixed the same day
gates / gates (push) Successful in 1m18s
2026-10-27 15:49:59 +01:00
admin 5ba1b86293 v0.346.1: SECURITY — traefik v3.7.16, the file manager 1.5.8-stable, cloudflared 2026.10.4 (felhom.eu R-1304, R-1305); test TestEnsureTraefik_ANewImageRecreatesTraefik (red first)
gates / gates (push) Successful in 50s
Built from the v0.346.0 release commit b1b9be3 + this one commit. MinAgent 0.158.1 (unchanged).
2026-10-27 15:48:38 +01:00
admin b1b9be3a8e v0.346.0: CHANGELOG header — the release (MinAgent 0.158.1, unchanged)
gates / gates (push) Successful in 55s
2026-10-27 15:07:25 +01:00
admin 710ceace12 fix(R-1250): the line-test hold waits until the held app has really slowed down before asking the agent
gates / gates (push) Successful in 51s
Measured on demo-hp 2026-10-27: qBittorrent 5.2.4 kept sending at full speed for ~14 s after its limit fell to
1 KiB/s; the agent reads the uplink 5-15 s after the call, so every test on request was refused "not quiet"
(four tries in an hour, 4.0-4.2 Mbit/s). waitDrained polls each held app's own upload (qBittorrent up_info_speed,
Transmission uploadSpeed) until <= 16 KiB/s twice, 2 s apart, at most 90 s; an unreadable speed waits 20 s.
Tests TestR1250_* (five), red-proved by four mutations.
2026-10-27 13:23:00 +01:00
admin 9b5bb0a9a6 REPORT-security-watch: the pin list for the security watch (felhom.eu R-1303). Docs only.
gates / gates (push) Successful in 58s
2026-10-26 23:55:06 +01:00
admin e01eb64b25 R-1303: every pin names its security-notice source (upstream.txt, # upstream: above each FROM); gate upstream + decoys. No runtime change.
gates / gates (push) Successful in 55s
2026-10-26 23:23:36 +01:00
admin 37f7e40b18 CHANGELOG: the unreleased header names every fix it carries (D53, R-1220, R-1218, R-1219, R-1187, R-1298, R-972)
gates / gates (push) Successful in 53s
2026-10-26 22:21:29 +01:00
admin 90a2530689 fix(R-1187): the .fab import loads the database through the backup side (mariadb-admin/mariadb, the container's own credentials)
gates / gates (push) Successful in 48s
Found live on 9202: every MariaDB 11+ import timed out (mysqladmin/mysql absent). Red-proved.
2026-10-26 21:58:11 +01:00
admin 5d07c4e923 REPORT-cloudflared-0.345.1: the v0.345.1 security release (R-1300) — a sibling of REPORT.md (the night session owns it). Docs only.
gates / gates (push) Successful in 1m10s
2026-10-26 21:44:07 +01:00
admin a3ed63ee9a fix(R-1187): the import's compose runs get the controller's path variables; a compose warning is never read as the container id
gates / gates (push) Successful in 50s
Found live on 9202 (grimmory import timed out on the DB step and left the app down). Red-proved.
2026-10-26 21:38:47 +01:00
admin a1c65b3d81 R-1300: SECURITY — cloudflared 2026.10.3 on main (same change as tag v0.345.1); build.sh may push from the pushed tag v<VERSION>
gates / gates (push) Successful in 1m19s
infra.CloudflaredImage 2026.9.3 -> 2026.10.3 (Cloudflare's eMudhra notice, 2026-10-20) and
TestEnsureCloudflared_ANewImageRecreatesTheTunnel (red-proved). build.sh: a --push may build from
the tag v<VERSION> as the server has it, pointing at HEAD (operator's yes 2026-10-26); four new
cases in test_build_push_once.sh, red-proved both ways. MinAgent 0.158.1 unchanged.
2026-10-26 21:01:40 +01:00
admin 2560cf1779 build(R-972): Go 1.27.3 + golang:1.27.3-trixie builder (GO-2026-6809) — govulncheck 1 → 0 called
gates / gates (push) Successful in 1m21s
2026-10-26 20:42:35 +01:00
admin cccb9aee84 fix(R-1187 b): restored links point only downward — no absolute target, no '..', no link on the way
gates / gates (push) Successful in 54s
Third automated security review finding, red-proved.
2026-10-26 20:33:26 +01:00
admin f24233c829 fix(R-1187 b): refuse a link whose parent path passes through a link; born keys listed; psql --set
gates / gates (push) Successful in 1m7s
Second automated security review finding, red-proved. The go-parity and docker -v gates that refused the push are green.
2026-10-26 20:30:34 +01:00
admin 106325de43 fix(R-1187 b): the import writes only through os.Root — never through a link that leaves the app's folder
Found by the automated security review of dfd0f8e. Red-proved. Commit only.
2026-10-26 20:28:04 +01:00
admin b156e4526a fix(R-1298): held-app reports only for installed apps (a restore hold always)
Red-proved. Commit only.
2026-10-26 20:26:44 +01:00
admin dfd0f8ec53 fix(R-1187 a,b,d,f,g): .fab — links carried and restored safely, FIFOs refused, owners kept, busy and bad-path refusals, postgis + ON_ERROR_STOP
Red-proved (6 tests). Commit only.
2026-10-26 20:26:02 +01:00
admin 1170b48e59 fix(R-1218, R-1219): stage the off-site password when its file exists; no recovery ceremony during a recovery offer
R-1218: escrowStart stages when OffboxRepoPasswordOnBox() (not OffboxConfigured()). R-1219: the top bar hides during an
offer; the start handler answers 409 (api.escrow.recovery_offer_open, hu+en) before staging. Red-proved. Commit only.
2026-10-26 20:20:59 +01:00
admin 7e15a374b2 fix(R-1220): an unreadable app.yaml counts as installed — its folders are never kept data
liveDriveBinds(drives): an app whose app.yaml exists but does not parse binds every folder its compose names on
every drive (fail closed); WARN per app. Red-proved (the live folder was listed). Commit only.
2026-10-26 20:13:44 +01:00
admin e333477b11 docs: REPORT — D53 (committed, not released; live-proven on 9202 against a test hub)
gates / gates (push) Successful in 58s
2026-10-26 19:16:59 +01:00
admin 5bd03ad152 feat(D53): the hub learns which apps are held — app_held / app_hold_cleared, daily repeat
gates / gates (push) Successful in 54s
internal/holdreport: one observer of the hold store, ticked every minute; app_held for a new or changed
hold (stack_name, reason, since, why), app_hold_cleared when gone (also while the controller was down:
settings.reported_holds), every hold again daily and at start. Severity info. RestoreHold.Why/WireReason
(holdWhy calls it). 8 tests, red-proved (inert Tick; unwired scheduler line). Commit only (felhom.eu 08 §10).
2026-10-26 18:23:54 +01:00
admin 20cf4bccfd docs: CONTEXT — D53 ruled, the held-app report is next (felhom.eu 08 §10)
gates / gates (push) Successful in 55s
2026-10-26 18:07:22 +01:00
admin 5ce54a5076 REPORT: the 2026-10-26 afternoon run. Docs only.
gates / gates (push) Successful in 1m37s
2026-10-26 14:37:53 +01:00
311 changed files with 14700 additions and 828 deletions

No files matched your search

+576
View File
@@ -1,3 +1,579 @@
## v0.354.0 (2026-11-19) — release 4: the off-site copies of a removed app end 30 days after „delete backup data”, the remove dialog names the day, the Backups page marks it with a take-back button (felhom.eu R-1374 part 1; D72, D84; decisions 315, 316) — RELEASED (image `sha256:c88522ed0ce607f5545b6406276969bb3aa4cc59375e5413bec0537766064e09`, from `440711b`, CI run id 2713; rc.1 on demo-hp's guest 9201 — the test household, which pressed „delete backup data” on it); per-box floors 2026-11-19 09:29 UTC, global floor 2026-11-19 09:32:18 UTC (MinAgent 0.158.1); golden 0.354.0 baked and vouched the same day. Needs hub ≥ 0.183.0 for the notice; an older hub gets nothing new
**MinAgent: 0.158.1** (unchanged — nothing in this release asks the agent for anything)
### The second build (2026-11-15) — the remove dialog shows one sentence about the off-site copies, not two (felhom.eu `09` §3 decision 316, R-1374)
**MinAgent: 0.158.1** (unchanged — nothing here asks the agent for anything)
- **The remove dialog (household-facing; NOT published — the operator reads it before a release).** Under „Mentési
adatok törlése” the dialog showed the older sentence on every box — „Az éjszakai restic pillanatképek nem
törölhetők egyenként — a megőrzési szabályok szerint automatikusan elavulnak.” — and, on a box with the hub's
off-site tier, the new line under it: „… A távoli másolatok még 30 napig megmaradnak. Törlésük napja: {dátum} …”.
Beside the new line the older one is no longer true. Now the dialog shows exactly ONE of them: the new line when
the API gave a date (`offsite_end_date`), the older sentence on every other box (the household's own NAS target,
no off-site tier). No string changed; `layout.html` only. Test
`TestD72_TheRemoveDialogShowsTheOlderSentenceOnlyWithoutTheDate` (both languages, both branches read from the
rendered script — no script engine runs in the suite, so no browser has run it); 3 mutations seen red. The 144
`i18n_parity` fixtures that hold the dialog were patched on those lines only (the fixture tool rewrites unrelated
lines — felhom.eu R-1401).
- **The hub's half of the same build needs nothing from the box** (the notice lock, felhom.eu `07` §8.2f): the hub
sends the household's notice from the report's `offsite.ended_apps`, which this controller already sends. The
box's event `offsite_end_scheduled` is still sent; a hub with the notice lock records it and mails nobody from it.
### The first build (2026-11-15) — the off-site copies of a removed app end 30 days after „delete backup data” (felhom.eu R-1374 part 1; D72, D84)
**MinAgent: 0.158.1** (unchanged — nothing here asks the agent for anything)
- **Review fix 5 (2026-11-15), the box's half — version skew.** A new box with an older hub sent its end records in
the window request; that hub reads 4 KiB of it (about 55 snapshot ids), then decided the window on a wrong count,
and the weekly clean-up stalled. Now the box sends `ended` ONLY to a hub whose last window answer said
`accepts_ended` (kept in `settings.json` → `offsite_hub_accepts_ended`, re-read from every answer, so a rolled-back
hub stops getting them after one answer); otherwise the request is the one every hub always got and the ordinary
clean-up runs. One request carries at most 5000 ids (`boundEndedClaims`). **Cost, said plainly:** after the hub is
updated the box learns it at its next nightly window request and sends from the one after. Tests
`TestD84_ANewBoxWithAnOlderHub_NothingEndedIsSentAndTheCleanUpStillRuns`, `TestD84_OneRequestCarriesABoundedNumberOfIds`
— seen red before the fix; 6 mutations seen red (felhom.eu `…/A/redproof-review-5.txt`).
- **Review fix 3 (2026-11-15): EVERY install deletes the off-site end record, not only a deploy.** A `.fab` import
(`SaveImportedAppConfig`) installed the app and the record survived; the restore that installs from a unit
(`PersistUnitRedeployConfigGate`) had the same hole. The rule now sits at ONE point: `stacks.SaveAppConfig`, the
only writer of an installed app's `app.yaml`, calls `noteAppInstalled` when the record says deployed (a hook per
stacks directory, registered by `SetMigrationDeps`). `TestD72_TheInstallWritersAreListed` lists every place that
sets `Deployed` or writes an `app.yaml`; a new writer fails it. **The living check is a method now**,
`stacks.Manager.IsLivingApp` (wired in `main.go`), and reads three places: the protected list, the manager's list
(deployed, being deployed, protected) and the app's record on disk — an installed app the manager does not list is
living. Tests `TestD72_AnImportDeletesTheEndRecord`, `TestD72_ARestoreIntoAnInstallDeletesTheEndRecord`,
`TestD72_ADriveFlipRecordWriteDeletesTheEndRecord`, `TestD72_SaveAppConfigIsTheOnePoint`, `TestD72_IsLivingApp` —
the first four seen red before the fix; 8 mutations seen red (felhom.eu `…/A/redproof-review-3.txt`).
- **Review fix 2 (2026-11-15): a take-back or an install DURING the clean-up window no longer loses the copies.** The
due records and the candidates were read once, before the hub was asked, and never again before the forget — so
„Mégis megtartom” (or an install) while the hub answered still deleted, after the page had said „kept”. The window
now reads the records again immediately before the forget (`Manager.lastLookAtEnded`) and takes out every id whose
record is gone, changed or no longer due. From that look until the forget has ended, a take-back for one of those
apps is answered „not marked, or already deleted”, never „kept” (`KeepOffsiteCopies`, one lock with the look).
**Not covered, said plainly:** an install of the app during the forget itself (restic is already removing).
Tests `TestD72_ATakeBackDuringTheWindowKeepsTheCopies`, `TestD72_AnInstallDuringTheWindowKeepsTheCopies` (three
ways), `TestD72_ATakeBackDuringTheForgetIsNotAnsweredKept` — the first two seen red on the pushed code; 3 mutations
seen red, one not provable and said so (felhom.eu `…/build-release-4-2026-11-15/A/redproof-review-2.txt`).
- **The off-site copies of a removed app end 30 days after „delete backup data” — the box's half (R-1374 part 1; D72
and D84, `09` §3 decisions 292 and 309; felhom.eu `07-backup-architecture.md` §8.2f). Built, NOT released; no box
has run it. It does nothing without a hub that knows it (felhom.eu `hub/CHANGELOG.md`, Unreleased): an older hub
agrees to no id, and then nothing of a removed app is deleted.**
(1) **The record.** `settings.OffsiteEnd` (`settings.json` → `offsite_ends`): `{app, removed_at, ends_at}`. One
writer, `backup.StartOffsiteEnd`, called by the removal ONLY when „delete backup data” was pressed
(`api.removeStack`) and by „Törlés 30 nap múlva” on the restore page. A second press changes nothing. **No record,
no deletion.** Only on a box with the hub-provisioned (pinned) off-site tier; the household's own NAS target is
unchanged.
(2) **The date before the press, and the way back.** `GET /api/stacks/{name}/backup-data` carries
`offsite_end_date`; the remove dialog shows the sentence with it. The restore page's off-site list shows a marked
app with „Mégis megtartom” (`POST /backup/offsite-end/keep`), a removed app with kept copies with „Törlés 30 nap
múlva” (`POST /backup/offsite-end/start`), and one history line per carried-out end. An install of the same app
deletes the record (`stacks.DeployStack`, at its first write).
(3) **The window.** `backup/offbox_ended.go`: after the fake-snapshot guard has passed the policy's own plan under
the cap exactly as before, the window adds the ids of snapshots whose app tags are ALL due records, that the hub
sent back (`OffsiteWindow.EndedAllowed`) and that the box named in the same request. `_shares`, the box's own
stacks and an installed app are never due (`SetOffsiteEndLiving`, wired in `main.go`; not wired → nothing is due).
The result names them apart (`removed_for_ended_apps`). `OffsiteWindowClient.Open` takes the claims; the request's
`ended` key is absent when there is none.
(4) **The hub report** carries the pending records (`offsite.ended_apps`) so the hub can start its own clock.
(5) **The mail (D84).** `Notifier.NotifyOffsiteEndScheduled` → `offsite_end_scheduled` (info), once per record
written, in both languages with each language's date form; details `subject` = app + the record's time.
**Household-facing texts, new, Hungarian and English — the operator reads them before the release:**
`offsite_end.dialog`, `offsite_end.marked`, `offsite_end.keep_button`, `offsite_end.kept_before`,
`offsite_end.start_button`, `offsite_end.done`, `flash.offsite_end.kept`, `flash.offsite_end.nothing_to_keep`,
`flash.offsite_end.not_possible`, `flash.offsite_end.failed`, `event.offsite_end_scheduled` (the full list with both
languages is in `07` §8.2f).
143 parity fixtures gained the dialog's one new script line (patched, not regenerated); one new parity case
(`backups_restore_offsite_end`).
Tests `TestD72_*`, `TestD84_*` (settings, backup, stacks, notify, api, web, offsiteapply); 56 mutations seen red,
none redone (felhom.eu `documentation/audits/build-release-4-2026-11-15/A/redproof-ctrl-{record,window,press,page}.txt`).
**A seam, named:** `api.removeStack`'s success path needs Docker, so its hook is pinned by reading the handler's
source (`TestD72_RemovalWritesTheEndRecordOnlyWithDeleteBackupData`); what the hook then does runs on the real code.
restic is the package's fake runner, as in the window's other tests — no real repository.
## v0.353.0 (2026-11-15) — a clock step is not a new boot (felhom.eu R-1395); HSTS one year (R-1050, decision 249); the web certificate's end date in the report (R-1379) — RELEASED (image `sha256:61cf2a8b…`, from `ae07ed4`, CI run id 2681; rc.1 on scratch guest 9202); per-box floors 10:08 UTC, global floor 2026-11-15 10:26:53 UTC (MinAgent 0.158.1)
**MinAgent: 0.158.1** (unchanged — the agent's boot key is optional: with an agent before 0.175.0 the controller behaves as before, so a clock step still recreates the drive-backed apps once on such a box; the fix needs agent 0.175.0 or newer on the same box. rc.1 on scratch guest 9202, 2026-11-15.)
- **A step of the host's clock no longer makes the controller recreate every drive-backed app (R-1395).** Found on
the N100 on 2026-11-14: its time service came back, stepped the clock by +32.7 s, and radarr, sonarr and qbittorrent
were recreated. **The boot token is the AGENT's, not the controller's:** `guest_boot_id` in the agent's `/disks`
answer is `<host boot TIME>-<guest init start>`, and the kernel computes the boot time from the wall clock. The only
reader in this repository is `web.processGuestBootChange` (it compares the token with `settings.LastGuestBootID`).
It now decides through `guestBootVerdict`, which prefers the agent's new `guest_boot_key`
(`<kernel boot_id>-<guest init start>`; an agent after 0.174.0 — built there, not released): the key equal to the
record is the same boot whatever the old token says; the first report with a key moves the record to the key
WITHOUT a recreate when the old token says „same boot”; an agent that sends no key gets the old rule, byte for
byte. Tests `TestGuestBootVerdict_AClockStepIsNotANewBoot` (14 cases), `TestGuestBootVerdict_IsWhatTheBootPassReads`;
8 mutations seen red (felhom.eu `documentation/audits/night-build-2026-11-14/C/redproof-controller-boot-key.txt`).
**Proven on Tester 1, 2026-11-15** (felhom.eu `documentation/audits/release-2b-3-2026-11-15/part3/`): a 150 s clock step in both directions recreated nothing; a real restart recreated the app. With an older agent a clock step still recreates the apps once.
- **The report carries the web certificate's end date (felhom.eu R-1379, D77, `09` §3 decision 298; `08` §12).** Only
the box knows it: the certificate lives in Traefik's store in the guest (`<stacks>/traefik/acme.json`), and nothing
read it — a renewal that failed was silent until the browser warning on the end date. `infra.ReadWebCerts` decodes
the store into a shape with NO key field, parses the certificate only, and returns names, end dates and the issuer's
name (at most 8, soonest first); the report's `web_certs` carries them. A missing or empty store is no field; a
broken store is a WARN line that does not quote the file, and the report still goes. The hub's warning (14 days
before) is built in its own repository, not released. Tests `TestReadWebCerts_*` (real certificates and keys made
in the test; the key, the account key and the e-mail must not appear in what is reported),
`TestWebCertsForReport_PathFieldAndBrokenStore`; 8 mutations seen red (one stayed green at first: the test had no
certificate in the folder — a real one and a decoy in the wrong folder were added). **Not proven on a box.**
- **After review (2026-11-14): only certificates of the household's CURRENT domain are reported** (`web_certs`; the
name, `*.<domain>`, or a name under it). Traefik's store keeps a certificate for a name the box no longer serves; it
can never renew, and reporting it would warn the operator about a name nobody uses. 2 mutations seen red.
- **HSTS is one year (R-1050, felhom.eu `09` §3 decision 249).** `infra.HSTSMaxAgeSeconds` 86400 → 31536000; still
no `includeSubDomains`, no `preload` (the test asserts both). The ruling's condition — a month with no https
trouble since 2026-10-15 — was searched on 2026-11-14: the open and closed registers (ASCII fragments, with a
positive and a negative control), the operator's mailbox, the hub's log since its start today; no report of a name
that does not open and none of a box answering http after the floor. **The release must be built on or after
2026-11-15** (the ruled date). A browser that has seen the new value keeps „https only” for that name for a year;
going back to one day in a later release does not shorten what a browser already holds.
## v0.352.1 (2026-11-14) — Go 1.27.4: the security fix GO-2026-6859 (felhom.eu R-1391) — RELEASED (image `sha256:1a6e8945…`, from `8747744b`, CI run id 2637; rc.1 on scratch guest 9202); per-box floors 09:18 UTC, global floor 2026-11-14 09:21 UTC (MinAgent 0.158.1); golden 0.352.1 baked and vouched the same day
### 2026-11-14
**MinAgent: 0.158.1** (unchanged).
**Why.** Go 1.27.3 has GO-2026-6859: an HTTP/1 server can crash with a runtime panic when a `MaxBytesReader` limit is
hit while the handler reads the request body and writes a response header at the same time. Fixed in Go 1.27.4
(published; checked on go.dev and on Docker Hub before the change).
**What changed.** `controller/go.mod` `go 1.27.4`; the builder image
`golang:1.27.4-trixie@sha256:b54b2639de8c1bfe538ec5ffc45f29b1932235ac5f6d63c059853646677112d9` (version and digest,
as before). No source change.
**Reach, read 2026-11-14 (20-minute read).** Seven places wrap a body in `MaxBytesReader` (`api/router.go limitBody`,
`web/poweroff_handlers.go`, `web/handler_export_upload.go` ×4, `web/escrow_handlers.go`). Each one reads the body to
its end in the handler's own goroutine and writes the answer after it; none starts a goroutine that reads the body,
and the controller has no `TimeoutHandler` and no `EnableFullDuplex`. So no controller handler matches the crash
pattern. The release is hygiene, not an urgent fix.
**Not in this release: HSTS one year (felhom.eu R-1050, `09` §3 decision 249).** The ruling allows it on or after
2026-11-15; this release was built on 2026-11-14 and the operator's words „one day early is OK” were not given.
**Tests.** `go build`, `go vet`, `go test ./...` green on Go 1.27.4; `controller_gates.py --fast` green.
**Released.** rc.1 on scratch guest 9202 (healthy, 0 ERROR lines). Tester 1, demo-hp and demo-felhom took 0.352.1 by
per-box floors within a minute; on each: every container healthy, 0 ERROR lines, the running binary reads `go1.27.4`,
`https_only_check.py` exit 0, and every public name still answers `strict-transport-security: max-age=86400` and
nothing more (26 names). Global floor in its own save; 35 minutes later: all three on the release, no new event but
`controller_updated`/`controller_started`. Per-box floors cleared. Evidence: felhom.eu
`documentation/audits/release-1-dates-2026-11-14/controller/`.
## v0.352.0 (2026-11-10) — R-1371: one fill warning per filesystem — RELEASED (image `sha256:3c785dd3…`, from `3dbb68c1`, CI 2615; rc.1 on scratch guest 9202); per-box floors 15:16 UTC, global floor 2026-11-10 15:31 UTC (MinAgent 0.158.1)
### 2026-11-10
**MinAgent: 0.158.1** (unchanged).
**Why (measured 2026-11-10, demo-hp guests 9201 and 9202 and the N100, read-only; felhom.eu
`documentation/audits/space-list-2026-11-10/evidence/extra/fs-identity.txt`).** The fill watch has two built-in targets:
"/" (the controller's overlay, which lies on the Docker data volume) and `/mnt/sys_drive`. Since the guest's two data
volumes became one they are ONE filesystem: the same size, the same free space. The target list was de-duplicated by
path only, so one fill would send two warnings with two names („Alkalmazások területe", „Rendszer- és mentési terület").
Not seen on a box: no disk was filled.
**The fix.** `fillTargets` now keeps one target per filesystem (`fillTargetsBy`); the first one stays, in the order app
area, system area, drives. A path whose filesystem cannot be identified is kept (one warning too many, never one too
few).
**The identity is NOT the device number alone** (`system.FilesystemKey`, `internal/system/fskey.go`). Inside the
container "/" is an overlay: it has its own device number and its own filesystem id (139 against 64519 on demo-hp), so a
plain `st_dev` compare would have passed its tests and changed nothing on a box. Equal size-and-free numbers are no
identity either: two reads in one loop already differed by one block. An overlay path is identified by the device of a
file Docker keeps on its data-root and bind-mounts into the container (`/etc/hostname`, `/etc/hosts`,
`/etc/resolv.conf`) — measured equal to `/mnt/sys_drive`'s device on all three guests.
**Tests.** `TestR1371_OneFillSendsOneWarning` (the real watcher and push closure: one warning, then one critical),
`TestR1371_TargetsByFilesystem`, `TestR1371_ProductionListUsesTheRealIdentity`,
`TestFilesystemKey_AnOverlayRootIsTheDockerDataRoot` (the measured numbers), `TestFilesystemKey_RealSyscalls`.
**Red seen three times:** no filesystem check (2 warnings); the production list not wired to the real identity; an
overlay keeping its own device number.
**Proven on boxes, 2026-11-10** (felhom.eu `documentation/audits/release-space-fixes-2026-11-10/controller/`).
Scratch guest 9202, filled past the warning line with one test file: the version before this one sent TWO warnings for
the one fill (two names); `0.352.0-rc.1` sent ONE, and cleared it silently when the file was gone. Tester 1, demo-hp and
demo-felhom took the release through per-box floors: each now checks 2 filesystems where it checked 3, all containers
healthy, the box walk and the https-only check green. Then the global floor, in its own save. **Correction to the
sentence above („Not seen on a box"):** it is now seen on a box, as two warnings on 9202.
**Not proven.** A real fill on a household's box. The critical step (95 %) on a box; a test covers it.
**Not fixed here:** the guest's own root disk (`/opt/docker/stacks` lies on it) has no fill watcher — a design point in
felhom.eu `16-storage-physical-identity.md`.
## v0.351.0 (2026-11-09) — old test builds and old infrastructure images are deleted (decision 56 amended, decision 285) — RELEASED (image `sha256:1d90563c…`, from `27360d6a`, CI 2603; rc.1 on Tester 1 by hand); per-box floors 12:14 UTC, global floor 2026-11-09 12:18 UTC on the operator's yes (MinAgent 0.158.1)
### 2026-11-09
**MinAgent: 0.158.1** (unchanged).
**Why (measured 2026-11-09, demo-hp guest 9201, `docker system df -v`):** the whole-guest backup copies `/var/lib/docker` (mp0,
`backup=1`), and demo-hp's local tier was refused for space again (felhom.eu R-548). Of 27.5 GB of images, 13.2 GB ran in
containers, 9.8 GB were the apps' undo images (decision 53, kept on purpose), 2.2 GB were 28 old controller images and
1.35 GB were old infrastructure and helper images. Nothing deleted the last two kinds.
**Controller images: a test build is a version (decision 56 amended).** `RetainControllerImages` left every `-rc` tag alone,
so 25 test builds stayed. Tags, the running version and the previous now parse with `util.ParseVersionPre` (an rc orders
below its release): an old rc goes like an old release; an rc above the running one or between the previous and the
running one stays; `latest` stays. A box that RUNS a test build is judged (it was skipped). The fallback previous prefers
a release over a newer test build. Tests `TestControllerRetention_OldTestBuildsGo`, `_BoxOnATestBuildIsJudged`; the
existing test's rc expectation changed with the rule.
**Infrastructure images (decision 285, new).** `RetainInfraImages(infra.Images())`, 3 minutes after every start: per pinned
repository the pin, newer versions, the previous pin and every in-use image stay; older and untagged ones go by exact
name/ID; never forced, never pruned; not while an app pulls (R-863, retried every 2 minutes, 30 tries) or while the
controller swaps itself. Tests `TestInfraRetention_*` (4). Customer boxes get a new traefik or cloudflared pin every few
weeks (~65–195 MB each); this is the part a customer box needs.
Red-proofs: six code mutants, each test red (the previous-pin keep, the in-use check, the R-863 lock, the tag parser, the
running-version parser, the release preference). Green gate: `go build`, `go vet`, `go test ./...` rc 0; `controller_gates.py --fast` OK.
## v0.350.0 (2026-11-03) — Traefik v3.7.17 (GHSA-xv5x-242w-7hf7); a restore forgets the update-held flag (R-1347); a failed put-back at start-up mails (R-1348); three false start-up lines (R-1339, R-1351, R-1323)
### 2026-11-03
**MinAgent: 0.158.1** (unchanged).
**Load test, scratch 9202 only, from the LAN, 2026-11-03** (felhom.eu `audits/release-2026-11-03/part1/`): the same many short TLS connections with an
`Authorization: NTLM` header to the dashboard route. v3.7.16: Traefik's anonymous memory 18.7 → 79.0 MiB after 920 connections, not released (stopped at
twice its start, as the test's bound says). v3.7.17: 16.2 → 25-26 MiB, flat for 25,116 connections and the whole 300 s.
**Traefik v3.7.17 (GHSA-xv5x-242w-7hf7, high, published 2026-11-02).** v3.7.14–v3.7.16: an unauthenticated client that
sends a `Negotiate` or `NTLM` `Authorization` header gets a dedicated backend transport per connection, and it is not
released when the connection closes: many short connections exhaust Traefik's memory, whether or not an NTLM backend
exists. Traefik fronts every box. `TraefikImage` v3.7.16 → v3.7.17; a running box takes it by the reconcile at start
(`TestEnsureTraefik_ANewImageRecreatesTraefik`). The upgrade notes name Go 1.27 (GODEBUG TLS settings: we set none; 500
request-header values at most, else 431) and the ingress-nginx provider (not used). Found by reading the release itself:
the watch had flagged it on a word-only line (felhom.eu R-1310).
**R-1347 — a restore that lifts an update hold forgets the „update held" flag.** `clearUpdateHoldAfterRestore` cleared the
hold in settings, but `stacks.Manager` kept `updateHeld`: the crash-loop watcher did not watch the app and the night leg
skipped it until the controller restarted. New seam `backup.SetUpdateHeldForgetter` (`stackMgr.ForgetUpdateHeld`). Tests
`TestR1347_*` (the seam, the wiring, and the consequence: the same restarts trip the watcher once the flag is gone).
**R-1348 — a failed put-back at start-up mails the operator.** `holdPutBackFailed` writes the D20 hold at `Recover`, before any
notifier exists, so only the hold reporter's info and the hub's later reminder said anything. `AppStopGuard.SetHeldNotify`
hands over what `Recover` held, once, and mails a later failure (a drive that returned) at once: the R-1340 sentence for
`MixedCauseInterruptedPutBack`, from the hold record. The mail's run name says „restore" for it, not „offsite-reconstitute"
(`heldRunKind`, seen on the live proof). Tests `TestR1348_*`. **Live proof 2026-11-03, scratch 9202, test image of c4b6844** (felhom.eu
`audits/security-2026-11-02/part3/`): a restore cut at „the restore copy is recorded", the volume held by a created-only
container, the controller started: hold `restore_mixed` / `interrupted_put_back`, the event `backup_run_failures` with the sentence in the sink.
**R-1347's live proof, same image:** an update with its undo copy cut off → hold `update_failed`; the household's restore → „the update hold is CLEARED", „its
update-held flag is forgotten"; six `kill -9` → the crash-loop watcher stops the app (`unhealthy_stop`), so it watches again.
**R-1339 — no false „drive … not mounted".** A per-app folder under a mounted drive is never a mountpoint itself; nine false lines
at every start on 9202. The folder still gets no bind and no skeleton of its own (the row's „not skipped" would write a
`userdata/` inside the app's folder and recreate the file manager, so the behaviour stays and only the line changes). A drive that
is really absent keeps its line, and a folder of it names the drive. `TestR1339_*`.
**R-1351 — FileBrowser's two start paths at boot take one lock.** `EnsureBaseStack`'s `compose up` and
`web.syncFileBrowserMounts`' `compose up --force-recreate` in the same second gave „Conflict. The container name … is already in
use", two ERROR lines and a first-boot WARN for an app that then ran healthy. `stacks.Manager.LockFileBrowserStack`.
`TestR1351_*`.
**R-1323 — „No such container" is not „every app can still reach it".** The checked container was replaced between the check and
the leave; the line now reads the CURRENT container's networks and says the truth. A current container on the app network, an
unreadable one, or any other failure keeps the alarm. `TestR1323_*`.
## v0.349.0 (2026-10-29) — the household line after an operator reboot and the busy file for it (D65 = A); a hold clear records the wanted stop (R-1350)
### 2026-10-29 (evening)
**MinAgent: 0.158.1** (unchanged). The new `GET /guest/operator-reboot` is asked once at start; an older agent answers
404, and such an agent cannot reboot from the hub either — nothing to show, nothing broken. The busy file is read BY the
agent (≥ the reboot_guest commit); an older agent never reads it.
- **D65 = A — the busy file (`internal/busymark`).** `<data dir>/ctl/busy`, rewritten every 15 s while a backup, a
restore, an off-site run, the night catch-up, an app update or an app export/import runs; removed when idle and at
start. The agent refuses the operator's „Reboot guest" while it is fresh. Tests `TestBusyFileFollowsTheWork`,
`TestBusyMarkPathIsTheOneTheAgentReads` (the path is the agent's guest path), `TestBusyMarkIsWiredAtStartup`.
- **D65 = A — „Felhom support restarted your box at <time>."** The dashboard's one neutral line for a day after an
operator reboot, HU/EN (`dashboard.operator_reboot`); the idle dashboard is byte-identical (the parity fixtures pass
unchanged). Tests `TestOperatorRebootNotice_*`, `TestWatchOperatorReboot_RetriesAndKeepsTheTime`.
- **R-1350 — no „installed app is not running" after the operator's hold clear.** Measured 2026-10-29 14:57 on Tester 1:
gokapi's crash-loop hold cleared from the hub, the app stayed stopped, and 30 s later `app_start_failed` went out —
the hold had kept it out of the dead-app scan while the household's recorded wish was still „running". The clear now
records the stop as wanted (desired state „stopped") for an app that is not up, once the hold is found and before it
is lifted; a running app's wish is left alone; a refused clear records nothing; the household's Start ends it.
Tests `TestR1350_*` (the consequence through `classifyRunStates`, the order against the lift, the refusal, the up
check, the wiring).
- Every new test seen failing by a mutation (17 mutants; two first-run mutants that did not compile were re-made so they
compile, and then failed).
## v0.348.0 (2026-10-29) — clear_hold from the hub (D64 = B); the box command clears through the running controller (R-1343); the held-app mail and line name the real cause (R-1340); the OOM line once per kill (R-1341); the restore copy safe during the stable-start watch (R-1342) — built from the commit carrying this heading
### 2026-10-29 (afternoon)
**MinAgent: 0.158.1** (unchanged). The next release also carries R-1342 (`652a690`, already on main, the entry below).
**No new event type** — the hub records the operator action's result as its own `operator_action` event.
- **`clear_hold` — a fifth verb in the CLOSED operator-action list (operator ruling D64 = B, 2026-10-29 12:10)**
(`internal/report/opactions.go`, wired in `cmd/controller/opactions_wiring.go`; arg = the app's stack name, letters,
digits, `-`, `_`, ≤64 — checked before any handler). It lifts the app's hold of ANY reason in the RUNNING controller
(`backup.AppStopGuard.ClearHoldByOperator` → `settings.ClearRestoreHold`: memory and `settings.json` together), so no
later save can write it back. It starts nothing. Refused, nothing changed: a bad name, an app with no hold. One log
line names who: „hold CLEARED by the operator via the hub, action #<id>". Every reader of the hold (page, start gate,
API, `RestoreHoldFor`, hold reporter) reads the same settings record; the ONE held flag cached elsewhere —
`stacks.Manager`'s „the last update ended held" (it made the crash-loop observer and the nightly update leg skip the
app) — is forgotten too (`ForgetUpdateHeld`). A `putback_pending` hold is also dropped from the app-stop marker, or the
next start with the drive bound would pour the old copy over what the app wrote after the clear; the copy stays on
disk. The hold reporter needs no change: its next tick (≤1 min) sends `app_hold_cleared`.
Tests: `TestOpActions_ClosedList` (updated deliberately), `TestOpActions_ClearHoldBadArgumentIsRefusedAndCallsNothing`,
`TestOpActions_ClearHoldDoneRefusedFailed`, `TestD64_ClearHoldViaTheHub`, `TestD64_ClearHoldRefusals`,
`TestD64_ClearHoldStaysGoneAfterALaterSave`, `TestD64_ClearPutBackPendingDropsTheMarkerEntry`,
`TestD64_TheHoldReporterTellsTheHubAfterTheClear`, `TestD64_ForgetUpdateHeld`, `TestD64_MainWiresTheNewPieces`.
- **R-1343 — the box command `--clear-restore-hold <app>` goes through the running controller** (`cmd/controller/holdclear.go`):
a unix socket `<data dir>/ctl/hold.sock`, 0600 in a 0700 dir, peer uid checked (SO_PEERCRED), nothing on TCP — not
reachable through traefik, the LAN or an app container. Output: „Cleared by the RUNNING controller … no restart is
needed". Only when no controller answers (no socket, or a stale one) does it edit `settings.json`, and it says so,
naming the restart INSIDE the guest (`pct exec <vmid> -- systemctl restart felhom-controller-bootstrap.service`); that
edit goes through the same door, so a waiting put-back is dropped from the marker there too. The
flag's help names the exact guest command. `--restore-holds` (the list) is unchanged.
Tests: `TestR1343_TheBoxCommandClearsThroughTheRunningController` (red with the socket skipped: „the hold came back
after a later save of the running controller" — R-1343 reproduced), `TestR1343_TheBoxCommandFallsBackWhenNoControllerRuns`,
`TestR1343_TheFallbackDropsAWaitingPutBackToo`, `TestHoldCtl_NotReachableFromOutside`,
`TestHoldCtl_UnknownRequestIsRefused`, `TestHoldCtl_ANonSocketFileIsNotReplaced`.
- **R-1340, second producer (found live 2026-10-29 on rc.1, Tester 1):** the hold's `Why()` — the hub's „Held apps" line,
the box's `app_held` event and `--restore-holds` — still said „held after an off-site restore failed its database
replay" for a LOCAL restore of an app with no database. It is now built from the record (`RestoreKind`, `MixedCause`,
`FailedStep`, `DBReplay`); a record from before these fields gets the neutral „held after a restore stopped half-way".
Test `TestR1340_WhyNamesTheMixedCause` (13 assertions failed on the old sentence).
- **R-1340 — the operator's „HELD STOPPED" mail names the real cause** (`cmd/controller/holdmail.go`
`heldStoppedOperatorText`, built from the hold record). Hold writers now record `RestoreKind` (off-site / local),
`MixedCause` (`definition_write` / `put_back` / `interrupted_put_back`), `FailedStep` (the put-back step that failed,
with its error), `DBReplay`, and the kept copy's folder (`settings.RestoreHold`, all `omitempty`). The mail never says
„database" unless the failure was a database replay, never „off-site" for a local restore; a pre-R-1340 mixed hold
names only what its record says. Legs unchanged (`restore-hold`, `restore-hold-mixed`); a local restore's RunKind is
`restore`. Tests (red with the old sentence/record): `TestR1340_UnhealthyStop`, `_UpdateFailed`,
`_RestoreFailedWithADatabase`, `_PutBackWithoutADatabase` (the measured Radicale case), `_PutBackAfterADatabaseReplay`,
`_DefinitionWrite`, `_LocalRestore`, `_PutBackPending`, `_InterruptedPutBack`, `_LegacyMixedHoldAssumesNothing`,
`_NotifyReadsTheHoldRecord`; writer side `TestR1340_AVolumeFailureWhosePutBackStopFailsRecordsTheStepAndNoDatabase`,
`_ADatabaseReplayFailureRecordsTheDatabase`, `_ADefinitionWriteFailureRecordsItsCause`, `_ALocalRestoreRecordsItsKind`,
`_AnInterruptedPutBackRecordsItsCause`. `TestEventMessageWireTextIsFrozen` is untouched (this text is passed through).
- **R-1341 — the OOM line once per NEW kill** (`cmd/controller/oomlog.go` `oomLogGate`, key = container + start time +
kill count): a second scan of the same kill logs nothing; a new kill or a restarted container logs again. The
`app_oom` event call is unchanged. Tests: `TestR1341_ASecondScanOfTheSameKillLogsNothing`, `_ANewKillLogsAgain`,
`_ARestartedContainerLogsAgain`, `_ContainersAreJudgedApart`.
### 2026-10-29 (after v0.347.0) — R-1342: the restore copy is safe during the stable-start watch; a removed app does not alarm
**MinAgent: 0.158.1** (unchanged). Found live on Tester 1 at 10:39 CET: a false `backup_run_failures` mail („Gokapi did
not start … the pre-restore copy is kept") after the copy had been deleted by hand mid-watch and the app removed.
- **(1) D62 gap — `internal/backup/restore_copies.go`:** while a stable-start watch (`releaseAfterStableStart`, and the
late-start watcher) holds a copy, the copy reads „checking" in the list (one line, no delete date) and
`DeleteRestoreCopy` refuses it (`ErrRestoreCopyNeeded`) — the operator's rule is „never while an operation runs on the
app". The mark lives in `Manager.watching` under `m.mu`, the lock the delete checks under.
- **(2) R-1270 watch — `internal/backup/restore_verdict.go`:** the watch ends quietly (`stableRemoved`, one INFO line, no
alarm) when the provider says the app was removed (`StackRemovalReporter`; the production `stackAdapter.StackRemoved`
with a compile-time assertion in `cmd/controller/main.go`). An installed app that never runs stably still alarms once.
- Tests `TestR1342_ACopyUnderTheStableWatchIsNotDeletable`, `TestR1342_AnAppRemovedDuringTheWatchRaisesNoAlarm` (each
red by a mutation), the control `TestR1342_AnInstalledUnstableAppStillAlarms`, and `TestR1342_EveryNeededReasonHasItsSentence`.
## v0.347.0 (2026-10-29) — D62: restore copies kept 30 days, listed, deletable by hand; R-1256: four restore edges, all proven live (D63); R-1254 controller half; R-528: the host's OOM count; an unknown app is a 404 — RELEASED (image `sha256:c79b06e6…`, from `fd75c7c`, CI 2491; rc.1 = `e3fce09` on scratch 9202); per-box floors 09:57 CET, global floor 2026-10-29 10:31 CET on the operator's yes (MinAgent 0.158.1)
### 2026-10-29 (attended) — D62 and D63
**MinAgent: 0.158.1** (unchanged). Needs hub ≥ the release carrying `restore_copy_deleted` (felhom.eu `19afefab`): an
older hub answers that one event 400 and the record is lost (the delete itself is unaffected).
- **D62 (operator ruling 2026-10-29 08:17) — the age: 30 days** (`restoreCopyUnusedAge`, was 14, the night's safest
reading). `TestD62_AnUnusedCopyIsKept30Days` (red at 14: the 20-day copy was swept).
- **D62 — the list (`backup.RestoreCopies`, `web.restoreCopyRows`, `backups_restore.html` „Megőrzött másolatok"):** each
restore copy shows the app, the date of the restore it protects, its size and „automatikusan törlődik: <date>". A copy
a hold or a pending put-back needs (a hold; the putback_pending hold; the app-stop marker naming it; an unreadable
marker) shows why in one line and its button is off — it never gets a date, because the sweep never takes it.
- **D62 — „Törlés most" (`POST /backup/restore-copy/delete`, `backup.DeleteRestoreCopy`):** the warning names the app
and the restore's date (the operator's text, hu + en); the household types the app's name. JSON answer: 200; 400 a
wrong name; 404 no such copy; 409 the copy is needed, or a backup/restore runs, or the app updates. The check and the
removal are one step under the backup manager's lock (no restore can begin in between). Path guard: both names one
path element, the copy a real directory (not a link) directly under `backups/restore-undo/<app>/`. One `[WARN]` log
line and one operator event `restore_copy_deleted` (who, app, restore date, size) per delete. CSRF as every form.
Tests `TestD62_*` (backup, web, notify) — each seen failing by a mutation of the check it pins.
- **D63 — the fault switch, TEST BUILDS ONLY (`cmd/controller/faultpoint_{on,off}.go`):** `go build -tags faultinject`
arms two points from a file (`<data>/faults/<point>` = „<skip> <fail>"): `defwrite-after-compose` (the definition
writer fails after the compose was written — H4) and `stop-<app>` (the app's stop fails — H5). Without the tag it
is a no-op that reads nothing; `TestD63_TheReleaseBuildHasNoFaultSwitch` pins that, and that build.sh and the
Dockerfile pass no build tag (red-proofed both ways).
### 2026-10-28 night — four restore edges (felhom.eu R-1256, review round 2 HUNT-1 H4/H5/H6/H8)
**MinAgent: 0.158.1** (unchanged). Each edge: a test seen failing first, then the fix; live proof on 9202 in the felhom.eu
night report (`audits/night-2026-10-28/`). **Live 2026-10-29 on 9202:** H5's busy volume (not written into, the live data
put back, no hold) and H8 (the 03:29 sweep removed the two old copies, kept the young one). **Live 2026-10-29 on Tester 1
(D63, a `-tags faultinject` test build):** H4 (the live definition written back before the start) and H5's failed stop
(nothing put back, the copy kept, the app held). H6: tests only (the old code refused at the early check too).
- **H4 — `internal/backup/offbox_reconstitute.go`:** an off-site restore whose definition write (or database-password
write) fails no longer starts the app at once. The writer writes the compose BEFORE the app's settings, so the stack
dir could hold the snapshot's (older) compose: the live definition is written back first, then the app starts
(`restartAtLiveDefinition`); when the write-back fails too, the app is held (`restore_mixed`), never started on the
snapshot's definition. Tests `TestR1256_H4_*`.
- **H5 — a put-back whose stop fails does not go on.** `putBackAfterFailedRestore` (off-site and local unit restore):
a failed stop pours nothing, keeps the copy and holds the app; a failed definition write-back keeps the copy too (D20:
a put-back that fails keeps its copy). `CrashPutBack.PutBackInterruptedRestore` (a restore cut by a power loss): a
failed stop is an error, so the start holds the app (R-1251 H2) instead of pouring under a running app.
`restoreDockerVolumesFrom`: a `docker volume rm -f` that fails (the volume is in use) counts as a failed volume — the
following `volume create` was a no-op and the tar was unpacked ON TOP of the old content (a merge). Tests
`TestR1256_H5_*`. One log line corrected: a failed start after a put-back no longer says the copy stays (it is removed;
the volumes are back).
- **H6 — a restore begins in the same step as the check for every other operation.** New
`backup.TryBeginRestoreOp` / `RestoreBusy` (under `m.mu`, the lock the second-drive mirror's `beginTier2Run` asks
under): a restore op in flight, the backup run, a second-drive copy. Every web restore handler begins through
`Server.beginRestoreOp` (a source test refuses a direct `BeginRestoreOp`); the kept loads (`LoadKeptApp`,
`LoadKeptOffsite`) return `ErrRestoreBusy` with nothing started, and `LoadKeptApp` takes the dated folder's file move
as `prepare`, inside the operation. The install-time „use my kept data" asks about the second-drive copy too
(`RestoreBusy`, was RestoreStatus/IsRunning only). Tests `TestR1256_H6_*` (backup, web, api).
- **R-1254 H2, the controller half (felhom.eu R-1254; agent `5ddd124`):** the escrow claim and confirm reach the agent
with their own 60 s timeout (`agentapi.escrowCallTimeout`; was the client's 15 s) — the agent may spend its 30 s
upload plus 15 s asking the hub before it answers, and a claim abandoned at 15 s could still store a package whose
code reached nobody. The confirm's household sentence: 502 (the hub holds another package) keeps „…a régi kódod
továbbra is érvényes…"; 504 (the agent cannot learn the outcome) or a failed call (0) now reads
`api.escrow.confirm_store_unknown` („Nem tudjuk biztosan… Őrizd meg mindkét kódot…", hu + en) and never promises the
previous code. `TestR1151_ConfirmAnswersInTheBoxLanguage`'s status-0 case changes with it, on purpose. Tests
`TestR1254_*` (agentapi, web), red before the fix.
- **R-528 — the OOM line sees a kill Docker does not report (felhom.eu R-528; agent `GET /guest/oom-kills`).** The
30-s dead-app scan (`stacks.ScanOOMKilled`) now also asks the host's agent once per scan for the kernel's per-container
`oom_kill` counter (`agentapi.GuestOOMKills`, wired in `cmd/controller/hostoom_wiring.go`, 5 s cap). A running
container whose current run has a count above 0 is an OOM kill whatever Docker's `OOMKilled` says: the existing
`app_oom` line (once per run, R-514/R-636) fires, its details carry `source` (`docker`, `cgroup` or `docker,cgroup`),
and the host's count is the run's kill count. An agent without the route (404) is asked again only after 10 minutes
and said once; no agent (9202) = Docker's flag only, as before. The inspect now reads `{{.Id}}` too. Tests
`TestR528_*` (stacks, cmd/controller), red before the fix (the host-counted kill was not seen) or red-proved by
mutation (the back-off, the wiring).
- **Found walking the capability map's B2 on 9202 (small, fixed in the session):** a Stop/Start of a name that is no
app on the box (the bootstrap-managed `felhom-controller`) answered 500 „…az alkalmazás beállításai nem menthetők." —
the desired-state write's „not found" read as a save failure. `stacks.SetDesiredState` returns the
`ErrStackNotFound` kind with the household's sentence (`err.stacks.alkalmazas_nem_talalhato`); `actionStack` answers
404 before recording any intent. Nothing was ever stopped. Test `TestAnActionOnANameThatIsNoAppIsA404` (red first).
- **H8 — `internal/backup/restore_copy_sweep.go`:** an unused restore copy goes after 14 days. Every 6 hours
(`restore-copy-sweep`) a copy is removed only when the app has no restore hold of any kind, the app-stop marker is
readable and does not name the app, no restore runs, and the copy is older than 14 days. Tests `TestR1256_H8_*`
(and the wiring test).
## v0.346.1 (2026-10-27) — SECURITY: traefik v3.7.16, the file manager 1.5.8-stable, cloudflared 2026.10.4 — built from v0.346.0 (`b1b9be3`) + one commit (felhom.eu R-1304, R-1305)
**MinAgent: 0.158.1** (unchanged). Box programs only; no other change from v0.346.0.
- `internal/infra`: `TraefikImage` `traefik:v3.7.13` → `traefik:v3.7.16` (12 notices between; none reaches our config —
docker + file providers, no FastProxy, no NTLM backend, no Kubernetes; the v3.7.14–16 migration notes touch only
Kubernetes provider names, OTel histograms and a CONNECT request now answered 501). `FileBrowserImage`
`gtstef/filebrowser:1.5.6-stable` → `1.5.8-stable` (GHSA-qx86-4v5r-26g5 TOTP re-enrolment, GHSA-3846-gh75-gp3m upload
share, and the 1.5.8 fixes; 1.5.7-stable is skipped — it broke existing TOTP sign-ins). `CloudflaredImage`
`2026.10.3` → `2026.10.4` (VULN-176088: the metrics server's debug endpoints; ours is not reachable from outside — low).
- How a box takes them: the reconcile at start, as for 0.345.1 — traefik's compose changes → `up -d --force-recreate`
(new test `TestEnsureTraefik_ANewImageRecreatesTraefik`, red-proved: it fails when a compose-only change is skipped);
cloudflared `TestEnsureCloudflared_ANewImageRecreatesTheTunnel`; the file manager
`TestReconcileFileBrowserImage_MovesOnlyTheImage` (mounts unchanged; it rejoins the app network only after the
password check, R-1281).
## v0.346.0 (2026-10-27) — D53: the hub learns which apps are held; an unreadable app.yaml keeps its folder (R-1220); the ceremony keeps the off-site key (R-1218, R-1219); safe .fab export/import (R-1187); holds of uninstalled apps are not reported (R-1298); Go 1.27.3 (R-972); the line-test hold waits for the seeder to slow down (R-1250) — RELEASED on the operator's yes (attended release block)
**MinAgent: 0.158.1** (unchanged). Operator ruling D53 (2026-10-26, felhom.eu `09` §3 decision 265): operator-only
reminders first. Needs hub with `app_held` / `app_hold_cleared` in `allowedEventTypes` (felhom.eu, same day) — an older
hub answers 400 to both and nothing else changes.
- `internal/holdreport`: ONE observer of the hold store (`settings.RestoreHolds`), ticked by the scheduler every minute
(`hold-report`). `app_held` for a new or changed hold (details `stack_name`, `reason` — the empty legacy reason is sent
as `restore_failed` — `since`, `why`), `app_hold_cleared` when a hold is gone; every hold is sent again once a day and
at each start (`repeat: true`). The last-reported set is kept in `settings.reported_holds`, so a hold cleared while the
controller was down is still reported cleared. Both severity info (the hub mails nothing on receipt).
- **R-972: Go 1.27.3** (`go.mod` + the builder image `golang:1.27.3-*` pinned by digest; released 2026-10-19 with a
security fix to `crypto/x509`). `govulncheck` v1.8.0: 1 called vulnerability before (GO-2026-6809), 0 after; full
`go build/vet/test` green. `golang.org/x/crypto` v0.58.0 is already the newest.
- **R-1220 (P2, delete path):** an app whose `app.yaml` EXISTS but cannot be read counts as INSTALLED (fail closed):
`stacks.liveDriveBinds(drives)` adds every folder its compose binds on every given drive, so „Megőrzött adatok" never
lists — and never offers to delete — that app's live folder; one WARN names the app. Before: a parse error gave a nil
`AppConfig`, the app read as not installed, its folder was a „leftover". Test `TestR1220_AnUnreadableAppYamlKeepsTheFolderLive`
(with a real leftover as the control), red-proved against the old code.
- **R-1218 (P2, key code):** the recovery ceremony stages the off-site repository password whenever the password FILE is
on the box (`backup.Manager.OffboxRepoPasswordOnBox`), not only when off-site is configured — a cleared or switched-off
target keeps the file, and a ceremony that sealed no password let the hub demote the household's good package (the
hub half refuses that demotion: felhom.eu hub, same night). Test `TestR1218_TheCeremonyStagesWhenThePasswordFileExists`
(off, cleared, and a box with no password as the control), red-proved („preflight,start" — no stage).
- **R-1219 (P2, key code):** during a recovery offer the top bar no longer urges the ceremony, and `POST
/api/escrow/start` answers 409 with `api.escrow.recovery_offer_open` (hu + en) before anything is staged or started.
Tests `TestR1219_*` (the bar with a real session, and the same box without an offer as the control), red-proved (bar
shown, start 200).
- **R-1187 (P2, `.fab` export/import) — (a), (b), (d), (f), (g):** (a) the export carries a symlink AS A LINK (never its
target's bytes) and stops with `err.appexport.kulonleges_fajl` naming the path on a FIFO, socket or device (a FIFO used
to hang it); a drive folder that cannot be packed now FAILS the export (it was left out with a WARN while the export
ended „done"). (b) the import keeps owners (`Lchown`) and modes and restores a link that stays inside the app's folder;
a link pointing outside is refused and listed in a WARN. (d) `StartImport` refuses (`err.appexport.import_foglalt`)
while another operation holds the app-stop marker (`BusyWith`). (f) a bundle whose `app.yaml` carries an empty,
relative or unclean `HDD_PATH` is refused before anything is touched (`err.appexport.hdd_path_hibas`). (g) the import
classifies databases with the backup side's predicate (`appbackup.DBTypeForImage`: postgis, pgvector, timescaledb) and
runs `psql -v ON_ERROR_STOP=1`. Tests `internal/appexport/r1187_abdfg_test.go` (6), red-proved with the old behaviour
behind the new function shapes (link packing error, a 10-s hang on the FIFO, link not restored, import not refused,
bad paths accepted, postgis missed).
**Follow-up (the automated security review, same night):** the import writes only through `os.Root`, so no entry is
written through a link already in the folder that points outside; such an entry is refused and listed. Test
`TestR1187b_NoWriteThroughALinkThatLeavesTheFolder`, red-proved (the file landed outside with plain `os.Create`).
A second review finding: a link entry whose parent path passes through a link („a" → „.", then „a/b/l" → „../..")
passed the path-text check while really pointing above the folder — now refused and listed
(`TestR1187b_NoLinkThroughALinkedParent`, red-proved). psql takes `--set=ON_ERROR_STOP=1` (the `-v` short form tripped
the docker `-v` gate); the four new message keys are listed in `scripts/i18n_go_keys.json` as born keys.
A third review finding: a link TARGET through a link already in the folder („x" → „evil/y", evil pointing out). The rule
is now strict and simple: a restored link points only DOWNWARD — relative, no „..", no link on its path or in its
target; everything else is refused and listed (`safeDownwardLink`; `TestR1187b_NoLinkTargetThroughALink`, red-proved).
**Found live on 9202 the same night (grimmory), fixed:** the import ran `compose` without the controller's own path
variables (`USERDATA_PATH`, `IMPORT_PATH` — `stacks.policyEnv` adds them at every install and start); compose printed
„The USERDATA_PATH variable is not set" and the DB step read that WARNING as the container id, waited 60 s and left the
app removed and not started. Now `withImportPathVars` gives the import's compose runs the same derivation (never a
bundle's value) and `containerIDFrom` takes only a line that IS an id. Tests `TestR1187_TheContainerIDIsNeverAComposeWarning`,
`TestR1187_TheImportEnvCarriesTheControllersPathVars`, red-proved.
**And the second cause, found by the same live run:** the import waited with `mysqladmin` and loaded with `mysql` —
names the MariaDB 11+ images do not ship (only `mariadb-admin` / `mariadb`; checked in `mariadb:11.4`) — and read the
password from two fixed env names, so EVERY `.fab` import of a MariaDB 11+ app timed out and left the app down. The
import now loads through the backup side: `appbackup.DiscoverDatabases` (the live container's own credentials) and
`appbackup.ImportDump` (mariadb / mariadb-admin; psql `ON_ERROR_STOP` + `--single-transaction`); the import's own
`waitForDB` / `importDBDump` are removed. `appbackup.DBTypeForImage` stays the classifier (g). Test
`TestR1187_TheImportLoadsTheDumpThroughTheBackupSide` (seams, no Docker), red-proved with the old body.
- **R-1298:** the hold report skips an install's hold (`unhealthy_stop`, `update_failed`, `putback_pending`) of an app that
is not installed (`holdreport.Reporter.SetInstalled`: the app's `app.yaml` exists — an unreadable one still counts,
R-1220) and reports it cleared if it was reported; a restore hold is always reported (R-379). 9202's four orphan holds
from a hand removal would otherwise have mailed weekly. Test `TestR1298_OnlyHoldsOfInstalledAppsAreReported`,
red-proved; the wiring test pins the `SetInstalled` line.
- **R-1250 (the line test for a box that seeds all day):** after the hold the controller now waits until every held app
REPORTS its own upload near zero (qBittorrent `transfer/info` `up_info_speed`, Transmission `session-stats`
`uploadSpeed`; ≤ 16 KiB/s on two readings 2 s apart, at most 90 s; an unreadable speed waits 20 s) and only then asks
the agent (`upwatch.waitDrained`). Measured on demo-hp 2026-10-27: qBittorrent 5.2.4 kept sending at full speed for
~14 s after its limit fell to 1 KiB/s, while the agent reads the uplink 5–15 s after the call — four tries in an hour,
each refused „not quiet" (4.0–4.2 Mbit/s). New `Holdable.UploadRate`. Tests `TestR1250_*` (five), red-proved by four
mutations (no wait; only the first app read; no fallback wait; no maximum → hangs).
- `settings.RestoreHold.Why()` / `WireReason()`: the hold sentence moved out of `cmd/controller` (`holdWhy` calls it), so
`--restore-holds` and the hub's list say the same thing.
- Tests `internal/holdreport/holdreport_test.go` (8): the report field, the daily repeat, cleared once, cleared while
down, a changed reason, the wire reason, the wiring in main, the record across a reload. Red-proved with an inert
`Tick` (all six behaviour tests failed) and with the scheduler line commented out (the wiring test failed).
- **R-1303 (tooling, no runtime change): every pin names where its security notices are published.** `internal/infra/
upstream.txt` beside `infra.go` (one line per `*Image` const), and a `# upstream:` comment directly above every
`FROM` (`Dockerfile`, `infra-images/samba/Dockerfile`) and `ARG RESTIC_VERSION`. Gate `upstream` (`--fast`, SHARED:
felhom.eu `scripts/security_watch_inventory.py --gate=controller`) refuses a pin with no line; decoys in
`scripts/test_gate_decoys.py` (a new const with no line, the line only in a comment, the comment one line too high,
a new FROM with none), red-proved. The nightly security watch (felhom.eu `scripts/security_watch.py`) reads them.
## v0.345.1 (2026-10-26) — SECURITY: cloudflared 2026.10.3 (Cloudflare's eMudhra notice) — built from v0.345.0 + one commit (R-1300)
**MinAgent: 0.158.1** (unchanged). **This entry on `main` records the same change as the tag `v0.345.1`** (the v0.345.0
commit `6bfb784` + one commit); the image is built from the TAG, so none of the „Unreleased" work above is in it — the
next release from `main` carries the bump by itself.
- **Security:** `infra.CloudflaredImage` `cloudflare/cloudflared:2026.9.3` → `2026.10.3` (Docker Hub index digest
`sha256:faa8e0a1475f137c910be6025f43c8e4092fdd35461b31e19fd1390657a1ff39`). Cloudflare's notice of 2026-10-20:
cloudflared before 2026.10.2 trusts eight eMudhra (emSign) intermediate CAs whose private keys were weak and are
recoverable — anyone holding them could pose as any website to cloudflared. The fix is the image's trust store.
- After the controller update `ensureCloudflared` sees the compose differ (the `image:` line) and runs `compose up -d`,
which recreates cloudflared on the new image. Test `TestEnsureCloudflared_ANewImageRecreatesTheTunnel`, red-proved.
- Origin check (read only): every tunnel routes `*.<domain>` → `https://traefik` with `noTLSVerify: true` (R-510) and
traefik answers with its self-signed default certificate — no eMudhra chain. felhom.eu
`documentation/audits/cloudflared-2026.10.3-2026-10-26/`.
- **`build.sh` (main only — the operator's yes, 2026-10-26):** a `--push` may also build from the tag `v<VERSION>` AS
THE SERVER HAS IT when it points at HEAD — a patch release off a released commit while `main` holds unreleased work.
A tag only on the clone, a tag on another commit, a tag of another version, or a server that cannot be asked is a
refusal; clean-tree stays required. Four new cases in `scripts/test_build_push_once.sh` (20/20), red-proved both
ways (the tag branch accepting anything: 4 fail; removed: 1 fails).
## v0.345.0 (2026-10-26) — the 50 % rule owns qBittorrent's NORMAL limit only (R-1292) — attended release run (afternoon)
Live before the release: Tester 1 on `0.345.0-rc.1` with a throwaway qBittorrent, alternative speed ON (the household's
+50
View File
@@ -1,5 +1,55 @@
# CONTEXT.md — Project Memory
> **2026-11-10 (afternoon, attended) — v0.352.0 RELEASED: one fill warning per filesystem (felhom.eu R-1371).**
> Global floor 15:31 UTC, MinAgent 0.158.1; rc.1 on scratch guest 9202, then the three test boxes through per-box
> floors, walk green (felhom.eu `audits/release-space-fixes-2026-11-10/controller/`). `fillTargets` keeps one target per
> filesystem (`system.FilesystemKey`; an overlay "/" is identified by a Docker-kept file's device, not by its own).
> Seen on 9202: two warnings for one fill before, one after. Still open, by design question: the guest's own root disk
> has no fill watcher (felhom.eu `16-storage-physical-identity.md`).
> **2026-11-09 (attended) — v0.351.0 RELEASED** (global floor 12:18 UTC, MinAgent 0.158.1; rc.1 on Tester 1, then the
> three test boxes through per-box floors, walk green; felhom.eu `audits/release-2026-11-09/`). Operator's word 2026-11-09 („go with A"): decision 56 amended
> (an old `-rc` controller image is deleted like an old release) and decision 285 (pinned infra images keep the pin + the
> previous pin). Measured cause: demo-hp's whole-guest local copy refused for space (felhom.eu R-548); 3.5 GB of its 27.5 GB
> of images were these kinds. The bigger lever — the whole-guest copy carries every Docker image — is a design question
> (felhom.eu register, filed the same day).
> **2026-11-03 (day, attended) — v0.350.0 RELEASED, the global floor since 08:18 CET (MinAgent 0.158.1).** Image `sha256:9ee53908…` from `5c336d8`. Traefik v3.7.17 (GHSA-xv5x), R-1347, R-1348, R-1339, R-1351, R-1323. Golden 0.350.0 vouched 10:18:10 CET.
>
> **2026-10-29 (evening, attended) — v0.349.0 RELEASED, the global floor since 19:24 CET (MinAgent 0.158.1).** Image
> `sha256:c5341883…` from `94049a7`. D65 = A: `internal/busymark` keeps `<data>/ctl/busy` fresh while the controller's
> own work runs (the agent refuses „Reboot guest" meanwhile); the dashboard shows „A Felhom ügyfélszolgálata HH:MM-kor
> újraindította a dobozt." for a day after an operator reboot (`GET /guest/operator-reboot`, asked once at start).
> R-1350: the operator's hold clear records the stop as wanted (desired state „stopped") before the hold is lifted —
> proven on Tester 1, no `app_start_failed` in 6.5 minutes. 30-minute watch clean; per-box floors cleared.
> **2026-10-29 (afternoon, attended) — v0.348.0 RELEASED, the global floor since 14:48 CET (MinAgent 0.158.1).** Image
> `sha256:672fc1c1…` from `2a0a17a` (CI 2515). D64 = B (`09` §3 decision 283): `clear_hold` is the fifth verb of the closed
> operator-action list; any hold reason; the running controller clears memory and `settings.json` together through
> `<data>/ctl/hold.sock` (0600, peer uid checked), and `--clear-restore-hold` goes through it when a controller runs
> (R-1343). R-1340 (both producers name the real cause), R-1341 (OOM line once per kill), R-1342 (no delete during the
> stable-start watch). Proven live on Tester 1 on the release build: a crash-loop hold cleared from the hub stayed
> cleared after the next settings save. Open: R-1350 (an `app_start_failed` 30 s after a clear), R-1347, R-1348.
> **2026-10-29 (attended release run) — v0.347.0 RELEASED, the global floor (MinAgent 0.158.1).** Image `sha256:c79b06e6…`
> from `fd75c7c` (CI 2491); rc.1 = `e3fce09` on scratch 9202. Carries the night's R-1256 (all four edges, H4 + H5's
> failed stop proven live on Tester 1 with a `-tags faultinject` test build — D63), R-1254 controller half, R-528, the
> unknown-app 404, and D62 (restore copies 30 days; „Törlés most" in the kept-copies list; `restore_copy_deleted` needs hub
> ≥ 0.175.0). The fault switch (`cmd/controller/faultpoint_{on,off}.go`) is a no-op in every build without the tag
> (`TestD63_TheReleaseBuildHasNoFaultSwitch`). Next here: R-1340 (the mixed-hold operator mail), R-1341 (the OOM WARN every
> 30 s), R-1339 (the false „not mounted" line).
> **2026-10-28 night (unattended) — R-1256, R-1254 (controller half), R-528 and the unknown-app 404 on `main`, NOT
> released (`342a394`, `e33cffa`, `eed23e7`, `20c5877`; MinAgent unchanged).** Restore ops begin through
> `Manager.TryBeginRestoreOp` / `web.beginRestoreOp` only (`TestR1256_H6_NoHandlerBeginsARestoreUnchecked` refuses a direct
> `BeginRestoreOp` in a handler). **Decided by CC unattended — operator may reverse:** an unused restore copy goes after
> 14 days (`restoreCopyUnusedAge`; felhom.eu `07` §6.3). H4 and H5's failed stop: tests only, live proof owed. H5 (busy
> volume) proven live on 9202, R-528 on Tester 1, with the local test tag `0.347.0-rc.n1028` (never pushed).
> **2026-10-26 (evening) — D53 ruled (felhom.eu `09` §3 decision 265): held apps reach the OPERATOR first.** Next here:
> the controller reports its holds (stack, reason, since) to the hub as `app_held` / `app_hold_cleared` events plus a
> daily re-send (felhom.eu `08` §10). Commit only; the release rides a later attended run.
> **2026-10-25 (Sunday, unattended) — D47, D48, R-1270, R-1271 on `main`, NOT released (next v0.343.0, MinAgent 0.158.1
> unchanged).** D47 (`02daebe`): `stacks.AppConfig.InstallID` (minted at install/import, taken from the unit by a
> restore, `EnsureInstallID` for older apps); `backup/unit_owner.go` `guardUnitWrite`/`guardUnitDir` in every unit writer
+19
View File
@@ -0,0 +1,19 @@
# REPORT — controller v0.346.1: traefik v3.7.16, the file manager 1.5.8-stable, cloudflared 2026.10.4 (security), 2026-10-27 (attended)
> A sibling of `REPORT.md`, not an overwrite: the release session of the same day (v0.346.0) owns `REPORT.md`.
## In plain words
- **What:** three box programs had public security notices: traefik (12 notices, none reaching our config), the file
manager (a TOTP re-enrolment and an upload-share flaw; 1.5.7 is skipped, it broke TOTP sign-ins) and cloudflared
(debug endpoints on its metrics server, not reachable from outside). Controller **0.346.1** = the released 0.346.0
(`b1b9be3`) + only the three new pins.
- **How a box takes them:** the reconcile at start recreates each container on its new image (traefik pinned by the new
test `TestEnsureTraefik_ANewImageRecreatesTraefik`, red-proved).
## Gates
`controller_gates.py` (full) green; `go test ./...` green (41 packages); `go build`, `go vet` green.
Evidence and the box proofs: felhom.eu `documentation/audits/security-app-updates-2026-10-27/part5/`. Register:
felhom.eu R-1304 (traefik), R-1305 (file manager).
+40
View File
@@ -0,0 +1,40 @@
# REPORT — controller v0.345.1: cloudflared 2026.10.3 (security), 2026-10-26 evening (attended)
> A sibling of `REPORT.md`, not an overwrite: the night session (D53, R-1218/1219/1220) owns `REPORT.md` tonight and
> writes into this repo at the same time.
## In plain words
- **What:** Cloudflare said on 2026-10-20 that cloudflared before 2026.10.2 trusts eight bad certificate issuers
(eMudhra, weak keys). Every Felhom box ran cloudflared 2026.9.3 in its guest. Controller **0.345.1** = the released
0.345.0 + only the new cloudflared pin `2026.10.3`. Nothing from tonight's `main` is in it.
- **Did it work:** yes. Every box with a tunnel (Tester 1, demo-hp, demo-felhom) runs controller 0.345.1 and cloudflared
2026.10.3, healthy; the hub says „running (connected)" for all three; all 29 public names still redirect http → https.
Tester4 moved to 0.345.1 by the global floor (it has no tunnel). Tester 2 has no box.
- **Gaps:** the tunnel was down about 2 s (Tester 1), 4 s (demo-felhom) and 11 s (demo-hp) while cloudflared restarted.
## What changed
| Where | What |
|---|---|
| tag `v0.345.1` = `f3204024` (on `6bfb784`) | `infra.CloudflaredImage` → `cloudflare/cloudflared:2026.10.3`; test `TestEnsureCloudflared_ANewImageRecreatesTheTunnel`; CHANGELOG entry |
| `main` `a1c65b3d` | the same change, plus `build.sh`: a `--push` may build from the pushed tag `v<VERSION>` when it is HEAD (operator's yes, this session); 4 new cases in `scripts/test_build_push_once.sh` |
- Red-proofs: the new reconcile test failed with the „compose changed" check removed; the build cases failed both ways
(tag branch accepting anything: 4 of 20 fail; tag branch removed: 1 of 20 fails).
- Gates `--fast` green on both commits; `go test ./...` green on the tag commit (`internal/stacks` 450 s under the night
session's load). CI by commit: `a1c65b3d` job 2392 success; `f3204024` job 2393 success (run_attempt 1 each).
- Image `gitea.dooplex.hu/admin/felhom-controller:0.345.1` (and `:latest`) digest
`sha256:7cfdf7e1f835628de9c7d536e0a60c06bad5bbe19e8133765cc0a6bb732dbff6`, built from `f3204024`.
- cloudflared image index digest `sha256:faa8e0a1475f137c910be6025f43c8e4092fdd35461b31e19fd1390657a1ff39`.
- How a box takes it: `controller/internal/stacks/infra.go` `ensureCloudflared` — the rendered compose differs (the
`image:` line) → `compose up -d` recreates the container. Seen on all three boxes: `[infra] cloudflared compose
changed … recreating cloudflared` 1–2 s after `[selfupdate] Post-update startup: update successful (0.345.0 → 0.345.1)`.
## For the night session
`main` carries the bump (`a1c65b3d`). Your next release from `main` keeps cloudflared 2026.10.3 — no action needed.
Your CHANGELOG „Unreleased" block is unchanged; the v0.345.1 section sits between it and v0.345.0.
Evidence: felhom.eu `documentation/audits/cloudflared-2026.10.3-2026-10-26/`. Register: R-1300 (closed), R-1301
(opened). Full session report: felhom.eu `REPORT-cloudflared-2026-10-26.md`.
+12
View File
@@ -0,0 +1,12 @@
# REPORT — the security watch's pin list (felhom.eu R-1303), 2026-10-26 night
> A sibling of `REPORT.md` (the night session owns it tonight). The full report: felhom.eu
> `REPORT-security-watch-2026-10-26.md`.
- **What changed here:** every pin now names where its security notices are published, and a push gate (`upstream`,
`--fast`) refuses a pin without one. The rule and its reader are shared: felhom.eu `scripts/security_watch_inventory.py`.
Decoys for the gate were red-proved with a reader that reads comment lines.
- **Why:** the nightly security watch (felhom.eu `scripts/security_watch.py`, CI 03:40 UTC) reads these lines. No
runtime change: nothing on a box changes, nothing is released.
- **First run:** see felhom.eu `documentation/audits/security-watch-2026-10-26/ADVISORIES-2026-10-26.md` and rows
R-1304 (traefik), R-1305 (the file manager), R-1306 (27 apps).
+12 -28
View File
@@ -1,30 +1,14 @@
# REPORT — controller v0.344.0 released (2026-10-26, attended release run)
# REPORT — controller 0.354.0 (2026-11-19)
**Plain words first.** Every box runs 0.344.0. The global floor was set at 09:07:47 UTC (MinAgent 0.158.1) on the
operator's yes, after the three test boxes moved through their per-box floors and the release-build checks passed. New
installs start on it too: golden 0.344.0 was baked and vouched the same day, and a fresh install came up on 0.344.0
with no update step. The file manager restarted once at the update, as the release notes say.
Released in the attended run of 2026-11-19 (release 4). The full report is felhom.eu `REPORT-release-4-2026-11-19.md`.
## Release
- Image `felhom-controller:0.344.0`, sha256 `9435165dab85b1200d94157ec49d8be065889139e1831a5476dc68f4b9474b8a`, built
from `0a59044` (CI 2355 ✓). The rc `0.344.0-rc.4` (same commit) ran on 9202 first; 9202 is back on 0.343.0.
- Per-box floors 0.344.0 for Tester 1, demo-hp, demo-felhom (08:15 UTC; each moved by the normal update path, healthy),
then the global floor (read back from the hub DB with its WAL and from the hub log), then the per-box floors cleared.
- Fleet after the floor: demo-felhom, demo-hp, tester-1 report 0.344.0; Tester-2 has no box since 2026-10-04 (R-862).
## Checks on the release build (felhom.eu `documentation/audits/release-monday-2026-10-26/`)
| Row | Check | Result |
|---|---|---|
| R-1281 | FileBrowser's networks; a forged header from apps; the household's files; OnlyOffice linked | on all three boxes FileBrowser only on `felhom-filebrowser` + `felhom-files`; qBittorrent/Sonarr/Radarr/Prowlarr → 000 (control: controller 404, traefik 301); Tester 1: dashboard → pass → cookie → listing 200, no cookie 401; OnlyOffice joined `felhom-files`, editor config 200, the OnlyOffice container fetched the document 200 — closed |
| R-1282 | „Később", then a controller restart | the stored 03:30 kept (start-up line + settings.json) — closed |
| R-1278 | install page with a kept backup | hint + link shown; none before or after — closed |
| R-1286 | Kimai's install id; the hold sentences | id written 07:01:55Z; `holdWhy` released — closed |
| R-1288 | released | proven live on the night's rig — closed |
| R-1261 | released | the live line test is Tuesday (R-1250's dated check) — stays VERIFY |
| D47 | upgrade count | 0 set aside on all three boxes; every app has an install id |
**Observation (NOT-A-FINDING):** on 9202's rc start the first FileBrowser round logged a WARN „could not join felhom-files
(files.<domain> stays unreachable)" because FileBrowser was being re-created in the same second; it joined 2 s later.
Log only, no event; the three release boxes logged no WARN.
- **What:** the off-site copies of a removed app end 30 days after „delete backup data”; the remove dialog names the
day (and shows the older sentence about the nightly snapshots only where no day is shown); the Backups page marks
the app with „keep it after all”; „delete in 30 days” for a removed app with copies and no mark. The household's
notice is sent by the hub (≥ 0.183.0), not by the box.
- **Image:** `sha256:c88522ed…`, from `440711b`, CI run 2713. MinAgent 0.158.1 (unchanged).
- **Proof:** rc.1 on demo-hp's guest 9201 (the test household): the press, the take-back, a second press and an
address change, each seen on the box, on the hub and in the inbox. The removal itself is first seen on 2026-12-22.
- **Floors:** tester-1 and demo-hp per box 09:29 UTC; global 09:32:18 UTC; the N100 by the floor at 09:32. Box walk
green on all three; per-box floors cleared.
- **Golden:** 0.354.0 baked and vouched 2026-11-19.
+12 -4
View File
@@ -35,7 +35,8 @@
| `dockerexec.BeginImageWork(args)` / `TryImageCleanup()` / `ImagePulling(args)` (v0.294.0, R-863) | controller/internal/dockerexec/imagework.go | `defer dockerexec.BeginImageWork(args)()` | **Every NEW place that runs `compose up/pull/create/run` must hold it** (the stacks compose helpers, appexport's restore and the FileBrowser sync already do) | An image pulled by compose is named by no container until compose creates one; a clean-up pass in that window deleted it (measured, R-863). The pass takes the lock exclusively without waiting; pulling commands wait for a running pass (seconds) |
| `nightchain.Ledger` / `CatchUp` / `ResumeWatch` / `ComputeBanner` (v0.295.0, R-871) | controller/internal/nightchain/ | `Open(path, now)`, `MarkEnded(leg, t)`, `Missed(now, W, loc)`, `Evaluate(ctx, why)` | "was a night missed?" and making it up; the missed-backup banner's rule | The ledger is an ATTEMPT record (ran to its end) — never evidence a backup exists; a NEW nightly backup leg must be wrapped by `withLeg` in main.go and listed in `nightchain.Order`, or the catch-up never makes it up; never add the update leg to `catchUpLegs` |
| `scheduler.DailyLateLimit` (v0.295.0) | controller/internal/scheduler/scheduler.go | — | a daily timer firing > 60 min late (host suspend) is skipped | do not "fix" a late fire by running it: the app-update leg would run at noon |
| `stacks.RetainControllerImages(ControllerImageRecord)` · `selfupdate.UpdateState.RecordedPrevious` (v0.285.0, decision 56) | controller/internal/stacks/controller_image_retention.go | `({Repo, Running, Previous})` | Deletes controller images older than the running + previous one | The previous comes from the SWAP RECORD (success onto the running version), version order only as the fallback; versions above the running one and non-version tags are kept; skipped while the controller swaps itself; same `imageDocker` seam |
| `stacks.RetainControllerImages(ControllerImageRecord)` · `selfupdate.UpdateState.RecordedPrevious` (v0.285.0, decision 56) | controller/internal/stacks/controller_image_retention.go | `({Repo, Running, Previous})` | Deletes controller images older than the running + previous one | The previous comes from the SWAP RECORD (success onto the running version), version order only as the fallback (a release preferred over a test build, v0.351.0); versions above the running one and non-version tags (`latest`) are kept — an `-rc` tag IS a version (`util.ParseVersionPre`) since v0.351.0; skipped while the controller swaps itself; same `imageDocker` seam |
| `stacks.RetainInfraImages(pins)` / `RunInfraImageRetention(ctx, pins, every, tries)` (v0.351.0, decision 285) | controller/internal/stacks/infra_image_retention.go | `(infra.Images())` | Deletes pinned infra images older than the pin + the previous pin | Per repository: the pin, newer versions, the previous pin and in-use images stay; untagged unused go; non-version tags stay; skipped (errImageRetentionBusy) while an app pulls (R-863) or the controller swaps; same `imageDocker` seam |
| `stacks.CloseSignupNow` / `CloseSignupOffered` / `applyNativeLock` (v0.282.0, decisions 47/49) | controller/internal/stacks/after_setup.go | `(name)` | The app's own sign-up switch after the setup; "close sign-up now" for an app installed before the rule | **Check the installed compose reads the variable** (an old install carries the old compose until its next update) — never record a lock that is not there. One run per app at a time (`nativeLockBusy`) |
| `backup.judgeCopy` / `HollowCopies` / `SetHollowCopyNotify` (Part D, v0.279.0) | controller/internal/backup/hollow_watch.go | `(app, tier, unitDir)` | A RUNNING app whose newest copy holds no data → operator digest once/day + page sentence | Uses `unitCarriesData` (the manifest, never size); a stopped held app is never flagged |
| `web.nightChain` (R-705, v0.279.0) | controller/internal/web/night_chain.go | `POST /api/debug/backup/night-chain` | The night's four legs now, in order | Refuses while any op/update/chain runs; the leg uses `RunUpdateLegNow` |
@@ -80,11 +81,15 @@
| `restoreOpInFlight` + `hasRecentRestoreResult` | controller/internal/web/restore_wizard.go | `(backup.RestoreOpStatus) bool` / `(st, app, now) bool` | THE "is a restore running / did one just finish" display reads | **TRAP (v0.154.0 shipped this bug): `Manager` has TWO running flags.** `IsRunning()` reads the CONCURRENCY flag, acquired inside the goroutine — and `RestoreOffboxScratch` never acquires it, so it is false for the whole verification restore. Display must read `RestoreStatus().Running` (set synchronously by `BeginRestoreOp`). Read the status ONCE per render or the strip and the suppression can disagree. `hasRecentRestoreResult` is app-bound and window-bounded — a process-wide result must not light another app's „Eredmény" |
| `restoreWizardPath` / `deriveWizardStep` / `resolveWizardApp` | controller/internal/web/restore_wizard.go | `(app) string` / `(restoreWizardInput) restoreWizardView` / `([]OffboxAppRow, name) *OffboxAppRow` | R-48 offsite restore wizard: URL builder + the PURE step/unlock derivation + the app-resolution refusals | The step is **never** taken from the request. Precedence is load-bearing: op-running outranks a stale `?full_prep=`, else a commit button reappears mid-restore. Truth table + red-proof: `restore_wizard_test.go`. Adding a form here that posts anywhere new breaks `TestRestoreWizard_NoNewMutationEndpoints` **by design** — R-48 adds no mutation surface |
| `restoreOpBlocked` | controller/internal/web/restore_wizard.go | `() (msg string, blocked bool)` | THE refusal gate before starting ANY restore | **Use this, never a bare `IsRunning()`.** It reads BOTH flags: `RestoreStatus().Running` (set synchronously by `BeginRestoreOp`, true for the whole off-box restore) and `IsRunning()` (the concurrency flag, the only one the nightly backup holds). **R-351: all seven handlers read only `IsRunning()`, which the goroutine acquires AFTER the handler returns — a second press started a second run and was told „…elindult".** Returns the Hungarian refusal, which names the running app and a route | **R-360 (v0.226.0): `offboxVerifyCopyDeleteHandler` was the LAST holdout and its doc comment claimed it already did this — the sentence is why nobody looked. `IsRunning()` is FALSE for the whole of a verification restore, so the copy a restore was writing into could be deleted from the UI (observed live 2026-08-21 22:35). No app-name comparison: refusing during ANY restore is stronger and uniform.**
| `Server.beginRestoreOp` → `backup.TryBeginRestoreOp` / `RestoreBusy` (R-1256 H6) | controller/internal/web/restore_wizard.go; controller/internal/backup/opstatus.go | `(op, stack) (msg string, ok bool)` / `(op, stack) (busy, mirrorApp string)` | THE way a restore op begins: the check for every other operation (a restore op, the backup run, a second-drive copy) and the record in ONE step under `m.mu` — the mirror asks under the same lock (`beginTier2Run`) | **Never call `BeginRestoreOp` from a handler** (`TestR1256_H6_NoHandlerBeginsARestoreUnchecked`): `restoreOpBlocked` asked early can be stale by the time the form is read, and a mirror that began in between ran beside the restore. `restoreOpBlocked` stays as the EARLY refusal; the kept loads begin inside `LoadKeptApp` / `LoadKeptOffsite` and return `ErrRestoreBusy` |
| `Manager.RestoreFromRecoveryUnitAt` / `RestoreFromRecoveryUnit` + `UnitRestoreResult` (R-353 v0.226.0; R-102 v0.229.0) | controller/internal/backup/restore_unit.go | `(stack, unitDir string) (UnitRestoreResult, error)` / `(stack string) (…)` | THE local recovery-unit restore, and the facts its surface must state | **Returns a RESULT, not just an error** — volumes replayed, DBs replayed, and what the manifest LISTED. The Manifest* counts are load-bearing: zero-replayed has two causes (the backup held no data / the backup listed data that did not come back) and they are opposite news. Pair it with `unitRestoreOutcomeMsg`; do NOT write a new sentence. **A claim about the APP is forbidden on this path** — it has no `SafetyDump` discriminator, unlike the off-site twin (CONTEXT.md ruling, 07-backup-architecture §6.3). `restoreDockerVolumes` now returns `(int, error)`; `restoreDockerVolumesFrom` is unchanged and still the shared implementation. **R-102: `…At` holds the whole body and takes the unit DIRECTORY; the one-argument form is the thin caller naming the primary unit.** THE SOURCE MOVES; THE DESTINATION DOES NOT — `GetAppDrivePath` still resolves where the data lands. The R-47 mutation order, the unit-over-guest secret precedence, the fail-closed data-key gate and the no-unit `RestoreApp` fallback are all pinned and unchanged. The volume leg goes through the R-354 `volumeReplayFrom` seam so the source directory is assertable without Docker |
| `Manager.putBackAfterFailedRestore` + `liveVolumeCopy` (R-893 option A, v0.336.0) | controller/internal/backup/offbox_restore_undo.go | `(stack, cause, live, copy, volumesMoved, filesPlaced, restart, holdKey) error` | THE restore undo — off-site (v0.336.0) and, since D22 (unreleased), the LOCAL unit restore (`RestoreFromRecoveryUnitAtWith`, so also the second drive's and a kept load): the live volumes it will replace, measured before the stop (`planLiveVolumeCopy`), copied right after it (`copyLiveVolumes`), poured back on any failure | One copy per restore under `<ns>/backups/restore-undo/<app>/` (no capture set reads `backups/`); the put-back uses the restore's own `volumeReplayFrom`/`restoreDockerVolumesFrom`, so there is one volume-replay implementation. A put-back that fails sets `keep` and HOLDS (option C) — never start on volumes that are not known to be back. Seams for tests without Docker: `undoVolumeProbeFn`, `undoVolumeTarFn`, `undoVolumeRemoveFn`; operator notice `SetRestorePutBackNotify` (leg `restore-put-back`). Pinned by `r893_putback_test.go` and `r1177_local_putback_test.go` |
| `Manager.putBackAfterFailedRestore` + `liveVolumeCopy` (R-893 option A, v0.336.0) | controller/internal/backup/offbox_restore_undo.go | `(stack, cause, live, copy, volumesMoved, filesPlaced, restart, holdKey, restoreKind) error` (R-1340: `restoreKind` = `settings.RestoreKindOffsite`/`Local`; a failed put-back records its step in the hold's `MixedCause`/`FailedStep`/`DBReplay`) | THE restore undo — off-site (v0.336.0) and, since D22 (unreleased), the LOCAL unit restore (`RestoreFromRecoveryUnitAtWith`, so also the second drive's and a kept load): the live volumes it will replace, measured before the stop (`planLiveVolumeCopy`), copied right after it (`copyLiveVolumes`), poured back on any failure | One copy per restore under `<ns>/backups/restore-undo/<app>/` (no capture set reads `backups/`); the put-back uses the restore's own `volumeReplayFrom`/`restoreDockerVolumesFrom`, so there is one volume-replay implementation. A put-back that fails sets `keep` and HOLDS (option C) — never start on volumes that are not known to be back. Seams for tests without Docker: `undoVolumeProbeFn`, `undoVolumeTarFn`, `undoVolumeRemoveFn`; operator notice `SetRestorePutBackNotify` (leg `restore-put-back`). Pinned by `r893_putback_test.go` and `r1177_local_putback_test.go` |
| `Manager.SweepUnusedRestoreCopies` (R-1256 H8) | controller/internal/backup/restore_copy_sweep.go | `(now) []string` | THE only AUTOMATIC remover of a restore copy nothing names any more (`restore-copy-sweep`, every 6 h); the household's „Törlés most" is `DeleteRestoreCopy` (D62, restore_copies.go — same „needed" rule via `restoreCopyNeededFor`, check + removal under `m.mu`) | Removes a copy only when ALL hold: older than 30 days (D62), the app has no restore hold of ANY kind, the app-stop marker is readable and does not name the app, no restore op runs. It answers „no" when it cannot answer — a held or waiting copy is support's way back |
| `CrashPutBack` + `Manager.persistUndoForCrash` + `AppStopGuard.SetUndo` (D22 / R-1195, v0.338.0) | controller/internal/backup/restore_crash_putback.go | `NewCrashPutBack(stop, writeDef, logger)`; `PutBackInterruptedRestore(stack, undoDir) error` | A restore cut by a power loss is put back at start: the copy (volumes + `definition/` + `undo.json`) is recorded in the app-stop marker once whole; `Recover` pours it back BEFORE the restart | Call `persistUndoForCrash` right after `copyLiveVolumes` in any new restore path. `Recover` runs before the backup manager exists, so the put-back is wired in main.go with `stackMgr.StopStack` and the stack adapter's definition writer. A failed put-back = a FAILED recovery (app not started, marker kept). The household reads `note.restore.interrupted_put_back` (`LoadRestoreRecordAfterRecovery`). Pinned by `TestR1195_*` |
| `tier2CaptureSetFull(...) (legs, missing, warns, classified)` + `keptCopyRels` + `dropKeptCopiesUnder` (R-1252, unreleased) | controller/internal/backup/tier2_capture.go, tier2_kept.go | `classified` = the legs come from a VALID backup block | **The second-drive reconcile deletes only under a valid classification**; a rejected or absent block keeps every dest dir; kept copies (D25) are always in the keep set; a mirror deleted by Remove drops its kept records | A new reconcile caller must take `classified` and the kept rels too — never reconcile against the legacy legs. A rejected block is told by `Manager.BackupBlockRejected` (stacks; via the adapter's optional `BackupBlockRejected` method) and signalled once a day (`SetTier2SettingsUnreadableNotify`). Pinned by `r1252_rejected_block_keeps_copies_test.go` |
| `holdreport.Reporter` + `settings.RestoreHold.Why` / `WireReason` (D53, unreleased) | controller/internal/holdreport/holdreport.go · controller/internal/settings/settings.go | `New(store, notifier.PushEvent, logger)`; `Tick(now)` from the scheduler | Tells the hub every hold in place (`app_held`), every hold gone (`app_hold_cleared`), each again daily | **One observer of the hold store — never a send inside a hold writer.** A new hold writer needs nothing here. The hold sentence is `RestoreHold.Why()` (one per reason) — never a second copy. Pinned by `internal/holdreport/holdreport_test.go` |
| `AppStopGuard.ResumePutBack` / `ResumeWaitingPutBacks` + `HoldReasonPutBackPending` (R-1251, unreleased) | controller/internal/backup/appstop_putback_wait.go | `ResumePutBack(stack) bool` (true = nothing owed, the caller may start); `ResumeWaitingPutBacks() []string` (puts back, then starts through the gated starter) | A cut restore's copy on a drive that is not bound is WAITING: Recover writes the restore hold `putback_pending` (copy in `SafetyDump`) and starts nothing; the put-back runs when the drive binds, before any start | **Any new path that starts an app when its drive arrives calls `ResumePutBack` first** (the boot recreate and `restartStacks` do, in web via `Server.resumePutBack`). Every other start path is covered by the hold store it already honours — do not add a second check. A failed put-back (at start or on resume) writes the D20 hold (`restore_mixed`) and drops the app from the marker. Needs `SetHolds` + `SetUndoReachable` before `Recover` (main.go). Pinned by `r1251_putback_waits_test.go`, `TestR1251_DriveStartPathsPutBackBeforeTheyStart`, `TestR1251_MainWiresThePutBackWait` |
| `AppStopGuard.ClearHoldByOperator` + `clearHoldNow` / `listenHoldCtl` / `clearRestoreHoldCLI` (D64 = B, R-1343, unreleased) | controller/internal/backup/hold_clear.go · controller/cmd/controller/holdclear.go | `ClearHoldByOperator(stack) (RestoreHold, error)`; `clearHoldNow(deps, stack, who) (msg, error)` | THE operator's hold clear, any reason — the hub's `clear_hold` and the box command `--clear-restore-hold` both go through `clearHoldNow` in the RUNNING controller | **Never clear a hold from a second process** — the running controller's next save writes it back (R-1343, measured). The box command reaches the running controller over `<data dir>/ctl/hold.sock` (unix, 0600, peer uid checked; never TCP/HTTP). A `putback_pending` clear also drops the app from the app-stop marker (the copy stays). Refusals (`ErrHoldBadStack`, `ErrNotHeld`) change nothing. The update's in-memory held flag goes via `stacks.Manager.ForgetUpdateHeld`. Pinned by `cmd/controller/holdclear_test.go` |
| `Manager.RestoreTier2Unit` + `Tier2Coverage.CanRestoreUnit` / `Tier2CopyDate` (R-102/R-103, v0.229.0) | controller/internal/backup/tier2_restore.go | `(stack string) (UnitRestoreResult, error)` / `() bool` / `() (string, bool)` | THE full restore from the SECOND DRIVE's mirror, and the predicate that gates it | **Do NOT widen `CanRestore()`** — it answers only "can the additive file restore run?" and one predicate answering two questions is R-356. Fail-closed: `tier2UnitIsOpenable` requires a parseable manifest, because a directory is not a package. The single-writer flag is taken INSIDE `RestoreFromRecoveryUnitAt` — a second `acquireRunning()` here would refuse the restore it guards. `Tier2CopyDate` prefers the SUCCESS anchor over the attempt clock (R-101) and reports which it returned |
| `unitRestoreOutcomeMsg` + its three message constants (R-353, v0.226.0) | controller/internal/web/handlers.go | `(app string, res backup.UnitRestoreResult) string` | THE customer sentence for a completed LOCAL restore | Twin of `reconstituteOutcomeMsg`; copy its SHAPE (clauses earned by having done the thing, no filesystem path, base names only), never its text. The constants are named because `r353_unit_outcome_test.go` asserts them verbatim — a silent edit is how an honest message drifts back into a comforting one, which is the documented history of the sentence it replaces |
| `offsiteNoSpaceMsgFmt` + `offsiteSizeUnknownMsg` (R-357, v0.226.0) | controller/internal/backup/offbox_restore.go | two consts | EVERY headroom refusal on the off-site restore surface | **All four gates share these** (prepare, scratch, place, and the destructive reconstitute). A customer meeting one wording on one path and a different one on another has to work out whether it is the same problem. **The reconstitute gate uses NO ×1.1 margin** — it copies a measured tree; `OffboxRestorePrepareFull`'s ×1.1 predicts a download. **Fail closed when either probe reads ≤ 0**: `free < need` with `need == 0` is FALSE, so an unmeasurable input sails through — a gate present and inert |
@@ -230,6 +235,7 @@
| `registerStoragePath` | controller/internal/web/storage_handlers.go | `(where, label, setDefault) error` | Post-enroll registration | The single funnel used by init/attach/manual-add |
| `system.IsMountPoint` / `IsWritable` / `PathsOverlap` | controller/internal/system/mounts_linux.go | `(path) bool` | Mount checks | `_other.go` stubs return permissive values — Linux behavior is the real one |
| `system.CheckBackupDestination` | controller/internal/system/mounts_linux.go | `(path) DestinationHealth` | Tier2/offbox target vetting | Detects same-physical-device (`SamePhysicalDevice`) |
| `system.FilesystemKey` (R-1371) | controller/internal/system/fskey.go | `(path) (key uint64, ok bool)` | "Are these two paths ONE filesystem?" — the fill watch's de-duplication | **Never compare `st_dev` (or `SamePhysicalDevice`) for a path that may be the container's "/"**: an overlay has its own device number and filesystem id. An overlay path gets the device of a Docker-kept file (`/etc/hostname` …) that lies on the data-root. `ok=false` = cannot tell → treat as a filesystem of its own. Seam: `filesystemKeyWith` |
| `backup.Manager.diskRelation` | controller/internal/backup/backup.go | `(a, b) (DiskRelation, reason)` — DiskDifferent / DiskSame / DiskUnknown | EVERY Tier-2 or one-copy "same disk?" decision (v0.317.0, felhom.eu `16-storage-physical-identity.md` §4) | Asks the host agent (`SetDiskJudge`, FeatureSameDisk ≥ agent 0.157.0); an older agent or an `unmapped` path → the old `sameDevice`/st_dev rule. Never call `sameDevice` directly for a Tier-2 decision — st_dev calls two partitions of one disk "different". Pinned by diskrelation_test.go |
| `web.Server.ensureInternalPlace` / `refuseInternalLifecycle` | controller/internal/web/internal_place.go | drive-gate tick hook; `(w, r, where) bool` | the internal data place (v0.318.0, `16` §5): bind on one tick, register (kind internal, default when none) on the next; refuse eject/decommission/wipe | Only an agent row of kind `internal` is enrolled without a press — a household drive never is. Pinned by internal_place_test.go + stacks d4_needs_drive_test.go (a media app lands on it) |
| `web.Server.offerRelationFor` | controller/internal/web/backup_target_offer.go | `(ctx, drive) offerRelation` (sameDiskFn seam) | the whole-box backup offer's disk question (R-1084) | Older agent → today's offer; an error → no promise. Pinned by r1084_offer_identity_test.go |
@@ -276,6 +282,7 @@
| `ConfigRefresher.Reconcile` | controller/internal/report/config_refresh.go | `(ackVersion int)` | Pull-based config refresh | Re-pulls controller.yaml (re-merging local_api), then graceful self-restart; first-run = baseline, no restart |
| `offsiteapply.HubRegistrar` / `HubWindowClient` / `PinnedProber` (v0.289.0, decisions 68–69) | controller/internal/offsiteapply/seams.go | `Register(ctx,pub)(fp,err)` · `Confirm` · `MoveAside` · `Open/Close` window · `Probe(ctx,host,user,port,kh,privPEM) bool` | EVERY off-site key install, the hub move-aside, the clean-up window | **The box never handles the sub-account password** — there is no consume path any more. `PinnedProber` is a POSITIVE observable (exit 0 + rclone output); "authenticates" is NOT enough — an unpinned key authenticates and can delete. |
| `Manager.offsiteWindowRetention` + `offsiteGuard` (v0.289.0, R-822) | controller/internal/backup/offbox_window.go | `(ctx, base, env, why)` · pure `(all, plan, now, newestAllowed, max) (ids, refuse)` | THE retention step for both callers (after a run, over quota) | Pinned tier: no window → nothing deleted; the guard runs BEFORE any forget; "young" = fewer than `keepDaily` CALENDAR days old (v0.294.0, R-867 — the line is built from the same constants as `retentionPolicy`; never an hour count); a young snapshot superseded the same day is EXCLUDED, any other young removal / future date / plan above `max_remove` REFUSES; tests run restic 0.14.0's policy itself (`restic0140Plan`, proven identical to the binary); forget is by explicit ids, oldest first. A due abandonment goes to `OffsiteAbandonClient` (hub, 7-day wait). NAS tier: the old SP-2 policy, unchanged. |
| `Manager.StartOffsiteEnd` / `KeepOffsiteCopies` + `settings.OffsiteEnd` (D72/D84, felhom.eu `07` §8.2f; built, not released) | controller/internal/backup/offbox_ended.go, controller/internal/settings/offsite_ends.go | `StartOffsiteEnd(app) (rec, created, err)` · pure `dueOffsiteEnds`, `endedCandidates`, `endedToRemove` | The off-site copies of a removed app end 30 days after „delete backup data”: the record, the press, the take-back, and the ended apps' ids in the weekly window | **NO RECORD = NO DELETION.** `StartOffsiteEnd` is the ONLY writer (it sends the household's one mail when it really wrote); an install deletes the record (`stacks.DeployStack`). The window removes an ended app's snapshot only when every app tag on it is a due record, the hub sent its id back (`OffsiteWindow.EndedAllowed`) and the box named it in the same window. `SetOffsiteEndLiving` not wired → nothing is ever due (wired to `stacks.Manager.IsLivingApp`). Only on the hub-provisioned (pinned) tier. **„The app became installed” is ONE point: `stacks.SaveAppConfig` → `noteAppInstalled`** — never add a second writer of an app's `app.yaml` (`TestD72_TheInstallWritersAreListed`). The window reads the records again right before the forget (`lastLookAtEnded`). |
| `offsiteapply.SettleProvider` / `SettleFunc` / `Bridge.AwaitSettle` / `ReconcileWhenSettled` (R-71a, v0.162.0) | controller/internal/offsiteapply/offsiteapply.go + seams.go | `SettleState() (version, floor string, updateRunning, floorKnown bool)` | THE settle-gate: defers the offsite one-time-password consume past a managed day-0 floor-update (the F10 race). Wire the `SettleFunc` adapter over `updater.GetFloor()`/`IsUpdateRunning()` — **the updater's knowledge is the ONE floor source; never fetch the floor a second way**. Gate ONLY the bridge goroutine, and only when an updater exists (nil `Settle` = reconcile immediately). Bounds `settlePoll`/`settleFloorSubBound`/`settleOverallBound`; the floor is in-memory (report-ACK-derived, ~5–10 s), NOT persisted → unknown until the first ACK on any restart. Inject `Now`/`Sleep` in tests (no real sleeps). B′: at/above-floor GOes on the first poll, zero wait. Do NOT touch the consume/persist order or the 404 contract — ordering only |
| `bootstrap.MaybeIngest` / `RefreshConfig` | controller/internal/bootstrap/bootstrap.go | bootstrap.json → controller.yaml | Day-0 + refresh | Overwrites controller.yaml, NEVER settings.json |
| `api.GracefulSelfRestart` | controller/internal/api/selfrestart.go | `(logger)` | Controller self-restart | Detached exit; bootstrap unit re-runs the image |
@@ -285,7 +292,7 @@
| `Manager.beginRunSummary` / `noteFailure` / `noteAttempted` / `emitRunSummary` / `SetRunSummaryNotify` (R-182, v0.194.0) | controller/internal/backup/runsummary.go | `(kind, runID) func()` / `(app, leg, reason)` / `(RunSummary)` | **THE per-run operator digest.** One `backup_run_failures` event at the end of a run listing every failed app, its leg and its reason — emitted ONLY when something failed | **The RECORD and the NOTIFICATION are different things and must stay so.** The per-app `recovery_unit_capture_failed` event is the record (hub routes it *record-only*, stored + logged every time); this digest is the notification. Before R-182 one event was both, and did neither: nine arrived, two were mailed, seven vanished before `LogNotification`. **Lifetime is `admissionSet`'s exactly** — absent collector means "no run in flight", never a stale answer. **A refusal is noted ONCE, inside `admitApp` where the verdict is taken**, not at the three legs that consult it: R-181's one-verdict-covers-all-three contract makes per-leg noting produce "2 of 1 apps failed". **Deliberate skips (disconnected / decommissioned) must NEVER be noted** — they have their own alert and a nightly digest about an unplugged drive is an ignored digest. **A clean run emits NOTHING**; silence is safe only because the hub's deadline check (`monitor/deadline.go:396,417`) raises a missed backup from report freshness independently — if that is ever weakened this design loses its footing. **`run_id` is unique per real run** (so the hub's 1-h cooldown cannot collapse a manual run into the nightly one) and **deliberately EMPTY on the periodic refresh sweep**, which must stay under that cooldown or a polled status page becomes a mail flood |
| `Manager.admitApp` / `beginAdmissionRun` / `decideAdmission` / `estimatedWriteBytes` (R-181, v0.193.0) | controller/internal/backup/admission.go | `(stackName) bool` / `() func()` | **THE reserve gate. Call it before ANY per-app backup write** — one verdict per app per run, covering the DB dump, the volume dump and the unit capture (all three write under one per-app root) | **Decided LAZILY at the app's first write, never once at run start** — app A's dump can put app B under the reserve, so a run-start verdict reads a disk that no longer exists. **Never re-decided between an app's own legs**: that is exactly the split R-181 closed (bulk written, capture refused). **Reset per run** via the closer `beginAdmissionRun` returns. **Must sit ahead of `DumpAppVolumesSafe`**, which stops the stack as its first act — a refusal decided inside it has already bounced the app. Fires **exactly one** `unitNotify` per refused app per run. Nil admission set (periodic status refresh) → decides fresh, which is still once per app per sweep. Wiring pinned by an **AST walk** in `TestAdmission_IsWiredIntoEveryProductionWriteLeg`, not `strings.Contains` |
| `Manager.floorVerdict` + `FloorUsedPercent`/`FloorFreeGiB` / `ErrCaptureFloor` / `floorReason` (R-165 B2 v0.192.0, size term R-181 v0.193.0) | controller/internal/backup/recovery_unit.go | `(*UnitSpace, estGiB float64) (*UnitSpace, floorReason)` | The pure two-question predicate behind `admitApp`: is the filesystem already below the reserve (`floorHeadroom`), and would THIS app's write take it below (`floorSize`)? | **Headroom is about the FILESYSTEM, never a per-unit cap** — a size cap is R-163 rebuilt inside one volume; the size term bounds the *delta*, not the unit. **REFUSES, never deletes:** nothing here is generational (a unit is one fixed path per app, a DB dump one fixed name), so pruning could only destroy a DIFFERENT app's only local copy — **never repurpose `pruneStalePrimaryDirs`**, which removes ORPHANED dirs from an app that moved drives and has no notion of age. Two terms (97% / 1 GiB) in `fillwatch`'s shape, deliberately BEYOND its critical band (95% / 2 GiB) so the customer is always warned first — pinned by `TestFloorSitsBelowTheCriticalWarningBand`. **`estGiB == 0` degrades to headroom-only on purpose** — refusing an app with no history makes the FIRST backup the one that can never happen. A nil reading neither refuses nor warns (§8.4). Inject `unitSpaceFn` in tests rather than manufacturing occupancy on a real disk |
| `fillwatch.Watcher` (`New`/`SetNotify`/`Check`) (R-167, v0.191.0) | controller/internal/fillwatch/fillwatch.go | `(statePath, logger, targetsFn, usageFn)` → `Check() error` | THE customer fill warning — warns BEFORE a filesystem fills, per FILESYSTEM (never per app: one full disk holding ten apps would fire ten times) | Emits the **pre-existing** `disk_warning`/`disk_critical` pair, which was allowlisted + copy'd + default-enabled with **no producer in any repo** until now — do NOT mint a new type beside it. **Two threshold terms, whichever trips first** (85% / 5 GiB; critical 95% / 2 GiB) because a percentage alone lies at both ends of this fleet's size range. **Edge-triggered on ESCALATION ONLY**, state persisted; de-escalation is silent and re-arms. Hysteresis dead zone between clear (75% / 7 GiB) and warn — pinned by `TestThresholdsKeepTheirHysteresisGap`. **A nil usage read is NEVER a warning** (§8.4). The hub has **no `customerMessages` entry** for either type on purpose — an entry would override the dynamic message and discard the drive label + free space. **Both languages (v0.309.0, R-521 F7):** the sentence is the bundle's `event.fill.*`, the household's rendering rides as `message_customer` via `Notifier.PushEventHousehold` (`SetLang`; `SetExtra` takes the language); a built-in area carries a `LabelKey`, a household's own drive label is used as written. Hungarian pinned byte-for-byte by `TestMessageHungarianWireText` (v0.309.0 dropped the formal „Kérjük," — R-516) |
| `fillwatch.Watcher` (`New`/`SetNotify`/`Check`) (R-167, v0.191.0) | controller/internal/fillwatch/fillwatch.go | `(statePath, logger, targetsFn, usageFn)` → `Check() error` | THE customer fill warning — warns BEFORE a filesystem fills, per FILESYSTEM (never per app: one full disk holding ten apps would fire ten times) | Emits the **pre-existing** `disk_warning`/`disk_critical` pair, which was allowlisted + copy'd + default-enabled with **no producer in any repo** until now — do NOT mint a new type beside it. **Two threshold terms, whichever trips first** (85% / 5 GiB; critical 95% / 2 GiB) because a percentage alone lies at both ends of this fleet's size range. **Edge-triggered on ESCALATION ONLY**, state persisted; de-escalation is silent and re-arms. Hysteresis dead zone between clear (75% / 7 GiB) and warn — pinned by `TestThresholdsKeepTheirHysteresisGap`. **A nil usage read is NEVER a warning** (§8.4). The hub has **no `customerMessages` entry** for either type on purpose — an entry would override the dynamic message and discard the drive label + free space. **Both languages (v0.309.0, R-521 F7):** the sentence is the bundle's `event.fill.*`, the household's rendering rides as `message_customer` via `Notifier.PushEventHousehold` (`SetLang`; `SetExtra` takes the language); a built-in area carries a `LabelKey`, a household's own drive label is used as written. Hungarian pinned byte-for-byte by `TestMessageHungarianWireText` (v0.309.0 dropped the formal „Kérjük," — R-516) **One target per filesystem (R-1371):** `fillTargets` (cmd/controller/main.go) de-duplicates by `system.FilesystemKey`, first target wins (app area, system area, drives); a new built-in target goes into that order on purpose. |
### Scheduler / time / UI
@@ -356,6 +363,7 @@
|---|---|---|---|
| `diskAgent` | controller/internal/web/storage_handlers.go | `*agentapi.Client` | `mockAgent` in controller/internal/web/storage_handlers_test.go |
| `netAgent` + `Server.netAgentFn/netProbeFn/netListFn` | controller/internal/web/netstorage_job.go (+ server.go fields) | `*agentapi.Client` / `runNetProbe` (linux re-exec) / `agent.ListNetStorage` | `fakeNetAgent` + fn injections in controller/internal/web/netstorage_job_test.go — the NAS add orchestration never shells/TLS-dials in tests |
| `faultPoint(point) error` (D63, TEST BUILDS ONLY) | controller/cmd/controller/faultpoint_{off,on}.go | a no-op without `-tags faultinject` (the release image); with it, a file `<data>/faults/<point>` = „<skip> <fail>" fails the named point | `TestD63_TheReleaseBuildHasNoFaultSwitch` (release build: no-op; build.sh/Dockerfile pass no tag), `TestD63_TheTestBuildFailsTheArmedPointOnDemand` (`go test -tags faultinject`). Points: `defwrite-after-compose`, `stop-<app>`. A live proof of a branch Docker cannot be made to take on demand goes here — never an env switch in the release binary |
| `healthSettle` / `healthInterval` / `healthTimeout` (package vars, R-488) | controller/internal/backup/restore.go | production 3 s / 5 s / 90 s — `waitForHealthy`'s clock, used by every restore path | shortened ONCE in controller/internal/backup/main_test.go `TestMain` (0 / 2 ms / 50 ms; the package went 444 s → ~2 s); `TestR488_HealthWaitDefaultsAreProduction` pins the production values. A new real-clock wait in this package goes behind the same kind of var, not a per-test sleep. Also: `newOffboxManager` installs a failing `SetOffboxSSH` fake, so no backup test spawns a real `ssh` |
| `Server.agentLogsFn` (func seam) | controller/internal/web/server.go | nil → `agentClient().DebugLogs` (agent GET /debug/logs) | injected in controller/internal/web/observability_test.go (incl. the pre-0.83 typed-404 notice path) |
| `escrowAgent` + `Server.escrowAgentFn/escrowStageFn/escrowStaleFn` | controller/internal/web/escrow_handlers.go (+ server.go fields) | `*agentapi.Client` / `PushOffboxPasswordForEscrow` / `report.EscrowAutoConfirmer.StaleBlob` (SetEscrowStale) | `fakeEscrowAgent` + fn injections in escrow_wizard_test.go — call-ORDER assertions (stage BEFORE trigger) + agent-never-called gates. The claim leg is the ONLY surface R crosses: no-store, never logged, never templated |
@@ -452,7 +460,7 @@ Cross-repo edges:
| timeAgo switch body ×2 | controller/internal/web/funcmap.go `timeAgo` vs `timeAgoStr` (identical formatting logic) |
| Budapest timezone loader ×4 | controller/internal/scheduler/scheduler.go `getBudapestLocation` vs controller/internal/web/funcmap.go `getTimezone` vs controller/internal/quiesce/quiesce.go `budapestLocation` vs controller/internal/api/kept_install.go `budapest` (v0.277.0, the kept choice's dates) (v0.168.0 window gate — Budapest wall-clock, kept local to avoid a scheduler↔quiesce import edge) |
| JSON writers ×5, 3 envelope shapes | api `writeJSON`; web `writeDiskJSON`, `jsonResponse`/`jsonError`, `writeDebugJSON` |
| Safe-name validators ×4 | controller/internal/web/validate.go `validStackName`; controller/internal/api/router.go `validStackParam` (same body — api↔web import cycle); controller/internal/backup/offbox.go `isSafeStackName`; controller/internal/appexport/validate.go `ValidateSegment` (strictest) |
| Safe-name validators ×5 | controller/internal/web/validate.go `validStackName`; controller/internal/api/router.go `validStackParam` (same body — api↔web import cycle); controller/internal/backup/offbox.go `isSafeStackName` (exported as `IsValidHoldStack` for the hold commands); controller/internal/report/opactions.go `validHoldStack` (same alphabet as `isSafeStackName` — report cannot import backup; clear_hold's argument check); controller/internal/appexport/validate.go `ValidateSegment` (strictest) |
| DB wait/import ×2 | controller/internal/appbackup/dbdump.go `waitDBReady`/`ImportDump` vs controller/internal/appexport/restore.go `waitForDB`/`importDBDump` |
| qBittorrent Web API login ×2 | controller/internal/mediawire/mediawire.go `qbLogin` (writes the drive wiring) vs controller/internal/upwatch/explain.go `QBittorrent.login` (reads every minute; keeps its session cookie, which mediawire's per-run login does not need) |
| compose exec ×2 | controller/internal/stacks/manager.go `composeExecCustomEnv` vs controller/internal/appexport/restore.go `composeExecEnv` (the latter has ctx+timeout; the former has the userdata belt) |
+5 -1
View File
@@ -7,7 +7,8 @@
# --- Build stage ---
# R-972 (v0.322.0): a supported, patched Go, pinned by version AND digest (no moving tag). Go 1.24 had no security fixes
# left (go.dev/doc/devel/release#policy). The builder's Debian does not reach the runtime (a static CGO-free binary).
FROM golang:1.27.2-trixie@sha256:47667934874913a449b96faa7ef4777fa285d9ec29126ee80ed61c45b7cccf0e AS builder
# upstream: osv:Go/stdlib
FROM golang:1.27.4-trixie@sha256:b54b2639de8c1bfe538ec5ffc45f29b1932235ac5f6d63c059853646677112d9 AS builder
ARG TARGETOS=linux
ARG TARGETARCH
@@ -47,8 +48,10 @@ RUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build \
# in third_party/restic/, fingerprint CF8F 18F2 8445 7597 3F79 D4E1 91A6 868B D3F7 A907 — no keyserver at build
# time); the download matches the published sum; and it matches the sum pinned HERE, so even a re-signed release
# cannot swap the binary. Pinned by TestR1105_ResticIsPinnedOutsideTheOS.
# upstream: gap:Debian announces package fixes as DSAs on security-tracker.debian.org, which the watch does not read; BEHIND on the point release is the signal
FROM debian:13.7-slim@sha256:a29215f6a35e51e22adffa17f89e9d2ef06214e64a2bad10d765c46aea49f11f AS restic
ARG TARGETARCH
# upstream: github:restic/restic
ARG RESTIC_VERSION=0.19.1
ARG RESTIC_SHA256_AMD64=f415415624dcc452f2a02b8c33641791a8c6d6d3b65bbb3543fcf9a25151585c
ARG RESTIC_SHA256_ARM64=a5f64aaab53d51e311fa3829124c5b703f2d14cf187d8640b6be3b2b49376465
@@ -74,6 +77,7 @@ RUN set -eu; \
# --- Runtime stage ---
# Debian 13 (R-1105, v0.323.0), pinned by point release AND digest. It waited on Debian 12 until the off-site code's
# restic assumptions were re-proven on 0.18 (07-backup-architecture.md §6.8); restic itself no longer comes from here.
# upstream: gap:Debian announces package fixes as DSAs on security-tracker.debian.org, which the watch does not read; BEHIND on the point release is the signal
FROM debian:13.7-slim@sha256:a29215f6a35e51e22adffa17f89e9d2ef06214e64a2bad10d765c46aea49f11f
# Install runtime dependencies — each one is a program the controller binary runs (R-1105 re-checked every exec):
+82 -2
View File
@@ -1017,7 +1017,8 @@ Each app can define rich metadata in `.felhom.yml`:
the hold is persisted in `Settings.RestoreHolds`, every start path refuses it (customer button,
app-stop `Recover()`, boot sweep, via `driveStartGate` **above** its driveless early return), the
app-stop marker is ended so nothing auto-restarts it, and the row goes red. Cleared with
`--clear-restore-hold <app>`, **which requires a controller restart**. `--single-transaction` on
`--clear-restore-hold <app>` (since 2026-10-29, R-1343: through the running controller, no restart — see
„Operator actions") or the hub's „Clear hold" (`clear_hold`). `--single-transaction` on
the Postgres import is a belt only; MariaDB DDL is not transactional, which is why the rollback
is the fix.
- **Off-site restore of one app: a failed restore puts the app back EXACTLY as it was and starts it (v0.336.0,
@@ -1034,6 +1035,18 @@ Each app can define rich metadata in `.felhom.yml`:
`healthy`; the copy then goes after a further 3 min of the same (10 s samples, watched up to 30 min; a new restore
of the app ends the watch). A restore whose app does not start reads „…még nem indult el…", keeps the copy and
alarms the operator once (D49 = A: nothing is poured back by itself). `restore_verdict.go`. `offbox_restore_undo.go`.
- **Restore edges (unreleased, R-1256, night 2026-10-28).** A put-back whose stop fails pours nothing, keeps the copy
and holds the app; a failed definition write-back keeps the copy; a volume whose `docker volume rm -f` fails is a
failed volume (never unpacked on top of the old content). An off-site restore whose definition write fails writes
the LIVE definition back before the start, or holds the app. Every restore begins in one step with the check for a
restore, the backup run and a second-drive copy (`TryBeginRestoreOp`, also both kept loads). A copy that nothing
needs (no hold of any kind, not named by the app-stop marker, no restore running) goes after 30 days, checked every
6 h (`restore_copy_sweep.go`; operator ruling D62, 2026-10-29).
- **Restore copies in the kept-copies list (unreleased, D62).** The restore page's „Megőrzött másolatok" lists each
restore copy: the app, the restore's date, the size, „automatikusan törlődik: <date>". „Törlés most" deletes one
earlier, after a warning naming the app and the date and the app's name typed (`POST /backup/restore-copy/delete`,
JSON; 409 while a backup/restore runs or the app updates). A copy a hold or a pending put-back needs: the button is
off, the reason on one line. Each delete: one log line and the operator event `restore_copy_deleted`.
- **A restore cut by a power loss, on a drive that comes back late (unreleased, R-1251).** The copy of the live
data lives on the app's drive. When it cannot be reached at start because the drive is not bound yet, the app is
HELD (`putback_pending`; „…A visszaállítás előtti adatai egy meghajtón vannak, amely most nem érhető el…") and no
@@ -1110,6 +1123,23 @@ The `/apps/{slug}` page renders hero section, screenshots, setup guide, and opti
**Remove modal** shows three sections: (1) always-removed items (Docker volumes, app.yaml, cross-drive schedule), (2) optional HDD data deletion with reimport warning, (3) optional backup data deletion (DB dumps + cross-drive rsync) with restic retention note.
**The off-site copies of a removed app (D72/D84, felhom.eu `07-backup-architecture.md` §8.2f — built, not released, no
box has run it).** On a box with the hub-provisioned off-site tier, „Mentési adatok törlése” deletes the local
backups at once and starts 30 days for the app's off-site copies: the dialog names the day before the press
(`offsite_end_date` in `GET /api/stacks/{name}/backup-data`), the box writes an *off-site end record*
(`settings.json` → `offsite_ends`) and the household gets one mail (the hub sends it itself, from the report's
`offsite.ended_apps`; the event `offsite_end_scheduled` is its record). The dialog shows the older sentence about
the nightly snapshots only on a box where no date is shown. The restore page's
off-site list shows „Törlésre kijelölve. Törlés napja: …” with „Mégis megtartom” (`POST /backup/offsite-end/keep`
deletes the record); a removed app with copies and no record shows „Törlés 30 nap múlva”
(`POST /backup/offsite-end/start`). An install of the same app deletes the record. The copies are removed only in
the weekly clean-up window, by snapshot id, for ids the hub agreed to — never without a record, never a snapshot
that also belongs to an installed app, never `_shares` or the box's own stacks. A box whose off-site target is the
household's own NAS keeps a removed app's copies as before. After the review of 2026-11-15: every install deletes
the record at one point (`stacks.SaveAppConfig`: a deploy, an import, a restore that installs); the window reads the
records again immediately before the forget, so a take-back or an install while it was being prepared keeps the copies;
and the box sends its end records only to a hub whose last window answer said `accepts_ended`.
**Protected stacks** (traefik, cloudflared, felhom-controller) cannot be stopped, removed, or deleted from the UI. Restart is allowed.
**Orphan detection**: Deployed stacks with no matching catalog template are marked as orphaned with an "Elavult" badge and can be safely deleted.
@@ -1488,6 +1518,10 @@ The nightly backup has two phases that run sequentially. All paths are **per-dri
> **OOM visibility (v0.243.0, R-514).** The 30 s dead-app check also reads `State.OOMKilled` for running app containers (`Manager.ScanOOMKilled`); the dashboard shows „Memória elfogyott" and the hub gets `app_oom` once per container run. The controller does not restart the app.
> **OOM storm (v0.265.0, R-636).** For a flagged container the scan also reads the kernel's own kill counter (`memory.events` `oom_kill`, plus `memory.max` / `memory.peak`) with one `docker exec … cat` — `OOMKilled` is sticky, so it cannot count. When the SAME container run's counter rises by **20 or more within 30 minutes**, the notifier sends **`app_oom_storm`** (severity `error`, operator-only, details `{app, container, kills, window_min, mem_limit, peak}`) — ONCE per container run. `app_oom` itself is unchanged. An unreadable counter (an image without `cat`) never escalates.
> **Host OOM count (unreleased, R-528, night 2026-10-28).** Docker inside an LXC guest misses real OOM kills. The scan
> also asks the agent for the host's per-container `oom_kill` (`GET /guest/oom-kills`, 5 s cap; a 404 from an older
> agent → 10 minutes before the next ask); a count above zero raises `app_oom` whatever `OOMKilled` says, with `source`
> (`docker`, `cgroup` or `docker,cgroup`) in the details. `cmd/controller/hostoom_wiring.go`, `internal/stacks/oom.go`.
> **Multi-tier whole-guest backup (v0.174.0, R-82 Slice B).** The agent can serve SEVERAL whole-guest
> backup tiers with independent cadences — "local daily + PBS weekly" (agent >= v0.97.0,
@@ -2203,6 +2237,10 @@ that folder is never a dead end, and an install never runs into it silently (R-6
- **Where it lives.** `<drive>/kept/` is beside `appdata/` and `userdata/`, inside neither: no app bind, FileBrowser
userdata source, Samba share or backup leg reads it. It is in `ProtectedHDDPaths`.
- **The drive-full warning** ends with the kept folders on that drive and their sizes (`fillwatch.SetExtra`).
- **One fill warning per filesystem (R-1371; committed 2026-11-10, not released).** The watch list (`fillTargets`) holds the
app area ("/"), the system area (`/mnt/sys_drive`) and each drive, and keeps ONE target per filesystem — the first, in that
order. On a box whose guest has one data volume the two areas are one filesystem, so the warning carries the app area's
name. The identity is `system.FilesystemKey`, not the device number: the container's "/" is an overlay.
- **The fill warning in the household's language (v0.309.0, R-521 F7).** `disk_warning` / `disk_critical` carry the
Hungarian sentence AND the household's own (`message_customer`), from the bundle keys `event.fill.*`; the two built-in
areas („Alkalmazások területe" = the guest's root filesystem as the controller sees it, „Rendszer- és mentési terület")
@@ -2227,10 +2265,16 @@ that folder is never a dead end, and an install never runs into it silently (R-6
- **Controller image retention (v0.285.0, decision 56)** — 3 minutes after every start the box keeps the controller
image it runs and the one before it (the swap record `update-state.json` `previous_image` of a swap that ended on the
running version; without one, the highest version below the running one), every version above the running one (a
pulled target) and every non-version tag (`latest`, `-rc`); older and untagged controller images are deleted by exact
pulled target) and every non-version tag (`latest`); since v0.351.0 a test build (`X.Y.Z-rc.N`) is a version below its
release, so an old one goes too, and the fallback previous prefers a release; older and untagged controller images are deleted by exact
name/ID after the in-use check. Nothing while the controller swaps itself; registry tags are never touched. The
agent's own roll-back needs only the running image (it restores what `/etc/felhom-controller-image` named when the
swap began). See `internal/stacks/controller_image_retention.go`.
- **Infrastructure image retention (v0.351.0, decision 285)** — in the same start-up pass, for each pinned infra image
(`infra.Images()`: traefik, cloudflared, FileBrowser, Samba) the box keeps the pin, every newer version, the highest
version below the pin (the previous pin) and every image a container uses; older and untagged images of that
repository are deleted by exact name/ID. Non-version tags stay. Skipped while an app pulls (R-863, retried every 2
minutes) or while the controller swaps itself. See `internal/stacks/infra_image_retention.go`.
- **The setup gate (v0.280.0, decision 46)** — `.felhom.yml` `setup_gate: true` + optional `setup_done_probe: {url, field,
done}`. A FRESH install is closed to everyone but the household: the traefik file
`<stacks>/traefik/dynamic/setup-gate-<app>.yml` is written BEFORE the first start (a failed write refuses the install) and
@@ -2283,6 +2327,10 @@ that folder is never a dead end, and an install never runs into it silently (R-6
- **R-1286 (v0.344.0).** A held app says WHY: each hold reason (a failed restore, an unhealthy stop by the crash-loop
guard, …) has its own sentence in the start gate, the boot sweep and `--restore-holds` (an unhealthy stop used to
read as a failed restore).
- **D53 (next release, felhom.eu `08` §10).** The hub learns which apps are held: `internal/holdreport` reads the hold
store every minute and sends `app_held` (stack, reason, since, the hold's sentence) for a new or changed hold and
`app_hold_cleared` when one is gone — also one cleared while the controller was down (`settings.reported_holds`) — and
repeats every hold daily and at start. Both are severity info; the hub's operator reminder after a grace is the mail.
- **R-690 (fixed here).** The removed-app restore (R-487) never found a unit on a DATA drive — it asked
`GetStackComposePath`, true for every catalog app — and restored with no env. It now asks `isStackDeployed`.
- `.felhom.yml` **`after_load: {service, user, command: [...]}`** — one command run with `docker compose exec -T`
@@ -2523,6 +2571,9 @@ that folder is never a dead end, and an install never runs into it silently (R-6
> - **Guest-reboot convergence is DETERMINISTIC** via the agent's `guest_boot_id`: the controller persists
> `LastGuestBootID` and, when it changes, recreates EVERY deployed drive-backed app onto the
> re-propagated drive (`processGuestBootChange` — no fragile container-uptime sampling).
> **Built, not released (2026-11-14, R-1395):** the boot pass decides through `guestBootVerdict` and prefers the
> agent's `guest_boot_key` (the kernel's `boot_id`, not the boot TIME) — a step of the host's clock moved the old
> token and recreated every drive-backed app (the N100, 2026-11-14). An agent that sends no key gets the old rule.
> **v0.71.0 — boot-race fix:** on a guest `pct reboot`, in-guest dockerd auto-starts the apps ~18s
> BEFORE the agent re-binds the drive, so their volume bind fails at create-time
> (`mkdir …/userdata: permission denied`, `RestartCount=0` → never retried → stuck `Exited`). The old
@@ -3595,6 +3646,9 @@ it), holds the app at 1 KiB/s (Transmission 1 kB/s), calls `POST /host/line-test
back — the household's own included; a change made during the test stays. A killed controller puts it back at start
(`RecoverHold`, before any rule); the 50 % rule skips while a record exists. Proven on demo-hp with a real seed (felhom.eu
`audits/dooplex-alarms-2026-10-24/`).
**v0.346.0 (R-1250):** between the hold and the call the controller waits until every held app reports its own upload
near zero (≤ 16 KiB/s twice, 2 s apart, at most 90 s; an unreadable speed waits 20 s) — qBittorrent sends at full
speed for ~14 s after its limit falls, which made the agent refuse every test „not quiet" (measured 2026-10-27).
**v0.344.0 (R-1261):** EVERY running seeder is held, one record per app (`upwatch.line_test_holds`); a record whose app
was removed while held is dropped (it used to stop the 50 % rule for good); qBittorrent's hold names its slot
(`up_limit` / `alt_up_limit` through `app/preferences` — `transfer/uploadLimit` follows the CURRENT speed mode), so a
@@ -3632,6 +3686,32 @@ Anything else is answered `refused` and calls nothing. Each id runs once per pro
(`operator_action_results: [{id, outcome, message}]`, outcome `done` / `refused` / `failed`). No action deletes data,
starts a countdown or shortens one (`TestOpActions_ClosedList`). The box's log records every action it receives.
- **`clear_hold` (2026-10-29, operator ruling D64 = B; arg = the app's stack name, letters/digits/`-`/`_`, ≤64):** lifts
the app's hold of ANY reason, in the RUNNING controller (`backup.AppStopGuard.ClearHoldByOperator`, the door
`clearHoldNow` in `cmd/controller/holdclear.go`): memory and `settings.json` together, so no later save writes it back
(R-1343). It starts nothing — the household's Start (or a restore) does. A waiting put-back (`putback_pending`) is
dropped from the app-stop marker too; its copy stays on disk. The update's in-memory „held" flag
(`stacks.Manager.ForgetUpdateHeld`) goes with it; the hold reporter's next tick (≤1 min) sends `app_hold_cleared`.
Refused, nothing changed: a bad name, or an app with no hold. No new event type: the hub records the result.
**R-1350 (2026-10-29):** for an app that is not up, the clear records the stop as WANTED (desired state „stopped",
`stacks.Manager.RecordStopWantedIfDown`) once the hold is found and BEFORE it is lifted
(`AppStopGuard.ClearHoldByOperatorThen`), so the dead-app scan sends no „Telepített alkalmazás nem fut" for it and the
boot reconciler does not start it; the household's Start records „running" and ends it.
- **The busy file for the host agent (D65 = A, 2026-10-29; `internal/busymark`).** While a backup, a restore, an
off-site run, the night catch-up, an app update or an app export/import runs, the controller rewrites
`<data dir>/ctl/busy` every 15 s (line 1 the UTC time, line 2 what runs, 0600) and removes it when idle. The agent reads
it before the operator's „Reboot guest" and refuses while it is fresh (≤ 90 s); a controller that stopped writing it
does not block the reboot.
- **„Felhom support restarted your box" (D65 = A).** At start the controller asks the agent `GET /guest/operator-reboot`
(retrying for up to 10 minutes; a 404 from an older agent ends it) and the dashboard shows one neutral line,
„A Felhom ügyfélszolgálata HH:MM-kor újraindította a dobozt." / „Felhom support restarted your box at HH:MM.", until a
day has passed since the reboot.
- **The box command `--clear-restore-hold <app>`** (`pct exec <vmid> -- docker exec felhom-controller felhom-controller
--clear-restore-hold <app>`) asks the running controller over a unix socket, `<data dir>/ctl/hold.sock` (0600 in a
0700 dir, peer uid checked, nothing on TCP — not reachable through traefik, the LAN or an app), and says no restart is
needed. Only when no controller answers does it edit `settings.json` itself, and it says so, naming the in-guest
restart. `--restore-holds` lists the holds (read-only).
#### Report Push (`internal/report/`)
Periodic JSON push (default every 15 min) to the central felhom-hub service:
+14 -1
View File
@@ -153,14 +153,27 @@ if [[ "${ACTION}" == "--push" || "${ACTION}" == "--multiarch" ]]; then
fi
head_sha=$(cd "${REPO_DIR}" && git rev-parse HEAD 2>/dev/null || echo unknown)
main_sha=$(cd "${REPO_DIR}" && git rev-parse origin/main 2>/dev/null || echo unknown)
# The one other source that can be fetched again: the tag v<VERSION> AS THE SERVER HAS IT, pointing at HEAD. That
# is a patch release built off a released version while main holds unreleased work (v0.345.1, R-1300, cloudflared's
# security bump, 2026-10-26 — operator's yes in that session). Only the tag that names THIS version counts; a tag
# only on this clone, a tag on another commit, or a server that cannot be asked is a refusal. Pinned by
# scripts/test_build_push_once.sh („tag" cases).
if [[ "${head_sha}" != "${main_sha}" ]]; then
error "${REPO_DIR} is not at origin/main — refusing to push."
tag_sha=$(cd "${REPO_DIR}" && GIT_TERMINAL_PROMPT=0 git ls-remote origin "refs/tags/v${VERSION}" "refs/tags/v${VERSION}^{}" 2>/dev/null \
| awk '$2 ~ /\^\{\}$/ {peeled=$1} $2 !~ /\^\{\}$/ {plain=$1} END {print (peeled != "" ? peeled : plain)}') || tag_sha="" # no origin / unreachable: the error below, not set -e
if [[ -n "${tag_sha}" && "${tag_sha}" == "${head_sha}" ]]; then
info "Source tree is clean and at the pushed tag v${VERSION} (not origin/main)."
else
error "${REPO_DIR} is not at origin/main, nor at a pushed tag v${VERSION} — refusing to push."
error " HEAD ${head_sha}"
error " origin/main ${main_sha}"
error " v${VERSION} on origin ${tag_sha:-<none>}"
error "An unpushed change does not exist; an image built from one cannot be fetched again."
exit 1
fi
else
info "Source tree is clean and at origin/main."
fi
else
error "${REPO_DIR} is not a git checkout — refusing to push a build whose source cannot be identified."
exit 1
@@ -0,0 +1,49 @@
package main
import (
"os"
"path/filepath"
"strings"
"testing"
"gitea.dooplex.hu/admin/felhom-controller/internal/busymark"
"gitea.dooplex.hu/admin/felhom-controller/internal/config"
)
// D65 = A: the agent reads ONE fixed guest path — the controller-data volume + data/ctl/busy
// (felhom-agent ControllerBusyMarkerGuestPath, and its sudoers line). The volume is mounted at
// /opt/docker/felhom-controller, so the controller must write <default data dir>/ctl/busy.
// RED-PROOF: rename holdCtlDir or busymark.FileName → the path moves → FAILS.
func TestBusyMarkPathIsTheOneTheAgentReads(t *testing.T) {
cfg, err := config.LoadFromBytes([]byte("customer:\n id: t\n domain: t.example\n"))
if err != nil {
t.Fatal(err)
}
got := filepath.Join(cfg.Paths.DataDir, holdCtlDir, busymark.FileName)
want := "/opt/docker/felhom-controller/data/ctl/busy" // = the agent's /var/lib/docker/volumes/felhom-controller-data/_data/data/ctl/busy
if got != want {
t.Fatalf("the busy file is %s, the agent reads %s — an operator reboot would never be refused for a backup", got, want)
}
}
// Every kind of work has its probe and the writer is started — a seam built and never wired is this project's commonest
// defect. RED-PROOF: delete any AddProbe line or the Run → FAILS.
func TestBusyMarkIsWiredAtStartup(t *testing.T) {
raw, err := os.ReadFile("main.go")
if err != nil {
t.Fatal(err)
}
src := string(raw)
for _, want := range []string{
`busyMark.AddProbe("an app update is running", stackMgr.AnyUpdating)`,
`return backupMgr.IsRunning() || backupMgr.RestoreStatus().Running`,
`busyMark.AddProbe("the night backup catch-up is running", catchUp.Running)`,
`busyMark.AddProbe("an app export or import is running", appExporter.IsRunning)`,
`go busyMark.Run(ctx)`,
`go webServer.WatchOperatorReboot(ctx)`, // the household line after an operator reboot
} {
if !strings.Contains(src, want) {
t.Fatalf("main.go does not contain %q", want)
}
}
}
@@ -0,0 +1,34 @@
//go:build faultinject
package main
import (
"os"
"path/filepath"
"testing"
)
// D63 (test build only): "<skip> <fail>" lets <skip> passes through, fails the next <fail>, then removes the file.
func TestD63_TheTestBuildFailsTheArmedPointOnDemand(t *testing.T) {
dir := t.TempDir()
t.Setenv("FELHOM_FAULT_DIR", dir)
p := filepath.Join(dir, "stop-radicale")
if err := os.WriteFile(p, []byte("1 1\n"), 0o600); err != nil {
t.Fatal(err)
}
if err := faultPoint("stop-radicale"); err != nil {
t.Fatalf("the first pass must go through: %v", err)
}
if err := faultPoint("stop-other"); err != nil {
t.Fatalf("another point is not armed: %v", err)
}
if err := faultPoint("stop-radicale"); err == nil {
t.Fatal("the second pass must fail")
}
if _, err := os.Stat(p); !os.IsNotExist(err) {
t.Fatalf("the spent file must be gone: %v", err)
}
if err := faultPoint("stop-radicale"); err != nil {
t.Fatalf("a spent point fails nothing: %v", err)
}
}
@@ -0,0 +1,40 @@
//go:build !faultinject
package main
import (
"os"
"path/filepath"
"regexp"
"strings"
"testing"
)
// goBuildTag is a `go build -tags …` flag (build.sh's own `--print-tags` option is not one).
var goBuildTag = regexp.MustCompile(`\s-tags[ =]`)
// D63: the fault switch exists only in a `-tags faultinject` test build. In this (the release) build an armed fault
// file injects nothing, and neither build.sh nor the Dockerfile passes a build tag.
// RED-PROOF: build the release build with the switch (drop the !faultinject line from faultpoint_off.go and the
// faultinject line from faultpoint_on.go) → the armed point fails → FAILS.
func TestD63_TheReleaseBuildHasNoFaultSwitch(t *testing.T) {
dir := t.TempDir()
t.Setenv("FELHOM_FAULT_DIR", dir)
for _, p := range []string{"defwrite-after-compose", "stop-radicale"} {
if err := os.WriteFile(filepath.Join(dir, p), []byte("0 5\n"), 0o600); err != nil {
t.Fatal(err)
}
if err := faultPoint(p); err != nil {
t.Fatalf("the release build injected a fault at %s: %v", p, err)
}
}
for _, f := range []string{"../../build.sh", "../../Dockerfile"} {
b, err := os.ReadFile(f)
if err != nil {
t.Fatal(err)
}
if goBuildTag.MatchString(string(b)) || strings.Contains(string(b), "faultinject") {
t.Fatalf("%s passes a build tag — the release image could carry the fault switch", f)
}
}
}
@@ -0,0 +1,9 @@
//go:build !faultinject
package main
// faultPoint is the D63 live-proof fault switch (operator ruling 2026-10-29: prove R-1256 H4 and H5's failed stop live,
// with a fault switch in a TEST build only). In every build without the `faultinject` tag — the release image among
// them: build.sh and the Dockerfile pass no build tags — it does nothing and reads nothing. Pinned by
// TestD63_TheReleaseBuildHasNoFaultSwitch; the switch itself is faultpoint_on.go.
func faultPoint(string) error { return nil }
@@ -0,0 +1,64 @@
//go:build faultinject
package main
import (
"fmt"
"log"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
)
// faultPoint (TEST BUILDS ONLY — `go build -tags faultinject`; never the release image, faultpoint_off.go) fails a named
// point on demand, for the D63 live proofs of R-1256 H4 (a definition write that fails after the compose was written)
// and H5 (a put-back whose stop fails). Armed by a file <dir>/<point> holding "<skip> <fail>": the next <skip> passes go
// through, the <fail> after them fail, and the file is removed when both are spent. <dir> is $FELHOM_FAULT_DIR, else
// /opt/docker/felhom-controller/faults (the controller's data volume). A file that does not parse fails nothing.
var faultMu sync.Mutex
func faultPoint(point string) error {
faultMu.Lock()
defer faultMu.Unlock()
dir := os.Getenv("FELHOM_FAULT_DIR")
if dir == "" {
dir = "/opt/docker/felhom-controller/faults"
}
p := filepath.Join(dir, point)
data, err := os.ReadFile(p)
if err != nil {
return nil
}
f := strings.Fields(string(data))
if len(f) != 2 {
log.Printf("[WARN] [faultinject] %s: %q does not parse as \"<skip> <fail>\" — nothing injected", p, strings.TrimSpace(string(data)))
return nil
}
skip, e1 := strconv.Atoi(f[0])
fail, e2 := strconv.Atoi(f[1])
if e1 != nil || e2 != nil || skip < 0 || fail < 0 {
return nil
}
write := func() {
if skip == 0 && fail == 0 {
_ = os.Remove(p)
return
}
_ = os.WriteFile(p, []byte(fmt.Sprintf("%d %d\n", skip, fail)), 0o600)
}
if skip > 0 {
skip--
write()
log.Printf("[WARN] [faultinject] %s: passed (skip left %d, fail left %d)", point, skip, fail)
return nil
}
if fail > 0 {
fail--
write()
log.Printf("[ERROR] [faultinject] %s: FAULT INJECTED (fail left %d)", point, fail)
return fmt.Errorf("FAULT INJECTED at %s (D63 test build)", point)
}
return nil
}
+282
View File
@@ -0,0 +1,282 @@
package main
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net"
"os"
"path/filepath"
"strings"
"time"
"gitea.dooplex.hu/admin/felhom-controller/internal/backup"
"gitea.dooplex.hu/admin/felhom-controller/internal/report"
"gitea.dooplex.hu/admin/felhom-controller/internal/settings"
)
// ── D64 = B + R-1343: the operator clears a hold in the RUNNING controller ─────────────────────────────────────────
//
// Two routes reach the same door (clearHoldNow):
// - the hub's „Clear hold" → the operator action clear_hold (internal/report/opactions.go), run in this process;
// - the box command `felhom-controller --clear-restore-hold <app>` (run with `docker exec` inside the guest) → the
// local socket below → the running controller.
// The running controller clears the hold in memory AND saves settings.json at once (backup.ClearHoldByOperator), so
// no later save — the hold reporter's, a hub report's — can write it back (R-1343). The household's „held" sentence
// goes with it: every reader (the page, the start gate, the API, the hold reporter) reads the same settings record.
// The ONE held flag kept elsewhere — stacks.Manager's „the last update ended held" — is forgotten here too.
// holdClearDeps are clearHoldNow's seams (production: holdClearDepsFor).
type holdClearDeps struct {
clear func(stack string, beforeLift func()) (settings.RestoreHold, error) // backup.AppStopGuard.ClearHoldByOperatorThen
forgetUpdateHeld func(stack string) bool // stacks.Manager.ForgetUpdateHeld (nil = none)
// keepStopped (R-1350) records that the stop is wanted for an app that is not up — run once the hold is found and
// BEFORE it is lifted: stacks.Manager.RecordStopWantedIfDown (nil = none).
keepStopped func(stack string) (bool, error)
logger *log.Logger
}
// clearHoldNow lifts stack's hold and returns the result sentence (English, operator-facing). who names the person
// and the route for the box's own log, e.g. „the operator via the hub, action #12". A refusal (bad name, no hold) is
// wrapped in report.ErrActionRefused, and nothing was changed.
func clearHoldNow(d holdClearDeps, stack, who string) (string, error) {
if d.clear == nil {
return "", fmt.Errorf("%w: clearing a hold is not available on this box", report.ErrActionRefused)
}
var before func()
if d.keepStopped != nil {
before = func() {
rec, kerr := d.keepStopped(stack)
switch {
case kerr != nil && d.logger != nil:
d.logger.Printf("[WARN] [hold] %s: the stop could not be recorded as wanted (%v) — the dead-app alarm may follow the clear (R-1350)", stack, kerr)
case rec && d.logger != nil:
d.logger.Printf("[INFO] [hold] %s: the stop is recorded as wanted (desired state: stopped) — no dead-app alarm; the household's Start ends it (R-1350)", stack)
}
}
}
h, err := d.clear(stack, before)
switch {
case errors.Is(err, backup.ErrHoldBadStack):
return "", fmt.Errorf("%w: %q is not a valid app name — nothing was changed", report.ErrActionRefused, stack)
case errors.Is(err, backup.ErrNotHeld):
return "", fmt.Errorf("%w: %s has no hold — nothing was changed", report.ErrActionRefused, stack)
case err != nil:
return "", fmt.Errorf("clearing the hold on %s failed: %v", stack, err)
}
if d.forgetUpdateHeld != nil && d.forgetUpdateHeld(stack) {
if d.logger != nil {
d.logger.Printf("[INFO] [hold] %s: the update's held state is forgotten with the hold", stack)
}
}
if d.logger != nil {
d.logger.Printf("[WARN] [hold] %s: hold CLEARED by %s — it was %s (set %s); the app is not started by this", stack, who, h.WireReason(), h.At)
}
msg := fmt.Sprintf("the hold on %s is cleared (it was: %s). The app is NOT started by this — the household's Start, or a restore, starts it", stack, h.Why())
if h.Reason == settings.HoldReasonPutBackPending {
dir := h.SafetyDump
if dir == "" {
dir = "(not named in the hold)"
}
msg += ". Its waiting put-back is dropped: the pre-restore copy stays on disk at " + dir + " and is never poured back by itself"
}
return msg, nil
}
// ── the local channel (R-1343) ────────────────────────────────────────────────────────────────────────────────────
//
// WHY A UNIX SOCKET IN THE CONTROLLER'S DATA DIR, mode 0600 in a 0700 directory, and nothing on TCP:
// - traefik, the LAN and every app reach the controller only over TCP (:8080, :8081). A unix socket has no port,
// so none of them can reach it, whatever a proxy header or a forwarded request says;
// - the data dir is the controller's own volume: no app container mounts it, and only root in the guest
// (`pct exec <vmid> -- docker exec felhom-controller …`, the operator gate this project already uses) can enter
// the controller's container to use it;
// - the directory is created 0700 BEFORE the socket is bound, so the moment between bind and chmod is not a window;
// - the peer's uid must equal this process's (SO_PEERCRED, holdctl_linux.go) — a second lock on the same door.
// The customer's HTTP surface is deliberately NOT used: it authenticates as the household, and a household clearing
// its own hold is what the hold exists to prevent. Pinned by TestHoldCtl_NotReachableFromOutside.
const (
holdCtlDir = "ctl"
holdCtlSock = "hold.sock"
// holdCtlOpClear is the one request this channel answers.
holdCtlOpClear = "clear_hold"
// holdCtlMaxRequest bounds what one request may send.
holdCtlMaxRequest = 4096
)
// holdCtlPath is the socket's path under the controller's data dir.
func holdCtlPath(dataDir string) string { return filepath.Join(dataDir, holdCtlDir, holdCtlSock) }
type holdCtlRequest struct {
Op string `json:"op"`
Stack string `json:"stack"`
}
type holdCtlResponse struct {
Outcome string `json:"outcome"` // done | refused | failed (report.Outcome*)
Message string `json:"message"`
}
// listenHoldCtl binds the socket and serves it until the listener is closed (closing it removes the socket file).
// clear is clearHoldNow bound to the running controller's deps.
func listenHoldCtl(path string, clear func(stack, who string) (string, error), logger *log.Logger) (net.Listener, error) {
dir := filepath.Dir(path)
if err := os.MkdirAll(dir, 0o700); err != nil {
return nil, err
}
if err := os.Chmod(dir, 0o700); err != nil {
return nil, err
}
// A socket left by a controller that died is replaced; anything else at that path is refused, never removed.
if fi, err := os.Lstat(path); err == nil {
if fi.Mode()&os.ModeSocket == 0 {
return nil, fmt.Errorf("%s exists and is not a socket — refusing to replace it", path)
}
if err := os.Remove(path); err != nil {
return nil, err
}
}
ln, err := net.Listen("unix", path)
if err != nil {
return nil, err
}
if err := os.Chmod(path, 0o600); err != nil {
ln.Close()
return nil, err
}
go func() {
for {
conn, err := ln.Accept()
if err != nil {
if !errors.Is(err, net.ErrClosed) && logger != nil {
logger.Printf("[WARN] [hold] local channel stopped: %v", err)
}
return
}
go serveHoldCtl(conn, clear, logger)
}
}()
return ln, nil
}
func serveHoldCtl(conn net.Conn, clear func(stack, who string) (string, error), logger *log.Logger) {
defer conn.Close()
_ = conn.SetDeadline(time.Now().Add(30 * time.Second))
answer := func(r holdCtlResponse) { _ = json.NewEncoder(conn).Encode(r) }
if ok, why := holdCtlPeerAllowed(conn); !ok {
if logger != nil {
logger.Printf("[WARN] [hold] local channel: a request was refused — %s", why)
}
answer(holdCtlResponse{Outcome: report.OutcomeRefused, Message: "refused: " + why})
return
}
line, err := bufio.NewReader(io.LimitReader(conn, holdCtlMaxRequest)).ReadBytes('\n')
if err != nil && len(line) == 0 {
answer(holdCtlResponse{Outcome: report.OutcomeRefused, Message: "no request was read"})
return
}
var req holdCtlRequest
if err := json.Unmarshal(line, &req); err != nil || req.Op != holdCtlOpClear {
answer(holdCtlResponse{Outcome: report.OutcomeRefused, Message: "unknown request — this channel only clears a hold"})
return
}
msg, err := clear(req.Stack, "the operator on the box (--clear-restore-hold)")
switch {
case err == nil:
answer(holdCtlResponse{Outcome: report.OutcomeDone, Message: msg})
case errors.Is(err, report.ErrActionRefused):
answer(holdCtlResponse{Outcome: report.OutcomeRefused, Message: strings.TrimPrefix(err.Error(), report.ErrActionRefused.Error()+": ")})
default:
answer(holdCtlResponse{Outcome: report.OutcomeFailed, Message: err.Error()})
}
}
// askRunningControllerToClear sends one clear request. reached=false: no controller answered at path (no socket, or
// a socket nobody listens on) — nothing was asked, so the caller may edit settings.json itself. reached=true with an
// error: the request may have been applied; the caller must not edit the file.
func askRunningControllerToClear(path, stack string) (resp holdCtlResponse, reached bool, err error) {
conn, err := net.DialTimeout("unix", path, 3*time.Second)
if err != nil {
return holdCtlResponse{}, false, err
}
defer conn.Close()
_ = conn.SetDeadline(time.Now().Add(60 * time.Second))
if err := json.NewEncoder(conn).Encode(holdCtlRequest{Op: holdCtlOpClear, Stack: stack}); err != nil {
return holdCtlResponse{}, true, err
}
if err := json.NewDecoder(io.LimitReader(conn, 64*1024)).Decode(&resp); err != nil {
return holdCtlResponse{}, true, err
}
return resp, true, nil
}
// clearRestoreHoldCLI is the box command `--clear-restore-hold <app>` (R-379, R-1343). It asks the running
// controller first; only when none answers does it edit settings.json itself, and it says which one happened.
// Returns the process exit code: 0 cleared, 2 refused (nothing changed), 1 failed or unknown.
func clearRestoreHoldCLI(dataDir, stack string, stdout, stderr io.Writer) int {
path := holdCtlPath(dataDir)
resp, reached, err := askRunningControllerToClear(path, stack)
if reached {
if err != nil {
fmt.Fprintf(stderr, "the running controller was reached, but its answer was lost: %v\n", err)
fmt.Fprintf(stderr, " The hold may or may not be cleared. Check with: felhom-controller --restore-holds\n")
fmt.Fprintf(stderr, " settings.json was NOT edited by this command.\n")
return 1
}
switch resp.Outcome {
case report.OutcomeDone:
fmt.Fprintf(stdout, "%s.\n", resp.Message)
fmt.Fprintf(stdout, " Cleared by the RUNNING controller (memory and settings.json together) — no restart is needed.\n")
return 0
case report.OutcomeRefused:
fmt.Fprintf(stderr, "%s\n", resp.Message)
return 2
default:
fmt.Fprintf(stderr, "the running controller could not clear the hold: %s\n", resp.Message)
return 1
}
}
// No controller answered: it is not running (or is older than this channel). The file is the only copy.
fmt.Fprintf(stdout, "No running controller answered on %s (%v).\n", path, err)
fmt.Fprintf(stdout, " Editing settings.json directly instead.\n")
if !backup.IsValidHoldStack(stack) {
fmt.Fprintf(stderr, "%q is not a valid app name — nothing was changed\n", stack)
return 2
}
lg := log.New(stderr, "", 0)
sett, lerr := settings.Load(filepath.Join(dataDir, "settings.json"), lg)
if lerr != nil {
fmt.Fprintf(stderr, "restore-hold: loading settings: %v\n", lerr)
return 1
}
// The same door as the running controller's (a waiting put-back is dropped from the app-stop marker too), over
// this process's copy — the only copy while no controller runs.
g := backup.NewAppStopGuard(filepath.Join(dataDir, "appstop-state.json"), lg)
g.SetHolds(sett)
h, cerr := g.ClearHoldByOperator(stack)
switch {
case errors.Is(cerr, backup.ErrNotHeld):
// "there was nothing to clear" is not success — a silent 0 here would let an operator believe they had
// unblocked an app whose name they mistyped.
fmt.Fprintf(stderr, "no restore hold in force for %q — nothing was changed\n", stack)
return 2
case cerr != nil:
fmt.Fprintf(stderr, "restore-hold: clearing %s: %v\n", stack, cerr)
return 1
}
fmt.Fprintf(stdout, "restore hold cleared for %s in settings.json (no controller was running to ask; it was: %s).\n", stack, h.Why())
if h.Reason == settings.HoldReasonPutBackPending {
fmt.Fprintf(stdout, " Its waiting put-back is dropped; the pre-restore copy stays on disk at %s.\n", orNone(h.SafetyDump))
}
fmt.Fprintf(stdout, " The controller reads it when it starts. If a controller IS running in this guest after all, restart it NOW,\n")
fmt.Fprintf(stdout, " INSIDE THE GUEST — from the Proxmox host: pct exec <vmid> -- systemctl restart felhom-controller-bootstrap.service\n")
fmt.Fprintf(stdout, " — or its next settings save writes the hold back (R-1343).\n")
return 0
}
// holdClearCommandHint is the exact guest command, for the help text and the operator's mail.
const holdClearCommandHint = "pct exec <vmid> -- docker exec felhom-controller felhom-controller --clear-restore-hold <app>"
+559
View File
@@ -0,0 +1,559 @@
package main
import (
"bytes"
"context"
"encoding/json"
"go/ast"
"go/parser"
"go/token"
"io"
"log"
"net"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"testing"
"time"
"gitea.dooplex.hu/admin/felhom-controller/internal/backup"
"gitea.dooplex.hu/admin/felhom-controller/internal/config"
"gitea.dooplex.hu/admin/felhom-controller/internal/holdreport"
"gitea.dooplex.hu/admin/felhom-controller/internal/report"
"gitea.dooplex.hu/admin/felhom-controller/internal/settings"
)
// D64 = B (operator ruling 2026-10-29 12:10) + R-1343: the operator clears a hold — from the hub (clear_hold) or with
// the box command — IN THE RUNNING CONTROLLER, so the hold is gone from memory and from settings.json together and no
// later save brings it back.
//
// RED-PROOFS (2026-10-29):
// - TestR1343_TheBoxCommandClearsThroughTheRunningController: with clearRestoreHoldCLI's socket call skipped (the
// old second-process edit of settings.json), it fails on „the hold came back after a later save of the running
// controller" — the R-1343 measurement, in a test;
// - TestD64_ClearPutBackPendingDropsTheMarkerEntry: with the dropFromMarker call removed from
// ClearHoldByOperator, it fails on „a later controller start poured the old copy back";
// - TestD64_ClearHoldViaTheHub: with the forgetUpdateHeld call removed from clearHoldNow, it fails on „the
// update's held flag was not forgotten".
// - TestD64_ClearHoldViaTheHub + TestD64_ClearHoldStaysGoneAfterALaterSave: with ClearHoldByOperator clearing a
// SECOND Settings loaded from disk (the old CLI's shape) instead of the running one, they fail on „the running
// controller still holds the app" / „the hold came back after a later save of the running controller".
// d64Rig is a running controller's hold side: its Settings, the app-stop guard wired to them, and a log.
type d64Rig struct {
dir string
sett *settings.Settings
guard *backup.AppStopGuard
logBuf *syncBuffer
logger *log.Logger
forgot []string
holdDeps holdClearDeps
}
type syncBuffer struct {
mu sync.Mutex
b bytes.Buffer
}
func (s *syncBuffer) Write(p []byte) (int, error) {
s.mu.Lock()
defer s.mu.Unlock()
return s.b.Write(p)
}
func (s *syncBuffer) String() string { s.mu.Lock(); defer s.mu.Unlock(); return s.b.String() }
func newD64Rig(t *testing.T) *d64Rig {
t.Helper()
r := &d64Rig{dir: t.TempDir(), logBuf: &syncBuffer{}}
r.logger = log.New(r.logBuf, "", 0)
sett, err := settings.Load(filepath.Join(r.dir, "settings.json"), r.logger)
if err != nil {
t.Fatal(err)
}
r.sett = sett
r.guard = backup.NewAppStopGuard(filepath.Join(r.dir, "appstop-state.json"), r.logger)
r.guard.SetHolds(sett)
r.holdDeps = holdClearDeps{
clear: r.guard.ClearHoldByOperatorThen,
forgetUpdateHeld: func(s string) bool { r.forgot = append(r.forgot, s); return true },
logger: r.logger,
}
return r
}
func (r *d64Rig) hold(t *testing.T, h settings.RestoreHold) {
t.Helper()
if h.At == "" {
h.At = "2026-10-29T08:18:00Z"
}
if err := r.sett.SetRestoreHold(h); err != nil {
t.Fatal(err)
}
}
func (r *d64Rig) onDisk(t *testing.T, stack string) bool {
t.Helper()
s, err := settings.Load(filepath.Join(r.dir, "settings.json"), log.New(io.Discard, "", 0))
if err != nil {
t.Fatal(err)
}
_, held := s.GetRestoreHold(stack)
return held
}
func (r *d64Rig) actions() *report.OperatorActions {
return report.NewOperatorActions(context.Background(), operatorActionHandlers(nil, nil, r.holdDeps, nil, r.logger), r.logger)
}
func onlyResult(t *testing.T, o *report.OperatorActions, id int64) report.OperatorActionResult {
t.Helper()
for _, x := range o.Results() {
if x.ID == id {
return x
}
}
t.Fatalf("no result for #%d: %+v", id, o.Results())
return report.OperatorActionResult{}
}
// The hub's clear_hold: the hold is gone (memory and disk), the household's held sentence is gone, the update's
// held flag is forgotten, the box logs who did it, and the result names what was cleared.
func TestD64_ClearHoldViaTheHub(t *testing.T) {
r := newD64Rig(t)
r.hold(t, settings.RestoreHold{Stack: "paperless", ReplayError: "ERROR: relation exists", RollbackErr: "psql: refused"})
cfg := &config.Config{}
cfg.Paths.DataDir = r.dir
mgr := backup.NewManager(cfg, r.sett, r.logger)
if held, why := mgr.RestoreHoldForLang("paperless", "hu"); !held || why == "" {
t.Fatal("fixture: the household must read a held sentence before the clear")
}
o := r.actions()
o.Reconcile([]report.OperatorAction{{ID: 12, Action: report.OpClearHold, Arg: "paperless"}})
res := onlyResult(t, o, 12)
if res.Outcome != report.OutcomeDone {
t.Fatalf("result %+v", res)
}
for _, want := range []string{"the hold on paperless is cleared", "held after a failed restore whose rollback also failed", "NOT started by this"} {
if !strings.Contains(res.Message, want) {
t.Errorf("result message %q lacks %q", res.Message, want)
}
}
if _, held := r.sett.GetRestoreHold("paperless"); held {
t.Fatal("the running controller still holds the app")
}
if r.onDisk(t, "paperless") {
t.Fatal("settings.json still holds the app")
}
if held, why := mgr.RestoreHoldForLang("paperless", "hu"); held || why != "" {
t.Fatalf("the household still reads a held sentence: %q", why)
}
if len(r.forgot) != 1 || r.forgot[0] != "paperless" {
t.Fatalf("the update's held flag was not forgotten: %v", r.forgot)
}
if lg := r.logBuf.String(); !strings.Contains(lg, "paperless: hold CLEARED by the operator via the hub, action #12") {
t.Fatalf("the box's log must say who cleared it:\n%s", lg)
}
}
// Refusals change nothing: an app nobody ever held, a second press on an app already cleared, a bad name.
func TestD64_ClearHoldRefusals(t *testing.T) {
r := newD64Rig(t)
r.hold(t, settings.RestoreHold{Stack: "kimai", Reason: settings.HoldReasonUpdateFailed})
o := r.actions()
o.Reconcile([]report.OperatorAction{{ID: 1, Action: report.OpClearHold, Arg: "nosuchapp"}})
if res := onlyResult(t, o, 1); res.Outcome != report.OutcomeRefused || !strings.Contains(res.Message, "nosuchapp has no hold") {
t.Fatalf("unknown app: %+v", res)
}
if _, held := r.sett.GetRestoreHold("kimai"); !held || !r.onDisk(t, "kimai") {
t.Fatal("a refusal changed another app's hold")
}
if len(r.forgot) != 0 {
t.Fatalf("a refusal touched the update state: %v", r.forgot)
}
o.Reconcile([]report.OperatorAction{{ID: 2, Action: report.OpClearHold, Arg: "kimai"}})
o.Reconcile([]report.OperatorAction{{ID: 3, Action: report.OpClearHold, Arg: "kimai"}})
if res := onlyResult(t, o, 3); res.Outcome != report.OutcomeRefused || !strings.Contains(res.Message, "kimai has no hold") {
t.Fatalf("not held (second press): %+v", res)
}
if _, err := clearHoldNow(r.holdDeps, "../kimai", "test"); err == nil || !strings.Contains(err.Error(), "not a valid app name") {
t.Fatalf("a bad name must be refused by the door itself too: %v", err)
}
}
// R-1343's order: clear, then ANOTHER component saves settings (the hold reporter, a hub report), then the file is
// read back — the hold must stay gone, in memory and on disk.
func TestD64_ClearHoldStaysGoneAfterALaterSave(t *testing.T) {
r := newD64Rig(t)
r.hold(t, settings.RestoreHold{Stack: "radicale", Reason: settings.HoldReasonRestoreMixed})
o := r.actions()
o.Reconcile([]report.OperatorAction{{ID: 5, Action: report.OpClearHold, Arg: "radicale"}})
if res := onlyResult(t, o, 5); res.Outcome != report.OutcomeDone {
t.Fatalf("result %+v", res)
}
if err := r.sett.SetReportedHolds(map[string]string{"other": "x|y"}); err != nil { // another component's save
t.Fatal(err)
}
if r.onDisk(t, "radicale") {
t.Fatal("the hold came back after a later save of the running controller")
}
if _, held := r.sett.GetRestoreHold("radicale"); held {
t.Fatal("the running controller holds the app again")
}
}
// The same order through the BOX COMMAND: it reaches the running controller over the socket; no restart.
func TestR1343_TheBoxCommandClearsThroughTheRunningController(t *testing.T) {
r := newD64Rig(t)
r.hold(t, settings.RestoreHold{Stack: "radicale", Reason: settings.HoldReasonRestoreMixed})
ln, err := listenHoldCtl(holdCtlPath(r.dir), func(stack, who string) (string, error) { return clearHoldNow(r.holdDeps, stack, who) }, r.logger)
if err != nil {
t.Fatal(err)
}
defer ln.Close()
var out, errb bytes.Buffer
if code := clearRestoreHoldCLI(r.dir, "radicale", &out, &errb); code != 0 {
t.Fatalf("exit %d, stdout %q, stderr %q", code, out.String(), errb.String())
}
if err := r.sett.SetReportedHolds(map[string]string{"other": "x|y"}); err != nil { // the running controller's next save
t.Fatal(err)
}
if r.onDisk(t, "radicale") {
t.Fatal("the hold came back after a later save of the running controller")
}
if !strings.Contains(out.String(), "Cleared by the RUNNING controller") || !strings.Contains(out.String(), "no restart is needed") {
t.Fatalf("the command must say it went through the running controller and needs no restart:\n%s", out.String())
}
if !strings.Contains(r.logBuf.String(), "hold CLEARED by the operator on the box (--clear-restore-hold)") {
t.Fatalf("the box's log must say who cleared it:\n%s", r.logBuf.String())
}
// A second run: refused through the socket, exit 2, nothing edited.
out.Reset()
errb.Reset()
if code := clearRestoreHoldCLI(r.dir, "radicale", &out, &errb); code != 2 || !strings.Contains(errb.String(), "radicale has no hold") {
t.Fatalf("not held: exit %d, stderr %q", code, errb.String())
}
}
// No controller runs (no socket, or a socket nobody listens on): the command edits settings.json and says so plainly,
// naming the guest restart for the case a controller runs after all.
func TestR1343_TheBoxCommandFallsBackWhenNoControllerRuns(t *testing.T) {
for _, stale := range []bool{false, true} {
r := newD64Rig(t)
r.hold(t, settings.RestoreHold{Stack: "kimai", Reason: settings.HoldReasonUpdateFailed})
if stale { // a socket left by a controller that died
ln, err := listenHoldCtl(holdCtlPath(r.dir), func(string, string) (string, error) { return "", nil }, r.logger)
if err != nil {
t.Fatal(err)
}
ln.(*net.UnixListener).SetUnlinkOnClose(false)
ln.Close()
}
var out, errb bytes.Buffer
if code := clearRestoreHoldCLI(r.dir, "kimai", &out, &errb); code != 0 {
t.Fatalf("stale=%v: exit %d, stderr %q", stale, code, errb.String())
}
for _, want := range []string{"No running controller answered", "Editing settings.json directly", "INSIDE THE GUEST", "pct exec <vmid> -- systemctl restart felhom-controller-bootstrap.service"} {
if !strings.Contains(out.String(), want) {
t.Errorf("stale=%v: output lacks %q:\n%s", stale, want, out.String())
}
}
if r.onDisk(t, "kimai") {
t.Fatalf("stale=%v: settings.json still holds the app", stale)
}
out.Reset()
errb.Reset()
if code := clearRestoreHoldCLI(r.dir, "kimai", &out, &errb); code != 2 {
t.Fatalf("stale=%v: not held must exit 2, got %d", stale, code)
}
if code := clearRestoreHoldCLI(r.dir, "../x", &out, &errb); code != 2 {
t.Fatalf("stale=%v: a bad name must exit 2, got %d", stale, code)
}
}
}
// A put-back WAITING for its drive is also in the app-stop marker: clearing the hold must drop it there too, or the
// next controller start with the drive bound would pour the old copy over what the app wrote after the clear. The
// copy itself stays on disk (nothing is deleted).
func TestD64_ClearPutBackPendingDropsTheMarkerEntry(t *testing.T) {
r := newD64Rig(t)
undo := filepath.Join(r.dir, "drive", "felhom-data", "backups", "restore-undo", "immich", "20261029T080000Z")
if err := os.MkdirAll(undo, 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(undo, "undo.json"), []byte(`{"stack":"immich"}`), 0o600); err != nil {
t.Fatal(err)
}
if err := r.guard.Begin("unit-restore:immich", backup.ReasonUnitRestore, []string{"immich"}); err != nil {
t.Fatal(err)
}
if err := r.guard.SetUndo("immich", undo); err != nil {
t.Fatal(err)
}
r.hold(t, settings.RestoreHold{Stack: "immich", Reason: settings.HoldReasonPutBackPending, SafetyDump: undo})
o := r.actions()
o.Reconcile([]report.OperatorAction{{ID: 3, Action: report.OpClearHold, Arg: "immich"}})
res := onlyResult(t, o, 3)
if res.Outcome != report.OutcomeDone || !strings.Contains(res.Message, "waiting put-back is dropped") || !strings.Contains(res.Message, undo) {
t.Fatalf("result %+v", res)
}
if _, err := os.Stat(filepath.Join(undo, "undo.json")); err != nil {
t.Fatal("the copy must stay on disk")
}
// The consequence: a later controller start with the drive bound pours nothing back.
poured := &recordingPutBacker{}
g2 := backup.NewAppStopGuard(filepath.Join(r.dir, "appstop-state.json"), r.logger)
g2.SetHolds(r.sett)
g2.SetPutBacker(poured)
g2.SetStarter(nopStarter{})
g2.SetUndoReachable(func(string, string) bool { return true })
g2.Recover()
if len(poured.stacks) != 0 {
t.Fatalf("a later controller start poured the old copy back over the app: %v", poured.stacks)
}
}
type recordingPutBacker struct{ stacks []string }
func (p *recordingPutBacker) PutBackInterruptedRestore(stack, _ string) error {
p.stacks = append(p.stacks, stack)
return nil
}
type nopStarter struct{}
func (nopStarter) StartStack(string) error { return nil }
// The hold reporter's next tick tells the hub the hold is gone (it reads the same settings record; nothing cached).
func TestD64_TheHoldReporterTellsTheHubAfterTheClear(t *testing.T) {
r := newD64Rig(t)
r.hold(t, settings.RestoreHold{Stack: "kimai", Reason: settings.HoldReasonUpdateFailed})
var events []string
rep := holdreport.New(r.sett, func(et, _, _ string, _ interface{}) { events = append(events, et) }, r.logger)
rep.Tick(timeAt(0))
o := r.actions()
o.Reconcile([]report.OperatorAction{{ID: 1, Action: report.OpClearHold, Arg: "kimai"}})
rep.Tick(timeAt(60))
if strings.Join(events, ",") != holdreport.EventHeld+","+holdreport.EventCleared {
t.Fatalf("events %v — want app_held then app_hold_cleared", events)
}
}
// „Not reachable from outside": the channel is a unix socket (no TCP anywhere in the file), 0600 in a 0700 directory
// — even when the directory existed with a looser mode — and main opens it once, under the data dir.
func TestHoldCtl_NotReachableFromOutside(t *testing.T) {
dir := t.TempDir()
if err := os.MkdirAll(filepath.Join(dir, holdCtlDir), 0o755); err != nil {
t.Fatal(err)
}
ln, err := listenHoldCtl(holdCtlPath(dir), func(string, string) (string, error) { return "", nil }, nil)
if err != nil {
t.Fatal(err)
}
defer ln.Close()
if n := ln.Addr().Network(); n != "unix" {
t.Fatalf("the channel listens on %q, want unix", n)
}
fi, err := os.Lstat(holdCtlPath(dir))
if err != nil || fi.Mode()&os.ModeSocket == 0 || fi.Mode().Perm() != 0o600 {
t.Fatalf("socket mode %v (err %v), want a socket with 0600", fi.Mode(), err)
}
di, _ := os.Stat(filepath.Join(dir, holdCtlDir))
if di.Mode().Perm() != 0o700 {
t.Fatalf("socket dir mode %v, want 0700", di.Mode().Perm())
}
// No TCP and no HTTP in the channel's file: every net.Listen/Dial names "unix".
f, err := parser.ParseFile(token.NewFileSet(), "holdclear.go", nil, parser.ImportsOnly)
if err != nil {
t.Fatal(err)
}
for _, im := range f.Imports {
if p, _ := strconv.Unquote(im.Path.Value); strings.HasPrefix(p, "net/http") {
t.Fatalf("holdclear.go imports %s — the channel must not be HTTP", p)
}
}
full, err := parser.ParseFile(token.NewFileSet(), "holdclear.go", nil, 0)
if err != nil {
t.Fatal(err)
}
nets := 0
ast.Inspect(full, func(n ast.Node) bool {
call, ok := n.(*ast.CallExpr)
if !ok {
return true
}
sel, ok := call.Fun.(*ast.SelectorExpr)
if !ok {
return true
}
if x, ok := sel.X.(*ast.Ident); ok && x.Name == "net" && len(call.Args) > 0 {
nets++
if lit, ok := call.Args[0].(*ast.BasicLit); !ok || lit.Value != `"unix"` {
t.Errorf("net.%s is called with a network other than \"unix\"", sel.Sel.Name)
}
}
return true
})
if nets < 2 {
t.Fatalf("expected the listen and the dial in holdclear.go, found %d net calls", nets)
}
// main opens it exactly once, at holdCtlPath(cfg.Paths.DataDir).
mf, err := parser.ParseFile(token.NewFileSet(), "main.go", nil, 0)
if err != nil {
t.Fatal(err)
}
opened := 0
ast.Inspect(mf, func(n ast.Node) bool {
call, ok := n.(*ast.CallExpr)
if !ok {
return true
}
if id, ok := call.Fun.(*ast.Ident); ok && id.Name == "listenHoldCtl" {
opened++
arg, ok := call.Args[0].(*ast.CallExpr)
if fn, ok2 := arg.Fun.(*ast.Ident); !ok || !ok2 || fn.Name != "holdCtlPath" {
t.Error("main must open the channel at holdCtlPath(<data dir>)")
}
}
return true
})
if opened != 1 {
t.Fatalf("main.go opens the channel %d time(s), want 1", opened)
}
}
// The socket answers only its one request; anything else is refused and calls nothing.
func TestHoldCtl_UnknownRequestIsRefused(t *testing.T) {
dir := t.TempDir()
called := 0
ln, err := listenHoldCtl(holdCtlPath(dir), func(string, string) (string, error) { called++; return "x", nil }, nil)
if err != nil {
t.Fatal(err)
}
defer ln.Close()
conn, err := net.Dial("unix", holdCtlPath(dir))
if err != nil {
t.Fatal(err)
}
defer conn.Close()
if _, err := conn.Write([]byte(`{"op":"set_hold","stack":"x"}` + "\n")); err != nil {
t.Fatal(err)
}
var resp holdCtlResponse
if err := json.NewDecoder(conn).Decode(&resp); err != nil {
t.Fatal(err)
}
if resp.Outcome != report.OutcomeRefused || called != 0 {
t.Fatalf("response %+v, calls %d — want refused and nothing called", resp, called)
}
}
// Something at the socket's path that is NOT a socket is refused, never removed.
func TestHoldCtl_ANonSocketFileIsNotReplaced(t *testing.T) {
dir := t.TempDir()
p := holdCtlPath(dir)
if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(p, []byte("keep me"), 0o600); err != nil {
t.Fatal(err)
}
if _, err := listenHoldCtl(p, func(string, string) (string, error) { return "", nil }, nil); err == nil {
t.Fatal("a regular file at the socket path must be refused")
}
if b, _ := os.ReadFile(p); string(b) != "keep me" {
t.Fatal("the file at the socket path was changed")
}
}
// main wires every piece once (the seam-built-but-never-wired trap): the clear door into the operator actions, the
// R-1340 text into the hold notification, the R-1341 gate into the OOM loop, and the box command.
func TestD64_MainWiresTheNewPieces(t *testing.T) {
f, err := parser.ParseFile(token.NewFileSet(), "main.go", nil, 0)
if err != nil {
t.Fatal(err)
}
found := map[string]int{}
var opArgs []ast.Expr
ast.Inspect(f, func(n ast.Node) bool {
call, ok := n.(*ast.CallExpr)
if !ok {
return true
}
switch fn := call.Fun.(type) {
case *ast.SelectorExpr:
if x, ok := fn.X.(*ast.Ident); ok {
found[x.Name+"."+fn.Sel.Name]++
}
case *ast.Ident:
found[fn.Name]++
if fn.Name == "operatorActionHandlers" {
opArgs = call.Args
}
}
return true
})
for _, want := range []string{"heldStoppedOperatorText", "heldHoldFromNotify", "oomLog.fresh", "clearRestoreHoldCLI", "listenHoldCtl", "clearHoldNow"} {
if found[want] != 1 {
t.Errorf("main.go calls %s %d time(s), want exactly 1", want, found[want])
}
}
if len(opArgs) < 3 {
t.Fatal("operatorActionHandlers call not found")
}
if id, ok := opArgs[2].(*ast.Ident); !ok || id.Name != "holdDeps" {
t.Error("main must hand holdDeps (the running controller's clear door) to operatorActionHandlers")
}
}
func timeAt(sec int) time.Time { return time.Date(2026, 10, 29, 12, 0, sec, 0, time.UTC) }
// No controller runs: the box command's own clear drops a waiting put-back from the app-stop marker too (the same
// door), so the next start with the drive bound pours nothing back.
// RED-PROOF (2026-10-29): with the fallback clearing through settings.ClearRestoreHold alone (its first shape in
// 5b3b541), this fails on „a later controller start poured the old copy back".
func TestR1343_TheFallbackDropsAWaitingPutBackToo(t *testing.T) {
r := newD64Rig(t)
undo := filepath.Join(r.dir, "drive", "felhom-data", "backups", "restore-undo", "immich", "20261029T080000Z")
if err := os.MkdirAll(undo, 0o700); err != nil {
t.Fatal(err)
}
if err := r.guard.Begin("unit-restore:immich", backup.ReasonUnitRestore, []string{"immich"}); err != nil {
t.Fatal(err)
}
if err := r.guard.SetUndo("immich", undo); err != nil {
t.Fatal(err)
}
r.hold(t, settings.RestoreHold{Stack: "immich", Reason: settings.HoldReasonPutBackPending, SafetyDump: undo})
var out, errb bytes.Buffer
if code := clearRestoreHoldCLI(r.dir, "immich", &out, &errb); code != 0 {
t.Fatalf("exit %d, stderr %q", code, errb.String())
}
if !strings.Contains(out.String(), "waiting put-back is dropped") {
t.Errorf("output must say the put-back is dropped:\n%s", out.String())
}
sett2, err := settings.Load(filepath.Join(r.dir, "settings.json"), log.New(io.Discard, "", 0))
if err != nil {
t.Fatal(err)
}
poured := &recordingPutBacker{}
g2 := backup.NewAppStopGuard(filepath.Join(r.dir, "appstop-state.json"), r.logger)
g2.SetHolds(sett2)
g2.SetPutBacker(poured)
g2.SetStarter(nopStarter{})
g2.SetUndoReachable(func(string, string) bool { return true })
g2.Recover()
if len(poured.stacks) != 0 {
t.Fatalf("a later controller start poured the old copy back over the app: %v", poured.stacks)
}
if _, err := os.Stat(undo); err != nil {
t.Fatal("the copy must stay on disk")
}
}
@@ -0,0 +1,34 @@
//go:build linux
package main
import (
"fmt"
"net"
"os"
"syscall"
)
// holdCtlPeerAllowed (R-1343) admits a peer on the hold socket only when its uid equals this process's (SO_PEERCRED).
// The socket's 0600 mode in a 0700 directory already says so; this is the second lock on the same door.
func holdCtlPeerAllowed(conn net.Conn) (bool, string) {
uc, ok := conn.(*net.UnixConn)
if !ok {
return false, "not a unix-socket peer"
}
raw, err := uc.SyscallConn()
if err != nil {
return false, "the peer's identity could not be read"
}
var cred *syscall.Ucred
var cerr error
if err := raw.Control(func(fd uintptr) {
cred, cerr = syscall.GetsockoptUcred(int(fd), syscall.SOL_SOCKET, syscall.SO_PEERCRED)
}); err != nil || cerr != nil || cred == nil {
return false, "the peer's identity could not be read"
}
if int(cred.Uid) != os.Geteuid() {
return false, fmt.Sprintf("the peer's uid %d is not this controller's", cred.Uid)
}
return true, ""
}
@@ -0,0 +1,14 @@
//go:build !linux
package main
import "net"
// holdCtlPeerAllowed: the peer check needs SO_PEERCRED (Linux, where the controller runs). Elsewhere the socket's
// 0600 mode in a 0700 directory is the only lock.
func holdCtlPeerAllowed(conn net.Conn) (bool, string) {
if _, ok := conn.(*net.UnixConn); !ok {
return false, "not a unix-socket peer"
}
return true, ""
}
+165
View File
@@ -0,0 +1,165 @@
package main
import (
"fmt"
"strings"
"gitea.dooplex.hu/admin/felhom-controller/internal/settings"
)
// ── R-1340: the operator's „HELD STOPPED" mail names the hold's REAL cause ────────────────────────────────────────
//
// Until 2026-10-29 the restore-hold mail told one story for every restore_mixed hold — R-893 option C's „its off-site
// database restore failed. The database was rolled back …, but its files and named volumes are the snapshot's" —
// written when option C was the only mixed hold. Measured on Tester 1 (D63's H5 proof): Radicale, which has no
// database, whose put-back stopped at „the app could not be stopped" with nothing moved, got exactly that text.
// Support read a wrong account of the box.
//
// The text is now built from the HOLD RECORD the writer persisted just before the mail (its reason and the R-1340
// fields: which restore, which branch, which step failed, whether the failure was a database replay, where the copy
// is kept). It never says „database" unless the restore's failure WAS a database replay, and never „off-site" for a
// restore from the app's own backup. One sentence per reason; pinned by TestR1340_* (holdmail_test.go).
// heldStoppedOperatorText is the operator mail for a held app: the message, its leg (the hub reads the leg, so the
// two existing ones are kept: restore-hold for a restore hold, restore-hold-mixed for a mixed one) and a short reason.
func heldStoppedOperatorText(h settings.RestoreHold) (msg, leg, reason string) {
stack := h.Stack
const tail = " The app will not start from any path until the hold is cleared (the hub's Clear hold button, or on the box: " + holdClearCommandHint + ")."
kind := restoreKindPhrase(h.RestoreKind)
switch h.Reason {
case settings.HoldReasonUnhealthyStop:
what := "a crash loop"
if h.UnhealthyKind == "oom_storm" {
what = "an out-of-memory storm"
}
trip := ""
if h.Trip >= 2 {
trip = fmt.Sprintf(" This is stop %d within 24 hours.", h.Trip)
}
msg = fmt.Sprintf("App %q is HELD STOPPED: the box stopped it for %s at %s.%s No restore or update was involved and no data was touched. "+
"The household's Start gives it one more try; clearing the hold lifts it too.", stack, what, h.At, trip)
return msg, "unhealthy-stop", "stopped for " + what
case settings.HoldReasonUpdateFailed:
undo := ""
switch h.UndoState {
case "untouched":
undo = " The automatic undo failed; the data was not touched."
case "half":
undo = " The automatic undo failed half-way; the data may be partly the new version's."
case "not_started":
undo = " The automatic undo did not start."
}
copyLine := " Restoring it from its backup starts it."
if h.NoWholeCopy {
copyLine = " No copy on this box brings it back whole — it needs support."
} else if h.CopyDate != "" {
copyLine = fmt.Sprintf(" Restoring it from its backup (tier %d, %s) starts it.", h.CopyTier, h.CopyDate)
}
msg = fmt.Sprintf("App %q is HELD STOPPED: its update at %s did not come up healthy.%s%s", stack, h.At, undo, copyLine) + tail
return msg, "update-hold", "update failed"
case settings.HoldReasonPutBackPending:
msg = fmt.Sprintf("App %q is HELD STOPPED: a restore was cut after its copy of the live data was taken, and that copy (%s) is on a drive that is not bound. "+
"The copy is poured back and the app started when the drive is bound. Clearing the hold DROPS that put-back; the copy stays on disk.", stack, orNone(h.SafetyDump))
return msg, "putback-pending", "put-back waits for its drive"
case settings.HoldReasonRestoreMixed:
return mixedHoldText(h, kind, tail)
default: // HoldReasonRestoreFailed: a database replay failed AND its rollback failed (holdAppAfterFailedRollback)
what := "its " + kind + " failed"
if h.DBReplay || h.RestoreKind == "" { // every restore hold before R-1340 was written by the database branch
what = "its " + kind + " failed at the database replay AND the rollback to the pre-restore database copy also failed — the database may be half-written"
}
msg = fmt.Sprintf("App %q is HELD STOPPED: %s.", stack, what) + tail +
fmt.Sprintf(" Replay error: %s. Rollback error: %s", orNone(h.ReplayError), orNone(h.RollbackErr))
reason = h.RollbackErr
if reason == "" {
reason = "rollback failed"
}
return msg, "restore-hold", reason
}
}
// heldRunKind names the run in the mail's subject. A hold that does not say which restore wrote it is an off-site one, the
// pre-R-1340 rule, EXCEPT an interrupted put-back: its record names no kind, and its restore may be either, so „restore" (R-1348,
// seen live 2026-11-03: a local restore's mail read „offsite-reconstitute"). Pinned by TestR1348_HeldRunKind.
func heldRunKind(h settings.RestoreHold) string {
if h.RestoreKind == settings.RestoreKindLocal || h.MixedCause == settings.MixedCauseInterruptedPutBack {
return "restore"
}
return "offsite-reconstitute"
}
func mixedHoldText(h settings.RestoreHold, kind, tail string) (msg, leg, reason string) {
stack := h.Stack
leg = "restore-hold-mixed"
failedAt := ""
if h.DBReplay {
failedAt = " at the database replay"
}
copyLine := " There is no copy of the live volumes."
if h.SafetyDump != "" {
copyLine = " The copy of the live data is kept at " + h.SafetyDump + "."
}
switch h.MixedCause {
case settings.MixedCauseDefinitionWrite:
msg = fmt.Sprintf("App %q is HELD STOPPED for support: its %s failed while writing the backup's app definition, before any data was touched, "+
"and %s. The app's data is the live data; the definition on disk may be the backup's.", stack, kind, orNone(h.FailedStep)) + tail +
" Error: " + orNone(h.ReplayError)
return msg, leg, "definition write failed; writing the live definition back failed too"
case settings.MixedCausePutBack:
msg = fmt.Sprintf("App %q is HELD STOPPED for support: its %s failed%s, and putting the live data back FAILED — %s. "+
"The app may be on a mix of the backup's and the live data.%s", stack, kind, failedAt, orNone(h.FailedStep), copyLine) + tail +
" Restore error: " + orNone(h.ReplayError)
return msg, leg, "put-back failed: " + firstClause(h.FailedStep)
case settings.MixedCauseInterruptedPutBack:
msg = fmt.Sprintf("App %q is HELD STOPPED for support: a restore cut by a stop could not be put back at the next start — %s. "+
"The app may be on a mix of the backup's and the live data.%s", stack, orNone(h.FailedStep), copyLine) + tail
return msg, leg, "interrupted restore: put-back failed"
}
// A mixed hold written before R-1340 carries no cause: name only what the record says, and assume nothing.
msg = fmt.Sprintf("App %q is HELD STOPPED for support: a restore stopped half-way (set %s); the app may be on a mix of the backup's and the live data. "+
"The hold record says: %s.", stack, h.At, orNone(h.ReplayError)) + tail
return msg, leg, "restore stopped half-way"
}
func restoreKindPhrase(k string) string {
switch k {
case settings.RestoreKindLocal:
return "restore from its own backup"
case settings.RestoreKindOffsite:
return "off-site restore"
}
return "restore"
}
func orNone(s string) string {
if strings.TrimSpace(s) == "" {
return "(none recorded)"
}
return s
}
// firstClause is a step's text up to its error (the short reason field).
func firstClause(s string) string {
if i := strings.Index(s, ":"); i > 0 {
return s[:i]
}
return s
}
// heldHoldFromNotify is the hold the notification describes: the record the writer persisted just before it, or —
// when that write failed — one rebuilt from the errors handed over (the pre-R-1340 rule: no rollback error = mixed).
func heldHoldFromNotify(get func(string) (settings.RestoreHold, bool), stack string, replayErr, rollbackErr error) settings.RestoreHold {
if get != nil {
if h, ok := get(stack); ok && (h.Reason == settings.HoldReasonRestoreFailed || h.Reason == settings.HoldReasonRestoreMixed) {
return h
}
}
h := settings.RestoreHold{Stack: stack, Reason: settings.HoldReasonRestoreMixed}
if rollbackErr != nil {
h.Reason, h.RollbackErr = settings.HoldReasonRestoreFailed, rollbackErr.Error()
}
if replayErr != nil {
h.ReplayError = replayErr.Error()
}
return h
}
+140
View File
@@ -0,0 +1,140 @@
package main
import (
"errors"
"strings"
"testing"
"gitea.dooplex.hu/admin/felhom-controller/internal/settings"
)
// R-1340: the operator's „HELD STOPPED" mail names the hold's real cause — one test per reason. Each asserts the words
// that MUST be there and the words that must NOT (the option-C database story was the bug).
//
// RED-PROOF (2026-10-29): with mixedHoldText's body replaced by the pre-R-1340 sentence („its off-site database restore
// failed. The database was rolled back to the pre-restore copy and the live definition written back, but its files
// and named volumes are the snapshot's"), TestR1340_PutBackWithoutADatabase, _DefinitionWrite, _LocalRestore and
// _InterruptedPutBack fail on „database" / „off-site" being present and their own step missing.
const optionCStory = "files and named volumes are the snapshot's"
func mustHave(t *testing.T, msg string, want ...string) {
t.Helper()
for _, w := range want {
if !strings.Contains(msg, w) {
t.Errorf("the mail must say %q:\n%s", w, msg)
}
}
}
func mustNotHave(t *testing.T, msg string, bad ...string) {
t.Helper()
for _, b := range bad {
if strings.Contains(strings.ToLower(msg), strings.ToLower(b)) {
t.Errorf("the mail must NOT say %q:\n%s", b, msg)
}
}
}
func TestR1340_UnhealthyStop(t *testing.T) {
msg, leg, _ := heldStoppedOperatorText(settings.RestoreHold{Stack: "romm", At: "2026-10-29T08:00:00Z", Reason: settings.HoldReasonUnhealthyStop, UnhealthyKind: "crash_loop"})
mustHave(t, msg, `"romm"`, "crash loop", "no data was touched", "Start gives it one more try")
mustNotHave(t, msg, "database", "restore failed", optionCStory)
if leg != "unhealthy-stop" {
t.Errorf("leg %q", leg)
}
oom, _, _ := heldStoppedOperatorText(settings.RestoreHold{Stack: "romm", Reason: settings.HoldReasonUnhealthyStop, UnhealthyKind: "oom_storm", Trip: 2})
mustHave(t, oom, "out-of-memory storm", "stop 2 within 24 hours")
}
func TestR1340_UpdateFailed(t *testing.T) {
msg, leg, _ := heldStoppedOperatorText(settings.RestoreHold{Stack: "kimai", At: "2026-10-29T03:10:00Z", Reason: settings.HoldReasonUpdateFailed,
UndoState: "half", CopyTier: 1, CopyDate: "2026-10-29T02:00:00Z"})
mustHave(t, msg, "update at 2026-10-29T03:10:00Z did not come up healthy", "undo failed half-way", "tier 1, 2026-10-29T02:00:00Z", "--clear-restore-hold")
mustNotHave(t, msg, "database", optionCStory)
if leg != "update-hold" {
t.Errorf("leg %q", leg)
}
}
func TestR1340_RestoreFailedWithADatabase(t *testing.T) {
msg, leg, reason := heldStoppedOperatorText(settings.RestoreHold{Stack: "paperless", Reason: settings.HoldReasonRestoreFailed, RestoreKind: settings.RestoreKindOffsite,
DBReplay: true, ReplayError: "ERROR: relation exists", RollbackErr: "psql: connection refused"})
mustHave(t, msg, "off-site restore failed at the database replay", "rollback to the pre-restore database copy also failed", "ERROR: relation exists", "psql: connection refused")
mustNotHave(t, msg, optionCStory)
if leg != "restore-hold" || reason != "psql: connection refused" {
t.Errorf("leg %q reason %q", leg, reason)
}
}
// The measured case: Radicale has no database; the volume could not be removed and the put-back's stop failed.
func TestR1340_PutBackWithoutADatabase(t *testing.T) {
msg, leg, reason := heldStoppedOperatorText(settings.RestoreHold{Stack: "radicale", Reason: settings.HoldReasonRestoreMixed, RestoreKind: settings.RestoreKindOffsite,
MixedCause: settings.MixedCausePutBack, FailedStep: "stopping the app before the put-back failed, so nothing was put back: compose down: timeout",
ReplayError: "volume rm -f radicale_data: volume is in use", SafetyDump: "/mnt/hdd/felhom-data/backups/restore-undo/radicale/20261029T081800Z"})
mustHave(t, msg, `"radicale"`, "off-site restore failed, and putting the live data back FAILED", "stopping the app before the put-back failed",
"compose down: timeout", "kept at /mnt/hdd/felhom-data/backups/restore-undo/radicale/20261029T081800Z", "volume is in use")
mustNotHave(t, msg, "database", "rolled back", optionCStory)
if leg != "restore-hold-mixed" || reason != "put-back failed: stopping the app before the put-back failed, so nothing was put back" {
t.Errorf("leg %q reason %q", leg, reason)
}
}
func TestR1340_PutBackAfterADatabaseReplay(t *testing.T) {
msg, _, _ := heldStoppedOperatorText(settings.RestoreHold{Stack: "immich", Reason: settings.HoldReasonRestoreMixed, RestoreKind: settings.RestoreKindOffsite,
MixedCause: settings.MixedCausePutBack, DBReplay: true, FailedStep: "putting the live volumes back failed: tar xf failed"})
mustHave(t, msg, "failed at the database replay", "putting the live volumes back failed: tar xf failed", "There is no copy of the live volumes")
}
func TestR1340_DefinitionWrite(t *testing.T) {
msg, _, _ := heldStoppedOperatorText(settings.RestoreHold{Stack: "gokapi", Reason: settings.HoldReasonRestoreMixed, RestoreKind: settings.RestoreKindOffsite,
MixedCause: settings.MixedCauseDefinitionWrite, FailedStep: "writing the live app definition back failed: app.yaml write failed", ReplayError: "app.yaml write failed"})
mustHave(t, msg, "while writing the backup's app definition, before any data was touched", "writing the live app definition back failed", "data is the live data")
mustNotHave(t, msg, "database", optionCStory)
}
func TestR1340_LocalRestore(t *testing.T) {
msg, _, _ := heldStoppedOperatorText(settings.RestoreHold{Stack: "app", Reason: settings.HoldReasonRestoreMixed, RestoreKind: settings.RestoreKindLocal,
MixedCause: settings.MixedCausePutBack, FailedStep: "putting the live volumes back failed: tar xf failed", SafetyDump: "/srv/undo/app/1"})
mustHave(t, msg, "restore from its own backup failed", "putting the live volumes back failed")
mustNotHave(t, msg, "off-site", "database", optionCStory)
}
func TestR1340_PutBackPending(t *testing.T) {
msg, leg, _ := heldStoppedOperatorText(settings.RestoreHold{Stack: "immich", Reason: settings.HoldReasonPutBackPending, SafetyDump: "/mnt/hdd/undo/immich/1"})
mustHave(t, msg, "copy (/mnt/hdd/undo/immich/1) is on a drive that is not bound", "poured back and the app started when the drive is bound", "DROPS that put-back")
mustNotHave(t, msg, "database", optionCStory)
if leg != "putback-pending" {
t.Errorf("leg %q", leg)
}
}
func TestR1340_InterruptedPutBack(t *testing.T) {
msg, _, _ := heldStoppedOperatorText(settings.RestoreHold{Stack: "immich", Reason: settings.HoldReasonRestoreMixed, MixedCause: settings.MixedCauseInterruptedPutBack,
FailedStep: "putting the interrupted restore's copy back failed: compose down: timeout", SafetyDump: "/mnt/hdd/undo/immich/1"})
mustHave(t, msg, "cut by a stop could not be put back", "compose down: timeout", "kept at /mnt/hdd/undo/immich/1")
mustNotHave(t, msg, "database", "off-site", optionCStory)
}
// A mixed hold written before R-1340 names only what its record says.
func TestR1340_LegacyMixedHoldAssumesNothing(t *testing.T) {
msg, _, _ := heldStoppedOperatorText(settings.RestoreHold{Stack: "x", At: "2026-10-01T00:00:00Z", Reason: settings.HoldReasonRestoreMixed, ReplayError: "boom"})
mustHave(t, msg, "stopped half-way", "The hold record says: boom")
mustNotHave(t, msg, "database", optionCStory)
}
// The notification reads the hold the writer persisted; when that write failed, it rebuilds one from the errors.
func TestR1340_NotifyReadsTheHoldRecord(t *testing.T) {
rec := settings.RestoreHold{Stack: "radicale", Reason: settings.HoldReasonRestoreMixed, MixedCause: settings.MixedCausePutBack, FailedStep: "x"}
get := func(s string) (settings.RestoreHold, bool) { return rec, s == "radicale" }
if h := heldHoldFromNotify(get, "radicale", errors.New("e"), nil); h.MixedCause != settings.MixedCausePutBack {
t.Fatalf("the persisted record was not used: %+v", h)
}
h := heldHoldFromNotify(get, "other", errors.New("replay"), errors.New("rollback"))
if h.Reason != settings.HoldReasonRestoreFailed || h.RollbackErr != "rollback" || h.ReplayError != "replay" {
t.Fatalf("fallback hold %+v", h)
}
if h := heldHoldFromNotify(nil, "other", errors.New("replay"), nil); h.Reason != settings.HoldReasonRestoreMixed {
t.Fatalf("no rollback error = mixed, got %+v", h)
}
}
@@ -0,0 +1,50 @@
package main
import (
"context"
"errors"
"log"
"net/http"
"sync"
"time"
"gitea.dooplex.hu/admin/felhom-controller/internal/agentapi"
)
// hostOOMSource (R-528) is the 30-s dead-app scan's host-side OOM counter: one agent call per scan (5 s cap). An agent
// without the route (404) is not asked again for hostOOMRetryAfter, and said once; any other failure is a nil answer
// for this scan only (Docker's flag still works). Pinned by TestR528_HostOOMSource*.
const hostOOMRetryAfter = 10 * time.Minute
func hostOOMSource(ask func(context.Context) (agentapi.GuestOOMKillsState, error), logger *log.Logger, now func() time.Time) func() map[string]int64 {
var mu sync.Mutex
var until time.Time
said := false
return func() map[string]int64 {
mu.Lock()
defer mu.Unlock()
if now().Before(until) {
return nil
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
st, err := ask(ctx)
if err != nil {
var se *agentapi.StatusError
if errors.As(err, &se) && se.Code == http.StatusNotFound {
until = now().Add(hostOOMRetryAfter)
if !said {
logger.Printf("[INFO] [deadapp] the agent has no OOM counter route (R-528) — Docker's OOM flag only; asked again in %s", hostOOMRetryAfter)
said = true
}
return nil
}
logger.Printf("[WARN] [deadapp] the host OOM counter could not be read: %v — Docker's OOM flag only for this scan", err)
return nil
}
if !st.Available {
return nil
}
return st.Containers
}
}
+136 -72
View File
@@ -34,12 +34,14 @@ import (
"gitea.dooplex.hu/admin/felhom-controller/internal/backupwindow"
"gitea.dooplex.hu/admin/felhom-controller/internal/bootrecon"
"gitea.dooplex.hu/admin/felhom-controller/internal/bootstrap"
"gitea.dooplex.hu/admin/felhom-controller/internal/busymark"
"gitea.dooplex.hu/admin/felhom-controller/internal/channelhealth"
cf "gitea.dooplex.hu/admin/felhom-controller/internal/cloudflare"
"gitea.dooplex.hu/admin/felhom-controller/internal/config"
"gitea.dooplex.hu/admin/felhom-controller/internal/crashboot"
"gitea.dooplex.hu/admin/felhom-controller/internal/crypto"
"gitea.dooplex.hu/admin/felhom-controller/internal/fillwatch"
"gitea.dooplex.hu/admin/felhom-controller/internal/holdreport"
"gitea.dooplex.hu/admin/felhom-controller/internal/infra"
"gitea.dooplex.hu/admin/felhom-controller/internal/integrations"
"gitea.dooplex.hu/admin/felhom-controller/internal/mailrelay"
@@ -91,8 +93,9 @@ func main() {
abandonStatus := flag.Bool("abandon-status", false, "R-241: print the state of this box's off-site abandonment countdown (set-aside path, due date, days left) and exit. Read-only.")
abandonExtend := flag.Int("abandon-extend", 0, "R-241 (operator): extend a running abandonment countdown by N days from now, then exit. Refuses when no countdown is running.")
abandonStop := flag.Bool("abandon-stop", false, "R-241 (operator): stop a running abandonment countdown, then exit. The set-aside history is kept and nothing is deleted. Refuses when no countdown is running.")
listRestoreHolds := flag.Bool("restore-holds", false, "R-379 (operator): list apps this controller is deliberately holding stopped after a failed database restore whose rollback also failed, then exit. Read-only.")
clearRestoreHold := flag.String("clear-restore-hold", "", "R-379 (operator): clear the restore hold on APP so it can start again, then exit. Clearing does NOT repair the database — check the app's data first; the undo copies are in its unit's db-dumps dir.")
listRestoreHolds := flag.Bool("restore-holds", false, "R-379 (operator): list the apps this controller is holding stopped (every reason, with why), then exit. Read-only.")
clearRestoreHold := flag.String("clear-restore-hold", "", "R-379/D64 (operator): clear the hold on APP (any reason), then exit. Run it inside the guest: "+holdClearCommandHint+
". It asks the RUNNING controller, so no restart is needed; only when no controller runs does it edit settings.json. Clearing repairs nothing and starts nothing — check the app's data first.")
flag.Parse()
if *showVersion {
@@ -171,21 +174,23 @@ func main() {
// starts, exactly like the other CLI subcommands: each loads config + settings, acts, and exits.
// R-379 (operator): the way OUT of a hold. A CLI subcommand rather than an API route, matching
// --abandon-stop above: the controller's HTTP surface is authenticated as the CUSTOMER, and
// clearing a hold is a decision that should follow an operator looking at the database. Reaching
// clearing a hold is a decision that should follow an operator looking at the data. Reaching
// this needs `docker exec` into the guest, which is the operator gate this project already uses.
// R-1343: the clear goes to the RUNNING controller over its local socket (holdclear.go); the list reads
// settings.json, which the running controller saves at every hold change.
if *listRestoreHolds || *clearRestoreHold != "" {
cfg, err := config.LoadPermissive(*configPath)
if err != nil {
fmt.Fprintf(os.Stderr, "restore-hold: loading config: %v\n", err)
os.Exit(1)
}
if *listRestoreHolds {
lg := log.New(os.Stderr, "", 0)
sett, err := settings.Load(cfg.Paths.DataDir+"/settings.json", lg)
if err != nil {
fmt.Fprintf(os.Stderr, "restore-hold: loading settings: %v\n", err)
os.Exit(1)
}
if *listRestoreHolds {
holds := sett.ListRestoreHolds()
if len(holds) == 0 {
fmt.Println("no restore holds in force")
@@ -196,34 +201,9 @@ func main() {
}
os.Exit(0)
}
cleared, err := sett.ClearRestoreHold(*clearRestoreHold)
if err != nil {
fmt.Fprintf(os.Stderr, "restore-hold: clearing %s: %v\n", *clearRestoreHold, err)
os.Exit(1)
}
if !cleared {
// "there was nothing to clear" is not success — a silent 0 here would let an operator
// believe they had unblocked an app whose name they mistyped.
fmt.Fprintf(os.Stderr, "no restore hold in force for %q — nothing was changed\n", *clearRestoreHold)
os.Exit(2)
}
// THE RESTART IS NOT OPTIONAL, and saying so is the difference between a route that works
// and one an operator believes worked. This runs as a SECOND process: it clears the hold in
// settings.json, but the RUNNING controller holds its own in-memory Settings and keeps
// refusing until it reloads. Measured on demo-hp 2026-08-22 — the clear succeeded, the file
// was correct, and the customer's start button still refused until the controller restarted.
//
// There is also a lost-update window while both processes hold the file: if the running
// controller saves settings.json from its own copy before the restart, the clear is undone.
// Restarting promptly closes it. A route that clears through the running controller would
// remove both problems and is the right shape later; it needs an operator tier the
// controller's HTTP surface does not have today (it authenticates as the CUSTOMER, and a
// customer clearing their own hold is precisely what the hold exists to prevent).
fmt.Printf("restore hold cleared for %s in settings.json.\n", *clearRestoreHold)
fmt.Printf(" NOW RESTART THE CONTROLLER, or it will keep refusing to start the app:\n")
fmt.Printf(" systemctl restart felhom-controller-bootstrap.service\n")
fmt.Printf(" Check the app's data first — the undo copies are in its unit's db-dumps dir.\n")
os.Exit(0)
// R-1343: through the RUNNING controller (holdclear.go) — the old second-process edit of settings.json was
// written back by the running controller's next save. Only when no controller answers is the file edited here.
os.Exit(clearRestoreHoldCLI(cfg.Paths.DataDir, *clearRestoreHold, os.Stdout, os.Stderr))
}
if *abandonStatus || *abandonExtend > 0 || *abandonStop {
@@ -484,6 +464,19 @@ func main() {
return stackMgr.DriveLive(hdd)
})
appStopRecovery := appStopGuard.Recover()
// D64 = B / R-1343: the operator's hold clear — ONE door for the hub's clear_hold and the box command, run in THIS
// process so memory and settings.json agree (holdclear.go). The box command reaches it over a unix socket in the
// data dir (0600, nothing on TCP). A socket that cannot be bound is logged; the command then says plainly that no
// running controller answered.
holdDeps := holdClearDeps{clear: appStopGuard.ClearHoldByOperatorThen, forgetUpdateHeld: stackMgr.ForgetUpdateHeld,
keepStopped: stackMgr.RecordStopWantedIfDown, logger: logger}
if holdLn, herr := listenHoldCtl(holdCtlPath(cfg.Paths.DataDir), func(stack, who string) (string, error) {
return clearHoldNow(holdDeps, stack, who)
}, logger); herr != nil {
logger.Printf("[ERROR] [hold] the local hold-clear channel could not be opened: %v — `--clear-restore-hold` will edit settings.json and need a restart", herr)
} else {
defer holdLn.Close()
}
// R-1251: a put-back that waited for its drive (a hold from an earlier start) runs now if that drive is bound.
if started := appStopGuard.ResumeWaitingPutBacks(); len(started) > 0 {
logger.Printf("[WARN] [appstop] %d app(s) whose interrupted restore waited for its drive are put back and started: %v", len(started), started)
@@ -586,6 +579,11 @@ func main() {
logger.Println("[INFO] Healthchecks ping UUIDs configured but no longer used — monitoring is now handled by the Hub")
}
// D65 = A (2026-10-29): the busy file the host agent reads before an operator reboot of the guest (internal/busymark).
// Probes are added where each component is built; the writer starts once the last one exists (after the exporter).
busyMark := &busymark.Writer{Path: filepath.Join(cfg.Paths.DataDir, holdCtlDir, busymark.FileName), Logger: logger}
busyMark.AddProbe("an app update is running", stackMgr.AnyUpdating)
// --- Initialize backup manager (app-data only: DB dumps + Docker-volume tars) ---
var backupMgr *backup.Manager
// R-550: the restore the last stop interrupted, found when the record loads; raised once the notifier exists.
@@ -597,6 +595,9 @@ func main() {
}
if cfg.Backup.Enabled {
backupMgr = backup.NewManager(cfg, sett, logger)
busyMark.AddProbe("a backup, a restore or an off-site run is running", func() bool {
return backupMgr.IsRunning() || backupMgr.RestoreStatus().Running
})
// The stray-copy fix: a second-drive copy container a previous controller process lost (restart, self-update)
// still runs `rsync --delete`. Remove every one BEFORE the scheduler or the web server can start a backup or a
// restore; until that succeeds, restores are refused. Pinned by TestStrayCopy_ClearIsWiredBeforeTheScheduler.
@@ -681,6 +682,7 @@ func main() {
backupMgr.SetVersionCheck(stackMgr.PinNotRunning)
// R-671 (v0.272.0): a restore that lifts an update hold removes the undo copies that hold kept.
backupMgr.SetUndoCopyRemover(stackMgr.RemoveUndoCopies)
backupMgr.SetUpdateHeldForgetter(stackMgr.ForgetUpdateHeld) // R-1347
}
if n := stackMgr.ResumeInterruptedUpdates(ctx); n > 0 {
logger.Printf("[WARN] [update] resumed %d interrupted update(s)", n)
@@ -1034,6 +1036,9 @@ func main() {
logger.Printf("[WARN] [deadapp] agent client init failed (%v) — the boot grace cannot learn of a crash boot; 90 s", err)
} else {
crashProbe = crashboot.AgentProbe(ac.CrashGuard)
// R-528: the 30-s scan also asks the host for the kernel's per-container OOM counter (Docker's own flag can
// stay false inside an LXC guest). TestR528_HostOOMSourceIsWiredAtStartup.
stackMgr.SetHostOOMKills(hostOOMSource(ac.GuestOOMKills, logger, time.Now))
}
}
bootGrace := crashboot.New(startTime, crashProbe, logger)
@@ -1063,6 +1068,21 @@ func main() {
go func() { defer aubBusy.Unlock(); aubRunner.Tick(time.Now()) }() // a run can take minutes; never block the scheduler
return nil
})
// D53 (felhom.eu `08` §10): tell the hub which apps are held — app_held for a new or changed hold, app_hold_cleared
// when one is gone, every hold again once a day and after each start. One observer of the hold store, so every
// writer is covered. Pinned by internal/holdreport.
holdReporter := holdreport.New(sett, notifier.PushEvent, logger)
// R-1298: „installed" = the app's app.yaml file exists (a product removal deletes it; an unreadable one still counts,
// the R-1220 rule). An install's hold of an app without one is not reported.
holdReporter.SetInstalled(func(stack string) bool {
_, err := os.Stat(filepath.Join(cfg.Paths.StacksDir, stack, "app.yaml"))
return err == nil
})
sched.Every("hold-report", time.Minute, func(ctx context.Context) error {
holdReporter.Tick(time.Now())
return nil
})
oomLog := &oomLogGate{} // R-1341
sched.Every("deadapp-check", 30*time.Second, func(ctx context.Context) error {
if bootGrace.Within(time.Now()) {
return nil // still inside the startup settle window (90 s, or ~15 min after a crash boot)
@@ -1078,9 +1098,13 @@ func main() {
if oerr != nil {
logger.Printf("[WARN] [deadapp] OOM scan failed: %v", oerr)
} else {
// R-1341: the line once per NEW kill (oomlog.go); the event call stays per scan — the notifier's cooldown
// keeps it to one, as before.
for _, o := range oomLog.fresh(ooms) {
logger.Printf("[WARN] [deadapp] %s: container %s was OOM-killed (started %s; kills %d, limit %s, peak %s; seen by %s)", o.Stack, o.Container, o.StartedAt, o.Kills, o.MemLimit, o.Peak, o.Source)
}
for _, o := range ooms {
logger.Printf("[WARN] [deadapp] %s: container %s was OOM-killed (started %s; kills %d, limit %s, peak %s)", o.Stack, o.Container, o.StartedAt, o.Kills, o.MemLimit, o.Peak)
notifier.NotifyAppOOM(o.Stack, o.Container, o.StartedAt, o.Kills, o.MemLimit, o.Peak)
notifier.NotifyAppOOMFrom(o.Stack, o.Container, o.StartedAt, o.Kills, o.MemLimit, o.Peak, o.Source)
}
}
// v0.269.0 (`09` §3 decision 28, R-667): a crash loop or an OOM storm is STOPPED by the box.
@@ -1199,7 +1223,7 @@ func main() {
// R-314/R-279/R-177 (`09` §3 decision 185): the operator's closed list of actions, carried in the
// report reply and run in THIS process (opactions_wiring.go). The result rides the next report;
// a finished result fires an out-of-cycle report through the trigger once it exists.
opActions := report.NewOperatorActions(ctx, operatorActionHandlers(backupMgr, sched, func() {
opActions := report.NewOperatorActions(ctx, operatorActionHandlers(backupMgr, sched, holdDeps, func() {
if f, ok := opActionReportFire.Load().(func()); ok && f != nil {
f()
}
@@ -1385,6 +1409,13 @@ func main() {
return nil
})
// R-1256 H8: a restore copy no hold, no pending put-back and no running restore needs goes after 14 days. Every 6
// hours — a copy outliving its age by hours costs disk, never data. TestR1256_H8_TheSweepIsWiredAtStartup.
sched.Every("restore-copy-sweep", 6*time.Hour, func(ctx context.Context) error {
backupMgr.SweepUnusedRestoreCopies(time.Now())
return nil
})
// Tier 2: off-drive copy of each HDD app's recovery unit + userdata (auto-enabled, auto-target).
// Runs after the DB dump so it copies a fresh unit.
backupMgr.SetTier2Notifier(func(stackName, destLabel string, dur time.Duration, err error) {
@@ -1523,24 +1554,20 @@ func main() {
// DELIBERATELY NOT `backup_failed`: customer-enabled by default, Hungarian "A biztonsági
// mentés sikertelen!", and this is a deliberate hold rather than a backup failure. R-171 one
// path over.
backupMgr.SetRestoreHoldNotify(func(stack string, replayErr, rollbackErr error) {
d := notify.BackupRunFailuresDetails{RunKind: "offsite-reconstitute", Failed: 1, Attempted: 1}
if rollbackErr == nil { // R-893: the rollback WORKED, but files/volumes/version had already moved
d.Apps = append(d.Apps, notify.RunFailureDetail{App: stack, Leg: "restore-hold-mixed", Reason: "replay failed after files/volumes/version moved"})
msg := fmt.Sprintf("App %q is HELD STOPPED for support: its off-site database restore failed. The database was rolled back to the pre-restore copy and the live definition written back, "+
"but its files and named volumes are the snapshot's — a mixed state (R-893). The app will not start from any path until the hold is cleared. Replay error: %v", stack, replayErr)
// R-1340: the text is built from the HOLD RECORD the writer persisted just before this call (holdmail.go) — its
// reason, which restore, which branch, which put-back step failed, whether it was a database replay — never the
// option-C database story for every cause.
holdNotify := func(stack string, replayErr, rollbackErr error) {
h := heldHoldFromNotify(sett.GetRestoreHold, stack, replayErr, rollbackErr)
msg, leg, reason := heldStoppedOperatorText(h)
d := notify.BackupRunFailuresDetails{RunKind: heldRunKind(h), Failed: 1, Attempted: 1}
d.Apps = append(d.Apps, notify.RunFailureDetail{App: stack, Leg: leg, Reason: reason})
notifier.NotifyBackupRunFailures(msg, d)
return
}
reason := "rollback failed"
if rollbackErr != nil {
reason = rollbackErr.Error()
}
d.Apps = append(d.Apps, notify.RunFailureDetail{App: stack, Leg: "restore-hold", Reason: reason})
msg := fmt.Sprintf("App %q is HELD STOPPED: its off-site database restore failed AND the rollback to the customer's own pre-restore copy also failed. "+
"The app will not start from any path until the hold is cleared. Replay error: %v. Rollback error: %v", stack, replayErr, rollbackErr)
notifier.NotifyBackupRunFailures(msg, d)
})
backupMgr.SetRestoreHoldNotify(holdNotify)
// R-1348: the hold an interrupted put-back wrote at START-UP (Recover, before any notifier existed) or on a resume.
// The same sentence (R-1340, MixedCauseInterruptedPutBack), the same mail.
appStopGuard.SetHeldNotify(func(stack string) { holdNotify(stack, nil, nil) })
// R-893 option A (D20 = A): a failed off-site restore that was PUT BACK — the live volumes and definition poured
// back and the app started. The same operator-tier event as the hold above (no new event type), its own leg.
// D47 follow-up: a unit of an earlier install was set aside whole — the operator sees it (its own leg).
@@ -1581,6 +1608,13 @@ func main() {
backupMgr.SetOffboxEnlargeBlockedNotifier(func(stack string, estBytes int64, usedGB, quotaGB int) {
notifier.NotifyOffboxEnlargeBlocked(stack, appbackup.HumanizeBytes(estBytes), usedGB, quotaGB) // R-585
})
// D72 / D84 (`07` §8.2f): the off-site copies of a removed app. (1) „Living": installed right now, or one of
// the box's own protected stacks — such an app's end record is never due, and it cannot get one. Without
// this seam nothing is ever due (backup/offbox_ended.go). (2) The household's one mail per press.
backupMgr.SetOffsiteEndLiving(stackMgr.IsLivingApp)
backupMgr.SetOffsiteEndNotify(func(rec settings.OffsiteEnd) {
notifier.NotifyOffsiteEndScheduled(rec.App, rec.RemovedAt, rec.EndsAt, rec.Ends().Local())
})
// v0.142.0 offsite-repo continuity: push a hub event on the orphaned/reset transitions (once per
// transition — the Manager guards nightly re-fire). Operator-visible on the customer page.
backupMgr.SetOffboxOrphanEvent(func(eventType, renamedTo string) {
@@ -1645,6 +1679,7 @@ func main() {
if quiesceLoop != nil {
quiesceLoop.SetCatchUpFn(catchUp.Running)
}
busyMark.AddProbe("the night backup catch-up is running", catchUp.Running)
catchUp.Evaluate(ctx, "controller start")
resumeTick := time.NewTicker(time.Minute)
go nightchain.ResumeWatch(ctx, resumeTick.C,
@@ -2034,6 +2069,10 @@ func main() {
prevCtl = st.RecordedPrevious(Version)
}
_, _ = stackMgr.RetainControllerImages(stacks.ControllerImageRecord{Repo: cfg.SelfUpdate.Image, Running: Version, Previous: prevCtl})
// decision 285 (2026-11-09): the pinned infrastructure images (traefik, cloudflared, FileBrowser, Samba) — keep
// the pin and the one before it. A pin moves only with a controller release, so once per start is enough; the
// infra stacks were reconciled long before these 3 minutes. Retried every 2 minutes while an app pulls (R-863).
stackMgr.RunInfraImageRetention(ctx, infra.Images(), 2*time.Minute, 30)
}()
// --- Initialize API router ---
@@ -2103,6 +2142,8 @@ func main() {
// this the export path would be the uncovered sibling of two covered ones, which is how a reader
// concludes the whole class is handled (§2.2).
appExporter.SetStopGuard(exportStopGuard{g: appStopGuard})
busyMark.AddProbe("an app export or import is running", appExporter.IsRunning)
go busyMark.Run(ctx)
// R-1279 (D48 for the import): the import downloads first, with the restores' helper and sentences.
if backupMgr != nil {
appExporter.SetImagePreparer(backupMgr.PrepareRestoreImages)
@@ -2111,6 +2152,7 @@ func main() {
// --- Initialize web server ---
webServer := web.NewServer(cfg, stackMgr, cpuCollector, backupMgr, sched, sett, alertMgr, notifier, updater, logger, Version)
go webServer.WatchOperatorReboot(ctx) // D65: „Felhom support restarted your box at …" after an operator reboot
// v0.316.0: which BUILD this is, not just which version it calls itself. Every shell's stylesheet
// URL is derived from it, so two builds of one version can never share a cache entry. Init-only,
// before the HTTP server starts.
@@ -2562,22 +2604,7 @@ type driveStartGate struct {
// stop read as „held after a failed restore whose rollback also failed" for 11 days on demo-hp, so the operator could
// not tell a crash loop from a broken restore). Pinned by TestR1286_EveryHoldReasonSaysWhatItIs.
func holdWhy(h settings.RestoreHold) string {
switch h.Reason {
case settings.HoldReasonUpdateFailed:
return "held after a failed update (" + h.At + ") — restore it from its backup to start it"
case settings.HoldReasonUnhealthyStop:
kind := h.UnhealthyKind
if kind == "" {
kind = "unhealthy"
}
return "stopped by the box for a " + strings.ReplaceAll(kind, "_", " ") + " (" + h.At + ") — the household's Start gives it one more try"
case settings.HoldReasonRestoreMixed:
return "held after an off-site restore failed its database replay (" + h.At + ") — clear the hold to start it"
case settings.HoldReasonPutBackPending:
return "held until the pre-restore copy is poured back (" + h.At + ") — the put-back starts it"
default:
return "held after a failed restore whose rollback also failed (" + h.At + ") — clear the hold to start it"
}
return h.Why() // one sentence per reason, shared with the hub's „Held apps" list (D53)
}
func (g driveStartGate) MayStart(stackName string) (bool, string) {
@@ -2682,11 +2709,18 @@ const fillWatchInterval = 10 * time.Minute
// silent exhaustion R-158 measured;
// - the registered DRIVES hold the customer's own data.
//
// De-duplicated by path: on a box where a drive is not a separate mount these collapse, and warning
// twice about one filesystem is exactly the noise the per-filesystem rule exists to prevent. A
// DECOMMISSIONED drive is dropped — it is deliberately out of service, and its fill is not news. A
// DISCONNECTED one is kept in the list but will read as unreadable and be skipped by §8.4, which is
// the correct outcome: its absence already has its own alert.
// ONE WARNING PER FILESYSTEM (R-1371). The list is de-duplicated by path AND by filesystem
// (fillTargetsBy). By path alone it was not enough: since the guest's two data volumes became one, "/"
// (the controller's overlay, which lies on the Docker data volume) and `/mnt/sys_drive` are ONE
// filesystem on every box measured 2026-11-10, so one fill sent two warnings with two names. The
// identity is system.FilesystemKey — NOT the plain device number, which an overlay hides (fskey.go).
// The FIRST target of a filesystem stays, in the order below: the app area, the system area, then the
// drives. A path whose filesystem cannot be identified is kept (one warning too many, never one too
// few). Pinned by TestR1371_OneFillSendsOneWarning.
//
// A DECOMMISSIONED drive is dropped — it is deliberately out of service, and its fill is not news. A
// DISCONNECTED one has no readable filesystem, so it is kept in the list, reads as unreadable and is
// skipped by §8.4, which is the correct outcome: its absence already has its own alert.
// fillEventPusher is the one notifier method fillEventPush needs — an interface so the R-521 F7 test
// can record what is pushed without a hub.
type fillEventPusher interface {
@@ -2712,13 +2746,26 @@ func fillEventPush(n fillEventPusher) func(fillwatch.Event) {
}
func fillTargets(cfg *config.Config, sett *settings.Settings) []fillwatch.Target {
return fillTargetsBy(cfg, sett, system.FilesystemKey)
}
// fillTargetsBy is fillTargets with the filesystem identity injected (the tests' seam). fsKey returns
// ok=false for a path whose filesystem it cannot identify.
func fillTargetsBy(cfg *config.Config, sett *settings.Settings, fsKey func(path string) (uint64, bool)) []fillwatch.Target {
seen := make(map[string]bool)
seenFS := make(map[uint64]bool)
var out []fillwatch.Target
add := func(path, label, labelKey string) {
if path == "" || seen[path] {
return
}
seen[path] = true
if key, ok := fsKey(path); ok {
if seenFS[key] {
return // this filesystem is watched already, under the target that came first
}
seenFS[key] = true
}
out = append(out, fillwatch.Target{Path: path, Label: label, LabelKey: labelKey})
}
@@ -3181,9 +3228,23 @@ func (a *stackAdapter) ListDeployedStacks() []backup.StackSummary {
}
func (a *stackAdapter) StopStack(name string) error {
if err := faultPoint("stop-" + name); err != nil { // D63: a no-op outside a -tags faultinject test build
return err
}
return a.mgr.StopStack(name)
}
// StackRemoved answers backup's optional StackRemovalReporter (R-1342): the app is known and no longer installed — a
// stable-start watch then ends quietly instead of alarming „did not start". An app this box does not know at all is
// not „removed" (no answer → the watch goes on as before).
func (a *stackAdapter) StackRemoved(name string) bool {
s, ok := a.mgr.GetStack(name)
return ok && !s.Deployed
}
// The watch reaches StackRemoved through a type assertion; this line makes the adapter's answer a compile-time fact.
var _ backup.StackRemovalReporter = (*stackAdapter)(nil)
// IsDeploying answers backup's optional deployingReporter (R-634): the volume leg asks it again
// immediately before it stops an app, because its list is taken once at the start of the run.
func (a *stackAdapter) IsDeploying(name string) bool {
@@ -3425,6 +3486,9 @@ func (a *stackAdapter) RecreateStackDefinitionFromUnit(name, composeSrcDir strin
return fmt.Errorf("restoring %s from unit: %w", fname, err)
}
}
if err := faultPoint("defwrite-after-compose"); err != nil { // D63: a no-op outside a -tags faultinject test build
return err
}
// R-1057 (v0.314.0): the gate as the backup recorded it — the unit's app.yaml, read BEFORE the write.
gate := stacks.ReadGateAtBackup(filepath.Join(composeSrcDir, "app.yaml"))
if err := a.mgr.PersistUnitRedeployConfigGate(name, fullEnv, gate); err != nil {
+43
View File
@@ -0,0 +1,43 @@
package main
import (
"strconv"
"gitea.dooplex.hu/admin/felhom-controller/internal/stacks"
)
// ── R-1341: the OOM line is logged once per NEW kill ──────────────────────────────────────────────────────────────
//
// ScanOOMKilled reports a container for as long as it lives after a kill (Docker's OOMKilled flag is sticky, and the
// kernel's kill counter never goes down), so the 30-s dead-app scan logged „[WARN] [deadapp] … was OOM-killed" about
// 2 880 times a day per container — measured 2026-10-29 on Tester 1 — while the notifier's cooldown kept the event to
// one. The line now goes out when the kill is NEW: the key is (container, its start time, the kill count), and a line
// is logged only when a container's key changes — a second scan of the same kill logs nothing, a new kill (the count
// went up) or a restarted container (a new start time) logs again. The event call is unchanged (every scan, the
// notifier decides). Pinned by TestR1341_*.
// oomLogGate remembers the last logged key per container. Not safe for concurrent use: the dead-app job runs serially.
type oomLogGate struct {
last map[string]string
}
func oomLogKey(o stacks.OOMContainer) string {
return o.StartedAt + "|" + strconv.FormatInt(o.Kills, 10)
}
// fresh returns the containers whose kill is new since the last scan, and remembers this scan's keys. A container
// absent from this scan is forgotten (it was removed or restarted clean), which also bounds the memory.
func (g *oomLogGate) fresh(ooms []stacks.OOMContainer) []stacks.OOMContainer {
next := make(map[string]string, len(ooms))
var out []stacks.OOMContainer
for _, o := range ooms {
k := oomLogKey(o)
next[o.Container] = k
if prev, ok := g.last[o.Container]; ok && prev == k {
continue
}
out = append(out, o)
}
g.last = next
return out
}
+64
View File
@@ -0,0 +1,64 @@
package main
import (
"testing"
"gitea.dooplex.hu/admin/felhom-controller/internal/stacks"
)
// R-1341: the „[WARN] [deadapp] … was OOM-killed" line goes out once per NEW kill, not every 30-s scan.
//
// RED-PROOF (2026-10-29): with oomLogGate.fresh returning its input unchanged (the pre-R-1341 loop logged every
// container every scan), TestR1341_ASecondScanOfTheSameKillLogsNothing fails on „logged 1 line(s), want 0".
func oom(container, started string, kills int64) stacks.OOMContainer {
return stacks.OOMContainer{Stack: "gokapi", Container: container, StartedAt: started, Kills: kills}
}
func TestR1341_ASecondScanOfTheSameKillLogsNothing(t *testing.T) {
g := &oomLogGate{}
scan := []stacks.OOMContainer{oom("gokapi", "2026-10-29T09:02:00Z", 1)}
if got := g.fresh(scan); len(got) != 1 {
t.Fatalf("the first sighting must log, logged %d line(s)", len(got))
}
for i := 0; i < 5; i++ {
if got := g.fresh(scan); len(got) != 0 {
t.Fatalf("scan %d of the same kill logged %d line(s), want 0", i+2, len(got))
}
}
}
func TestR1341_ANewKillLogsAgain(t *testing.T) {
g := &oomLogGate{}
g.fresh([]stacks.OOMContainer{oom("gokapi", "2026-10-29T09:02:00Z", 1)})
got := g.fresh([]stacks.OOMContainer{oom("gokapi", "2026-10-29T09:02:00Z", 2)})
if len(got) != 1 || got[0].Kills != 2 {
t.Fatalf("a new kill (count 1→2) must log once, got %+v", got)
}
if got := g.fresh([]stacks.OOMContainer{oom("gokapi", "2026-10-29T09:02:00Z", 2)}); len(got) != 0 {
t.Fatalf("the same new kill must not log twice, got %+v", got)
}
}
func TestR1341_ARestartedContainerLogsAgain(t *testing.T) {
g := &oomLogGate{}
g.fresh([]stacks.OOMContainer{oom("gokapi", "2026-10-29T09:02:00Z", 1)})
if got := g.fresh([]stacks.OOMContainer{oom("gokapi", "2026-10-29T09:30:00Z", 1)}); len(got) != 1 {
t.Fatalf("a restarted container's kill must log, got %+v", got)
}
}
// Two containers are judged apart; one that leaves the scan is forgotten, so its return logs again.
func TestR1341_ContainersAreJudgedApart(t *testing.T) {
g := &oomLogGate{}
a, b := oom("a", "t1", 1), oom("b", "t1", 1)
if got := g.fresh([]stacks.OOMContainer{a, b}); len(got) != 2 {
t.Fatalf("first scan: %+v", got)
}
if got := g.fresh([]stacks.OOMContainer{a}); len(got) != 0 {
t.Fatalf("a seen again must not log: %+v", got)
}
if got := g.fresh([]stacks.OOMContainer{a, b}); len(got) != 1 || got[0].Container != "b" {
t.Fatalf("b came back after leaving the scan: %+v", got)
}
}
+10 -2
View File
@@ -17,18 +17,26 @@ import (
// executor is built earlier than the trigger, so it reads it through this holder.
var opActionReportFire atomic.Value
// operatorActionHandlers wires the four operator actions (R-314/R-279/R-177, `09` §3 decision 185)
// operatorActionHandlers wires the five operator actions (R-314/R-279/R-177, `09` §3 decision 185)
// to the running process. ONE wiring site, called from main and from the wiring test, so the test
// exercises the doors production uses (the seam-built-but-never-wired trap).
//
// offsite_backup_now makes the SAME four checks as the household's „back up now"
// (offboxRunHandler) and then runs the same call, so an operator press can never do what the
// household's own press cannot.
func operatorActionHandlers(backupMgr *backup.Manager, sched *scheduler.Scheduler, resultReady func(), logger *log.Logger) report.OperatorActionHandlers {
//
// clear_hold (D64 = B) goes through clearHoldNow with hold — the same door the box command's socket uses
// (holdclear.go), so the hub's button and the box command can never differ. hold.clear nil = not available.
func operatorActionHandlers(backupMgr *backup.Manager, sched *scheduler.Scheduler, hold holdClearDeps, resultReady func(), logger *log.Logger) report.OperatorActionHandlers {
h := report.OperatorActionHandlers{ResultReady: resultReady}
if sched != nil {
h.RunJob = sched.RunNow
}
if hold.clear != nil {
h.ClearHold = func(stack string, actionID int64) (string, error) {
return clearHoldNow(hold, stack, fmt.Sprintf("the operator via the hub, action #%d", actionID))
}
}
if backupMgr == nil {
return h
}
@@ -57,7 +57,7 @@ func TestD1_AbandonStopActsOnTheRunningManagerAndDisk(t *testing.T) {
t.Fatal("fixture: a countdown must be running")
}
o := report.NewOperatorActions(context.Background(), operatorActionHandlers(mgr, nil, nil, logger), logger)
o := report.NewOperatorActions(context.Background(), operatorActionHandlers(mgr, nil, holdClearDeps{}, nil, logger), logger)
o.Reconcile([]report.OperatorAction{{ID: 1, Action: report.OpAbandonStop}})
if mgr.AbandonStatus().Active {
@@ -97,7 +97,7 @@ func TestD1_OffsiteBackupNowRefusesWithoutATarget(t *testing.T) {
t.Fatal("no restic may run")
return nil, nil
})
o := report.NewOperatorActions(context.Background(), operatorActionHandlers(mgr, nil, nil, logger), logger)
o := report.NewOperatorActions(context.Background(), operatorActionHandlers(mgr, nil, holdClearDeps{}, nil, logger), logger)
o.Reconcile([]report.OperatorAction{{ID: 9, Action: report.OpOffsiteBackupNow}})
if r := o.Results(); len(r) != 1 || r[0].Outcome != report.OutcomeRefused {
t.Fatalf("result = %+v", r)
@@ -115,7 +115,7 @@ func TestD1_RunJobUsesTheScheduler(t *testing.T) {
defer cancel()
sched.Start(ctx)
defer sched.Stop()
o := report.NewOperatorActions(ctx, operatorActionHandlers(nil, sched, nil, logger), logger)
o := report.NewOperatorActions(ctx, operatorActionHandlers(nil, sched, holdClearDeps{}, nil, logger), logger)
o.Reconcile([]report.OperatorAction{{ID: 1, Action: report.OpRunJob, Arg: "fill-watch"}, {ID: 2, Action: report.OpRunJob, Arg: "offsite-proof"}})
select {
case od := <-ran:
@@ -0,0 +1,13 @@
package main
import "testing"
// TestR1256_H8_TheSweepIsWiredAtStartup — R-1256 H8: an unused restore copy goes only through
// SweepUnusedRestoreCopies, so main.go must CALL it (the seam-built-but-never-wired class).
// RED-PROOF: delete the `restore-copy-sweep` job — this fails.
func TestR1256_H8_TheSweepIsWiredAtStartup(t *testing.T) {
lines, _, _ := slice4CallLines(t)
if len(lines["SweepUnusedRestoreCopies"]) == 0 {
t.Fatal("SweepUnusedRestoreCopies is never called — an unused restore copy would stay on the drive for ever")
}
}
@@ -20,7 +20,9 @@ func TestR1286_EveryHoldReasonSaysWhatItIs(t *testing.T) {
}{
{settings.RestoreHold{Stack: "kimai", At: "2026-10-14T09:06:31Z", Reason: settings.HoldReasonUnhealthyStop, UnhealthyKind: "crash_loop"}, "stopped by the box for a crash loop"},
{settings.RestoreHold{Stack: "a", At: "t", Reason: settings.HoldReasonUpdateFailed}, "failed update"},
{settings.RestoreHold{Stack: "b", At: "t", Reason: settings.HoldReasonRestoreMixed}, "off-site restore failed its database replay"},
// R-1340 (2026-10-29): a record with no cause fields no longer claims „off-site … database replay" — that was the
// false story (a local restore of an app with no database read the same); it says what is known.
{settings.RestoreHold{Stack: "b", At: "t", Reason: settings.HoldReasonRestoreMixed}, "restore stopped half-way"},
{settings.RestoreHold{Stack: "c", At: "t", Reason: settings.HoldReasonPutBackPending}, "pre-restore copy is poured back"},
{settings.RestoreHold{Stack: "d", At: "t"}, "failed restore whose rollback also failed"},
} {
@@ -0,0 +1,41 @@
package main
import (
"testing"
"gitea.dooplex.hu/admin/felhom-controller/internal/settings"
)
// R-1347 and R-1348: each seam is CALLED from main.go (an AST walk) — a seam built and never wired is the project's
// oldest shape.
func TestR1347_UpdateHeldForgetterIsWiredAtStartup(t *testing.T) {
lines, _, _ := slice4CallLines(t)
if len(lines["SetUpdateHeldForgetter"]) == 0 {
t.Fatal("main.go never calls SetUpdateHeldForgetter — a restored app would stay unwatched until the controller restarts")
}
}
func TestR1348_HeldNotifyIsWiredAtStartup(t *testing.T) {
lines, _, _ := slice4CallLines(t)
if len(lines["SetHeldNotify"]) == 0 {
t.Fatal("main.go never calls SetHeldNotify — a failed put-back at start-up would mail nobody")
}
}
// The mail's run name for an interrupted put-back. RED (2026-11-03, live on 9202): the sink showed run_kind offsite-reconstitute for a
// local restore.
func TestR1348_HeldRunKind(t *testing.T) {
for _, c := range []struct {
h settings.RestoreHold
want string
}{
{settings.RestoreHold{Reason: settings.HoldReasonRestoreMixed, MixedCause: settings.MixedCauseInterruptedPutBack}, "restore"},
{settings.RestoreHold{RestoreKind: settings.RestoreKindLocal}, "restore"},
{settings.RestoreHold{RestoreKind: settings.RestoreKindOffsite}, "offsite-reconstitute"},
{settings.RestoreHold{Reason: settings.HoldReasonRestoreMixed}, "offsite-reconstitute"},
} {
if got := heldRunKind(c.h); got != c.want {
t.Errorf("%+v: run kind %q, want %q", c.h, got, c.want)
}
}
}
+80
View File
@@ -0,0 +1,80 @@
package main
import (
"os"
"strings"
"testing"
"time"
"gitea.dooplex.hu/admin/felhom-controller/internal/report"
"gitea.dooplex.hu/admin/felhom-controller/internal/settings"
"gitea.dooplex.hu/admin/felhom-controller/internal/stacks"
)
// R-1350 (measured 2026-10-29 14:57 on Tester 1): the operator cleared gokapi's crash-loop hold from the hub, the app
// stayed stopped (the clear starts nothing), and 30 s later the dead-app scan sent „Telepített alkalmazás nem fut:
// Gokapi" — the hold had kept the app out of the scan, and the household's recorded wish was still „running".
// The fix: the clear records that the stop is WANTED (desired state „stopped") for an app that is not up, BEFORE the
// hold is lifted; a later Start records „running" and ends it.
// The consequence, through the scan's own derivation: a stopped app whose wish is „running" is DOWN (the alarm); the
// same app with the wish „stopped" is not.
func TestR1350_AStopWantedIsNotDown(t *testing.T) {
st := func(desired string) []stacks.Stack {
return []stacks.Stack{{Name: "gokapi", Deployed: true, State: stacks.StateStopped, AppConfig: &stacks.AppConfig{DesiredState: desired}}}
}
if _, states := classifyRunStates(st(stacks.DesiredStateRunning), nil, nil, time.Now()); len(states) != 1 || !states[0].Down {
t.Fatalf("fixture: a stopped app wished running must be down: %+v", states)
}
if _, states := classifyRunStates(st(stacks.DesiredStateStopped), nil, nil, time.Now()); len(states) != 1 || states[0].Down {
t.Fatalf("a stopped app wished stopped is down — the alarm fires: %+v", states)
}
}
// The clear records the wish BEFORE the hold is lifted (a dead-app scan between the two would read „no hold, wished
// running" and mail), and only for an app that IS held. RED-PROOF: drop the keepStopped call from the clear → FAILS
// („not recorded"); call it after the lift → FAILS („after the hold was lifted").
func TestR1350_TheClearRecordsTheStopIsWanted(t *testing.T) {
r := newD64Rig(t)
r.hold(t, settings.RestoreHold{Stack: "gokapi", Reason: settings.HoldReasonUnhealthyStop, UnhealthyKind: "crash_loop", Trip: 1})
var recorded []string
var heldWhenRecorded bool
r.holdDeps.keepStopped = func(stack string) (bool, error) {
recorded = append(recorded, stack)
_, heldWhenRecorded = r.sett.GetRestoreHold(stack)
return true, nil
}
o := r.actions()
o.Reconcile([]report.OperatorAction{{ID: 21, Action: report.OpClearHold, Arg: "gokapi"}})
if res := onlyResult(t, o, 21); res.Outcome != report.OutcomeDone {
t.Fatalf("result %+v", res)
}
if len(recorded) != 1 || recorded[0] != "gokapi" {
t.Fatalf("the stop was not recorded as wanted: %v", recorded)
}
if !heldWhenRecorded {
t.Fatal("the wish was recorded after the hold was lifted — a scan in between mails app_start_failed")
}
if lg := r.logBuf.String(); !strings.Contains(lg, "gokapi: the stop is recorded as wanted") {
t.Fatalf("the box's log must say it:\n%s", lg)
}
// a refusal (no hold) records nothing — a down app with no hold is a real fault the alarm must keep
o.Reconcile([]report.OperatorAction{{ID: 22, Action: report.OpClearHold, Arg: "kimai"}})
if res := onlyResult(t, o, 22); res.Outcome != report.OutcomeRefused {
t.Fatalf("result %+v", res)
}
if len(recorded) != 1 {
t.Fatalf("a refused clear recorded a wish: %v", recorded)
}
}
// The running controller's clear is wired with the record. RED-PROOF: drop keepStopped from main.go's holdDeps → FAILS.
func TestR1350_MainWiresTheRecord(t *testing.T) {
raw, err := os.ReadFile("main.go")
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(raw), "keepStopped: stackMgr.RecordStopWantedIfDown") || !strings.Contains(string(raw), "clear: appStopGuard.ClearHoldByOperatorThen") {
t.Fatal("main.go's hold clear does not record the wanted stop (R-1350)")
}
}
@@ -0,0 +1,183 @@
package main
import (
"io"
"log"
"os"
"path/filepath"
"testing"
"gitea.dooplex.hu/admin/felhom-controller/internal/config"
"gitea.dooplex.hu/admin/felhom-controller/internal/fillwatch"
"gitea.dooplex.hu/admin/felhom-controller/internal/settings"
"gitea.dooplex.hu/admin/felhom-controller/internal/system"
)
// R-1371 — one warning per filesystem.
//
// The box as measured 2026-11-10 (demo-hp, the N100, Tester 1): "/" and `/mnt/sys_drive` are ONE filesystem, seen
// through two paths. The filesystem identity here is the one system.FilesystemKey gives on those boxes (its own rule
// is pinned by TestFilesystemKey_AnOverlayRootIsTheDockerDataRoot): equal for the two paths, another for a drive.
//
// RED-PROOF (observed 2026-11-10, then restored): with the filesystem check removed from fillTargetsBy this test fails
// with "one filling filesystem sent 2 warnings".
func boxKeys(extra map[string]uint64) func(string) (uint64, bool) {
keys := map[string]uint64{system.DockerVolumePath: 64519, "/mnt/sys_drive": 64519}
for p, k := range extra {
keys[p] = k
}
return func(p string) (uint64, bool) { k, ok := keys[p]; return k, ok }
}
func settingsWithDrives(t *testing.T, paths ...settings.StoragePath) *settings.Settings {
t.Helper()
sett, err := settings.Load(filepath.Join(t.TempDir(), "settings.json"), log.New(io.Discard, "", 0))
if err != nil {
t.Fatal(err)
}
for _, sp := range paths {
if err := sett.AddStoragePath(sp); err != nil {
t.Fatal(err)
}
}
return sett
}
// The consequence: the one filesystem fills, and the household gets ONE warning, then ONE critical — through the real
// watcher and the real push closure.
func TestR1371_OneFillSendsOneWarning(t *testing.T) {
cfg := &config.Config{}
cfg.Paths.SystemDataPath = "/mnt/sys_drive"
sett := settingsWithDrives(t, settings.StoragePath{Path: "/mnt/felhom-drives/usb", Label: "Családi lemez", Schedulable: true})
key := boxKeys(map[string]uint64{"/mnt/felhom-drives/usb": 2049})
pct := 50.0
usage := func(p string) *fillwatch.Usage {
if p == "/mnt/felhom-drives/usb" {
return &fillwatch.Usage{UsedPercent: 20, AvailGB: 700, UsedGB: 200, TotalGB: 900}
}
// "/" and /mnt/sys_drive: the same filesystem, so the same numbers.
return &fillwatch.Usage{UsedPercent: pct, AvailGB: 68.7 * (100 - pct) / 100, UsedGB: 68.7 * pct / 100, TotalGB: 68.7}
}
w := fillwatch.New(filepath.Join(t.TempDir(), "fill.json"), log.New(io.Discard, "", 0),
func() []fillwatch.Target { return fillTargetsBy(cfg, sett, key) }, usage)
rec := &fakeFillPusher{}
w.SetNotify(fillEventPush(rec))
check := func() {
t.Helper()
for i := 0; i < 2; i++ {
if err := w.Check(); err != nil {
t.Fatal(err)
}
}
}
check()
if len(rec.got) != 0 {
t.Fatalf("a half-full filesystem sent %d events", len(rec.got))
}
pct = 90
check()
if len(rec.got) != 1 {
t.Fatalf("one filling filesystem sent %d warnings (%+v), want exactly 1", len(rec.got), rec.got)
}
if rec.got[0].eventType != "disk_warning" {
t.Fatalf("event = %s, want disk_warning", rec.got[0].eventType)
}
if d, _ := rec.got[0].details.(map[string]any); d == nil || d["path"] != system.DockerVolumePath {
t.Fatalf("the warning is for %v, want the first target of the filesystem (%q)", rec.got[0].details, system.DockerVolumePath)
}
pct = 97
check()
if len(rec.got) != 2 || rec.got[1].eventType != "disk_critical" {
t.Fatalf("after 97%% the events are %+v, want one warning then one critical", rec.got)
}
}
// What stays and what goes, target by target.
func TestR1371_TargetsByFilesystem(t *testing.T) {
cfg := &config.Config{}
cfg.Paths.SystemDataPath = "/mnt/sys_drive"
paths := func(ts []fillwatch.Target) []string {
var out []string
for _, tg := range ts {
out = append(out, tg.Path)
}
return out
}
eq := func(got, want []string) bool {
if len(got) != len(want) {
return false
}
for i := range got {
if got[i] != want[i] {
return false
}
}
return true
}
// One volume, no drive: one target, and it is the app area (the first one added).
got := fillTargetsBy(cfg, nil, boxKeys(nil))
if len(got) != 1 || got[0].Path != system.DockerVolumePath || got[0].LabelKey != "event.fill.label_apps" {
t.Fatalf("one-volume box: targets = %+v, want only the app area", got)
}
// The OLD layout (two volumes): both areas stay.
two := func(p string) (uint64, bool) {
return map[string]uint64{system.DockerVolumePath: 1, "/mnt/sys_drive": 2}[p], p == system.DockerVolumePath || p == "/mnt/sys_drive"
}
if got := paths(fillTargetsBy(cfg, nil, two)); !eq(got, []string{"/", "/mnt/sys_drive"}) {
t.Fatalf("two-volume box: targets = %v, want both areas", got)
}
sett := settingsWithDrives(t,
settings.StoragePath{Path: "/mnt/felhom-drives/a", Label: "A", Schedulable: true},
settings.StoragePath{Path: "/mnt/felhom-drives/b", Label: "B", Schedulable: true}, // a second folder of drive A's filesystem
settings.StoragePath{Path: "/mnt/felhom-drives/gone", Label: "Gone", Schedulable: true}, // unplugged: no identity
settings.StoragePath{Path: "/mnt/felhom-drives/gone2", Label: "Gone2", Schedulable: true}, // unplugged too
settings.StoragePath{Path: "/mnt/sys_drive/internal", Label: "Belső", Schedulable: true}, // a "drive" that is the system volume
)
key := boxKeys(map[string]uint64{"/mnt/felhom-drives/a": 2049, "/mnt/felhom-drives/b": 2049, "/mnt/sys_drive/internal": 64519})
want := []string{"/", "/mnt/felhom-drives/a", "/mnt/felhom-drives/gone", "/mnt/felhom-drives/gone2"}
if got := paths(fillTargetsBy(cfg, sett, key)); !eq(got, want) {
t.Fatalf("targets = %v, want %v — one per filesystem, and every path with no identity kept", got, want)
}
// No identity at all (not Linux, or nothing readable): the list is the old one, by path.
none := func(string) (uint64, bool) { return 0, false }
if got := paths(fillTargetsBy(cfg, nil, none)); !eq(got, []string{"/", "/mnt/sys_drive"}) {
t.Fatalf("no identity: targets = %v, want both paths (one warning too many, never one too few)", got)
}
}
// The wiring: the production list uses the real identity. On this machine "/mnt/sys_drive" does not exist, so it has
// no identity and stays; a folder and its sub-folder are one filesystem and collapse.
func TestR1371_ProductionListUsesTheRealIdentity(t *testing.T) {
dir := t.TempDir()
if _, ok := system.FilesystemKey(dir); !ok {
t.Skip("no filesystem identity on this machine (not Linux)")
}
cfg := &config.Config{}
cfg.Paths.SystemDataPath = dir
sett := settingsWithDrives(t, settings.StoragePath{Path: filepath.Join(dir, "sub"), Label: "Sub", Schedulable: true})
if err := os.MkdirAll(filepath.Join(dir, "sub"), 0o755); err != nil {
t.Fatal(err)
}
got := fillTargets(cfg, sett)
for _, tg := range got {
if tg.Path == filepath.Join(dir, "sub") {
t.Fatalf("fillTargets kept %q, a sub-folder of the system area's filesystem: targets = %+v", tg.Path, got)
}
}
// "/" and dir are one filesystem or two; the list must hold exactly that many targets.
rootKey, okRoot := system.FilesystemKey(system.DockerVolumePath)
dirKey, _ := system.FilesystemKey(dir)
want := 2
if okRoot && rootKey == dirKey {
want = 1
}
if len(got) != want {
t.Fatalf("fillTargets = %+v, want %d target(s): one per filesystem among / and %s", got, want, dir)
}
}
@@ -0,0 +1,60 @@
package main
import (
"context"
"errors"
"io"
"log"
"net/http"
"testing"
"time"
"gitea.dooplex.hu/admin/felhom-controller/internal/agentapi"
)
// R-528: the scan's host counter source. An old agent (404) is asked again only after hostOOMRetryAfter; a transient
// failure is retried at the next scan; the counters pass through.
// RED-PROOF: drop the 404 back-off → an old agent is asked at every 30-s scan (calls 3, not 1) → FAILS.
func TestR528_HostOOMSourceBacksOffAnOldAgent(t *testing.T) {
clock := time.Date(2026, 10, 28, 23, 0, 0, 0, time.UTC)
calls := 0
var answer error = &agentapi.StatusError{Path: "/guest/oom-kills", Code: http.StatusNotFound}
src := hostOOMSource(func(context.Context) (agentapi.GuestOOMKillsState, error) {
calls++
if answer != nil {
return agentapi.GuestOOMKillsState{}, answer
}
return agentapi.GuestOOMKillsState{Available: true, Containers: map[string]int64{"id": 2}}, nil
}, log.New(io.Discard, "", 0), func() time.Time { return clock })
for i := 0; i < 3; i++ {
if got := src(); got != nil {
t.Fatalf("an old agent: %v", got)
}
clock = clock.Add(30 * time.Second)
}
if calls != 1 {
t.Fatalf("an old agent was asked %d times in 90 s, want 1", calls)
}
clock = clock.Add(hostOOMRetryAfter)
answer = nil
if got := src(); got["id"] != 2 || calls != 2 {
t.Fatalf("after the back-off, an upgraded agent: %v (calls %d)", got, calls)
}
answer = errors.New("timeout")
if got := src(); got != nil || calls != 3 {
t.Fatalf("a transient failure: %v", got)
}
answer = nil
if got := src(); got["id"] != 2 || calls != 4 {
t.Fatalf("the next scan after a transient failure must ask again: %v (calls %d)", got, calls)
}
}
// The source is wired into the stack manager at startup (the seam-built-but-never-wired class).
// RED-PROOF: delete the SetHostOOMKills line in main.go → FAILS.
func TestR528_HostOOMSourceIsWiredAtStartup(t *testing.T) {
lines, _, _ := slice4CallLines(t)
if len(lines["SetHostOOMKills"]) == 0 || len(lines["hostOOMSource"]) == 0 {
t.Fatal("the host OOM counter is never wired — the 30-s scan would read Docker's flag only (R-528)")
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
module gitea.dooplex.hu/admin/felhom-controller
go 1.27.2
go 1.27.4
require (
github.com/emersion/go-sasl v0.0.0-20241020182733-b788ff22d5a6
+1
View File
@@ -24,6 +24,7 @@
# Evidence: felhom.eu/documentation/audits/DIAG-sharing-2026-07-20.md.
# 1.2.0 (R-972): Alpine 3.24.2, pinned by digest — the same base as the hub. 3.21 carried 48 fixable high findings
# (audits/security-review-2026-10-12/scanners/). Same packages; scanner before → after in the controller's v0.323.0 CHANGELOG.
# upstream: gap:Alpine's package fixes (Samba among them) are in its secdb, which the watch does not read; BEHIND on the point release is the signal
FROM alpine:3.24.2@sha256:294b683cb724975bec92580e1e685676bd4b50bda910ddb8c51d4cabeaec77e6
# samba = smbd + nmbd + smbpasswd/testparm (meta-package proven installable in the spike);
+17 -1
View File
@@ -392,6 +392,10 @@ type DisksResponse struct {
// GuestBootID changes on every guest boot (host or guest reboot) but is stable across a
// controller-only restart — the deterministic signal the controller recreates drive-backed apps on.
GuestBootID string `json:"guest_boot_id,omitempty"`
// GuestBootKey (R-1395; an agent after 0.174.0) is the same signal built from the kernel's boot_id instead of
// the boot TIME: a step of the host's clock moves the boot time (and so GuestBootID) and does not move this.
// "" from an older agent — the controller then reads GuestBootID as before. See web.guestBootVerdict.
GuestBootKey string `json:"guest_boot_key,omitempty"`
}
// FormatResult mirrors POST /disks/format (the success/refusal payload).
@@ -1071,6 +1075,18 @@ func (c *Client) RemoveNetStorage(ctx context.Context, name string) error {
// status, even on a non-2xx (so callers like FormatDisk can read a 403 refusal body). A transport or
// envelope-parse failure is still an error; an `ok:false` business refusal is NOT (the data carries it).
func (c *Client) postWithStatus(ctx context.Context, path string, body any) (apiResponse, int, error) {
return c.postWithStatusOn(c.hc, ctx, path, body)
}
// postWithStatusTimeout is postWithStatus with its own overall timeout (the escrow claim and confirm, R-1254). It shares
// the pinned transport.
func (c *Client) postWithStatusTimeout(ctx context.Context, path string, body any, timeout time.Duration) (apiResponse, int, error) {
hc := *c.hc
hc.Timeout = timeout
return c.postWithStatusOn(&hc, ctx, path, body)
}
func (c *Client) postWithStatusOn(hc *http.Client, ctx context.Context, path string, body any) (apiResponse, int, error) {
var env apiResponse
buf, err := json.Marshal(body)
if err != nil {
@@ -1083,7 +1099,7 @@ func (c *Client) postWithStatus(ctx context.Context, path string, body any) (api
req.Header.Set("Authorization", "Bearer "+c.token)
req.Header.Set("Content-Type", "application/json")
start := time.Now()
resp, err := c.hc.Do(req)
resp, err := hc.Do(req)
if err != nil {
logx.Debugf(c.logger, "[agentapi] POST %s failed after %dms: %v", path, time.Since(start).Milliseconds(), err)
return env, 0, fmt.Errorf("agentapi: POST %s: %w", path, err)
+10 -2
View File
@@ -6,6 +6,7 @@ import (
"errors"
"fmt"
"net/http"
"time"
)
// Controller-driven escrow ceremony client methods (v0.127.0, agent ≥ v0.88.0). The claim call
@@ -108,8 +109,15 @@ type EscrowClaim struct {
//
// R-1151: the claim asks the agent to keep the new package until the household typed the code back
// (`defer_upload`). An agent older than 0.160.0 ignores the body and uploads as before.
// escrowCallTimeout bounds the claim and the confirm (R-1254 H2). The agent may take its whole upload timeout (30 s)
// plus its question to the hub (15 s) before it answers; the client's own 15 s used to abandon the call while the
// agent went on — a claim abandoned that way could still store the package, and its code reached nobody. 60 s
// outlasts both (TestR1254_ClaimAndConfirmOutwaitTheAgentsUpload; the agent side: escrowUploadTimeout,
// escrowHoldTimeout in felhom-agent internal/localapi/escrow_ceremony.go — if either grows, this must too).
var escrowCallTimeout = 60 * time.Second
func (c *Client) EscrowCeremonyClaim(ctx context.Context) (EscrowClaim, int, error) {
env, status, err := c.postWithStatus(ctx, "/escrow/ceremony/claim", map[string]bool{"defer_upload": true})
env, status, err := c.postWithStatusTimeout(ctx, "/escrow/ceremony/claim", map[string]bool{"defer_upload": true}, escrowCallTimeout)
if err != nil {
return EscrowClaim{}, status, err
}
@@ -141,7 +149,7 @@ func (c *Client) EscrowCeremonyClaim(ctx context.Context) (EscrowClaim, int, err
// match (still waiting), 410 the window ran out, 404 nothing waits (superseded, restarted), 502 the hub failed (still
// waiting). The words are part of the recovery code — never logged.
func (c *Client) EscrowCeremonyConfirm(ctx context.Context, words []string) (int, error) {
env, status, err := c.postWithStatus(ctx, "/escrow/ceremony/confirm", map[string][]string{"words": words})
env, status, err := c.postWithStatusTimeout(ctx, "/escrow/ceremony/confirm", map[string][]string{"words": words}, escrowCallTimeout)
if err != nil {
return status, err
}
+31
View File
@@ -0,0 +1,31 @@
package agentapi
import (
"context"
"encoding/json"
"fmt"
)
// GuestOOMKillsState mirrors the agent's GET /guest/oom-kills (R-528, agent ≥ the R-528 commit): the kernel's oom_kill
// counter of each of THIS guest's containers, read on the host — Docker's own OOMKilled flag can stay false inside an
// LXC guest. Containers maps the full 64-hex container id to the count for the container's current run.
// Available=false: the guest has no cgroup folder the host can read. An agent that predates the route answers 404 (a
// *StatusError) — the controller then keeps Docker's flag only.
type GuestOOMKillsState struct {
VMID int `json:"vmid"`
Available bool `json:"available"`
Containers map[string]int64 `json:"containers"`
}
// GuestOOMKills calls GET /guest/oom-kills.
func (c *Client) GuestOOMKills(ctx context.Context) (GuestOOMKillsState, error) {
var out GuestOOMKillsState
body, err := c.get(ctx, "/guest/oom-kills")
if err != nil {
return out, err
}
if err := json.Unmarshal(body, &out); err != nil {
return out, fmt.Errorf("agentapi: decode /guest/oom-kills: %w", err)
}
return out, nil
}
@@ -0,0 +1,33 @@
package agentapi
import (
"context"
"encoding/json"
"fmt"
"time"
)
// OperatorReboot calls GET /guest/operator-reboot (D65 = A, agent ≥ the reboot_guest commit): the time the operator
// rebooted THIS guest from the hub, when it is less than a day old; the zero time when there is none. An agent that
// predates the route answers 404 (a *StatusError) — such an agent cannot reboot from the hub either, so there is
// nothing to show and no MinAgent is needed.
func (c *Client) OperatorReboot(ctx context.Context) (time.Time, error) {
body, err := c.get(ctx, "/guest/operator-reboot")
if err != nil {
return time.Time{}, err
}
var out struct {
At string `json:"at"`
}
if err := json.Unmarshal(body, &out); err != nil {
return time.Time{}, fmt.Errorf("agentapi: decode /guest/operator-reboot: %w", err)
}
if out.At == "" {
return time.Time{}, nil
}
at, err := time.Parse(time.RFC3339, out.At)
if err != nil {
return time.Time{}, fmt.Errorf("agentapi: /guest/operator-reboot: bad time %q", out.At)
}
return at, nil
}
@@ -0,0 +1,42 @@
package agentapi
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
// R-1254 H2: the agent's claim/confirm may take its whole upload timeout (30 s) plus the hub question (15 s) before it
// answers. The controller's agent client gives up at 15 s — and a claim the controller abandons can still complete on
// the agent: the hub then holds a package whose code nobody saw. The two calls carry their own, longer timeout.
// RED-PROOF: send claim/confirm through the plain 15 s client again → the slow agent below times them out → FAILS.
func TestR1254_ClaimAndConfirmOutwaitTheAgentsUpload(t *testing.T) {
if escrowCallTimeout < 45*time.Second+10*time.Second {
t.Fatalf("escrowCallTimeout %s must outlast the agent's upload (30 s) + hub question (15 s) with room", escrowCallTimeout)
}
mux := http.NewServeMux()
mux.HandleFunc("POST /escrow/ceremony/claim", func(w http.ResponseWriter, r *http.Request) {
time.Sleep(300 * time.Millisecond)
_, _ = w.Write([]byte(`{"ok":true,"data":{"recovery_code":"a-b-c"}}`))
})
mux.HandleFunc("POST /escrow/ceremony/confirm", func(w http.ResponseWriter, r *http.Request) {
time.Sleep(300 * time.Millisecond)
_, _ = w.Write([]byte(`{"ok":true,"data":{"uploaded":true}}`))
})
s := httptest.NewTLSServer(mux)
defer s.Close()
c := clientFor(t, s, strings.TrimPrefix(s.URL, "https://"))
c.hc.Timeout = 100 * time.Millisecond // the client's own short timeout, scaled down
old := escrowCallTimeout
escrowCallTimeout = 5 * time.Second
defer func() { escrowCallTimeout = old }()
if claim, st, err := c.EscrowCeremonyClaim(context.Background()); err != nil || st != http.StatusOK || claim.Code != "a-b-c" {
t.Fatalf("a slow claim was abandoned: %+v %d %v", claim, st, err)
}
if st, err := c.EscrowCeremonyConfirm(context.Background(), []string{"a", "c"}); err != nil || st != http.StatusOK {
t.Fatalf("a slow confirm was abandoned: %d %v", st, err)
}
}
@@ -0,0 +1,136 @@
package api
import (
"encoding/json"
"go/ast"
"go/parser"
"go/token"
"io"
"log"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
"gitea.dooplex.hu/admin/felhom-controller/internal/backup"
"gitea.dooplex.hu/admin/felhom-controller/internal/config"
"gitea.dooplex.hu/admin/felhom-controller/internal/i18n"
"gitea.dooplex.hu/admin/felhom-controller/internal/settings"
)
// D72 / D84 (`09` §3 decisions 292, 309; `07-backup-architecture.md` §8.2f).
// RED-PROOFS: felhom.eu/documentation/audits/build-release-4-2026-11-15/A/redproof-ctrl-press.txt.
func endsRouter(t *testing.T, transport string) (*Router, *settings.Settings) {
t.Helper()
r, _ := newR442Router(t, "deployed: true\nenv: {}\n")
lg := log.New(io.Discard, "", 0)
sett, err := settings.Load(filepath.Join(t.TempDir(), "settings.json"), lg)
if err != nil {
t.Fatal(err)
}
if err := sett.SetOffboxTarget(&settings.OffboxTarget{Enabled: true, Host: "h", User: "u", RepoPath: "/r", Transport: transport}); err != nil {
t.Fatal(err)
}
cfg := &config.Config{}
cfg.Paths.DataDir = t.TempDir()
r.backupMgr = backup.NewManager(cfg, sett, lg)
r.sett = sett
return r, sett
}
// THE DATE IS SHOWN BEFORE THE PRESS (D72): the dialog's data carries the day the off-site copies would be deleted —
// today + 30 days, in the household's date form — only on a box where a press starts the clock.
func TestD72_BackupDataCarriesTheEndDateBeforeThePress(t *testing.T) {
get := func(r *Router, lang string) map[string]any {
w := httptest.NewRecorder()
r.getStackBackupData(w, httptest.NewRequest(http.MethodGet, "/api/stacks/app/backup-data?lang="+lang, nil), "app")
var resp struct {
OK bool `json:"ok"`
Data map[string]any `json:"data"`
}
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil || !resp.OK {
t.Fatalf("backup-data: %s (%v)", w.Body.String(), err)
}
return resp.Data
}
r, sett := endsRouter(t, settings.TransportRclonePinned)
want := time.Now().Add(settings.OffsiteEndAfter).Local()
for _, lang := range []string{"hu", "en"} {
got, _ := get(r, lang)["offsite_end_date"].(string)
if got != i18n.FormatDate(lang, want) && got != i18n.FormatDate(lang, want.Add(-time.Minute)) {
t.Errorf("[%s] offsite_end_date = %q, want %q (today + 30 days)", lang, got, i18n.FormatDate(lang, want))
}
}
// reading the dialog's data writes NOTHING: the record is the press's, not the look's
if n := len(sett.GetOffsiteEnds()); n != 0 {
t.Fatalf("opening the dialog wrote %d end record(s)", n)
}
// the household's own NAS (no hub window): the dialog says nothing about off-site copies
r2, _ := endsRouter(t, "")
if v, has := get(r2, "hu")["offsite_end_date"]; has {
t.Fatalf("a box without the hub's tier names an end date: %v", v)
}
}
// MUST-HOLD 1, at the handler: the end record is written ONLY when the household pressed „delete backup data”.
// removeStack's success path needs Docker, so this reads the handler's source (as R-486/R-491 do): every call of
// StartOffsiteEnd in removeStack sits inside an `if` whose condition names body.RemoveBackups — and there is one.
// What the call then does is pinned on the real code in backup (TestD84_OnePressOneMail and the window tests).
func TestD72_RemovalWritesTheEndRecordOnlyWithDeleteBackupData(t *testing.T) {
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "router.go", nil, 0)
if err != nil {
t.Fatal(err)
}
calls, guarded := 0, 0
for _, d := range f.Decls {
fn, ok := d.(*ast.FuncDecl)
if !ok || fn.Name.Name != "removeStack" || fn.Body == nil {
continue
}
isCall := func(n ast.Node) bool {
s, ok := n.(*ast.SelectorExpr)
return ok && s.Sel.Name == "StartOffsiteEnd"
}
ast.Inspect(fn.Body, func(n ast.Node) bool {
if isCall(n) {
calls++
}
ifs, ok := n.(*ast.IfStmt)
if !ok {
return true
}
names := false
ast.Inspect(ifs.Cond, func(c ast.Node) bool {
if s, ok := c.(*ast.SelectorExpr); ok && s.Sel.Name == "RemoveBackups" {
names = true
}
return true
})
if names {
ast.Inspect(ifs.Body, func(b ast.Node) bool {
if isCall(b) {
guarded++
}
return true
})
}
return true
})
}
if calls != 1 || guarded != 1 {
t.Fatalf("removeStack: %d call(s) of StartOffsiteEnd, %d inside `if … body.RemoveBackups …` — want exactly one, guarded: "+
"a removal that KEEPS the backups must write no end record", calls, guarded)
}
raw, err := os.ReadFile("router.go")
if err != nil {
t.Fatal(err)
}
if n := strings.Count(string(raw), "StartOffsiteEnd("); n != 1 {
t.Fatalf("router.go calls StartOffsiteEnd %d time(s) — the removal is its only caller here", n)
}
}
+11 -6
View File
@@ -94,7 +94,9 @@ func (r *Router) keptDataAtInstall(w http.ResponseWriter, req *http.Request, nam
writeJSON(w, http.StatusConflict, apiResponse{OK: false, Error: data.UseOff, Data: data})
return true
}
if st := r.backupMgr.RestoreStatus(); st.Running || r.backupMgr.IsRunning() {
// R-1256 H6: every operation — a restore, a backup run, a second-drive copy — not only the first two; and the
// load itself begins in the same step as this question (startKeptLoad → ErrRestoreBusy).
if busy, _ := r.backupMgr.RestoreBusy(); busy != "" {
writeJSON(w, http.StatusConflict, apiResponse{OK: false, Error: r.msgLang(lang, "api.kept.busy")})
return true
}
@@ -104,7 +106,11 @@ func (r *Router) keptDataAtInstall(w http.ResponseWriter, req *http.Request, nam
}
r.logger.Printf("[INFO] [api] Deploy %s: USE MY KEPT DATA — loading from %s (tier %d, %s) under the kept files %v", name, src, cp.c.Tier, cp.c.Time.UTC().Format(time.RFC3339), old)
r.dropLeftoverHold(name, "use-kept-data") // R-704: this is a new install of an app that is not installed
r.startKeptLoad(name, hdd, cp.c, lang, nil)
if err := r.startKeptLoad(name, hdd, cp.c, lang, nil); err != nil {
r.logger.Printf("[WARN] [api] Deploy %s: use my kept data REFUSED at its start: %v", name, err)
writeJSON(w, http.StatusConflict, apiResponse{OK: false, Error: r.msgLang(lang, "api.kept.busy")})
return true
}
writeJSON(w, http.StatusAccepted, apiResponse{OK: true, Message: r.msgLang(lang, "kept.load.started", display)})
return true
default:
@@ -120,7 +126,7 @@ func (r *Router) keptCopyName(lang string, c backup.KeptCopy) string {
// startKeptLoad runs the load and, when it succeeded, the app's after_load. then(ok) runs last. The
// off-site copy goes through LoadKeptOffsite (download the unit alone, judge it, then the same restore).
func (r *Router) startKeptLoad(name, drive string, c backup.KeptCopy, lang string, then func(ok bool)) {
func (r *Router) startKeptLoad(name, drive string, c backup.KeptCopy, lang string, then func(ok bool)) error {
display := name
if st, ok := r.stackMgr.GetStack(name); ok && st.Meta.DisplayName != "" {
display = st.Meta.DisplayName
@@ -128,10 +134,9 @@ func (r *Router) startKeptLoad(name, drive string, c backup.KeptCopy, lang strin
okMsg := func(error) string { return r.msgLang(lang, "kept.load.done", display) }
failMsg := func(err error) string { return r.msgLang(lang, "kept.load.failed", display, err) }
if c.Tier == backup.KeptTierOffsite {
r.backupMgr.LoadKeptOffsite(name, drive, c, nil, okMsg, failMsg, r.keptAfterLoad(name, then))
return
return r.backupMgr.LoadKeptOffsite(name, drive, c, nil, okMsg, failMsg, r.keptAfterLoad(name, then))
}
r.backupMgr.LoadKeptApp(name, c.UnitDir, okMsg, failMsg, r.keptAfterLoad(name, then))
return r.backupMgr.LoadKeptApp(name, c.UnitDir, nil, okMsg, failMsg, r.keptAfterLoad(name, then))
}
// keptAfterLoad runs the app's after_load when the load succeeded, then then(ok).
+44 -1
View File
@@ -162,7 +162,10 @@ func TestR691_InstallChoiceNamesTheOffsiteCopy(t *testing.T) {
// copy, restic and the unit restore behind their seams — no Docker).
// COMPANION RED-PROOF: remove the dropLeftoverHold call from keptDataAtInstall → the hold is still there
// after the 202 and the first assertion fails; remove it from deployStack → the AST check fails.
func TestR704_AFreshInstallDropsALeftoverHold(t *testing.T) {
// keptInstallRig is an installable app with old data on its drive and an off-site copy of its unit; done receives
// once per unit restore the load reaches.
func keptInstallRig(t *testing.T) (*Router, *settings.Settings, string, chan struct{}) {
t.Helper()
dir := t.TempDir()
drive := filepath.Join(dir, "drive")
cfg := &config.Config{}
@@ -234,6 +237,11 @@ func TestR704_AFreshInstallDropsALeftoverHold(t *testing.T) {
return backup.UnitRestoreResult{}, nil
})
r := &Router{stackMgr: m, backupMgr: bm, sett: sett, logger: log.New(io.Discard, "", 0)}
return r, sett, drive, done
}
func TestR704_AFreshInstallDropsALeftoverHold(t *testing.T) {
r, sett, drive, done := keptInstallRig(t)
// A leftover update hold from an earlier install (the demo-hp shape): the new install drops it.
_ = sett.SetRestoreHold(settings.RestoreHold{Stack: "cloudapp", At: "2026-09-13T19:56:32Z", Reason: settings.HoldReasonUpdateFailed})
@@ -287,3 +295,38 @@ func TestR704_AFreshInstallDropsALeftoverHold(t *testing.T) {
t.Fatalf("deployStack must call dropLeftoverHold before DeployStack (drop=%v deploy=%v)", dropAt, deployAt)
}
}
// R-1256 H6: the install-time „use my kept data" asks about EVERY operation — a second-drive copy too, not only a
// restore record and the backup run — and the load begins in the same step as the question.
// RED-PROOF: restore the RestoreStatus/IsRunning-only check and LoadKept*'s plain BeginRestoreOp → 202 and the load
// runs beside the copy → FAILS.
func TestR1256_H6_AKeptLoadAtInstallIsRefusedWhileASecondDriveCopyRuns(t *testing.T) {
r, _, drive, done := keptInstallRig(t)
end := backup.MarkTier2CopyForTest("someapp")
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/api/stacks/cloudapp/deploy?lang=en", nil)
r.keptDataAtInstall(w, req, "cloudapp", drive, "use")
end()
if w.Code != http.StatusConflict {
t.Fatalf("a load during a second-drive copy: code %d, want 409 — body %s", w.Code, w.Body.String())
}
select {
case <-done:
t.Fatal("the load ran beside the second-drive copy")
case <-time.After(300 * time.Millisecond):
}
if st := r.backupMgr.RestoreStatus(); st.Running {
t.Fatal("a refused load left a restore op recorded")
}
// The copy ended: the same press loads.
w = httptest.NewRecorder()
r.keptDataAtInstall(w, httptest.NewRequest(http.MethodPost, "/api/stacks/cloudapp/deploy?lang=en", nil), "cloudapp", drive, "use")
if w.Code != http.StatusAccepted {
t.Fatalf("after the copy: code %d — body %s", w.Code, w.Body.String())
}
select {
case <-done:
case <-time.After(10 * time.Second):
t.Fatal("the load never reached the unit restore")
}
}
+24
View File
@@ -16,6 +16,7 @@ import (
"gitea.dooplex.hu/admin/felhom-controller/internal/backup"
cf "gitea.dooplex.hu/admin/felhom-controller/internal/cloudflare"
"gitea.dooplex.hu/admin/felhom-controller/internal/config"
"gitea.dooplex.hu/admin/felhom-controller/internal/i18n"
"gitea.dooplex.hu/admin/felhom-controller/internal/integrations"
"gitea.dooplex.hu/admin/felhom-controller/internal/metrics"
"gitea.dooplex.hu/admin/felhom-controller/internal/notify"
@@ -771,6 +772,12 @@ func (r *Router) actionStack(w http.ResponseWriter, req *http.Request, action, n
// above, so nothing is recorded for an action that was never going to happen.
if desired, ok := desiredStateForAction(action); ok {
if derr := r.stackMgr.SetDesiredState(name, desired); derr != nil {
if errors.Is(derr, stacks.ErrStackNotFound) {
// no app by that name on this box (e.g. the bootstrap-managed controller): a 404, not a save failure
r.logger.Printf("[WARN] [api] %s for %s refused: no such app", action, name)
writeJSON(w, stackOpStatusFor(derr), apiResponse{OK: false, Error: r.errText(req, derr)})
return
}
r.logger.Printf("[ERROR] [api] %s for %s refused: could not record desired state: %v", action, name, derr)
writeJSON(w, http.StatusInternalServerError, apiResponse{
OK: false,
@@ -957,6 +964,10 @@ func (r *Router) getStackBackupData(w http.ResponseWriter, req *http.Request, na
writeJSON(w, http.StatusNotFound, apiResponse{OK: false, Error: r.errText(req, err)})
return
}
// D72: the date is on the dialog BEFORE the press. Only where a press would start the 30 days.
if r.backupMgr != nil && r.backupMgr.OffsiteEndOffered() {
resp.OffsiteEndDate = i18n.FormatDate(r.langFor(req), r.backupMgr.OffsiteEndDateIfPressedNow().Local())
}
writeJSON(w, http.StatusOK, apiResponse{OK: true, Data: resp})
}
@@ -1095,6 +1106,19 @@ func (r *Router) removeStack(w http.ResponseWriter, req *http.Request, name stri
if body.RemoveBackups {
resp.BackupPathsRemoved = append(resp.BackupPathsRemoved, r.removeVerificationCopy(name)...)
}
// D72 / D84 (`07` §8.2f): „delete backup data” deletes the LOCAL backups now (above) and starts the 30 days of
// the app's OFF-SITE copies: the end record, and the household's one mail. Never on a removal that kept the
// backups; never on a box without the hub-provisioned tier (nothing would carry the deletion out).
if body.RemoveBackups && r.backupMgr != nil {
switch rec, created, serr := r.backupMgr.StartOffsiteEnd(name); {
case errors.Is(serr, backup.ErrOffsiteEndNotOffered):
r.dbg("removeStack: %s: no hub-provisioned off-site tier — no off-site end record", name)
case serr != nil:
r.logger.Printf("[WARN] [api] remove %s: its off-site end record was NOT written (%v) — its off-site copies stay; the Backups page offers „delete in 30 days”", name, serr)
case created:
r.logger.Printf("[INFO] [api] remove %s: its off-site copies end %s (D72)", name, rec.EndsAt)
}
}
// R-486 (v0.240.0): the app's backup preferences — and with them the Tier-2 RECORD that
// tier2RecordedCopyDir needs — are forgotten ONLY when the customer asked for the backups to be
@@ -0,0 +1,29 @@
package api
import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
// Found walking the capability map's B2 („App lifecycle") on 9202, 2026-10-28 night: a Stop of a name that is no app
// on this box (`felhom-controller` — bootstrap-managed, not a stack) answered 500 „…az alkalmazás beállításai nem
// menthetők." — the desired-state write's „not found" read as a save failure. It is a 404 now, before any intent is
// recorded. RED-PROOF: drop the ErrStackNotFound branch in actionStack → 500 → FAILS.
func TestAnActionOnANameThatIsNoAppIsA404(t *testing.T) {
r, _, _, _ := newSlice4Router(t)
for _, action := range []string{"stop", "start"} {
w := httptest.NewRecorder()
r.actionStack(w, httptest.NewRequest("POST", "/api/stacks/nosuchapp/"+action, nil), action, "nosuchapp")
var resp apiResponse
_ = json.Unmarshal(w.Body.Bytes(), &resp)
if w.Code != http.StatusNotFound {
t.Fatalf("%s of a name that is no app: %d %q — want 404", action, w.Code, resp.Error)
}
if strings.Contains(strings.ToLower(resp.Error), "mentheto") || strings.Contains(resp.Error, "menthetők") {
t.Fatalf("%s: the answer still blames a save: %q", action, resp.Error)
}
}
}
@@ -42,6 +42,9 @@ func dbTypeForImage(image string) (DBType, bool) {
return DBType(""), false
}
// DBTypeForImage is dbTypeForImage for other packages (R-1187 g: the .fab import classifies with the SAME predicate).
func DBTypeForImage(image string) (DBType, bool) { return dbTypeForImage(image) }
// composeServicesDoc is the minimal view of a compose file needed here: the `services:` MAP and each
// service's `image:`. Deliberately a real YAML parse and not a line scan — a top-level `volumes:`
// block (immich's `immich_ml_cache:`) has exactly the shape a naive scan misreads as a service, and
+4 -3
View File
@@ -728,10 +728,11 @@ func (e *Exporter) exportHDDData(req ExportRequest, dataDir string, manifest *Ma
e.debugf("tarring HDD mount: %s → %s (%d exclude(s))", mount, tarPath, len(excludes))
tarStart := time.Now()
if err := tarDirectoryExcluding(mount, tarPath, excludes); err != nil {
// v0.125.0: claim the subdir ONLY on success — a claimed-but-absent tar would trip
// the packaging assertion; an honestly-skipped mount stays out of the manifest.
e.logger.Printf("[WARN] Export: failed to tar %s (excluded from the bundle): %v", mount, err)
// R-1187 (a): a folder that cannot be packed FAILS the export. It used to be left out with a WARN while the
// export ended „done" — a bundle silently missing a whole drive folder. Pinned by TestR1187a_*.
e.logger.Printf("[WARN] Export: failed to pack %s — the export FAILS rather than leave it out (R-1187 a): %v", mount, err)
os.Remove(tarPath)
return err
} else {
manifest.HDDSubdirs = append(manifest.HDDSubdirs, subdir)
if info, _ := os.Stat(tarPath); info != nil {
+16 -2
View File
@@ -2,6 +2,7 @@ package appexport
import (
"archive/tar"
"gitea.dooplex.hu/admin/felhom-controller/internal/util"
"io"
"os"
"path/filepath"
@@ -289,7 +290,20 @@ func tarDirectoryExcluding(sourceDir, outputPath string, excludeRels []string) e
return nil
}
}
header, err := tar.FileInfoHeader(info, "")
// R-1187 (a): a symlink is carried AS A LINK (its target's bytes never — the walk used to copy them into the link
// header, the tar failed, and the whole folder was left out); a FIFO, socket or device stops the export with a
// sentence naming the path (os.Open on a FIFO used to HANG the export). Pinned by TestR1187a_*.
mode := info.Mode()
if mode&(os.ModeNamedPipe|os.ModeSocket|os.ModeDevice|os.ModeCharDevice|os.ModeIrregular) != 0 {
return util.MsgError("err.appexport.kulonleges_fajl", path)
}
link := ""
if mode&os.ModeSymlink != 0 {
if link, err = os.Readlink(path); err != nil {
return err
}
}
header, err := tar.FileInfoHeader(info, link)
if err != nil {
return err
}
@@ -297,7 +311,7 @@ func tarDirectoryExcluding(sourceDir, outputPath string, excludeRels []string) e
if err := tw.WriteHeader(header); err != nil {
return err
}
if info.IsDir() {
if info.IsDir() || link != "" {
return nil
}
f, err := os.Open(path)
@@ -0,0 +1,274 @@
package appexport
import (
"archive/tar"
"io"
"log"
"os"
"path/filepath"
"strconv"
"strings"
"syscall"
"testing"
"time"
)
// R-1187 (a), (b), (d), (f), (g) — the open parts of the `.fab` data-loss row. Each test asserts the CONSEQUENCE for
// the household's files. Red-proved 2026-10-26 night against the code before the fix (function shapes added first with
// the old behaviour, so every failure below was a behaviour failure, not a compile error).
func r1187TarEntries(t *testing.T, path string) map[string]*tar.Header {
t.Helper()
f, err := os.Open(path)
if err != nil {
t.Fatal(err)
}
defer f.Close()
out := map[string]*tar.Header{}
tr := tar.NewReader(f)
for {
h, err := tr.Next()
if err == io.EOF {
return out
}
if err != nil {
t.Fatalf("reading %s: %v", path, err)
}
out[h.Name] = h
}
}
// (a) A symlink in a drive folder is carried AS A LINK — before, the walk wrote a link header and then copied the
// target's bytes into it, the tar failed, and the whole folder was left out with only a WARN (the export ended „done").
func TestR1187a_ASymlinkIsCarriedAsALink(t *testing.T) {
src := t.TempDir()
os.WriteFile(filepath.Join(src, "photo.jpg"), []byte("jpeg"), 0o644)
os.Symlink("photo.jpg", filepath.Join(src, "latest.jpg"))
os.Symlink("/etc/hostname", filepath.Join(src, "outside"))
out := filepath.Join(t.TempDir(), "x.tar")
if err := tarDirectoryExcluding(src, out, nil); err != nil {
t.Fatalf("a folder with symlinks could not be packed: %v", err)
}
e := r1187TarEntries(t, out)
if h := e["latest.jpg"]; h == nil || h.Typeflag != tar.TypeSymlink || h.Linkname != "photo.jpg" {
t.Fatalf("the inside link is not carried as a link: %+v", h)
}
if h := e["outside"]; h == nil || h.Typeflag != tar.TypeSymlink || h.Size != 0 {
t.Fatalf("the outside link must be carried as a bare link (never its target's bytes): %+v", h)
}
if h := e["photo.jpg"]; h == nil || h.Typeflag != tar.TypeReg {
t.Fatalf("the regular file is missing: %+v", h)
}
}
// (a) A FIFO stops the export with a sentence naming the path — never a hang on os.Open, never a silent drop. The
// export of the folder FAILS as a whole (exportHDDData returns the error; the job then fails).
func TestR1187a_AFifoFailsTheExportNamingThePath(t *testing.T) {
mount := filepath.Join(t.TempDir(), "appdata-x")
os.MkdirAll(mount, 0o755)
os.WriteFile(filepath.Join(mount, "keep.txt"), []byte("k"), 0o644)
fifo := filepath.Join(mount, "pipe")
if err := syscall.Mkfifo(fifo, 0o644); err != nil {
t.Skipf("no FIFO here: %v", err)
}
prov := &r1187HDDProvider{rtProvider: rtProvider{stackDir: t.TempDir()}, mounts: []string{mount}}
e := NewExporter(prov, log.New(io.Discard, "", 0), "test")
done := make(chan error, 1)
go func() { done <- e.exportHDDData(ExportRequest{StackName: "x"}, t.TempDir(), &Manifest{}) }()
select {
case err := <-done:
if err == nil || !strings.Contains(err.Error(), fifo) {
t.Fatalf("a FIFO must fail the export naming %s, got %v", fifo, err)
}
case <-time.After(10 * time.Second):
t.Fatal("the export HUNG on a FIFO")
}
}
type r1187HDDProvider struct {
rtProvider
mounts []string
}
func (p *r1187HDDProvider) GetStackHDDMounts(string) []string { return p.mounts }
// (b) The import keeps owners and modes, restores a link that stays inside the app's folder, and refuses (and lists) a
// link that points outside it. Before: only folders and regular files were written — owners lost, every link dropped.
func TestR1187b_TheImportKeepsOwnersModesAndInsideLinks(t *testing.T) {
tarPath := filepath.Join(t.TempDir(), "d.tar")
f, _ := os.Create(tarPath)
tw := tar.NewWriter(f)
tw.WriteHeader(&tar.Header{Name: "sub/", Typeflag: tar.TypeDir, Mode: 0o750, Uid: 1000, Gid: 1000})
tw.WriteHeader(&tar.Header{Name: "sub/a.txt", Typeflag: tar.TypeReg, Mode: 0o640, Size: 2, Uid: 1000, Gid: 1001})
tw.Write([]byte("hi"))
tw.WriteHeader(&tar.Header{Name: "link-in", Typeflag: tar.TypeSymlink, Linkname: "sub/a.txt", Uid: 1000, Gid: 1000})
tw.WriteHeader(&tar.Header{Name: "link-out", Typeflag: tar.TypeSymlink, Linkname: "../../etc/passwd"})
tw.WriteHeader(&tar.Header{Name: "link-abs", Typeflag: tar.TypeSymlink, Linkname: "/etc/passwd"})
tw.Close()
f.Close()
var chowned []string
old := lchownFn
lchownFn = func(_ *os.Root, p string, uid, gid int) error {
chowned = append(chowned, filepath.Base(p)+":"+strconv.Itoa(uid)+":"+strconv.Itoa(gid))
return nil
}
defer func() { lchownFn = old }()
dest := t.TempDir()
refused, err := extractTar(tarPath, dest)
if err != nil {
t.Fatal(err)
}
if fi, err := os.Stat(filepath.Join(dest, "sub/a.txt")); err != nil || fi.Mode().Perm() != 0o640 {
t.Fatalf("mode not kept: %v %v", fi, err)
}
if l, err := os.Readlink(filepath.Join(dest, "link-in")); err != nil || l != "sub/a.txt" {
t.Fatalf("the inside link was not restored: %q %v", l, err)
}
for _, bad := range []string{"link-out", "link-abs"} {
if _, err := os.Lstat(filepath.Join(dest, bad)); err == nil {
t.Fatalf("a link pointing OUTSIDE the app's folder was restored: %s", bad)
}
}
if strings.Join(refused, ",") != "link-out,link-abs" {
t.Fatalf("the refused links must be listed, got %v", refused)
}
got := strings.Join(chowned, ",")
for _, want := range []string{"sub:1000:1000", "a.txt:1000:1001", "link-in:1000:1000"} {
if !strings.Contains(got, want) {
t.Fatalf("owner %s not restored (got %s)", want, got)
}
}
}
// (d) An import is refused while another operation holds the app-stop marker (a restore, a put-back, a stop-first
// export) — before, StartImport checked only its own job slot.
func TestR1187d_AnImportWaitsForARestore(t *testing.T) {
e := NewExporter(&rtProvider{stackDir: t.TempDir()}, log.New(io.Discard, "", 0), "test")
e.SetStopGuard(&busyGuard{})
fab := filepath.Join(t.TempDir(), "x.fab")
os.WriteFile(fab, []byte("x"), 0o644)
err := e.StartImport(ImportRequest{FABPath: fab})
if err == nil || !strings.Contains(err.Error(), "unit-restore:bookstack") {
t.Fatalf("an import started while a restore holds the box: %v", err)
}
if e.activeJob != nil {
t.Fatal("a refused import created a job")
}
}
// (f) A bundle whose app.yaml carries an empty or relative HDD_PATH is refused BEFORE anything is touched — before, an
// empty one made the drive tars extract into a RELATIVE path (the controller's working directory).
func TestR1187f_AnEmptyOrRelativeHDDPathIsRefused(t *testing.T) {
for _, tc := range []struct {
hdd string
ok bool
}{{"", false}, {"data", false}, {"/mnt/drive/../../etc", false}, {"/mnt/sys_drive", true}} {
tmp := t.TempDir()
os.MkdirAll(filepath.Join(tmp, "config"), 0o755)
os.WriteFile(filepath.Join(tmp, "config", "app.yaml"), []byte("env:\n HDD_PATH: \""+tc.hdd+"\"\n"), 0o644)
os.MkdirAll(filepath.Join(tmp, "data", "hdd"), 0o755)
os.WriteFile(filepath.Join(tmp, "data", "hdd", "appdata.tar"), []byte("not empty"), 0o644)
err := validateBundleData(tmp, &Manifest{HDDSubdirs: []string{"appdata"}, HasHDDData: true})
if tc.ok != (err == nil) {
t.Errorf("HDD_PATH %q: refused=%v, want refused=%v (%v)", tc.hdd, err != nil, !tc.ok, err)
}
}
}
// (g) PostGIS / pgvector / timescaledb images are PostgreSQL for the import too (the backup side's predicate, R-484),
// and psql stops on the first error (the dump is --clean --if-exists, so ON_ERROR_STOP is safe).
func TestR1187g_PostgisIsPostgresAndPsqlStopsOnError(t *testing.T) {
for _, img := range []string{"postgis/postgis:16-3.5-alpine", "pgvector/pgvector:pg16", "timescale/timescaledb:2.14.2-pg16", "postgres:16"} {
if info := classifyDBImage("db", img, "c"); info == nil || info.DBType != "postgres" {
t.Errorf("%s is not classified as PostgreSQL: %+v", img, info)
}
}
// The load itself goes through appbackup.ImportDump (psql -v ON_ERROR_STOP=1 --single-transaction) since the
// import's own client calls were removed — TestR1187_TheImportLoadsTheDumpThroughTheBackupSide.
}
// (b), the security review's case: a link already in the destination folder (left by the old app, or made by an earlier
// entry) that points OUTSIDE must never be written through — a tar entry „evil/passwd" would otherwise create a file
// wherever „evil" points. Every write is confined to the app's folder (os.Root). RED-PROOF: with plain os.Create the
// outside file is created.
func TestR1187b_NoWriteThroughALinkThatLeavesTheFolder(t *testing.T) {
outside := t.TempDir()
dest := t.TempDir()
os.Symlink(outside, filepath.Join(dest, "evil")) // pre-existing, pointing out
tarPath := filepath.Join(t.TempDir(), "d.tar")
f, _ := os.Create(tarPath)
tw := tar.NewWriter(f)
tw.WriteHeader(&tar.Header{Name: "evil/passwd", Typeflag: tar.TypeReg, Mode: 0o644, Size: 3})
tw.Write([]byte("pwn"))
tw.WriteHeader(&tar.Header{Name: "ok.txt", Typeflag: tar.TypeReg, Mode: 0o644, Size: 2})
tw.Write([]byte("ok"))
tw.Close()
f.Close()
old := lchownFn
lchownFn = func(*os.Root, string, int, int) error { return nil }
defer func() { lchownFn = old }()
extractTar(tarPath, dest)
if _, err := os.Stat(filepath.Join(outside, "passwd")); err == nil {
t.Fatal("a file was written OUTSIDE the app's folder through a pre-existing link")
}
}
// (b), the security review's second case — a parser differential: link „a" → „." makes „a/b" really „b", so a later
// link „a/b/l" → „../.." passes a path-TEXT check (root/a/b/../.. = root) while it really points one level ABOVE the
// app's folder. A link entry whose parent path passes through a link is refused and listed. RED-PROOF: with the text
// check only, „a/b/l" is created and points outside.
func TestR1187b_NoLinkThroughALinkedParent(t *testing.T) {
dest := t.TempDir()
tarPath := filepath.Join(t.TempDir(), "d.tar")
f, _ := os.Create(tarPath)
tw := tar.NewWriter(f)
tw.WriteHeader(&tar.Header{Name: "a", Typeflag: tar.TypeSymlink, Linkname: "."})
tw.WriteHeader(&tar.Header{Name: "a/b/", Typeflag: tar.TypeDir, Mode: 0o755})
tw.WriteHeader(&tar.Header{Name: "a/b/l", Typeflag: tar.TypeSymlink, Linkname: "../.."})
tw.Close()
f.Close()
old := lchownFn
lchownFn = func(*os.Root, string, int, int) error { return nil }
defer func() { lchownFn = old }()
refused, err := extractTar(tarPath, dest)
if err != nil {
t.Fatal(err)
}
for _, p := range []string{filepath.Join(dest, "b", "l"), filepath.Join(dest, "a", "b", "l")} {
if _, err := os.Lstat(p); err == nil {
real, _ := filepath.EvalSymlinks(p)
t.Fatalf("a link through a linked parent was created (%s → %s)", p, real)
}
}
if !strings.Contains(strings.Join(refused, ","), "a/b/l") {
t.Fatalf("the refused link must be listed, got %v", refused)
}
}
// (b), the security review's third case: a link TARGET that passes through a link already in the folder („evil" → an
// outside folder, then „x" → „evil/y") reads as inside by its text and really points outside. Restored links may only
// point DOWNWARD to real folders: no absolute target, no „..", no link on the way. RED-PROOF: the text check created „x".
func TestR1187b_NoLinkTargetThroughALink(t *testing.T) {
outside := t.TempDir()
dest := t.TempDir()
os.Symlink(outside, filepath.Join(dest, "evil"))
tarPath := filepath.Join(t.TempDir(), "d.tar")
f, _ := os.Create(tarPath)
tw := tar.NewWriter(f)
tw.WriteHeader(&tar.Header{Name: "x", Typeflag: tar.TypeSymlink, Linkname: "evil/y"})
tw.WriteHeader(&tar.Header{Name: "up", Typeflag: tar.TypeSymlink, Linkname: "sub/../sub"})
tw.Close()
f.Close()
old := lchownFn
lchownFn = func(*os.Root, string, int, int) error { return nil }
defer func() { lchownFn = old }()
refused, _ := extractTar(tarPath, dest)
if _, err := os.Lstat(filepath.Join(dest, "x")); err == nil {
t.Fatal("a link whose target passes through an outside-pointing link was created")
}
if strings.Join(refused, ",") != "x,up" {
t.Fatalf("both links must be refused and listed, got %v", refused)
}
}
@@ -0,0 +1,47 @@
package appexport
import (
"context"
"io"
"log"
"strings"
"testing"
"gitea.dooplex.hu/admin/felhom-controller/internal/appbackup"
)
// R-1187, found live on 9202 2026-10-26 night: the `.fab` import waited with `mysqladmin` and loaded with `mysql` — names
// the MariaDB 11+ images do not ship (only mariadb-admin / mariadb; measured in mariadb:11.4) — and read the password
// from the app's env under two fixed names (grimmory's is DB_ROOT_PASSWORD). Every import of a MariaDB 11+ app timed
// out and left the app down. The import now uses the BACKUP side's discovery (the live container's own credentials)
// and appbackup.ImportDump (mariadb / mariadb-admin, psql ON_ERROR_STOP + --single-transaction). The seams keep this
// test off the real Docker (R-650). RED-PROOF: the old body (its own waitForDB + importDBDump) never reaches the seams.
func TestR1187_TheImportLoadsTheDumpThroughTheBackupSide(t *testing.T) {
oldD, oldI := discoverDBsFn, importDumpFn
defer func() { discoverDBsFn, importDumpFn = oldD, oldI }()
discoverDBsFn = func(ctx context.Context, l *log.Logger, debug bool, known []string) ([]appbackup.DiscoveredDB, error) {
return []appbackup.DiscoveredDB{
{ContainerName: "paperless-postgres", ContainerID: "1b47ee5f58d2", DBType: appbackup.DBTypePostgres, StackName: "paperless-ngx"},
{ContainerName: "grimmory-db", ContainerID: "2310c379bd74", DBType: appbackup.DBTypeMariaDB, DBName: "grimmory", StackName: "grimmory"},
}, nil
}
var got appbackup.DiscoveredDB
var gotPath string
importDumpFn = func(ctx context.Context, db appbackup.DiscoveredDB, dumpPath string, l *log.Logger, debug bool) error {
got, gotPath = db, dumpPath
return nil
}
e := NewExporter(&rtProvider{}, log.New(io.Discard, "", 0), "test")
err := e.importIntoContainer("grimmory", "2310c379bd742a9bbb3a78ceb60d1872edb2dfe0ddc15b134edb9142b048e558", "mariadb", "/tmp/x/grimmory-mariadb.sql.gz", nil)
if err != nil {
t.Fatalf("import: %v", err)
}
if got.ContainerName != "grimmory-db" || gotPath != "/tmp/x/grimmory-mariadb.sql.gz" {
t.Fatalf("the dump did not go through the backup side's ImportDump for the started container: %+v %q", got, gotPath)
}
// A container the backup side cannot see is a clear refusal, never a guess.
err = e.importIntoContainer("grimmory", "ffffffffffff", "mariadb", "/tmp/x/d.sql.gz", nil)
if err == nil || !strings.Contains(err.Error(), "ffffffffffff") {
t.Fatalf("an undiscovered container must be refused naming it, got %v", err)
}
}
@@ -0,0 +1,40 @@
package appexport
import (
"testing"
"gitea.dooplex.hu/admin/felhom-controller/internal/appbackup"
)
// R-1187, found live on 9202 2026-10-26 night (grimmory): the import ran `compose` WITHOUT the two path variables the
// controller adds at every install and start (USERDATA_PATH, IMPORT_PATH — stacks.policyEnv). Compose then printed
// „The USERDATA_PATH variable is not set" on its combined output, the DB step read that WARNING as the container id,
// waited 60 s for a container that does not exist, and left the app removed and not started. Both halves pinned here.
// RED-PROOF: with the old helpers (the first output line; the env unchanged) both tests fail.
func TestR1187_TheContainerIDIsNeverAComposeWarning(t *testing.T) {
out := []byte("time=\"2026-10-26T20:18:06Z\" level=warning msg=\"The \\\"USERDATA_PATH\\\" variable is not set. Defaulting to a blank string.\"\n" +
"1047c698c778ab12cd34ef56ab78cd90ef12ab34cd56ef78ab90cd12ef34ab56\n")
if got := containerIDFrom(out); got != "1047c698c778ab12cd34ef56ab78cd90ef12ab34cd56ef78ab90cd12ef34ab56" {
t.Fatalf("container id = %q", got)
}
if got := containerIDFrom([]byte("time=x level=warning msg=y\n")); got != "" {
t.Fatalf("a warning alone must give no id, got %q", got)
}
}
func TestR1187_TheImportEnvCarriesTheControllersPathVars(t *testing.T) {
env := map[string]string{"HDD_PATH": "/mnt/felhom-drives/d", "USERDATA_PATH": "/mnt/felhom-drives/d/appdata/other", "X": "1"}
got := withImportPathVars(env, "/mnt/felhom-drives/d", "/mnt/sys_drive/felhom-data/userdata/import")
if got["USERDATA_PATH"] != appbackup.UserdataDir("/mnt/felhom-drives/d") {
t.Fatalf("USERDATA_PATH = %q — must be the controller's own derivation, never the bundle's", got["USERDATA_PATH"])
}
if got["IMPORT_PATH"] != "/mnt/sys_drive/felhom-data/userdata/import" || got["X"] != "1" || got["HDD_PATH"] != "/mnt/felhom-drives/d" {
t.Fatalf("env = %v", got)
}
if env["USERDATA_PATH"] != "/mnt/felhom-drives/d/appdata/other" {
t.Fatal("the caller's map was changed")
}
if g := withImportPathVars(map[string]string{"IMPORT_PATH": "/x"}, "", ""); g["USERDATA_PATH"] != "" || g["IMPORT_PATH"] != "" {
t.Fatalf("no namespace / no import root must leave neither variable: %v", g)
}
}
+214 -145
View File
@@ -5,11 +5,11 @@ import (
"compress/gzip"
"context"
"fmt"
"gitea.dooplex.hu/admin/felhom-controller/internal/appbackup"
"gitea.dooplex.hu/admin/felhom-controller/internal/dockerexec"
"gitea.dooplex.hu/admin/felhom-controller/internal/util"
"io"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
@@ -184,6 +184,16 @@ func (e *Exporter) StartImport(req ImportRequest) error {
e.debugf("StartImport rejected: another job is already running")
return fmt.Errorf("export or import already in progress")
}
// R-1187 (d): another operation holds the app-stop marker (a restore, a put-back, a stop-first export) — an import
// now would stop and rewrite an app that operation is moving. Refused before anything is read. Pinned by
// TestR1187d_AnImportWaitsForARestore.
if e.stopGuard != nil {
if busy := e.stopGuard.BusyWith(); busy != "" {
e.mu.Unlock()
e.logger.Printf("[WARN] Import: refused — another operation holds the box (%s) (R-1187 d)", busy)
return util.MsgError("err.appexport.import_foglalt", busy)
}
}
// Validate file exists
info, err := os.Stat(req.FABPath)
@@ -431,6 +441,8 @@ func (e *Exporter) executeImport(req ImportRequest, job *Job) {
e.failJob(job, step, fmt.Sprintf("Konfiguráció visszaállítása sikertelen: %v", err))
return
}
// R-1187 (found live): compose runs below see the controller's path variables, as at every install and start.
env = withImportPathVars(env, e.provider.GetStackNamespaceRoot(manifest.AppName), e.provider.GetImportRoot())
e.debugf("config restored: %d env vars", len(env))
if e.debug {
for k := range env {
@@ -674,9 +686,14 @@ func (e *Exporter) restoreHDDData(tmpDir string, manifest *Manifest, composePath
e.logger.Printf("[INFO] Import: extracting HDD data %s → %s", subdir, destPath)
extractStart := time.Now()
if err := extractTar(tarPath, destPath); err != nil {
refused, err := extractTar(tarPath, destPath)
if err != nil {
return fmt.Errorf("extracting %s: %w", subdir, err)
}
if len(refused) > 0 {
e.logger.Printf("[WARN] Import: %s — %d link(s) pointing outside the app's folder were NOT restored (R-1187 b): %s",
subdir, len(refused), strings.Join(refused, ", "))
}
e.debugf("restoreHDDData: extracted %s in %v", subdir, time.Since(extractStart))
}
@@ -726,6 +743,16 @@ func resolveHDDMounts(composePath string, env map[string]string) []string {
// validateBundleData asserts every manifest-claimed data tar exists non-empty in the extracted
// bundle (v0.125.0, scenario C). Pure read — called before ANY destructive import step.
func validateBundleData(tmpDir string, manifest *Manifest) error {
// R-1187 (f): drive data needs an ABSOLUTE, clean HDD_PATH from the bundle's app.yaml — an empty one made the drive
// tars extract into a relative path (the controller's working directory). Refused before anything is touched.
// Pinned by TestR1187f_AnEmptyOrRelativeHDDPathIsRefused.
if len(manifest.HDDSubdirs) > 0 {
env, _ := readPlaintextAppYaml(filepath.Join(tmpDir, "config", "app.yaml"))
hdd := strings.TrimSpace(env["HDD_PATH"])
if hdd == "" || !filepath.IsAbs(hdd) || filepath.Clean(hdd) != hdd || strings.Contains(hdd, "..") {
return util.MsgError("err.appexport.hdd_path_hibas", hdd)
}
}
for _, v := range manifest.VolumeNames {
if err := ValidateSegment("volume_name", v); err != nil {
return err
@@ -856,29 +883,53 @@ func (e *Exporter) restoreDatabase(manifest *Manifest, tmpDir, composePath, stac
}
e.debugf("restoreDatabase: container ID=%s", containerID)
// Wait for DB readiness
e.logger.Printf("[INFO] Import: waiting for DB readiness (container %s)", containerID[:12])
e.debugf("restoreDatabase: waiting for DB readiness...")
waitStart := time.Now()
if err := waitForDB(containerID, dbSvc.DBType, env); err != nil {
e.debugf("restoreDatabase: DB not ready after %v: %v", time.Since(waitStart), err)
return fmt.Errorf("waiting for DB: %w", err)
}
e.debugf("restoreDatabase: DB ready in %v", time.Since(waitStart))
// Import the dump
e.logger.Printf("[INFO] Import: importing database dump")
e.debugf("restoreDatabase: importing dump into container %s", containerID[:12])
// Wait for readiness and import the dump.
importStart := time.Now()
if err := importDBDump(containerID, dumpGzPath, dbSvc.DBType, env); err != nil {
if err := e.importIntoContainer(manifest.AppName, containerID, dbSvc.DBType, dumpGzPath, env); err != nil {
e.debugf("restoreDatabase: import failed after %v: %v", time.Since(importStart), err)
return fmt.Errorf("importing dump: %w", err)
return err
}
e.debugf("restoreDatabase: dump imported in %v", time.Since(importStart))
return nil
}
// Seams for importIntoContainer (a test replaces them; production is the backup side's own code).
var (
discoverDBsFn = appbackup.DiscoverDatabases
importDumpFn = appbackup.ImportDump
)
// importIntoContainer waits for the database and loads the dump — through the BACKUP side (R-1187, found live on 9202):
// the container's own credentials from appbackup's discovery, and appbackup.ImportDump (mariadb / mariadb-admin, which
// the MariaDB 11+ images ship; psql ON_ERROR_STOP + --single-transaction). The import's own waitForDB/importDBDump used
// mysqladmin/mysql (absent from mariadb:11.4) and two fixed env names for the password, so every MariaDB 11+ import
// timed out. Pinned by TestR1187_TheImportLoadsTheDumpThroughTheBackupSide.
func (e *Exporter) importIntoContainer(app, containerID, dbType, dumpPath string, env map[string]string) error {
ctx := context.Background()
dbs, err := discoverDBsFn(ctx, e.logger, e.debug, []string{app})
if err != nil {
return fmt.Errorf("finding the database container: %w", err)
}
for _, db := range dbs {
if db.ContainerID == "" || !(strings.HasPrefix(containerID, db.ContainerID) || strings.HasPrefix(db.ContainerID, containerID)) {
continue
}
e.logger.Printf("[INFO] Import: loading the database dump into %s (%s)", db.ContainerName, db.DBType)
if err := importDumpFn(ctx, db, dumpPath, e.logger, e.debug); err != nil {
return fmt.Errorf("importing dump: %w", err)
}
return nil
}
return fmt.Errorf("the started database container %s is not among the databases the box can see", shortID(containerID))
}
func shortID(id string) string {
if len(id) > 12 {
return id[:12]
}
return id
}
// findDumpFile finds the gzipped SQL dump in the database directory.
func findDumpFile(dbDir string) (string, error) {
entries, err := os.ReadDir(dbDir)
@@ -967,11 +1018,12 @@ func findDBServiceInCompose(composePath string) *dbServiceInfo {
}
func classifyDBImage(service, image, container string) *dbServiceInfo {
img := strings.ToLower(image)
if strings.Contains(img, "postgres") {
// R-1187 (g): the backup side's predicate (appbackup.DBTypeForImage, R-484) — postgis / pgvector / timescaledb are
// PostgreSQL too. The import used its own narrower list and skipped adventurelog's and dawarich's database.
switch t, ok := appbackup.DBTypeForImage(image); {
case ok && t == appbackup.DBTypePostgres:
return &dbServiceInfo{ServiceName: service, DBType: "postgres", ContainerName: container}
}
if strings.Contains(img, "mariadb") || strings.Contains(img, "mysql") {
case ok && t == appbackup.DBTypeMariaDB:
return &dbServiceInfo{ServiceName: service, DBType: "mariadb", ContainerName: container}
}
return nil
@@ -1002,118 +1054,43 @@ func getComposeContainerID(stackDir string, env map[string]string, service strin
if err != nil {
return "", fmt.Errorf("compose ps: %w", err)
}
id := strings.TrimSpace(string(out))
id := containerIDFrom(out)
if id == "" {
return "", fmt.Errorf("no container found for service %s", service)
}
// Take the first line in case of multiple
if idx := strings.Index(id, "\n"); idx > 0 {
id = id[:idx]
}
return id, nil
}
// waitForDB polls until the database is ready to accept connections.
func waitForDB(containerID, dbType string, env map[string]string) error {
timeout := 60 * time.Second
start := time.Now()
for {
if time.Since(start) > timeout {
return fmt.Errorf("timeout waiting for %s to become ready", dbType)
// containerIDFrom picks the container id out of `compose ps -q` output: the first line that IS an id (12–64 hex). The
// output is combined, so a compose WARNING can come first — it was read as the id once (R-1187, found live on 9202).
func containerIDFrom(out []byte) string {
for _, line := range strings.Split(string(out), "\n") {
line = strings.TrimSpace(line)
if n := len(line); n >= 12 && n <= 64 && strings.Trim(line, "0123456789abcdef") == "" {
return line
}
var cmd *exec.Cmd
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
switch dbType {
case "postgres":
user := env["POSTGRES_USER"]
if user == "" {
user = "postgres"
}
cmd = dockerexec.CommandContext(ctx, "docker", "exec", containerID,
"pg_isready", "-U", user)
case "mariadb":
password := env["MYSQL_ROOT_PASSWORD"]
if password == "" {
password = env["MARIADB_ROOT_PASSWORD"]
}
cmd = dockerexec.CommandContext(ctx, "docker", "exec", containerID,
"mysqladmin", "ping", "-u", "root", "-p"+password)
default:
cancel()
return fmt.Errorf("unknown DB type: %s", dbType)
}
err := cmd.Run()
cancel()
if err == nil {
return nil
}
time.Sleep(2 * time.Second)
}
return ""
}
// importDBDump imports a (possibly gzipped) SQL dump into the running database container.
func importDBDump(containerID, dumpPath, dbType string, env map[string]string) error {
// Open the dump file
f, err := os.Open(dumpPath)
if err != nil {
return err
// withImportPathVars is the import's env as `compose` must see it: the bundle's values plus the two path variables the
// controller itself adds at every install and start (stacks.policyEnv) — USERDATA_PATH always the controller's own
// derivation from the namespace root (never a bundle's value), IMPORT_PATH the drop-zone root. Without them compose
// printed a warning the DB step read as the container id (R-1187, live on 9202). Returns a new map.
func withImportPathVars(env map[string]string, nsRoot, importRoot string) map[string]string {
out := make(map[string]string, len(env)+2)
for k, v := range env {
out[k] = v
}
defer f.Close()
// If gzipped, wrap in gzip reader
var reader io.Reader = f
if strings.HasSuffix(dumpPath, ".gz") {
gr, err := gzip.NewReader(f)
if err != nil {
return fmt.Errorf("opening gzip: %w", err)
delete(out, "USERDATA_PATH")
delete(out, "IMPORT_PATH")
if nsRoot != "" {
out["USERDATA_PATH"] = appbackup.UserdataDir(nsRoot)
}
defer gr.Close()
reader = gr
if importRoot != "" {
out["IMPORT_PATH"] = importRoot
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute)
defer cancel()
var cmd *exec.Cmd
switch dbType {
case "postgres":
user := env["POSTGRES_USER"]
if user == "" {
user = "postgres"
}
dbName := env["POSTGRES_DB"]
if dbName == "" {
dbName = user
}
cmd = dockerexec.CommandContext(ctx, "docker", "exec", "-i", containerID,
"psql", "-U", user, "-d", dbName)
case "mariadb":
password := env["MYSQL_ROOT_PASSWORD"]
if password == "" {
password = env["MARIADB_ROOT_PASSWORD"]
}
dbName := env["MYSQL_DATABASE"]
if dbName == "" {
dbName = env["MARIADB_DATABASE"]
}
cmd = dockerexec.CommandContext(ctx, "docker", "exec", "-i", containerID,
"mysql", "-u", "root", "-p"+password, dbName)
default:
return fmt.Errorf("unknown DB type: %s", dbType)
}
cmd.Stdin = reader
out, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("%s import failed: %s — %w", dbType, strings.TrimSpace(string(out)), err)
}
return nil
return out
}
// extractTarGz extracts a tar.gz archive to a directory.
@@ -1170,50 +1147,142 @@ func extractTarGz(tgzPath, destDir string) error {
}
}
// extractTar extracts a plain tar archive to a directory.
func extractTar(tarPath, destDir string) error {
// safeDownwardLink is the rule for a restored link: a relative target with no „.." component, and no symbolic link on
// the way — not among the folders of the link's own path, not among the existing components of its target.
func safeDownwardLink(rt *os.Root, name, target string) bool {
if target == "" || filepath.IsAbs(target) {
return false
}
for _, part := range strings.Split(filepath.ToSlash(target), "/") {
if part == ".." {
return false
}
}
if parentThroughLink(rt, name) {
return false
}
acc := filepath.Dir(name)
for _, part := range strings.Split(filepath.Clean(target), string(os.PathSeparator)) {
acc = filepath.Join(acc, part)
fi, err := rt.Lstat(acc)
if err != nil {
break // not there (yet): nothing further down can be a link that exists now
}
if fi.Mode()&os.ModeSymlink != 0 {
return false
}
}
return true
}
// parentThroughLink is true when any folder on name's path (inside the root) is a symbolic link.
func parentThroughLink(rt *os.Root, name string) bool {
dir := filepath.Dir(name)
if dir == "." {
return false
}
acc := ""
for _, part := range strings.Split(dir, string(os.PathSeparator)) {
acc = filepath.Join(acc, part)
fi, err := rt.Lstat(acc)
if err != nil {
return false // not there yet: MkdirAll creates real folders
}
if fi.Mode()&os.ModeSymlink != 0 {
return true
}
}
return false
}
// lchownFn is the owner seam (a test records it; production is os.Lchown).
var lchownFn = func(r *os.Root, name string, uid, gid int) error { return r.Lchown(name, uid, gid) }
// extractTar extracts a plain tar archive (one drive folder) into destDir and returns the entries it REFUSED.
//
// R-1187 (b): owners and modes are kept (Lchown — the controller runs as root on a box), and a symlink is restored when
// it stays inside destDir; a link pointing outside (absolute, or climbing out with ..) is refused and listed — never
// followed, never created. Only folders, regular files and links exist in a drive tar (the export refuses the rest).
// Pinned by TestR1187b_TheImportKeepsOwnersModesAndInsideLinks.
func extractTar(tarPath, destDir string) ([]string, error) {
f, err := os.Open(tarPath)
if err != nil {
return err
return nil, err
}
defer f.Close()
root := filepath.Clean(destDir)
// Every write goes through os.Root: no entry can create or write a file outside destDir, not even through a link
// already in the folder (left by the old app, or made by an earlier entry) that points out — the security review's
// case, pinned by TestR1187b_NoWriteThroughALinkThatLeavesTheFolder.
rt, err := os.OpenRoot(root)
if err != nil {
return nil, err
}
defer rt.Close()
var refused []string
tr := tar.NewReader(f)
for {
hdr, err := tr.Next()
if err == io.EOF {
return nil
return refused, nil
}
if err != nil {
return err
return refused, err
}
target := filepath.Join(destDir, hdr.Name)
// Security: prevent path traversal
if !strings.HasPrefix(filepath.Clean(target), filepath.Clean(destDir)+string(os.PathSeparator)) {
continue
name := filepath.Clean(hdr.Name)
if name == "." || filepath.IsAbs(name) || name == ".." || strings.HasPrefix(name, ".."+string(os.PathSeparator)) {
continue // path traversal
}
switch hdr.Typeflag {
case tar.TypeDir:
if err := os.MkdirAll(target, os.FileMode(hdr.Mode)); err != nil {
return err
if err := rt.MkdirAll(name, os.FileMode(hdr.Mode).Perm()); err != nil {
return refused, err
}
rt.Chmod(name, os.FileMode(hdr.Mode).Perm())
case tar.TypeReg:
if err := os.MkdirAll(filepath.Dir(target), 0755); err != nil {
return err
if dir := filepath.Dir(name); dir != "." {
if err := rt.MkdirAll(dir, 0755); err != nil {
return refused, err
}
outFile, err := os.Create(target)
}
out, err := rt.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, os.FileMode(hdr.Mode).Perm())
if err != nil {
return err
refused = append(refused, hdr.Name) // e.g. its path goes through a link that leaves the folder
continue
}
if _, err := io.Copy(outFile, tr); err != nil {
outFile.Close()
return err
if _, err := io.Copy(out, tr); err != nil {
out.Close()
return refused, err
}
outFile.Close()
os.Chmod(target, os.FileMode(hdr.Mode))
out.Close()
rt.Chmod(name, os.FileMode(hdr.Mode).Perm())
case tar.TypeSymlink:
// A restored link may only point DOWNWARD inside the folder, through real folders: no absolute target, no
// „..", and no link on the way — neither on the link's own path nor in its target. Such a link can never
// resolve outside the app's folder, whatever else the folder holds. Everything else is refused and listed.
// (Three rounds of the automated security review: a link written through, a linked parent, a target through
// a link. Pinned by TestR1187b_*.)
if !safeDownwardLink(rt, name, hdr.Linkname) {
refused = append(refused, hdr.Name)
continue
}
dst := hdr.Linkname
if dir := filepath.Dir(name); dir != "." {
if err := rt.MkdirAll(dir, 0755); err != nil {
return refused, err
}
}
rt.Remove(name)
if err := rt.Symlink(dst, name); err != nil {
refused = append(refused, hdr.Name)
continue
}
default:
refused = append(refused, hdr.Name)
continue
}
if err := lchownFn(rt, name, hdr.Uid, hdr.Gid); err != nil && !os.IsPermission(err) {
return refused, fmt.Errorf("setting the owner of %s: %w", hdr.Name, err)
}
}
}
@@ -137,6 +137,10 @@ type AppStopGuard struct {
// whether the drive a copy lives on is bound. nil = the pre-R-1251 behaviour.
holds AppStopHolds
undoReachable func(stack, dir string) bool
// heldNotify and heldPending (R-1348, appstop_putback_wait.go): the operator mail for a failed put-back. Recover runs
// before the notifier exists, so a hold written then waits in heldPending until SetHeldNotify.
heldNotify func(stack string)
heldPending []string
// liveOp (R-1253) is the operation of THIS process that holds the marker now (set by Begin, cleared by End). The
// marker has one slot; BeginExclusive refuses to replace a live one. A marker left by a crash has no live op.
@@ -119,15 +119,49 @@ func (g *AppStopGuard) holdPutBackFailed(stack, dir string, cause error) bool {
return false
}
h := settings.RestoreHold{Stack: stack, At: g.now().UTC().Format(time.RFC3339), Reason: settings.HoldReasonRestoreMixed,
ReplayError: "interrupted restore, put-back failed: " + cause.Error(), SafetyDump: dir}
ReplayError: "interrupted restore, put-back failed: " + cause.Error(), SafetyDump: dir,
MixedCause: settings.MixedCauseInterruptedPutBack, FailedStep: "putting the interrupted restore's copy back failed: " + cause.Error()}
if err := g.holds.SetRestoreHold(h); err != nil {
g.logger.Printf("[ERROR] [appstop] %s: the failed put-back could not be recorded as a hold: %v — the marker is kept", stack, err)
return false
}
g.logger.Printf("[ERROR] [appstop] %s: the interrupted restore could NOT be put back (%v) — the app is HELD for support, the copy stays at %s (R-1251 H2)", stack, cause, dir)
g.notifyHeld(stack)
return true
}
// SetHeldNotify wires the operator mail for a failed put-back (R-1348; main.go: the R-1340 sentence from the hold record)
// and hands over what Recover held before the notifier existed. Each held app is mailed once. Pinned by TestR1348_* and
// TestR1348_HeldNotifyIsWiredAtStartup.
func (g *AppStopGuard) SetHeldNotify(fn func(stack string)) {
if g == nil {
return
}
g.liveMu.Lock()
g.heldNotify = fn
waiting := g.heldPending
g.heldPending = nil
g.liveMu.Unlock()
if fn == nil {
return
}
for _, stack := range waiting {
fn(stack)
}
}
func (g *AppStopGuard) notifyHeld(stack string) {
g.liveMu.Lock()
fn := g.heldNotify
if fn == nil {
g.heldPending = append(g.heldPending, stack)
}
g.liveMu.Unlock()
if fn != nil {
fn(stack)
}
}
// clearPutBackPending lifts this app's waiting-put-back hold, and only that kind.
func (g *AppStopGuard) clearPutBackPending(stack string) {
if g.holds == nil {
+15
View File
@@ -127,6 +127,15 @@ type Manager struct {
offsiteMoveAside func(ctx context.Context) (string, error)
// offsiteWindow (v0.289.0, decision 68) asks the hub for a clean-up window. nil → no box retention.
offsiteWindow OffsiteWindowClient
// offsiteEndLiving (D72): "installed now, or a protected stack" — nil → no ended app is ever due (offbox_ended.go).
offsiteEndLiving func(app string) bool
// offsiteEndNotify (D84) tells the household ONCE per press that an app's off-site copies are marked for
// deletion. Wired in main.go to the notifier; nil-safe. Called only when a record was really written.
offsiteEndNotify func(rec settings.OffsiteEnd)
// offsiteEndMu guards offsiteEndRemoving: the apps whose off-site copies a clean-up window is removing RIGHT NOW
// (from its last look at the records until its forget has ended). A take-back for such an app is not „kept”.
offsiteEndMu sync.Mutex
offsiteEndRemoving map[string]bool
// offsiteAbandon (v0.290.0, decision 74) hands a due set-aside deletion to the hub.
offsiteAbandon OffsiteAbandonClient
@@ -219,6 +228,9 @@ type Manager struct {
// undoCopyRemover (R-671, v0.272.0) deletes an app's leftover undo copies — stacks.Manager.RemoveUndoCopies,
// wired in main.go (SetUndoCopyRemover). nil-safe: without it the copies stay, as before.
undoCopyRemover func(stackName string) int
// updateHeldForgetter (R-1347) forgets the stack manager's „last update ended held" flag when a restore lifts the update
// hold — stacks.Manager.ForgetUpdateHeld, wired in main.go (SetUpdateHeldForgetter). nil-safe.
updateHeldForgetter func(stackName string) bool
// R-475 update-precondition seams, one per tier. Nil → the real Tier2UnitRestorePoint /
// ListRestorePoints / OffsiteSnapshotTimes. They let a test reach Tier 1 and Tier 3 without a drive
@@ -340,6 +352,9 @@ type Manager struct {
// R-550: persistence of the above (restore_record.go) and the per-app interrupted notices.
opRecordPath string
opInterrupted map[string]RestoreOpResult
// R-1342: the restore copies a stable-start watch still holds (copy dir → true), guarded by mu. While one is here the
// copy is the way back if the restored app turns out unstable: „Törlés most" refuses it (restore_copies.go).
watching map[string]bool
// R-519: the app-data run record (run_record.go) and the start of the last run a stop cut off (zero = none).
runRecordPath string
runInterrupted time.Time
@@ -0,0 +1,185 @@
package backup
import (
"errors"
"os"
"path/filepath"
"testing"
"time"
"gitea.dooplex.hu/admin/felhom-controller/internal/settings"
)
// D62 (operator ruling 2026-10-29): an unused restore copy is kept 30 days; the household sees each copy (app, the
// restore's date, size, the day it goes) and may delete one earlier. A copy a hold or a pending put-back needs is never
// deleted, by the sweep or by hand.
// RED-PROOF: with the age at 14 days the 20-day copy is swept → FAILS; at 30 days only the 31-day copy goes.
func TestD62_AnUnusedCopyIsKept30Days(t *testing.T) {
m, _ := newOffboxManager(t)
now := time.Now()
day29 := r1256Copy(t, m, "a", 29*24*time.Hour, now)
day20 := r1256Copy(t, m, "b", 20*24*time.Hour, now)
day31 := r1256Copy(t, m, "c", 31*24*time.Hour, now)
got := m.SweepUnusedRestoreCopies(now)
if len(got) != 1 || got[0] != day31 {
t.Fatalf("swept %v — want only the 31-day copy %s", got, day31)
}
if !r1256Exists(day29) || !r1256Exists(day20) {
t.Fatal("a copy younger than 30 days was swept")
}
if restoreCopyUnusedAge != 30*24*time.Hour {
t.Fatalf("restoreCopyUnusedAge = %s, D62 says 30 days", restoreCopyUnusedAge)
}
}
// The list shows each copy with its restore date, its size and the day it goes; a needed copy has no such day and
// says why. RED-PROOF: drop the hold check from restoreCopyNeededFor → the held copy is offered → FAILS.
func TestD62_TheListShowsDateSizeAndWhyACopyIsNeeded(t *testing.T) {
m, sett := newOffboxManager(t)
now := time.Now().UTC().Truncate(time.Second)
free := r1256Copy(t, m, "free", 2*24*time.Hour, now)
r1256Copy(t, m, "held", 2*24*time.Hour, now)
r1256Copy(t, m, "waiting", 2*24*time.Hour, now)
r1256Copy(t, m, "named", 2*24*time.Hour, now)
if err := sett.SetRestoreHold(settings.RestoreHold{Stack: "held", At: now.Format(time.RFC3339), Reason: settings.HoldReasonRestoreMixed}); err != nil {
t.Fatal(err)
}
if err := sett.SetRestoreHold(settings.RestoreHold{Stack: "waiting", At: now.Format(time.RFC3339), Reason: settings.HoldReasonPutBackPending}); err != nil {
t.Fatal(err)
}
if err := m.appStop.Begin("unit-restore:named", ReasonUnitRestore, []string{"named"}); err != nil {
t.Fatal(err)
}
list := m.RestoreCopies()
if len(list) != 4 {
t.Fatalf("listed %d copies, want 4: %+v", len(list), list)
}
want := map[string]string{"free": "", "held": RestoreCopyNeededHold, "waiting": RestoreCopyNeededPutBack, "named": RestoreCopyNeededPutBack}
for _, c := range list {
if c.Needed != want[c.App] {
t.Errorf("%s: needed %q, want %q", c.App, c.Needed, want[c.App])
}
if !c.At.Equal(now.Add(-2 * 24 * time.Hour)) {
t.Errorf("%s: restore date %s, want the stamp's %s", c.App, c.At, now.Add(-2*24*time.Hour))
}
if c.SizeBytes != int64(len("LIVE")) {
t.Errorf("%s: size %d", c.App, c.SizeBytes)
}
if c.Needed == "" && !c.DeleteOn.Equal(c.At.Add(30*24*time.Hour)) {
t.Errorf("%s: deleted on %s, want 30 days after the restore", c.App, c.DeleteOn)
}
if c.Needed != "" && !c.DeleteOn.IsZero() {
t.Errorf("%s: a needed copy shows a delete day %s — the sweep never takes it", c.App, c.DeleteOn)
}
if c.App == "free" && c.Path != free {
t.Errorf("path %s, want %s", c.Path, free)
}
}
}
// A held or waiting copy cannot be deleted by hand. RED-PROOF: drop the Needed check in DeleteRestoreCopy → FAILS.
func TestD62_AHeldCopyCannotBeDeleted(t *testing.T) {
m, sett := newOffboxManager(t)
now := time.Now()
for _, tc := range []struct{ app, reason string }{
{"held", settings.HoldReasonRestoreMixed},
{"waiting", settings.HoldReasonPutBackPending},
{"failed", settings.HoldReasonRestoreFailed},
} {
dir := r1256Copy(t, m, tc.app, time.Hour, now)
if err := sett.SetRestoreHold(settings.RestoreHold{Stack: tc.app, At: now.Format(time.RFC3339), Reason: tc.reason}); err != nil {
t.Fatal(err)
}
if _, err := m.DeleteRestoreCopy(tc.app, filepath.Base(dir)); !errors.Is(err, ErrRestoreCopyNeeded) {
t.Errorf("%s: err %v, want ErrRestoreCopyNeeded", tc.app, err)
}
if !r1256Exists(dir) {
t.Errorf("%s: a held copy was deleted", tc.app)
}
}
// a copy a cut restore names (the marker) is needed too
named := r1256Copy(t, m, "named", time.Hour, now)
if err := m.appStop.Begin("unit-restore:named", ReasonUnitRestore, []string{"named"}); err != nil {
t.Fatal(err)
}
if _, err := m.DeleteRestoreCopy("named", filepath.Base(named)); !errors.Is(err, ErrRestoreCopyNeeded) || !r1256Exists(named) {
t.Errorf("a copy the marker names: err %v, exists %v", err, r1256Exists(named))
}
// an unreadable marker offers nothing
mustWrite(t, m.appStop.path, "{not json")
free := r1256Copy(t, m, "free", time.Hour, now)
if _, err := m.DeleteRestoreCopy("free", filepath.Base(free)); !errors.Is(err, ErrRestoreCopyNeeded) || !r1256Exists(free) {
t.Errorf("an unreadable marker: err %v, exists %v", err, r1256Exists(free))
}
}
// A delete removes ONLY that copy: the app's other copy, another app's copy and anything outside the copy tree stay;
// a name that is not one path element, or a link in the copy's place, is refused.
// RED-PROOF: remove the validCopyName check → "../.." reaches outside → FAILS; remove the Lstat link check → the
// link is followed/removed → FAILS.
func TestD62_ADeleteRemovesOnlyThatCopy(t *testing.T) {
m, _ := newOffboxManager(t)
now := time.Now()
one := r1256Copy(t, m, "app", 3*time.Hour, now)
two := r1256Copy(t, m, "app", 2*time.Hour, now)
other := r1256Copy(t, m, "other", 3*time.Hour, now)
got, err := m.DeleteRestoreCopy("app", filepath.Base(one))
if err != nil {
t.Fatal(err)
}
if got.Path != one || got.SizeBytes != int64(len("LIVE")) || got.App != "app" {
t.Fatalf("returned %+v", got)
}
if r1256Exists(one) || !r1256Exists(two) || !r1256Exists(other) {
t.Fatalf("one gone=%v, two kept=%v, other kept=%v", !r1256Exists(one), r1256Exists(two), r1256Exists(other))
}
// path guard
outside := filepath.Join(m.namespaceRoot(m.systemDataPath), "backups", "primary", "keep.txt")
mustWrite(t, outside, "UNIT")
for _, bad := range [][2]string{{"app", ".."}, {"..", "primary"}, {"app", "../../primary"}, {"", "x"}, {"app", ""}, {"app/x", "y"}} {
if _, err := m.DeleteRestoreCopy(bad[0], bad[1]); !errors.Is(err, ErrRestoreCopyNotFound) {
t.Errorf("DeleteRestoreCopy(%q,%q) = %v, want not found", bad[0], bad[1], err)
}
}
if !r1256Exists(outside) || !r1256Exists(two) {
t.Fatal("a bad name reached outside the copy")
}
// a link in a copy's place is not a copy
target := t.TempDir()
mustWrite(t, filepath.Join(target, "precious"), "X")
link := filepath.Join(filepath.Dir(two), "20260101T000000Z")
if err := os.Symlink(target, link); err != nil {
t.Fatal(err)
}
if _, err := m.DeleteRestoreCopy("app", "20260101T000000Z"); !errors.Is(err, ErrRestoreCopyNotFound) {
t.Errorf("a link: %v, want not found", err)
}
if !r1256Exists(filepath.Join(target, "precious")) {
t.Fatal("the link's target was removed")
}
if _, err := m.DeleteRestoreCopy("app", "20990101T000000Z"); !errors.Is(err, ErrRestoreCopyNotFound) {
t.Errorf("a missing copy: %v", err)
}
}
// While a backup or restore runs, a delete is refused and nothing moves. RED-PROOF: drop the busy check → FAILS.
func TestD62_NoDeleteWhileAnOperationRuns(t *testing.T) {
m, _ := newOffboxManager(t)
c := r1256Copy(t, m, "app", time.Hour, time.Now())
m.BeginRestoreOp("restore", "other")
if _, err := m.DeleteRestoreCopy("app", filepath.Base(c)); !errors.Is(err, ErrRestoreCopyBusy) || !r1256Exists(c) {
t.Fatalf("during a restore: err %v, exists %v", err, r1256Exists(c))
}
m.EndRestoreOp(true, "ok")
if err := m.acquireRunning(); err != nil {
t.Fatalf("could not take the backup single-flight: %v", err)
}
if _, err := m.DeleteRestoreCopy("app", filepath.Base(c)); !errors.Is(err, ErrRestoreCopyBusy) || !r1256Exists(c) {
t.Fatalf("during a backup run: err %v, exists %v", err, r1256Exists(c))
}
m.ReleaseRunningForTest()
if _, err := m.DeleteRestoreCopy("app", filepath.Base(c)); err != nil || r1256Exists(c) {
t.Fatalf("control: with nothing running the delete goes through: %v", err)
}
}
+76
View File
@@ -0,0 +1,76 @@
package backup
import (
"errors"
"gitea.dooplex.hu/admin/felhom-controller/internal/settings"
)
// ── D64 = B (operator ruling 2026-10-29 12:10) + R-1343: the operator clears a hold IN THE RUNNING CONTROLLER ──────
//
// One door for both of the operator's routes — the hub's „Clear hold" (operator action clear_hold) and the box command
// `--clear-restore-hold`, which now asks the running controller over its local socket (cmd/controller/holdctl.go).
//
// WHY IN THIS PROCESS (R-1343, measured 2026-10-29 on Tester 1): the CLI used to run as a SECOND process that edited
// settings.json while the running controller kept the hold in its own in-memory Settings — and that controller's next
// save (after a hub report) wrote the hold back. Clearing through the running Settings removes the hold from memory
// AND saves the file at once, so no later save of any component can bring it back.
// Pinned by TestD64_ClearHoldStaysGoneAfterALaterSave (cmd/controller).
//
// EVERY REASON (D64 = B): the hold's reason does not matter — R-379 now reads „a person — on the box, or the operator
// on the hub". One reason needs a second act: a put-back WAITING for its drive (HoldReasonPutBackPending) is also
// recorded in the app-stop marker, and a controller start with the drive bound would pour that old copy back over
// whatever the app wrote after the clear. So the clear also drops the app from the marker; the copy stays on disk
// (nothing is deleted). It runs under resumeMu, so it can never interleave with a put-back of the same app.
// Pinned by TestD64_ClearPutBackPendingDropsTheMarkerEntry.
// ErrHoldBadStack: the argument is not a valid stack name. ErrNotHeld: the app has no hold. Both are refusals —
// nothing was changed.
var (
ErrHoldBadStack = errors.New("not a valid app name")
ErrNotHeld = errors.New("this app has no hold")
)
// IsValidHoldStack reports whether s may name an app for the hold commands (the backup package's strict
// isSafeStackName: letters, digits, '-' and '_', at most 64).
func IsValidHoldStack(s string) bool { return isSafeStackName(s) }
// ClearHoldByOperator lifts stack's hold, whatever its reason, in the hold store the running controller uses, and
// returns the hold it lifted. A waiting put-back is dropped from the app-stop marker too (see above). Refusals
// (ErrHoldBadStack, ErrNotHeld) change nothing.
func (g *AppStopGuard) ClearHoldByOperator(stack string) (settings.RestoreHold, error) {
return g.ClearHoldByOperatorThen(stack, nil)
}
// ClearHoldByOperatorThen is ClearHoldByOperator with beforeLift run once the hold is FOUND and before it is lifted,
// under the same lock (R-1350: the household's „the stop is wanted" is recorded before the hold stops keeping the app out
// of the dead-app scan). beforeLift is not run on a refusal.
func (g *AppStopGuard) ClearHoldByOperatorThen(stack string, beforeLift func()) (settings.RestoreHold, error) {
if !isSafeStackName(stack) {
return settings.RestoreHold{}, ErrHoldBadStack
}
if g == nil || g.holds == nil {
return settings.RestoreHold{}, errors.New("no hold store is wired on this box")
}
resumeMu.Lock()
defer resumeMu.Unlock()
h, ok := g.holds.GetRestoreHold(stack)
if !ok {
return settings.RestoreHold{}, ErrNotHeld
}
if beforeLift != nil {
beforeLift()
}
cleared, err := g.holds.ClearRestoreHold(stack)
if err != nil {
return h, err
}
if !cleared {
return settings.RestoreHold{}, ErrNotHeld
}
if h.Reason == settings.HoldReasonPutBackPending {
g.dropFromMarker(stack)
g.logger.Printf("[WARN] [appstop] %s: its waiting put-back is DROPPED with the hold — the copy stays on disk at %s and is never poured back by itself", stack, h.SafetyDump)
}
return h, nil
}
+26 -5
View File
@@ -301,8 +301,12 @@ func (m *Manager) downloadKeptOffsiteUnit(ctx context.Context, app, drive string
// LoadKeptOffsite is LoadKeptApp from the off-site copy c: download the unit alone, judge it, then
// prepare (nil = nothing; a dated folder's files move back here), then the one unit restore, then
// after(ok). A download failure or a refusal never reaches prepare, so the kept files stay as they were.
func (m *Manager) LoadKeptOffsite(app, drive string, c KeptCopy, prepare func() error, okMsg, failMsg func(err error) string, after func(ok bool)) {
m.BeginRestoreOp("restore", app)
// ErrRestoreBusy (nothing started, after not called) when another operation runs (R-1256 H6).
func (m *Manager) LoadKeptOffsite(app, drive string, c KeptCopy, prepare func() error, okMsg, failMsg func(err error) string, after func(ok bool)) error {
if busy, _ := m.TryBeginRestoreOp("restore", app); busy != "" {
m.logger.Printf("[WARN] [backup] kept load %s REFUSED: a %s operation runs (R-1256)", app, busy)
return ErrRestoreBusy
}
go func() {
start := time.Now()
fail := func(err error) {
@@ -345,6 +349,7 @@ func (m *Manager) LoadKeptOffsite(app, drive string, c KeptCopy, prepare func()
after(true)
}
}()
return nil
}
// RemovedUnitOnDrive is the start-fresh hook (stacks.SetKeptUnitFinder): the removed app's OWN unit when
@@ -370,11 +375,26 @@ func (m *Manager) PrimaryUnitHome(app, drive string) string {
// LoadKeptApp runs the load as a restore operation the backup pages already follow (the poll banner):
// Begin → RestoreFromRecoveryUnitAt(app, unitDir) → End, then after(ok) in the same goroutine (the
// after_load command, the kept folder's tidy-up). The caller has checked RestoreStatus/IsRunning.
func (m *Manager) LoadKeptApp(app, unitDir string, okMsg, failMsg func(err error) string, after func(ok bool)) {
m.BeginRestoreOp("restore", app)
// after_load command, the kept folder's tidy-up). prepare (nil = nothing) runs first, inside the operation — a dated
// folder's files move back there. R-1256 H6: the op is begun in the same step as the check for every other operation;
// a refusal returns ErrRestoreBusy with nothing started and nothing moved.
func (m *Manager) LoadKeptApp(app, unitDir string, prepare func() error, okMsg, failMsg func(err error) string, after func(ok bool)) error {
if busy, _ := m.TryBeginRestoreOp("restore", app); busy != "" {
m.logger.Printf("[WARN] [backup] kept load %s REFUSED: a %s operation runs (R-1256)", app, busy)
return ErrRestoreBusy
}
go func() {
start := time.Now()
if prepare != nil {
if perr := prepare(); perr != nil {
m.logger.Printf("[ERROR] [backup] kept load %s: preparing the kept files FAILED: %v — nothing was loaded", app, perr)
m.EndRestoreOp(false, failMsg(perr))
if after != nil {
after(false)
}
return
}
}
res, err := m.keptUnitRestore()(app, unitDir)
if errors.Is(err, ErrRestoreNotStarted) {
m.keptLoadNotStarted(app, err, after)
@@ -395,6 +415,7 @@ func (m *Manager) LoadKeptApp(app, unitDir string, okMsg, failMsg func(err error
after(true)
}
}()
return nil
}
// keptLoadNotStarted (R-1270): the kept data is loaded but the app did not start in time. Never „done": the record says
+14
View File
@@ -714,6 +714,14 @@ func (m *Manager) OffboxConfigured() bool {
return true
}
// OffboxRepoPasswordOnBox reports whether the off-site repository password FILE is on the box — whatever the target's
// state. R-1218: ClearOffboxTarget keeps that file on purpose, and a switched-off target keeps it too, so a recovery
// ceremony run then must still seal it; OffboxConfigured() is the wrong question for „is there a key to escrow".
func (m *Manager) OffboxRepoPasswordOnBox() bool {
_, err := os.Stat(m.offboxPwPath())
return err == nil
}
// offboxRepoPwPattern matches a valid restic repo password (generateOffboxPassword = 32 rand bytes → 64 hex).
var offboxRepoPwPattern = regexp.MustCompile(`^[0-9a-fA-F]{64}$`)
@@ -1672,6 +1680,11 @@ type OffboxReportStatus struct {
// hub cannot see that and must not infer it. It keeps being sent until the ACK stops reporting a
// superseded package, so a lost request retries by itself rather than leaving the pair half-gone.
// Absent/false on every other box, so a healthy report is byte-identical to v0.205.0's.
// EndedApps (D72/D84, `07` §8.2f part 4) — the pending off-site end records: apps the household removed with
// „delete backup data”, whose off-site copies end 30 days later. The hub starts ITS OWN clock from its own
// records (and, for an app it never saw installed, from the first report that names it here); the dates in
// this list decide nothing there. Absent when there is none, so a report without one is byte-identical.
EndedApps []OffsiteEndedApp `json:"ended_apps,omitempty"`
AbandonPurgeRequested bool `json:"abandon_purge_requested,omitempty"`
LastRun string `json:"last_run,omitempty"` // RFC3339
LastStatus string `json:"last_status,omitempty"` // "ok" | "incomplete" (R-203) | "error" | "running"
@@ -1937,6 +1950,7 @@ func (m *Manager) OffboxReportStatus() *OffboxReportStatus {
LastProofResult: t.LastProofResult,
LastProofReason: t.LastProofReason,
AbandonPurgeRequested: t.AbandonPurgeRequested, // R-241: declared until the hub drops the package
EndedApps: m.OffsiteEndedAppsForReport(), // D72: the pending off-site end records
}
}
+342
View File
@@ -0,0 +1,342 @@
package backup
import (
"errors"
"sort"
"time"
"gitea.dooplex.hu/admin/felhom-controller/internal/settings"
)
// D72 / D84 (`09` §3 decisions 292 and 309; `07-backup-architecture.md` §8.2f, parts 3 and 4) — THE OFF-SITE COPIES OF
// A REMOVED APP END 30 DAYS AFTER „DELETE BACKUP DATA”, IN THE WEEKLY WINDOW AND NOWHERE ELSE.
//
// What this file adds to the clean-up window (offbox_window.go) and what it must never do:
//
// - NO RECORD, NO DELETION. Only an off-site end record (settings.OffsiteEnd, written by the household's press)
// that is DUE makes a snapshot a candidate. A removal that kept the backups, a rebuilt guest, an app removed
// before this existed: there is no record, so there is no candidate.
// - A LIVING APP'S COPY IS NEVER REMOVED BY ANOTHER APP'S END. A snapshot is a candidate only when EVERY app tag
// it carries belongs to a due record — a snapshot with two apps' tags stays until both have ended. The shares
// pseudo-app (`_shares`), the infrastructure stacks and an app that is installed right now are never due.
// - THE HUB AGREES FIRST. The candidates go to the hub with the window request; the box removes ONLY the ids the
// hub sends back (OffsiteWindow.EndedAllowed) — and of those, only ids it named itself in this same window.
// A hub that does not know this (an older hub) sends none, and then nothing of an ended app is removed.
// - ONE GUARD, NO SECOND PATH. The fake-snapshot guard runs first, on the whole repository and on the policy's own
// plan under the window's cap, exactly as before. If it refuses, the ended apps wait with everything else.
// The ended ids are OUTSIDE the cap (D84) and are named apart in the result (removed_for_ended_apps), so the
// hub's 07:10 audit can explain them.
// OffsiteEndedClaim is one due end record as the box sends it with the window request: the app, the record's own
// dates (the hub does not decide by them) and the snapshot ids the box would remove.
type OffsiteEndedClaim struct {
App string `json:"app"`
RemovedAt string `json:"removed_at"`
EndsAt string `json:"ends_at"`
SnapshotIDs []string `json:"snapshot_ids"`
}
// maxEndedClaimIDs is the most snapshot ids ONE window request carries (the hub reads as many: its maxEndedClaimIDs).
const maxEndedClaimIDs = 5000
// OffsiteEndedRefusal is one refusal the hub sent back, in its own words (logged).
type OffsiteEndedRefusal struct {
App string `json:"app"`
Reason string `json:"reason"`
}
// OffsiteEndedApp is one pending end record on the hub report (`offsite.ended_apps`): it lets the hub start its own
// clock for an app it never saw installed (`07` §8.2f part 4). The dates are the box's; the hub decides by its own.
type OffsiteEndedApp struct {
App string `json:"app"`
RemovedAt string `json:"removed_at"`
EndsAt string `json:"ends_at"`
}
// SetOffsiteEndLiving wires "is this app installed on this box right now, or one of the box's own protected stacks".
// An app for which it answers true is never due. NOT WIRED (nil) = NOTHING IS DUE: a box that cannot tell what it
// runs must not delete any app's history. Wired in cmd/controller/main.go; pinned by TestD72_MainWiresTheLivingCheck.
func (m *Manager) SetOffsiteEndLiving(fn func(app string) bool) { m.offsiteEndLiving = fn }
// appTags returns a snapshot's app tags: every tag but the tier's marker.
func appTags(s guardSnap) []string {
var out []string
for _, t := range s.Tags {
if t != "" && t != OffboxMarkerTag {
out = append(out, t)
}
}
return out
}
// dueOffsiteEnds is the PURE first half: the records that may be claimed now. living == nil → none.
func dueOffsiteEnds(ends []settings.OffsiteEnd, now time.Time, living func(string) bool) map[string]settings.OffsiteEnd {
due := map[string]settings.OffsiteEnd{}
if living == nil {
return due
}
for _, e := range ends {
if !settings.ValidOffsiteEndApp(e.App) || e.App == SharesPseudoStack || !e.Due(now) || living(e.App) {
continue
}
due[e.App] = e
}
return due
}
// endedCandidates is the PURE second half: from the repository's snapshots and the due records, the claims to send
// (sorted by app; an app with no candidate is not claimed) and the set of candidate ids.
//
// A snapshot is a candidate only when it carries at least one app tag, EVERY app tag it carries is a due record,
// and it is not younger than any of those records' removal (a snapshot made under that tag AFTER the removal is not
// the removed app's copy — a later install's, or a planted one).
func endedCandidates(snaps []guardSnap, due map[string]settings.OffsiteEnd) (claims []OffsiteEndedClaim, candidate map[string]bool) {
candidate = map[string]bool{}
byApp := map[string][]string{}
for _, s := range snaps {
apps := appTags(s)
if len(apps) == 0 || s.ID == "" {
continue
}
ok := true
for _, a := range apps {
e, isDue := due[a]
if !isDue || s.Time.After(e.Removed().Add(offsiteGuardSkew)) {
ok = false
break
}
}
if !ok {
continue
}
candidate[s.ID] = true
for _, a := range apps {
byApp[a] = append(byApp[a], s.ID)
}
}
for app, ids := range byApp {
sort.Strings(ids)
e := due[app]
claims = append(claims, OffsiteEndedClaim{App: app, RemovedAt: e.RemovedAt, EndsAt: e.EndsAt, SnapshotIDs: ids})
}
sort.Slice(claims, func(i, j int) bool { return claims[i].App < claims[j].App })
return claims, candidate
}
// endedToRemove is the PURE third half: of the ids the hub agreed to, those the box itself named as candidates in
// this window and that the policy's own plan does not already remove (those stay under the cap). Sorted.
func endedToRemove(allowed []string, candidate map[string]bool, policyIDs []string) []string {
inPolicy := make(map[string]bool, len(policyIDs))
for _, id := range policyIDs {
inPolicy[id] = true
}
seen := map[string]bool{}
var out []string
for _, id := range allowed {
if candidate[id] && !inPolicy[id] && !seen[id] {
seen[id] = true
out = append(out, id)
}
}
sort.Strings(out)
return out
}
// appStillInStore reports whether any snapshot still carries app's tag.
func appStillInStore(snaps []guardSnap, app string) bool {
for _, s := range snaps {
for _, t := range s.Tags {
if t == app {
return true
}
}
}
return false
}
// dropEndsWithNoCopies deletes the due records of apps that have NO snapshot in the repository at all: there is
// nothing to end, and a record that can never complete would be asked of the hub every week for ever. It writes no
// history line (nothing was deleted). Called only after a listing that succeeded.
func (m *Manager) dropEndsWithNoCopies(snaps []guardSnap, due map[string]settings.OffsiteEnd) {
for app, e := range due {
if appStillInStore(snaps, app) {
continue
}
if done, err := m.settings.CompleteOffsiteEnd(app, e.RemovedAt, m.now(), 0); err != nil {
m.logger.Printf("[WARN] [offbox] ended app %s: the store holds no copy of it, but its end record could not be closed: %v", app, err)
} else if done {
m.logger.Printf("[INFO] [offbox] ended app %s: the off-site store holds no copy of it — its end record is closed, nothing was deleted", app)
}
delete(due, app)
}
}
// completeOffsiteEnds closes the record of every app whose copies this window removed: at least one of its claimed
// ids is gone and no snapshot carries its tag any more. An app that still has a snapshot (one shared with a living
// app, or one the hub did not agree to) keeps its record and is asked again at the next window.
func (m *Manager) completeOffsiteEnds(claims []OffsiteEndedClaim, removed []string, after []guardSnap) {
gone := make(map[string]bool, len(removed))
for _, id := range removed {
gone[id] = true
}
for _, c := range claims {
n := 0
for _, id := range c.SnapshotIDs {
if gone[id] {
n++
}
}
if n == 0 || appStillInStore(after, c.App) {
continue
}
if _, err := m.settings.CompleteOffsiteEnd(c.App, c.RemovedAt, m.now(), n); err != nil {
m.logger.Printf("[WARN] [offbox] ended app %s: its %d off-site snapshot(s) are removed, but the end record could not be closed: %v", c.App, n, err)
}
}
}
// OffsiteEndedAppsForReport returns the pending end records for the hub report.
func (m *Manager) OffsiteEndedAppsForReport() []OffsiteEndedApp {
var out []OffsiteEndedApp
for _, e := range m.settings.GetOffsiteEnds() {
out = append(out, OffsiteEndedApp{App: e.App, RemovedAt: e.RemovedAt, EndsAt: e.EndsAt})
}
return out
}
// ── The household's side: the press, the take-back, the date ────────────────────────────────────────────────────────
// ErrOffsiteEndNotOffered: this box has no hub-provisioned off-site tier, so there is no weekly window that could
// carry the deletion out — and no record is written. (The household's own NAS target is pruned by the box itself and
// keeps a removed app's copies, as before: `07` §8.2f.)
var ErrOffsiteEndNotOffered = errors.New("no hub-provisioned off-site tier on this box")
// ErrOffsiteEndLiving: the app is installed right now, is one of the box's own stacks, or the box cannot tell.
var ErrOffsiteEndLiving = errors.New("the app is installed or is not an app a household removes")
// OffsiteEndOffered reports whether a press can start the 30 days here: the box has the hub-provisioned tier
// (switched on or not — a tier that is off only makes the deletion wait).
func (m *Manager) OffsiteEndOffered() bool {
return m != nil && m.settings != nil && m.settings.GetOffboxTarget().Pinned()
}
// SetOffsiteEndNotify wires the household's one mail per press (D84).
func (m *Manager) SetOffsiteEndNotify(fn func(rec settings.OffsiteEnd)) { m.offsiteEndNotify = fn }
// OffsiteEndDateIfPressedNow is the date the remove dialog shows BEFORE the press.
func (m *Manager) OffsiteEndDateIfPressedNow() time.Time {
return m.now().Add(settings.OffsiteEndAfter)
}
// StartOffsiteEnd is THE press: „delete backup data” at a removal, or „delete in 30 days” on the Backups page. It
// writes the end record and tells the household once. A second press for the same app changes nothing and tells
// nobody (created == false). The ONLY writer of an end record.
func (m *Manager) StartOffsiteEnd(app string) (rec settings.OffsiteEnd, created bool, err error) {
if !m.OffsiteEndOffered() {
return settings.OffsiteEnd{}, false, ErrOffsiteEndNotOffered
}
if !settings.ValidOffsiteEndApp(app) || app == SharesPseudoStack || m.offsiteEndLiving == nil || m.offsiteEndLiving(app) {
return settings.OffsiteEnd{}, false, ErrOffsiteEndLiving
}
rec, created, err = m.settings.StartOffsiteEnd(app, m.now())
if err != nil || !created {
return rec, false, err
}
if m.offsiteEndNotify != nil {
m.offsiteEndNotify(rec)
}
return rec, true, nil
}
// KeepOffsiteCopies is „keep it after all”: it deletes the end record. Returns whether there was one TO KEEP: false
// also while a clean-up window is removing this app's copies right now (its last look at the records is behind it) —
// the page then says „not marked, or already deleted”, never „kept” over copies that are going.
func (m *Manager) KeepOffsiteCopies(app string) (bool, error) {
m.offsiteEndMu.Lock()
defer m.offsiteEndMu.Unlock()
if m.offsiteEndRemoving[app] {
m.logger.Printf("[WARN] [offbox] keep-after-all for %s came while the clean-up window is removing its off-site copies — too late, not kept", app)
return false, nil
}
return m.settings.CancelOffsiteEnd(app, "the household keeps the copies")
}
// lastLookAtEnded reads the end records AGAIN, immediately before the forget, and keeps of the agreed ids only those
// whose EVERY app still has the SAME record (app and removed_at), still due, still not installed. It returns the ids
// and the claims that are left, and marks those apps as „being removed” until endedRemovalOver. One lock with
// KeepOffsiteCopies, so a take-back is either before this look (its record is gone: its ids are taken out here) or
// after it (answered „too late”).
//
// NOT covered, said plainly: an INSTALL of the app during the forget itself. It deletes the record through settings
// (stacks.SaveAppConfig), restic is already removing, and the copies go. The window is one `forget … --prune`.
func (m *Manager) lastLookAtEnded(snaps []guardSnap, claims []OffsiteEndedClaim, endedIDs []string) ([]string, []OffsiteEndedClaim) {
m.offsiteEndMu.Lock()
defer m.offsiteEndMu.Unlock()
m.offsiteEndRemoving = nil
if len(endedIDs) == 0 {
return nil, claims
}
due := dueOffsiteEnds(m.settings.GetOffsiteEnds(), m.now(), m.offsiteEndLiving)
claimed := make(map[string]string, len(claims))
for _, c := range claims {
claimed[c.App] = c.RemovedAt
}
for app, e := range due {
if at, ok := claimed[app]; !ok || at != e.RemovedAt {
delete(due, app) // a record this window did not claim, or one written anew since: not this window's
}
}
var left []OffsiteEndedClaim
for _, c := range claims {
if _, ok := due[c.App]; ok {
left = append(left, c)
} else {
m.logger.Printf("[WARN] [offbox] ended app %s: its end record changed while the window was being prepared (taken back, installed again, or written anew) — nothing of it is removed", c.App)
}
}
_, candidate := endedCandidates(snaps, due)
var ids []string
for _, id := range endedIDs {
if candidate[id] {
ids = append(ids, id)
}
}
if len(ids) > 0 {
m.offsiteEndRemoving = map[string]bool{}
for app := range due {
m.offsiteEndRemoving[app] = true
}
}
return ids, left
}
// endedRemovalOver ends the „being removed” mark (the forget has ended, whatever its result).
func (m *Manager) endedRemovalOver() {
m.offsiteEndMu.Lock()
m.offsiteEndRemoving = nil
m.offsiteEndMu.Unlock()
}
// PendingOffsiteEnds and OffsiteEndsHistory are what the Backups page shows.
func (m *Manager) PendingOffsiteEnds() []settings.OffsiteEnd { return m.settings.GetOffsiteEnds() }
func (m *Manager) OffsiteEndsHistory() []settings.OffsiteEndDone {
return m.settings.GetOffsiteEndsDone()
}
// boundEndedClaims cuts a request to at most limit snapshot ids in all (the hub reads no more). What is cut is asked
// again in a later window: the record stays while a copy of the app is in the store.
func boundEndedClaims(claims []OffsiteEndedClaim, limit int) []OffsiteEndedClaim {
left := limit
var out []OffsiteEndedClaim
for _, c := range claims {
if left <= 0 {
break
}
if len(c.SnapshotIDs) > left {
c.SnapshotIDs = c.SnapshotIDs[:left]
}
left -= len(c.SnapshotIDs)
out = append(out, c)
}
return out
}
@@ -0,0 +1,135 @@
package backup
import (
"context"
"strings"
"testing"
"gitea.dooplex.hu/admin/felhom-controller/internal/settings"
)
// Review of 2026-11-15, finding 2: the due records and the candidates were read ONCE, before the hub was asked, and
// never again before the forget. A take-back („Mégis megtartom”) or an install in that interval — the hub's answer,
// the dry run, the guard: seconds to minutes — still lost the copies, while the page had just said „the off-site
// copies are kept”. The window now reads the records again IMMEDIATELY before the forget.
// RED-PROOF: felhom.eu/documentation/audits/build-release-4-2026-11-15/A/redproof-review-2.txt.
// racingHub runs `during` while the hub answers — after the box has sent its claims, before it removes anything.
type racingHub struct {
*agreeingHub
during func()
}
func (h *racingHub) Open(ctx context.Context, n int, ended []OffsiteEndedClaim) (OffsiteWindow, error) {
w, err := h.agreeingHub.Open(ctx, n, ended)
h.during()
return w, err
}
func TestD72_ATakeBackDuringTheWindowKeepsTheCopies(t *testing.T) {
m, sett, er, hub := endedBox(t, "immich")
pressed(t, sett, "kimai", 31)
pressed(t, sett, "vikunja", 31)
m.SetOffsiteWindowClient(&racingHub{agreeingHub: hub, during: func() {
if kept, err := m.KeepOffsiteCopies("kimai"); err != nil || !kept {
t.Fatalf("keep: %v %v", kept, err)
}
}})
m.offsiteWindowRetention(context.Background(), nil, nil, "after-run")
if len(hub.claims) != 2 {
t.Fatalf("fixture: both apps must have been claimed before the take-back, got %+v", hub.claims)
}
if _, ok := sett.GetOffsiteEnd("kimai"); ok {
t.Fatal("fixture: the take-back did not delete the record")
}
got := er.removedIDs()
for _, id := range got {
if id == "k1-full" {
t.Fatalf("the page said „the off-site copies are kept”, no record exists, and the window removed kimai's copy (%v)", got)
}
}
// the OTHER app's end is not disturbed by the take-back
if strings.Join(got, ",") != strings.Join(ids("v1", "v2", "v3"), ",") {
t.Fatalf("removed %v, want vikunja's three and nothing of kimai", got)
}
if r := hub.closed[0].RemovedForEndedApps; strings.Join(r, ",") != strings.Join(ids("v1", "v2", "v3"), ",") {
t.Fatalf("removed_for_ended_apps = %v", r)
}
}
// The same interval, an INSTALL: the record is deleted by the install (stacks) and the app is living again.
func TestD72_AnInstallDuringTheWindowKeepsTheCopies(t *testing.T) {
for _, how := range []string{"the install deleted the record", "the app is living again (the record is still there)", "removed again: a NEW record with a new time"} {
t.Run(how, func(t *testing.T) {
m, sett, er, hub := endedBox(t, "immich")
pressed(t, sett, "kimai", 31)
live := map[string]bool{"immich": true}
m.SetOffsiteEndLiving(func(app string) bool { return live[app] })
m.SetOffsiteWindowClient(&racingHub{agreeingHub: hub, during: func() {
switch how {
case "the install deleted the record":
if _, err := sett.CancelOffsiteEnd("kimai", "the app is installed again"); err != nil {
t.Fatal(err)
}
live["kimai"] = true
case "the app is living again (the record is still there)":
live["kimai"] = true
default: // installed, removed again with „delete backup data”: the 30 days start again
if _, err := sett.CancelOffsiteEnd("kimai", "the app is installed again"); err != nil {
t.Fatal(err)
}
if _, _, err := sett.StartOffsiteEnd("kimai", m.now()); err != nil {
t.Fatal(err)
}
}
}})
m.offsiteWindowRetention(context.Background(), nil, nil, "after-run")
if len(hub.claims) != 1 {
t.Fatalf("fixture: kimai must have been claimed first: %+v", hub.claims)
}
if got := er.removedIDs(); len(got) != 0 {
t.Fatalf("the window removed %v of an app that was installed again while the hub answered", got)
}
if len(sett.GetOffsiteEndsDone()) != 0 {
t.Fatalf("a history line for an end that did not happen: %+v", sett.GetOffsiteEndsDone())
}
})
}
}
// A take-back that comes while the forget itself runs is TOO LATE, and the page must not say „kept”: the answer is
// „nothing to keep”, the record stays for the window to close, and the copies go as the window had decided.
func TestD72_ATakeBackDuringTheForgetIsNotAnsweredKept(t *testing.T) {
m, sett, er, hub := endedBox(t, "immich")
pressed(t, sett, "kimai", 31)
base := er.run
var keptAnswer, asked bool
m.SetOffboxRunner(func(ctx context.Context, env []string, args ...string) ([]byte, error) {
if contains(args, "forget") && !contains(args, "--dry-run") {
k, err := m.KeepOffsiteCopies("kimai")
if err != nil {
t.Fatal(err)
}
keptAnswer, asked = k, true
}
return base(ctx, env, args...)
})
m.offsiteWindowRetention(context.Background(), nil, nil, "after-run")
if !asked || keptAnswer {
t.Fatalf("asked=%v kept=%v — a take-back during the forget was answered „kept” while the copies were being removed", asked, keptAnswer)
}
if got := er.removedIDs(); strings.Join(got, ",") != strings.Join(ids("k1"), ",") {
t.Fatalf("removed %v", got)
}
if _, ok := sett.GetOffsiteEnd("kimai"); ok || len(sett.GetOffsiteEndsDone()) != 1 {
t.Fatalf("the end must be closed as carried out: pending=%v history=%+v", ok, sett.GetOffsiteEndsDone())
}
// after the window the mark is gone: a later record can be taken back again
pressed(t, sett, "vikunja", 1)
if k, err := m.KeepOffsiteCopies("vikunja"); err != nil || !k {
t.Fatalf("after the window a take-back must work again: %v %v", k, err)
}
_ = hub
}
var _ = settings.OffsiteEndAfter
@@ -0,0 +1,86 @@
package backup
import (
"context"
"fmt"
"strings"
"testing"
"time"
)
// Review of 2026-11-15, finding 5 — VERSION SKEW. A new box with an older hub: the window request with `ended` can
// pass that hub's 4 KiB read limit (about 55 ids); the hub then reads no count, opens the window with the smallest
// cap, and the guard refuses the honest plan every week — the ordinary clean-up stalls. The box now sends its end
// records ONLY to a hub that said, in its last window answer, that it reads them.
// RED-PROOF: felhom.eu/documentation/audits/build-release-4-2026-11-15/A/redproof-review-5.txt.
func TestD84_ANewBoxWithAnOlderHub_NothingEndedIsSentAndTheCleanUpStillRuns(t *testing.T) {
m, sett, er, hub := endedBox(t, "immich")
if err := sett.SetOffsiteHubAcceptsEnded(false); err != nil { // a box that has never heard a hub say it
t.Fatal(err)
}
hub.oldHub = true
pressed(t, sett, "vikunja", 31)
old := time.Now().Add(-60 * 24 * time.Hour)
er.plan = []guardSnap{tagged("p1", old, "immich"), tagged("p2", old.Add(time.Minute), "immich")} // the week's honest plan
er.snaps = append(er.snaps, er.plan...)
for week := 1; week <= 2; week++ {
m.offsiteWindowRetention(context.Background(), nil, nil, "after-run")
if len(hub.claims) != 0 {
t.Fatalf("week %d: the box sent %d end record(s) to a hub that never said it reads them — that hub reads 4 KiB and would stall", week, len(hub.claims))
}
er.plan = nil // the policy's two are gone after the first window (the fake's plan does not follow by itself)
}
// the ordinary weekly clean-up ran: the policy's two went in the first window, and nothing of the removed app
if got := er.removedIDs(); strings.Join(got, ",") != strings.Join(ids("p1", "p2"), ",") {
t.Fatalf("removed %v, want the policy's own two and nothing of the removed app", got)
}
if hub.closed[0].Outcome != "pruned" || len(hub.closed[0].RemovedForEndedApps) != 0 {
t.Fatalf("the first window: %+v", hub.closed[0])
}
if _, ok := sett.GetOffsiteEnd("vikunja"); !ok {
t.Fatal("the record was lost while the hub could not be asked")
}
// The hub is updated. An ordinary night's answer (not granted) says accepts_ended; the next window carries the
// end records, and the removed app's copies go.
hub.oldHub, hub.notGranted = false, true
m.offsiteWindowRetention(context.Background(), nil, nil, "after-run")
if len(hub.claims) != 0 || !sett.GetOffsiteHubAcceptsEnded() {
t.Fatalf("the night the box LEARNS it: claims=%d learned=%v — it must send none yet and remember the answer", len(hub.claims), sett.GetOffsiteHubAcceptsEnded())
}
hub.notGranted = false
m.offsiteWindowRetention(context.Background(), nil, nil, "after-run")
if len(hub.claims) != 1 || hub.claims[0].App != "vikunja" {
t.Fatalf("after the hub said it reads end records the box sent %+v", hub.claims)
}
if got := er.removedIDs(); len(got) != 5 {
t.Fatalf("removed %v, want the policy's two and vikunja's three", got)
}
// … and if the hub is rolled BACK, the box stops sending at once after the first answer without the word
pressed(t, sett, "kimai", 31)
hub.oldHub = true
m.offsiteWindowRetention(context.Background(), nil, nil, "after-run") // this one still carries claims (the box had heard yes)
m.offsiteWindowRetention(context.Background(), nil, nil, "after-run")
if len(hub.claims) != 0 || sett.GetOffsiteHubAcceptsEnded() {
t.Fatalf("after a rolled-back hub's answer the box still sends end records: claims=%d learned=%v", len(hub.claims), sett.GetOffsiteHubAcceptsEnded())
}
}
// One request never carries more ids than the hub reads (5000): the rest go in a later window.
func TestD84_OneRequestCarriesABoundedNumberOfIds(t *testing.T) {
m, sett, er, hub := endedBox(t, "immich")
pressed(t, sett, "bigapp", 31)
old := time.Now().Add(-60 * 24 * time.Hour)
for i := 0; i < maxEndedClaimIDs+200; i++ {
er.snaps = append(er.snaps, tagged(fmt.Sprintf("b%05d", i), old, "bigapp"))
}
hub.notGranted = true
m.offsiteWindowRetention(context.Background(), nil, nil, "after-run")
n := 0
for _, c := range hub.claims {
n += len(c.SnapshotIDs)
}
if n != maxEndedClaimIDs {
t.Fatalf("one request carried %d snapshot ids, want the limit %d", n, maxEndedClaimIDs)
}
}
@@ -0,0 +1,579 @@
package backup
import (
"context"
"os"
"path/filepath"
"sort"
"strings"
"testing"
"time"
"gitea.dooplex.hu/admin/felhom-controller/internal/settings"
)
// D72 / D84 (`09` §3 decisions 292 and 309; `07-backup-architecture.md` §8.2f): the off-site copies of a removed app
// end 30 days after „delete backup data”, in the weekly window, for ids the hub agreed to. restic is the package's
// fake runner (as in offbox_window_test.go); here it keeps state, so a forget really removes what it names.
// RED-PROOFS: felhom.eu/documentation/audits/build-release-4-2026-11-15/A/redproof-ctrl-window.txt.
// endedRunner: `snapshots` lists what is left, `forget --dry-run` gives the policy's plan, a real `forget` removes
// the ids it names (and is recorded).
type endedRunner struct {
snaps []guardSnap
plan []guardSnap
forgets [][]string
}
func (e *endedRunner) run(_ context.Context, _ []string, args ...string) ([]byte, error) {
switch {
case contains(args, "forget") && contains(args, "--dry-run"):
return planJSON(e.plan), nil
case contains(args, "forget"):
e.forgets = append(e.forgets, append([]string{}, args...))
gone := map[string]bool{}
for _, a := range args {
gone[a] = true
}
var left []guardSnap
for _, s := range e.snaps {
if !gone[s.ID] {
left = append(left, s)
}
}
e.snaps = left
return nil, nil
case contains(args, "snapshots"):
return snapJSON(e.snaps), nil
}
return nil, nil
}
// removedIDs are the snapshot ids every real forget named, sorted.
func (e *endedRunner) removedIDs() []string {
var out []string
for _, f := range e.forgets {
for _, a := range f {
if strings.HasSuffix(a, "-full") {
out = append(out, a)
}
}
}
sort.Strings(out)
return out
}
func tagged(id string, at time.Time, tags ...string) guardSnap {
s := snap(id, at)
s.Tags = append([]string{OffboxMarkerTag}, tags...)
return s
}
func ids(names ...string) []string {
out := make([]string, 0, len(names))
for _, n := range names {
out = append(out, n+"-full")
}
sort.Strings(out)
return out
}
// agreeingHub is the fake hub: it grants the window and agrees to exactly the ids in `allow` — or, with allowAll, to
// EVERY id in the repository (a hub that would agree to anything: the box must still remove only its own candidates).
type agreeingHub struct {
fakeWindow
allow []string
allowAll func() []string
refuse []OffsiteEndedRefusal
maxRm int
// oldHub: a hub from before ended apps — it never says accepts_ended. notGranted: the answer of an ordinary night.
oldHub bool
notGranted bool
}
func (h *agreeingHub) Open(ctx context.Context, n int, ended []OffsiteEndedClaim) (OffsiteWindow, error) {
h.opened++
h.claims = ended
w := OffsiteWindow{Granted: true, ID: 7, NewestAllowed: time.Now(), MaxRemove: h.maxRm, EndedAllowed: h.allow, EndedRefused: h.refuse, AcceptsEnded: !h.oldHub}
if h.notGranted {
w = OffsiteWindow{Reason: "not due", AcceptsEnded: !h.oldHub}
}
if h.allowAll != nil {
w.EndedAllowed = h.allowAll()
}
return w, nil
}
// endedBox: a pinned box whose living check says `living` apps are installed. The repository, 60 days old:
// vikunja ×3 (v1..v3), immich ×2 (i1,i2), one snapshot of BOTH (vi), the shares (s1), kimai ×1 (k1).
func endedBox(t *testing.T, living ...string) (*Manager, *settings.Settings, *endedRunner, *agreeingHub) {
t.Helper()
m, sett := newOffboxManager(t)
pinTarget(t, sett)
old := time.Now().Add(-60 * 24 * time.Hour)
er := &endedRunner{snaps: []guardSnap{
tagged("v1", old, "vikunja"), tagged("v2", old.Add(time.Hour), "vikunja"), tagged("v3", old.Add(2*time.Hour), "vikunja"),
tagged("i1", old, "immich"), tagged("i2", old.Add(time.Hour), "immich"),
tagged("vi", old, "vikunja", "immich"),
tagged("s1", old, SharesPseudoStack),
tagged("k1", old, "kimai"),
}}
m.SetOffboxRunner(er.run)
if err := sett.SetOffsiteHubAcceptsEnded(true); err != nil { // the box has heard this hub say it knows ended apps
t.Fatal(err)
}
hub := &agreeingHub{maxRm: 5}
hub.allowAll = func() []string {
var all []string
for _, s := range er.snaps {
all = append(all, s.ID)
}
return all
}
m.SetOffsiteWindowClient(hub)
live := map[string]bool{}
for _, l := range living {
live[l] = true
}
m.SetOffsiteEndLiving(func(app string) bool { return live[app] })
return m, sett, er, hub
}
// pressed writes an end record as the household's press `daysAgo` days ago.
func pressed(t *testing.T, sett *settings.Settings, app string, daysAgo int) settings.OffsiteEnd {
t.Helper()
rec, created, err := sett.StartOffsiteEnd(app, time.Now().Add(-time.Duration(daysAgo)*24*time.Hour))
if err != nil || !created {
t.Fatalf("press for %s: created=%v err=%v", app, created, err)
}
return rec
}
// MUST-HOLD 1 — NO RECORD, NO DELETION, EVER. The hub here agrees to EVERY id in the repository, and still nothing is
// removed: a removal that kept the backups, a rebuilt guest and an app removed before this was built all look the
// same on the box — there is no record.
func TestD72_NoRecordNoDeletion(t *testing.T) {
for _, name := range []string{
"removed without „delete backup data”",
"a rebuilt guest (its settings are new)",
"an app removed before this was built",
} {
t.Run(name, func(t *testing.T) {
m, _, er, hub := endedBox(t, "immich")
m.offsiteWindowRetention(context.Background(), nil, nil, "after-run")
if hub.opened != 1 || len(hub.claims) != 0 {
t.Fatalf("opened=%d claims=%+v — with no record the box must claim nothing", hub.opened, hub.claims)
}
if got := er.removedIDs(); len(got) != 0 {
t.Fatalf("with NO end record the window removed %v", got)
}
if len(er.snaps) != 8 {
t.Fatalf("%d snapshots left of 8", len(er.snaps))
}
if len(hub.closed) != 1 || len(hub.closed[0].RemovedForEndedApps) != 0 {
t.Fatalf("the result names ended removals: %+v", hub.closed)
}
})
}
}
// MUST-HOLD 3 and 5 — the due app's own snapshots go, by id, in the window; the snapshot it shares with a living
// app, the living app's snapshots and the shares stay; the result names them apart; the record becomes history.
func TestD72_TheEndedAppsOwnSnapshotsGoAndNothingElse(t *testing.T) {
m, sett, er, hub := endedBox(t, "immich")
rec := pressed(t, sett, "vikunja", 31)
m.offsiteWindowRetention(context.Background(), nil, nil, "after-run")
if len(hub.claims) != 1 || hub.claims[0].App != "vikunja" || strings.Join(hub.claims[0].SnapshotIDs, ",") != strings.Join(ids("v1", "v2", "v3"), ",") {
t.Fatalf("the claim sent to the hub = %+v, want vikunja with v1,v2,v3 only (not the snapshot shared with immich)", hub.claims)
}
if hub.claims[0].RemovedAt != rec.RemovedAt || hub.claims[0].EndsAt != rec.EndsAt {
t.Fatalf("the claim does not carry the record's dates: %+v vs %+v", hub.claims[0], rec)
}
if got := er.removedIDs(); strings.Join(got, ",") != strings.Join(ids("v1", "v2", "v3"), ",") {
t.Fatalf("removed %v, want exactly vikunja's own three", got)
}
left := map[string]bool{}
for _, s := range er.snaps {
left[s.ShortID] = true
}
for _, keep := range []string{"i1", "i2", "vi", "s1", "k1"} {
if !left[keep] {
t.Errorf("%s was removed — a living app's copy, the shares, or another app's", keep)
}
}
if len(er.forgets) != 1 || !contains(er.forgets[0], "--prune") {
t.Fatalf("want ONE forget … --prune (the window's own call), got %v", er.forgets)
}
if len(hub.closed) != 1 {
t.Fatalf("the window was not closed once: %+v", hub.closed)
}
r := hub.closed[0]
if r.Outcome != "pruned" || r.CountBefore != 8 || r.CountAfter != 5 || strings.Join(r.RemovedForEndedApps, ",") != strings.Join(ids("v1", "v2", "v3"), ",") {
t.Fatalf("result = %+v, want pruned 8 -> 5 with removed_for_ended_apps = v1,v2,v3", r)
}
// vikunja still has the shared snapshot in the store, so its record stays pending (asked again next week).
if _, ok := sett.GetOffsiteEnd("vikunja"); !ok {
t.Fatal("the record was closed although a snapshot with vikunja's tag is still in the store")
}
if len(sett.GetOffsiteEndsDone()) != 0 {
t.Fatalf("a history line was written while a copy is left: %+v", sett.GetOffsiteEndsDone())
}
}
// A snapshot with two apps' tags goes only when BOTH have ended — and then the records become history.
func TestD72_ASharedSnapshotGoesWhenBothHaveEnded(t *testing.T) {
m, sett, er, hub := endedBox(t) // nothing is installed
pressed(t, sett, "vikunja", 40)
pressed(t, sett, "immich", 31)
m.offsiteWindowRetention(context.Background(), nil, nil, "after-run")
if got := er.removedIDs(); strings.Join(got, ",") != strings.Join(ids("i1", "i2", "v1", "v2", "v3", "vi"), ",") {
t.Fatalf("removed %v, want both apps' snapshots and the shared one", got)
}
if len(er.snaps) != 2 {
t.Fatalf("left %d, want the shares and kimai", len(er.snaps))
}
if n := len(sett.GetOffsiteEnds()); n != 0 {
t.Fatalf("%d record(s) still pending after every copy went", n)
}
h := sett.GetOffsiteEndsDone()
if len(h) != 2 {
t.Fatalf("history = %+v, want one line per app", h)
}
got := map[string]int{}
for _, d := range h {
got[d.App] = d.Snapshots
}
if got["vikunja"] != 4 || got["immich"] != 3 {
t.Fatalf("history counts = %v, want vikunja 4 (three + the shared), immich 3", got)
}
_ = hub
}
// MUST-HOLD 3 — `_shares` and the box's own stacks are never eligible, even with a record that somehow exists.
func TestD72_SharesAndInfraAreNeverEligible(t *testing.T) {
now := time.Now()
old := now.Add(-60 * 24 * time.Hour)
rec := func(app string) settings.OffsiteEnd {
return settings.OffsiteEnd{App: app, RemovedAt: now.Add(-40 * 24 * time.Hour).Format(time.RFC3339), EndsAt: now.Add(-10 * 24 * time.Hour).Format(time.RFC3339)}
}
living := func(app string) bool { return app == "traefik" } // the box's own stacks answer true (main.go: IsProtectedStack)
due := dueOffsiteEnds([]settings.OffsiteEnd{rec(SharesPseudoStack), rec(OffboxMarkerTag), rec("traefik"), rec("vikunja")}, now, living)
if len(due) != 1 || due["vikunja"].App != "vikunja" {
t.Fatalf("due = %v, want vikunja only", due)
}
claims, cand := endedCandidates([]guardSnap{tagged("s1", old, SharesPseudoStack), tagged("t1", old, "traefik"), tagged("v1", old, "vikunja"),
{ID: "u1-full", ShortID: "u1", Time: old, Tags: []string{OffboxMarkerTag}}, {ID: "n1-full", ShortID: "n1", Time: old}}, due)
if len(claims) != 1 || len(cand) != 1 || !cand["v1-full"] {
t.Fatalf("claims=%+v candidates=%v — the shares, an infra stack, a marker-only and an untagged snapshot are never candidates", claims, cand)
}
// and no such record can be written by the press
m, sett, _, _ := endedBox(t, "traefik")
for _, app := range []string{SharesPseudoStack, OffboxMarkerTag, "traefik"} {
if _, created, err := m.StartOffsiteEnd(app); err == nil || created {
t.Errorf("%q got an end record", app)
}
}
if n := len(sett.GetOffsiteEnds()); n != 0 {
t.Fatalf("%d record(s) written", n)
}
}
// MUST-HOLD 2, the box's half — THE BOX REMOVES ONLY WHAT THE HUB AGREED TO. An older hub (no answer), a refusal, and
// a box whose clock is a month ahead (it asks on day 2; the hub, by its own clock, refuses): nothing of the app goes
// and the record stays for the next window.
func TestD84_TheBoxRemovesOnlyWhatTheHubAgreedTo(t *testing.T) {
for _, c := range []struct {
name string
allow []string
refuse []OffsiteEndedRefusal
want []string
}{
{"a hub that does not know ended apps answers nothing", nil, nil, nil},
{"the hub refuses the app (the box's clock is a month ahead: absent 2 days by the hub's clock)", nil,
[]OffsiteEndedRefusal{{App: "vikunja", Reason: "the hub has seen the app absent since … — 2 full day(s), 30 needed"}}, nil},
{"the hub agrees to two of the three ids", ids("v1", "v3"), nil, ids("v1", "v3")},
{"the hub „agrees” to ids the box never named (a living app's, the shares)", ids("i1", "i2", "s1", "vi", "v2"), nil, ids("v2")},
} {
t.Run(c.name, func(t *testing.T) {
m, sett, er, hub := endedBox(t, "immich")
hub.allowAll, hub.allow, hub.refuse = nil, c.allow, c.refuse
pressed(t, sett, "vikunja", 31)
m.offsiteWindowRetention(context.Background(), nil, nil, "after-run")
if got := er.removedIDs(); strings.Join(got, ",") != strings.Join(c.want, ",") {
t.Fatalf("removed %v, want %v", got, c.want)
}
if _, ok := sett.GetOffsiteEnd("vikunja"); !ok {
t.Fatal("the record is gone although copies of the app are left — the next window could not finish the job")
}
if got := hub.closed[0].RemovedForEndedApps; strings.Join(got, ",") != strings.Join(c.want, ",") {
t.Fatalf("removed_for_ended_apps = %v, want %v", got, c.want)
}
})
}
}
// MUST-HOLD 5 — BEHIND THE SAME GUARD, AND THE CAP'S OWN RULE IS NOT TOUCHED. (a) the guard refuses (a future-dated
// snapshot): the ended apps wait with everything else. (b) the policy's plan is above the cap: refused as always —
// the ended apps do not push it through and do not go themselves. (c) the plan is exactly the cap: it goes, and the
// agreed ended ids go BESIDE it — more than the cap in one window.
func TestD84_OneGuard_AndTheAllowanceIsBesideTheCap(t *testing.T) {
old := time.Now().Add(-60 * 24 * time.Hour)
policy := func(n int) []guardSnap { // n old snapshots of the living app the policy wants to remove
var out []guardSnap
for i := 0; i < n; i++ {
out = append(out, tagged("p"+string(rune('a'+i)), old.Add(time.Duration(i)*time.Minute), "immich"))
}
return out
}
t.Run("the guard refuses: nothing goes, the ended apps wait", func(t *testing.T) {
m, sett, er, hub := endedBox(t, "immich")
pressed(t, sett, "vikunja", 31)
er.snaps = append(er.snaps, tagged("fut", time.Now().Add(72*time.Hour), "immich"))
m.offsiteWindowRetention(context.Background(), nil, nil, "after-run")
if len(er.forgets) != 0 || hub.closed[0].Outcome != "guard-refused" || len(hub.closed[0].RemovedForEndedApps) != 0 {
t.Fatalf("forgets=%v result=%+v — a refused guard must delete nothing", er.forgets, hub.closed[0])
}
if _, ok := sett.GetOffsiteEnd("vikunja"); !ok {
t.Fatal("the record was lost at a refused window")
}
})
t.Run("the policy's plan is above the cap: refused, with or without ended apps", func(t *testing.T) {
m, sett, er, hub := endedBox(t, "immich")
pressed(t, sett, "vikunja", 31)
er.plan = policy(6) // cap 5
er.snaps = append(er.snaps, er.plan...)
m.offsiteWindowRetention(context.Background(), nil, nil, "after-run")
if len(er.forgets) != 0 || hub.closed[0].Outcome != "guard-refused" || !strings.Contains(hub.closed[0].Reason, "more than one week") {
t.Fatalf("forgets=%v result=%+v — the cap's own refusal must stand", er.forgets, hub.closed[0])
}
})
t.Run("the plan is exactly the cap: it goes, and the ended ids go beside it", func(t *testing.T) {
m, sett, er, hub := endedBox(t, "immich")
pressed(t, sett, "vikunja", 31)
er.plan = policy(5) // cap 5
er.snaps = append(er.snaps, er.plan...)
m.offsiteWindowRetention(context.Background(), nil, nil, "after-run")
got := er.removedIDs()
if len(got) != 8 {
t.Fatalf("removed %d (%v), want the policy's 5 and vikunja's 3", len(got), got)
}
r := hub.closed[0]
if r.Outcome != "pruned" || r.CountBefore-r.CountAfter != 8 || len(r.RemovedForEndedApps) != 3 {
t.Fatalf("result = %+v, want a fall of 8 with 3 named for ended apps (so 5 are under the cap)", r)
}
})
t.Run("an ended id the policy already removes stays under the cap and is not named twice", func(t *testing.T) {
m, sett, er, hub := endedBox(t, "immich")
pressed(t, sett, "vikunja", 31)
er.plan = []guardSnap{er.snaps[0]} // v1 is in the policy's own plan
m.offsiteWindowRetention(context.Background(), nil, nil, "after-run")
if got := hub.closed[0].RemovedForEndedApps; strings.Join(got, ",") != strings.Join(ids("v2", "v3"), ",") {
t.Fatalf("removed_for_ended_apps = %v, want v2,v3 (v1 went under the cap)", got)
}
if got := er.removedIDs(); len(got) != 3 {
t.Fatalf("removed %v", got)
}
})
}
// WRONG CASE — an ended app that is INSTALLED AGAIN the day before the window. The install deletes the record
// (stacks.DeployStack; TestD72_AnInstallDeletesTheEndRecord). And if a record were still there: an installed app is
// never due — nothing is claimed, nothing goes.
func TestD72_AnAppInstalledAgainIsNeverDue(t *testing.T) {
m, sett, er, hub := endedBox(t, "immich", "vikunja") // vikunja is installed again
pressed(t, sett, "vikunja", 31)
m.offsiteWindowRetention(context.Background(), nil, nil, "after-run")
if len(hub.claims) != 0 || len(er.removedIDs()) != 0 {
t.Fatalf("claims=%+v removed=%v — an installed app's history must not be touched", hub.claims, er.removedIDs())
}
}
// A box that cannot tell what it runs (the seam is not wired) has nothing due and can write no record.
func TestD72_WithoutTheLivingCheckNothingIsDue(t *testing.T) {
m, sett, er, hub := endedBox(t)
m.SetOffsiteEndLiving(nil)
pressed(t, sett, "vikunja", 31)
m.offsiteWindowRetention(context.Background(), nil, nil, "after-run")
if len(hub.claims) != 0 || len(er.removedIDs()) != 0 {
t.Fatalf("claims=%+v removed=%v", hub.claims, er.removedIDs())
}
if _, created, err := m.StartOffsiteEnd("kimai"); err == nil || created {
t.Fatal("a press wrote a record on a box that cannot tell what is installed")
}
}
// A record that is not due yet (29 days) claims nothing; a snapshot made under the app's tag AFTER the removal is
// not the removed app's copy and is never a candidate.
func TestD72_NotDueYet_AndASnapshotYoungerThanTheRemoval(t *testing.T) {
m, sett, er, hub := endedBox(t, "immich")
pressed(t, sett, "vikunja", 29)
m.offsiteWindowRetention(context.Background(), nil, nil, "after-run")
if len(hub.claims) != 0 || len(er.removedIDs()) != 0 {
t.Fatalf("29 days: claims=%+v removed=%v", hub.claims, er.removedIDs())
}
m2, sett2, er2, hub2 := endedBox(t, "immich")
pressed(t, sett2, "kimai", 31)
er2.snaps = append(er2.snaps, tagged("k2", time.Now().Add(-20*24*time.Hour), "kimai")) // 11 days AFTER the removal
m2.offsiteWindowRetention(context.Background(), nil, nil, "after-run")
if got := er2.removedIDs(); strings.Join(got, ",") != strings.Join(ids("k1"), ",") {
t.Fatalf("removed %v, want k1 only — k2 was made after the removal", got)
}
if _, ok := sett2.GetOffsiteEnd("kimai"); !ok {
t.Fatal("the record closed although a snapshot with the tag is left")
}
_ = hub2
}
// An app that has NO copy in the store: its due record is closed with no history line and nothing is asked of the hub.
func TestD72_ARecordWithNoCopiesIsClosedQuietly(t *testing.T) {
m, sett, er, hub := endedBox(t, "immich")
pressed(t, sett, "neverbackedup", 31)
m.offsiteWindowRetention(context.Background(), nil, nil, "after-run")
if len(hub.claims) != 0 || len(er.removedIDs()) != 0 {
t.Fatalf("claims=%+v removed=%v", hub.claims, er.removedIDs())
}
if _, ok := sett.GetOffsiteEnd("neverbackedup"); ok || len(sett.GetOffsiteEndsDone()) != 0 {
t.Fatalf("want the record closed with no history line; pending=%v history=%+v", ok, sett.GetOffsiteEndsDone())
}
}
// WRONG CASE — THE OFF-SITE TIER IS SWITCHED OFF AT THE DATE. No run, no window, no call to the store; the record
// stays and does nothing. And the household's own NAS target (no hub window) never removes an ended app's copies.
func TestD72_TierOffAtTheDate_TheRecordWaits(t *testing.T) {
m, sett, er, hub := endedBox(t, "immich")
rec := pressed(t, sett, "vikunja", 31)
if err := sett.UpdateOffboxStatus(func(o *settings.OffboxTarget) { o.Enabled = false }); err != nil {
t.Fatal(err)
}
_ = m.RunOffboxBackup(context.Background())
if hub.opened != 0 || len(er.forgets) != 0 {
t.Fatalf("with the tier OFF the box opened %d window(s) and ran %d forget(s)", hub.opened, len(er.forgets))
}
if got, ok := sett.GetOffsiteEnd("vikunja"); !ok || got != rec {
t.Fatalf("the record changed while the tier was off: %+v ok=%v", got, ok)
}
// The household's own NAS: the box prunes by the policy alone; no id of an ended app is ever named.
m2, sett2 := newOffboxManager(t) // Transport "" = the NAS
if _, _, err := sett2.StartOffsiteEnd("vikunja", time.Now().Add(-31*24*time.Hour)); err != nil {
t.Fatal(err)
}
er2 := &endedRunner{snaps: []guardSnap{tagged("v1", time.Now().Add(-60*24*time.Hour), "vikunja")}}
m2.SetOffboxRunner(er2.run)
m2.SetOffsiteEndLiving(func(string) bool { return false })
m2.offsiteWindowRetention(context.Background(), nil, nil, "after-run")
if got := er2.removedIDs(); len(got) != 0 {
t.Fatalf("on the household's own NAS the box removed %v by id", got)
}
if _, created, err := m2.StartOffsiteEnd("kimai"); err != ErrOffsiteEndNotOffered || created {
t.Fatalf("a press on a box without the hub's tier: created=%v err=%v, want ErrOffsiteEndNotOffered and no record", created, err)
}
}
// MUST-HOLD 7 and the wrong case TWO PRESSES — one record, ONE mail; the date does not move. A press for an
// installed app writes nothing and mails nobody.
func TestD84_OnePressOneMail(t *testing.T) {
m, sett, _, _ := endedBox(t, "immich")
var mails []settings.OffsiteEnd
m.SetOffsiteEndNotify(func(rec settings.OffsiteEnd) { mails = append(mails, rec) })
first, created, err := m.StartOffsiteEnd("vikunja")
if err != nil || !created {
t.Fatalf("first press: created=%v err=%v", created, err)
}
if first.Ends().Sub(first.Removed()) != settings.OffsiteEndAfter {
t.Fatalf("the record's end is not 30 days after the press: %+v", first)
}
second, created2, err := m.StartOffsiteEnd("vikunja")
if err != nil || created2 || second != first {
t.Fatalf("second press: created=%v rec=%+v err=%v — want the first record, unchanged", created2, second, err)
}
if len(mails) != 1 || mails[0] != first {
t.Fatalf("two presses gave %d mail(s): %+v — want ONE, for the record", len(mails), mails)
}
if _, c, err := m.StartOffsiteEnd("immich"); err != ErrOffsiteEndLiving || c {
t.Fatalf("a press for an INSTALLED app: created=%v err=%v", c, err)
}
if len(mails) != 1 || len(sett.GetOffsiteEnds()) != 1 {
t.Fatalf("mails=%d records=%d after a refused press", len(mails), len(sett.GetOffsiteEnds()))
}
// MUST-HOLD 4 — the household takes it back: the record is gone, and the next window claims nothing.
if kept, err := m.KeepOffsiteCopies("vikunja"); err != nil || !kept {
t.Fatalf("keep: %v %v", kept, err)
}
if n := len(sett.GetOffsiteEnds()); n != 0 {
t.Fatalf("%d record(s) after the take-back", n)
}
if len(mails) != 1 {
t.Fatalf("the take-back sent a mail: %d", len(mails))
}
}
// The take-back before the window: with the record deleted, the window removes nothing of the app.
func TestD72_AfterTheTakeBackTheWindowRemovesNothing(t *testing.T) {
m, sett, er, hub := endedBox(t, "immich")
pressed(t, sett, "vikunja", 31)
if kept, err := m.KeepOffsiteCopies("vikunja"); err != nil || !kept {
t.Fatalf("keep: %v %v", kept, err)
}
m.offsiteWindowRetention(context.Background(), nil, nil, "after-run")
if len(hub.claims) != 0 || len(er.removedIDs()) != 0 {
t.Fatalf("claims=%+v removed=%v after „keep it after all”", hub.claims, er.removedIDs())
}
}
// The hub report carries the pending records (so the hub can start its own clock for an app it never saw).
func TestD72_TheReportCarriesThePendingRecords(t *testing.T) {
m, sett, _, _ := endedBox(t, "immich")
if st := m.OffboxReportStatus(); st == nil || len(st.EndedApps) != 0 {
t.Fatalf("no record: %+v", st)
}
rec := pressed(t, sett, "vikunja", 3)
st := m.OffboxReportStatus()
if st == nil || len(st.EndedApps) != 1 || st.EndedApps[0].App != "vikunja" || st.EndedApps[0].RemovedAt != rec.RemovedAt || st.EndedApps[0].EndsAt != rec.EndsAt {
t.Fatalf("report = %+v, want the pending record", st)
}
}
// The living check and the mail are WIRED in main.go — without the first nothing is ever due, without the second no
// household is told. (A seam nobody wires is a feature that does not exist.)
func TestD72_MainWiresTheLivingCheck(t *testing.T) {
raw, err := os.ReadFile(filepath.Join("..", "..", "cmd", "controller", "main.go"))
if err != nil {
t.Fatal(err)
}
src := string(raw)
for _, want := range []string{"backupMgr.SetOffsiteEndLiving(stackMgr.IsLivingApp)",
"backupMgr.SetOffsiteEndNotify(func(rec settings.OffsiteEnd) {", "notifier.NotifyOffsiteEndScheduled(rec.App, rec.RemovedAt, rec.EndsAt"} {
if !strings.Contains(src, want) {
t.Errorf("main.go lacks %q", want)
}
}
}
// The result names for the hub's audit only ids that are REALLY gone: a forget that removed nothing (the provider
// refused, the call failed) names none, and the record stays for the next window.
func TestD84_TheResultNamesOnlyIdsThatAreReallyGone(t *testing.T) {
m, sett, er, hub := endedBox(t, "immich")
pressed(t, sett, "kimai", 31)
base := er.run
m.SetOffboxRunner(func(ctx context.Context, env []string, args ...string) ([]byte, error) {
if contains(args, "forget") && !contains(args, "--dry-run") {
er.forgets = append(er.forgets, append([]string{}, args...))
return []byte("Fatal: unable to remove"), context.DeadlineExceeded // nothing is removed
}
return base(ctx, env, args...)
})
m.offsiteWindowRetention(context.Background(), nil, nil, "after-run")
if len(er.forgets) != 1 || len(hub.closed) != 1 {
t.Fatalf("forgets=%d closed=%d", len(er.forgets), len(hub.closed))
}
r := hub.closed[0]
if r.Outcome != "error" || len(r.RemovedForEndedApps) != 0 || r.CountAfter != r.CountBefore {
t.Fatalf("result = %+v — a failed forget removed nothing, so nothing may be named as removed for ended apps", r)
}
if _, ok := sett.GetOffsiteEnd("kimai"); !ok || len(sett.GetOffsiteEndsDone()) != 0 {
t.Fatal("the record was closed although its copy is still in the store")
}
}
@@ -425,9 +425,12 @@ func (m *Manager) holdAppAfterFailedRollback(stack string, replayErr, rollbackEr
m.logger.Printf("[ERROR] [offbox] %s: cannot persist the restore hold — no settings wired; the app is stopped but NOTHING will refuse a restart", stack)
return
}
// R-1340: this branch is only ever an off-site restore's database replay (offbox_reconstitute's rollback).
h := settings.RestoreHold{
Stack: stack,
At: time.Now().UTC().Format(time.RFC3339),
RestoreKind: settings.RestoreKindOffsite,
DBReplay: true,
}
if replayErr != nil {
h.ReplayError = replayErr.Error()
@@ -447,6 +450,15 @@ func (m *Manager) holdAppAfterFailedRollback(stack string, replayErr, rollbackEr
}
}
// mixedHoldWhy (R-1340) is what a restore_mixed hold records about its cause (settings.RestoreHold's R-1340 fields).
type mixedHoldWhy struct {
kind string // settings.RestoreKind*
cause string // settings.MixedCause*
step string // the step that failed, with its error
dbReplay bool // the restore's own failure was its database replay
copyDir string // where the copy of the live volumes is kept; "" = none kept
}
// liveDefinition is the app's definition as it ran before an off-site restore wrote the snapshot's
// (R-893): a copy of its compose files in a temporary folder, and its full env held in memory only.
type liveDefinition struct {
@@ -511,7 +523,11 @@ func (m *Manager) captureLiveDefinition(stack string) (*liveDefinition, error) {
// written back (when the snapshot's was written), the database service is stopped again, and the app is
// held with HoldReasonRestoreMixed. The operator is notified with no rollback error — that is how the
// notification tells this case from R-379's double failure.
func (m *Manager) holdAppAfterMixedRestore(stack string, replayErr error, live *liveDefinition) {
//
// why (R-1340) is what the hold records about its cause, so the operator's mail tells the real story — this hold is
// written by three different branches now (a definition write, a put-back that failed at one of its steps), not
// only by option C's database replay.
func (m *Manager) holdAppAfterMixedRestore(stack string, replayErr error, live *liveDefinition, why mixedHoldWhy) {
// The hold is PERSISTED FIRST (security review 2026-10-08): a controller that dies between the stop and
// the hold would otherwise restart the app from the R-166 marker with nothing refusing it. When the hold
// cannot be persisted, the app-stop marker is KEPT, so nothing reads the window as finished.
@@ -519,7 +535,8 @@ func (m *Manager) holdAppAfterMixedRestore(stack string, replayErr error, live *
if m.settings == nil {
m.logger.Printf("[ERROR] [offbox] %s: cannot persist the restore hold — no settings wired; the app is stopped but NOTHING will refuse a restart", stack)
} else {
h := settings.RestoreHold{Stack: stack, At: time.Now().UTC().Format(time.RFC3339), Reason: settings.HoldReasonRestoreMixed}
h := settings.RestoreHold{Stack: stack, At: time.Now().UTC().Format(time.RFC3339), Reason: settings.HoldReasonRestoreMixed,
RestoreKind: why.kind, MixedCause: why.cause, FailedStep: why.step, DBReplay: why.dbReplay, SafetyDump: why.copyDir}
if replayErr != nil {
h.ReplayError = replayErr.Error()
}
@@ -548,6 +565,26 @@ func (m *Manager) holdAppAfterMixedRestore(stack string, replayErr error, live *
}
}
// restartAtLiveDefinition (R-1256 H4) is the failure branch of the definition write, taken while no data has moved.
// The writer writes the compose before the app's settings, so a failure can leave the snapshot's compose in the
// stack dir: the LIVE definition is written back first, and only then is the app started. When the write-back fails
// too, the app is held stopped (restore_mixed) — a start would run the snapshot's definition over the live data.
// Pinned by TestR1256_H4_*.
func (m *Manager) restartAtLiveDefinition(stack string, live *liveDefinition, cause error, restartStack func() error) {
if live != nil {
if err := m.stackProvider.RecreateStackDefinitionFromUnit(stack, live.dir, live.env); err != nil {
m.logger.Printf("[ERROR] [offbox] %s: the definition write failed (%v) and writing the live definition back failed too: %v — holding the app stopped", stack, cause, err)
m.holdAppAfterMixedRestore(stack, cause, nil, mixedHoldWhy{kind: settings.RestoreKindOffsite, cause: settings.MixedCauseDefinitionWrite,
step: "writing the live app definition back failed: " + err.Error()})
return
}
m.logger.Printf("[INFO] [offbox] %s: the definition write failed (%v); the live definition is written back before the start", stack, cause)
}
if sErr := restartStack(); sErr != nil {
m.logger.Printf("[WARN] [offbox] %s: restart after a failed definition write also failed: %v", stack, sErr)
}
}
// SetRestoreHoldNotify wires the operator notification for a held app (cmd/controller/main.go).
func (m *Manager) SetRestoreHoldNotify(fn func(stack string, replayErr, rollbackErr error)) {
m.restoreHoldNotify = fn
@@ -1005,16 +1042,12 @@ func (m *Manager) ReconstituteFromOffsite(ctx context.Context, stack string, ack
// yet — a failure here restarts the app as it was.
if defineFromSnapshot {
if err := m.stackProvider.RecreateStackDefinitionFromUnit(stack, scratchCompose, snapEnv); err != nil {
if sErr := restartStack(); sErr != nil {
m.logger.Printf("[WARN] [offbox] %s: restart after a failed definition write also failed: %v", stack, sErr)
}
m.restartAtLiveDefinition(stack, liveDef, err, restartStack)
return res, fmt.Errorf("restoring %s: writing the snapshot's definition failed: %w", stack, err)
}
} else if len(credOverlay) > 0 {
if err := m.stackProvider.(secretValueSetter).SetStackSecretValues(stack, credOverlay); err != nil {
if sErr := restartStack(); sErr != nil {
m.logger.Printf("[WARN] [offbox] %s: restart after a failed password write also failed: %v", stack, sErr)
}
m.restartAtLiveDefinition(stack, liveDef, err, restartStack)
return res, fmt.Errorf("restoring %s: writing the backup's database password failed: %w", stack, err)
}
m.logger.Printf("[INFO] [offbox] %s: the backup's database password(s) %v written into the app's settings before the data (R-1106)", stack, credNames(credOverlay))
@@ -1045,7 +1078,7 @@ func (m *Manager) ReconstituteFromOffsite(ctx context.Context, stack string, ack
// R-893 option A: no volume has moved yet, so only the live definition is written back and the app starts.
// The failing copy may have placed part of its files, so the sentence names placed files (+1).
if definitionMoved {
return res, m.putBackAfterFailedRestore(stack, cErr, liveDef, undo, false, res.FilesPlaced+1, restartStack, "err.backup.restore_failed_held_mixed")
return res, m.putBackAfterFailedRestore(stack, cErr, liveDef, undo, false, res.FilesPlaced+1, restartStack, "err.backup.restore_failed_held_mixed", settings.RestoreKindOffsite)
}
// Nothing moved yet: best-effort bring-up — a failed restore must not also be an outage.
if sErr := restartStack(); sErr != nil {
@@ -1080,7 +1113,7 @@ func (m *Manager) ReconstituteFromOffsite(ctx context.Context, stack string, ack
// R-893 option A: the replay removes a volume BEFORE it recreates it, so even nVols == 0 may have lost one —
// with a copy, it is always poured back; with no copy the old rule decides (and holds when one moved).
if definitionMoved || nVols > 0 || undo != nil {
return res, m.putBackAfterFailedRestore(stack, vErr, liveDef, undo, nVols > 0 || undo != nil, res.FilesPlaced, restartStack, "err.backup.restore_failed_held_mixed")
return res, m.putBackAfterFailedRestore(stack, vErr, liveDef, undo, nVols > 0 || undo != nil, res.FilesPlaced, restartStack, "err.backup.restore_failed_held_mixed", settings.RestoreKindOffsite)
}
// Nothing replaced yet: bring the app back up rather than leaving an outage, then surface it.
if sErr := restartStack(); sErr != nil {
@@ -1099,7 +1132,7 @@ func (m *Manager) ReconstituteFromOffsite(ctx context.Context, stack string, ack
if err := m.stackProvider.StartStackServices(stack, dbServices); err != nil {
// R-893 option C (security review 2026-10-08): volumes or the definition already moved → HOLD.
if definitionMoved || res.VolumesReplayed > 0 {
return res, m.putBackAfterFailedRestore(stack, err, liveDef, undo, res.VolumesReplayed > 0, res.FilesPlaced, restartStack, "err.backup.restore_failed_held_mixed")
return res, m.putBackAfterFailedRestore(stack, err, liveDef, undo, res.VolumesReplayed > 0, res.FilesPlaced, restartStack, "err.backup.restore_failed_held_mixed", settings.RestoreKindOffsite)
}
// Best-effort bring-up: a failed restore must not also be an outage.
if sErr := restartStack(); sErr != nil {
@@ -1151,7 +1184,7 @@ func (m *Manager) ReconstituteFromOffsite(ctx context.Context, stack string, ack
// under them — the copy of the live volumes is poured back over the rolled-back database, the live
// definition written back, and the app starts exactly as it was. A put-back that fails holds, as before.
if definitionMoved || res.VolumesReplayed > 0 {
return res, m.putBackAfterFailedRestore(stack, iErr, liveDef, undo, res.VolumesReplayed > 0, res.FilesPlaced, restartStack, "err.backup.db_restore_failed_held_mixed")
return res, m.putBackAfterFailedRestore(stack, iErr, liveDef, undo, res.VolumesReplayed > 0, res.FilesPlaced, restartStack, "err.backup.db_restore_failed_held_mixed", settings.RestoreKindOffsite)
}
if sErr := restartStack(); sErr != nil {
m.logger.Printf("[WARN] [offbox] %s: start after a successful rollback failed: %v", stack, sErr)
@@ -11,6 +11,7 @@ import (
"time"
"gitea.dooplex.hu/admin/felhom-controller/internal/dockerexec"
"gitea.dooplex.hu/admin/felhom-controller/internal/settings"
"gitea.dooplex.hu/admin/felhom-controller/internal/util"
)
@@ -219,28 +220,46 @@ func (m *Manager) putBack(stack string, c *liveVolumeCopy) error {
// failure's own held sentence) and the copy stays on disk. volumesMoved with no copy is such a case: nothing can
// put them back. filesPlaced chooses the household's sentence: placed files are not taken back (as ruled for
// option C, a file mix does not hold), so the sentence then says so instead of „nothing changed".
//
// restoreKind (R-1340) is settings.RestoreKindOffsite or RestoreKindLocal: the hold records it, with the step that
// failed and whether the restore's failure was a database replay (holdKey says so — it is the callers' own choice of
// the household's sentence), so the operator's mail names the real cause.
func (m *Manager) putBackAfterFailedRestore(stack string, cause error, live *liveDefinition, c *liveVolumeCopy, volumesMoved bool,
filesPlaced int, restart func() error, holdKey string) error {
filesPlaced int, restart func() error, holdKey, restoreKind string) error {
why := func(step string) mixedHoldWhy {
w := mixedHoldWhy{kind: restoreKind, cause: settings.MixedCausePutBack, step: step,
dbReplay: holdKey == "err.backup.db_restore_failed_held_mixed"}
if c != nil && c.keep {
w.copyDir = c.dir
}
return w
}
if volumesMoved && c == nil {
m.logger.Printf("[ERROR] [offbox] %s: volumes were replaced and there is no copy to put back — holding the app", stack)
m.holdAppAfterMixedRestore(stack, cause, live)
m.holdAppAfterMixedRestore(stack, cause, live, why("the restore had already changed the app's data and there was no copy of the live volumes to put back"))
return util.MsgError(holdKey, stack)
}
// R-1256 H5: a put-back under an app that could not be stopped could mix the copy with what the app writes.
// Nothing is poured; the copy is kept and the app held (D20: a put-back that fails holds and keeps its copy).
if err := m.stackProvider.StopStack(stack); err != nil {
m.logger.Printf("[WARN] [offbox] %s: stopping the app before the put-back failed: %v", stack, err)
c.keepIfAny()
m.logger.Printf("[ERROR] [offbox] %s: stopping the app before the put-back FAILED: %v — nothing is put back; the copy stays at %s; holding the app", stack, err, c.dirOrNone())
m.holdAppAfterMixedRestore(stack, cause, live, why("stopping the app before the put-back failed, so nothing was put back: "+err.Error()))
return util.MsgError(holdKey, stack)
}
if volumesMoved {
if err := m.putBack(stack, c); err != nil {
c.keep = true
m.logger.Printf("[ERROR] [offbox] %s: putting the live volumes back FAILED: %v — the copy stays at %s; holding the app", stack, err, c.dir)
m.holdAppAfterMixedRestore(stack, cause, live)
m.holdAppAfterMixedRestore(stack, cause, live, why("putting the live volumes back failed: "+err.Error()))
return util.MsgError(holdKey, stack)
}
}
if live != nil {
if err := m.stackProvider.RecreateStackDefinitionFromUnit(stack, live.dir, live.env); err != nil {
m.logger.Printf("[ERROR] [offbox] %s: writing the live definition back FAILED: %v — holding the app", stack, err)
m.holdAppAfterMixedRestore(stack, cause, live)
c.keepIfAny() // R-1256 H5 (D20): a put-back that fails keeps its copy for support
m.logger.Printf("[ERROR] [offbox] %s: writing the live definition back FAILED: %v — the copy stays at %s; holding the app", stack, err, c.dirOrNone())
m.holdAppAfterMixedRestore(stack, cause, live, why("writing the live app definition back failed: "+err.Error()))
return util.MsgError(holdKey, stack)
}
}
@@ -249,12 +268,19 @@ func (m *Manager) putBackAfterFailedRestore(stack string, cause error, live *liv
m.restorePutBackNotify(stack, cause)
}
if err := restart(); err != nil {
m.logger.Printf("[ERROR] [offbox] %s: start after the put-back failed: %v (the copy stays at %s)", stack, err, c.dirOrNone())
m.logger.Printf("[ERROR] [offbox] %s: start after the put-back failed: %v (the live volumes and definition are back; the copy %s is removed)", stack, err, c.dirOrNone())
return util.MsgError("err.backup.restore_failed_put_back_not_started", stack)
}
return putBackMessage(stack, filesPlaced)
}
// keepIfAny marks the copy as kept for support (no copy: nothing to keep).
func (c *liveVolumeCopy) keepIfAny() {
if c != nil {
c.keep = true
}
}
func (c *liveVolumeCopy) dirOrNone() string {
if c == nil {
return "(no volume copy)"
+60 -4
View File
@@ -56,6 +56,14 @@ type OffsiteWindow struct {
NewestAllowed time.Time
MaxRemove int
Reason string // why not granted (logged)
// D84 (`09` §3 decision 309): the snapshot ids of ENDED apps the hub agreed to — their own allowance, outside
// MaxRemove — and what it refused. Empty from a hub that does not know ended apps: then none is removed.
EndedAllowed []string
EndedRefused []OffsiteEndedRefusal
// AcceptsEnded: this hub said, in this answer, that it reads `ended` in a window request (the hub's
// `accepts_ended`; review of 2026-11-15, version skew). An older hub does not say it, and then the box sends it
// no end records: that hub reads only 4 KiB of the request and would decide the window on a wrong count.
AcceptsEnded bool
}
// OffsiteWindowResult is what the box reports when it is done (the hub closes the window on it).
@@ -66,11 +74,16 @@ type OffsiteWindowResult struct {
Removed int `json:"removed"`
Outcome string `json:"outcome"` // pruned | nothing | guard-refused | error
Reason string `json:"reason,omitempty"`
// RemovedForEndedApps names the snapshots this window removed for ended apps (D84) — only ids the hub agreed
// to, and only those that are really gone. The hub's 07:10 audit explains its vanished files by this list.
RemovedForEndedApps []string `json:"removed_for_ended_apps,omitempty"`
}
// OffsiteWindowClient is the hub side (offsiteapply.HubWindowClient in production).
type OffsiteWindowClient interface {
Open(ctx context.Context, countBefore int) (OffsiteWindow, error)
// Open asks for a window. ended are the box's DUE off-site end records with the ids it would remove (D72/D84);
// the hub answers which ids it agrees to.
Open(ctx context.Context, countBefore int, ended []OffsiteEndedClaim) (OffsiteWindow, error)
Close(ctx context.Context, r OffsiteWindowResult) error
}
@@ -225,11 +238,27 @@ func (m *Manager) offsiteWindowRetention(ctx context.Context, base, env []string
m.logger.Printf("[WARN] [offbox] retention skipped (%s): %v", why, err)
return
}
w, err := m.offsiteWindow.Open(ctx, len(snaps))
// D72/D84: the ended apps' candidates, from the records that are due. No record → no candidate.
due := dueOffsiteEnds(m.settings.GetOffsiteEnds(), m.now(), m.offsiteEndLiving)
m.dropEndsWithNoCopies(snaps, due)
claims, candidate := endedCandidates(snaps, due)
// VERSION SKEW (review of 2026-11-15): the end records go ONLY to a hub that said, in its last window answer,
// that it reads them. An older hub reads 4 KiB of the request; a larger one made it open the window on a wrong
// count, and the weekly clean-up stalled. A hub that has not said it gets the request it always got.
if len(claims) > 0 && !m.settings.GetOffsiteHubAcceptsEnded() {
m.logger.Printf("[INFO] [offbox] %d removed app(s) are due, but the hub has not said that it reads end records (an older hub) — none is sent, nothing of them is removed; the ordinary clean-up goes on", len(claims))
claims, candidate = nil, map[string]bool{}
}
claims = boundEndedClaims(claims, maxEndedClaimIDs)
w, err := m.offsiteWindow.Open(ctx, len(snaps), claims)
if err != nil {
m.logger.Printf("[WARN] [offbox] retention skipped (%s): asking the hub for a window failed: %v", why, err)
return
}
// Remember what THIS answer said (granted or not): the next request follows it.
if serr := m.settings.SetOffsiteHubAcceptsEnded(w.AcceptsEnded); serr != nil {
m.logger.Printf("[WARN] [offbox] the hub's answer about end records could not be saved: %v", serr)
}
if !w.Granted {
m.logger.Printf("[INFO] [offbox] retention skipped (%s): no clean-up window now (%s) — nothing deleted (decision 68)", why, w.Reason)
return
@@ -255,6 +284,22 @@ func (m *Manager) offsiteWindowRetention(ctx context.Context, base, env []string
m.logger.Printf("[ERROR] [offbox] clean-up window %d: the fake-snapshot guard REFUSED — nothing deleted: %s (R-822)", w.ID, refuse)
return
}
for _, r := range w.EndedRefused {
m.logger.Printf("[WARN] [offbox] clean-up window %d: the hub REFUSED the ended app %q — nothing of it is removed: %s", w.ID, r.App, r.Reason)
}
// The ended apps' ids: outside the cap, only what the hub agreed to AND this box named in this window.
endedIDs := endedToRemove(w.EndedAllowed, candidate, ids)
if len(endedIDs) > 0 {
m.logger.Printf("[INFO] [offbox] clean-up window %d: %d snapshot(s) of removed apps are due and agreed by the hub — removed beside the policy's %d (D84)", w.ID, len(endedIDs), len(ids))
}
// THE LAST LOOK (review of 2026-11-15). The records were read before the hub was asked; the hub's answer, the dry
// run and the guard took seconds to minutes. A take-back („Mégis megtartom”) or an install in that time deleted
// the record — so the records are read AGAIN here, immediately before the forget, and an id whose record is gone,
// changed or no longer due is taken out. From here until the forget has ended, a take-back for one of these apps
// is answered „not marked, or already deleted” (KeepOffsiteCopies), never „kept”.
endedIDs, claims = m.lastLookAtEnded(snaps, claims, endedIDs)
defer m.endedRemovalOver()
ids = append(ids, endedIDs...)
if len(ids) == 0 {
res.Outcome = "nothing"
m.logger.Printf("[INFO] [offbox] clean-up window %d: the policy removes nothing", w.ID)
@@ -271,8 +316,19 @@ func (m *Manager) offsiteWindowRetention(ctx context.Context, base, env []string
}
if after, lerr := m.listGuardSnaps(ctx, base, env); lerr == nil {
res.CountAfter = len(after)
// Named apart for the hub's audit — only the agreed ids that are REALLY gone from the repository.
still := make(map[string]bool, len(after))
for _, s := range after {
still[s.ID] = true
}
for _, id := range endedIDs {
if !still[id] {
res.RemovedForEndedApps = append(res.RemovedForEndedApps, id)
}
}
m.completeOffsiteEnds(claims, res.RemovedForEndedApps, after)
}
res.Removed = res.CountBefore - res.CountAfter
m.logger.Printf("[INFO] [offbox] clean-up window %d (%s): %d of %d planned snapshot(s) removed, %d -> %d, in %s",
w.ID, why, res.Removed, len(plan), res.CountBefore, res.CountAfter, time.Since(start).Round(time.Second))
m.logger.Printf("[INFO] [offbox] clean-up window %d (%s): %d of %d planned snapshot(s) removed (%d of them for removed apps), %d -> %d, in %s",
w.ID, why, res.Removed, len(ids), len(res.RemovedForEndedApps), res.CountBefore, res.CountAfter, time.Since(start).Round(time.Second))
}
@@ -56,13 +56,15 @@ func (w *windowRunner) run(_ context.Context, _ []string, args ...string) ([]byt
}
type fakeWindow struct {
claims []OffsiteEndedClaim
grant OffsiteWindow
opened int
closed []OffsiteWindowResult
}
func (f *fakeWindow) Open(context.Context, int) (OffsiteWindow, error) {
func (f *fakeWindow) Open(_ context.Context, _ int, ended []OffsiteEndedClaim) (OffsiteWindow, error) {
f.opened++
f.claims = ended
return f.grant, nil
}
func (f *fakeWindow) Close(_ context.Context, r OffsiteWindowResult) error {
+47
View File
@@ -62,6 +62,53 @@ type RestoreOpStatus struct {
func (m *Manager) BeginRestoreOp(op, stack string) {
m.mu.Lock()
defer m.mu.Unlock()
m.beginRestoreOpLocked(op, stack)
}
// Why a new restore may not begin now (R-1256 H6). "" = it may.
const (
RestoreBusyRestore = "restore" // a restore op is in flight (the record the pages follow)
RestoreBusyBackup = "backup" // the single-flight backup/restore run is held (the night run never records an op)
RestoreBusyMirror = "mirror" // a second-drive copy runs, or one a previous process lost may still run
)
// TryBeginRestoreOp is BeginRestoreOp that refuses — in the SAME step, under m.mu — while another restore op, a
// backup run or a second-drive copy runs. R-1256 H6: the pages asked (RestoreStatus, IsRunning,
// Tier2CopyBlocksRestore) and recorded the op later; a mirror that began in between ran beside the restore. The mirror
// asks under the same m.mu (beginTier2Run), so one of the two always sees the other. Lock order m.mu → tier2Copies,
// as in beginTier2Run. Returns the busy reason ("" = begun) and, for a mirror, its app ("" when unknown).
// Pinned by TestR1256_H6_*.
func (m *Manager) TryBeginRestoreOp(op, stack string) (busy, mirrorApp string) {
m.mu.Lock()
defer m.mu.Unlock()
if busy, app := m.restoreBusyLocked(); busy != "" {
return busy, app
}
m.beginRestoreOpLocked(op, stack)
return "", ""
}
// RestoreBusy is TryBeginRestoreOp's question alone — for a refusal asked early, before a request is read further.
func (m *Manager) RestoreBusy() (busy, mirrorApp string) {
m.mu.Lock()
defer m.mu.Unlock()
return m.restoreBusyLocked()
}
func (m *Manager) restoreBusyLocked() (string, string) {
if m.opRunning {
return RestoreBusyRestore, m.opStack
}
if m.running {
return RestoreBusyBackup, ""
}
if app, blocked := m.Tier2CopyBlocksRestore(); blocked {
return RestoreBusyMirror, app
}
return "", ""
}
func (m *Manager) beginRestoreOpLocked(op, stack string) {
m.opRunning = true
m.opName = op
m.opStack = stack
@@ -0,0 +1,358 @@
package backup
import (
"context"
"errors"
"io"
"log"
"os"
"path/filepath"
"strings"
"testing"
"time"
"gitea.dooplex.hu/admin/felhom-controller/internal/settings"
)
// R-1256 (review round 2, HUNT-1): four restore edges — H4, H5, H6 and H8, each pinned below.
//
// H4: an off-site restore writes the snapshot's definition before any data moves. The writer
// (stackAdapter.RecreateStackDefinitionFromUnit) writes the compose FIRST and the app's settings after, so a
// failure can come back with the snapshot's compose already in the stack dir. The failure branch used to start
// the app at once — on the snapshot's (older) compose, over the live data. Now the live definition is written
// back first; only then is the app started. When the write-back fails too, the app is held, never started.
// r1256DefFailProvider fails the FIRST definition write (the snapshot's), after recording it — as the real
// writer does when its compose write succeeded and its settings write did not.
type r1256DefFailProvider struct {
*r893Provider
failWrites int // how many writes fail, from the first
failFrom int // when set, every write from this one (1-based) on fails
}
func (p *r1256DefFailProvider) RecreateStackDefinitionFromUnit(name, composeDir string, env map[string]string) error {
if err := p.r893Provider.RecreateStackDefinitionFromUnit(name, composeDir, env); err != nil {
return err
}
if len(p.defs) <= p.failWrites || (p.failFrom > 0 && len(p.defs) >= p.failFrom) {
return errors.New("app.yaml write failed")
}
return nil
}
func r1256DefFailFixture(t *testing.T, failWrites int) (*Manager, *r1256DefFailProvider, *int) {
t.Helper()
m, vp, _, notified, _ := r893FixtureA(t, true, 0)
p := &r1256DefFailProvider{r893Provider: vp, failWrites: failWrites}
m.SetStackProvider(p)
return m, p, notified
}
// RED-PROOF: remove the live write-back from the definition-write failure branch (restartStack alone) → one
// definition write (the snapshot's), then the start → FAILS.
func TestR1256_H4_AFailedDefinitionWriteStartsTheAppAtItsLiveDefinition(t *testing.T) {
m, p, notified := r1256DefFailFixture(t, 1)
_, err := m.ReconstituteFromOffsite(context.Background(), "immich", false)
if err == nil {
t.Fatal("a failed definition write must be surfaced")
}
if len(p.defs) != 2 || !strings.Contains(strings.Join(p.defs[1], " "), "postgres:18-alpine") {
t.Fatalf("definition writes %v — want the snapshot's, then the LIVE one written back", p.defs)
}
if !p.fullStarted {
t.Fatalf("the app must run again at its live definition — calls %v", p.calls)
}
// The write-back comes BEFORE the start.
lastRecreate, lastStart := -1, -1
for i, c := range p.calls {
switch c {
case "recreate":
lastRecreate = i
case "start":
lastStart = i
}
}
if lastRecreate > lastStart {
t.Fatalf("the app was started before the live definition was written back — calls %v", p.calls)
}
if held, _ := m.RestoreHoldFor("immich"); held {
t.Fatal("the live definition is back: the app must not be held")
}
if *notified != 0 {
t.Errorf("hold notices %d, want 0", *notified)
}
}
// The write-back fails too: the stack dir may still hold the snapshot's compose, so the app is NOT started; it is
// held (restore_mixed: the definition moved and could not be put back) and the operator is told once.
// RED-PROOF: start the app when the write-back fails → fullStarted → FAILS.
func TestR1256_H4_AFailedWriteBackHoldsTheApp(t *testing.T) {
m, p, notified := r1256DefFailFixture(t, 2)
_, err := m.ReconstituteFromOffsite(context.Background(), "immich", false)
if err == nil {
t.Fatal("a failed definition write must be surfaced")
}
if p.fullStarted {
t.Fatalf("the app was STARTED although its live definition could not be written back — calls %v", p.calls)
}
held, _ := m.RestoreHoldFor("immich")
if !held {
t.Fatal("no hold: every start path would start the app on the snapshot's definition")
}
if k := m.HoldKind("immich"); k != settings.HoldReasonRestoreMixed {
t.Errorf("hold kind %q, want %q", k, settings.HoldReasonRestoreMixed)
}
if *notified != 1 {
t.Errorf("the operator must be told once, got %d", *notified)
}
}
// ---- H5: a put-back whose stop fails must not go on; `volume rm -f` errors count; a failed put-back keeps its copy.
// r1256StopFailProvider fails the Nth StopStack (1-based).
type r1256StopFailProvider struct {
*r893Provider
failAt, n int
}
func (p *r1256StopFailProvider) StopStack(name string) error {
p.n++
err := p.r893Provider.StopStack(name)
if p.n == p.failAt {
return errors.New("compose down: timeout")
}
return err
}
// The off-site put-back: the replay fails after the snapshot's volume replaced the live one; the stop before the
// put-back fails. Pouring the copy back under a running app could mix it with what the app writes, so nothing is
// poured, the copy is KEPT, and the app is held.
// RED-PROOF: restore the „(continuing)" WARN in putBackAfterFailedRestore → the copy is poured and the app started
// → FAILS.
func TestR1256_H5_APutBackWhoseStopFailsDoesNotPourAndKeepsTheCopy(t *testing.T) {
m, vp, rig, _, notified, putBack := r893PutBackFixture(t)
p := &r1256StopFailProvider{r893Provider: vp, failAt: 2} // 1 = the restore's stop, 2 = the put-back's
m.SetStackProvider(p)
_, err := m.ReconstituteFromOffsite(context.Background(), "immich", false)
if err == nil {
t.Fatal("a failed restore must be surfaced")
}
if p.n < 2 {
t.Fatalf("the put-back's stop never ran (stops %d) — the fixture did not reach the put-back", p.n)
}
if len(rig.poured) != 0 || len(rig.removed) != 0 {
t.Fatalf("the copy was poured (%v) / volumes removed (%v) after a FAILED stop", rig.poured, rig.removed)
}
if vp.fullStarted {
t.Fatalf("the app was started after a failed put-back — calls %v", vp.calls)
}
if held, _ := m.RestoreHoldFor("immich"); !held {
t.Fatal("a put-back that could not run must hold the app (D20)")
}
if left := undoCopies(t, rig.undoRoot); len(left) == 0 {
t.Fatal("the copy must be KEPT after a failed put-back (D20)")
}
if *notified != 1 || *putBack != 0 {
t.Errorf("hold notices %d (want 1), put-back notices %d (want 0)", *notified, *putBack)
}
}
// The live definition cannot be written back after the volumes were poured: the app is held and the copy is KEPT
// (D20: a put-back that fails keeps its copy for support).
// RED-PROOF: drop `c.keep = true` from the definition write-back failure branch → the copy is removed → FAILS.
func TestR1256_H5_AFailedDefinitionWriteBackKeepsTheCopy(t *testing.T) {
m, vp, rig, _, _, _ := r893PutBackFixture(t)
// A version change, so a live definition exists to be written back; the second write (the write-back) fails.
if err := os.WriteFile(vp.composePath, []byte(vtCompose("18")), 0o644); err != nil {
t.Fatal(err)
}
vp.livePins = ParseComposeImages(vp.composePath)
p := &r1256DefFailProvider{r893Provider: vp, failWrites: 0}
p.failFrom = 2
m.SetStackProvider(p)
_, err := m.ReconstituteFromOffsite(context.Background(), "immich", false)
if err == nil {
t.Fatal("a failed restore must be surfaced")
}
if len(p.defs) < 2 {
t.Fatalf("the write-back never ran: writes %v", p.defs)
}
if held, _ := m.RestoreHoldFor("immich"); !held {
t.Fatal("a failed write-back must hold the app")
}
if left := undoCopies(t, rig.undoRoot); len(left) == 0 {
t.Fatal("the copy must be KEPT after a failed put-back (D20)")
}
}
// The crash put-back (a restore cut by a power loss): the stop before pouring fails → an error (the guard then
// holds the app and keeps the copy, R-1251 H2), nothing poured.
// RED-PROOF: restore the „(continuing)" WARN in PutBackInterruptedRestore → nil error, the copy poured → FAILS.
func TestR1256_H5_ACrashPutBackWhoseStopFailsRefuses(t *testing.T) {
dir := t.TempDir()
undo := filepath.Join(dir, "backups", "restore-undo", "app", "20261028T000000Z")
mustWrite(t, filepath.Join(undo, "undo.json"), `{"stack":"app","copied":["app_data"],"definition":false}`)
mustWrite(t, filepath.Join(undo, "app_data.tar"), "LIVE")
poured := 0
cp := NewCrashPutBack(func(string) error { return errors.New("compose down: timeout") }, nil, log.New(io.Discard, "", 0))
cp.volReplay = func(string, string) (int, error) { poured++; return 1, nil }
if err := cp.PutBackInterruptedRestore("app", undo); err == nil {
t.Fatal("a put-back whose stop failed must return an error")
}
if poured != 0 {
t.Fatal("the copy was poured back under an app that could not be stopped")
}
if _, err := os.Stat(filepath.Join(undo, "app_data.tar")); err != nil {
t.Fatal("the copy must stay on disk")
}
}
// restoreDockerVolumesFrom: a `docker volume rm -f` that fails (the volume is still in use) used to be ignored; the
// `volume create` that follows is a no-op on an existing volume, so the tar was unpacked ON TOP of the old content —
// a merge. Now that volume counts as failed and is not touched.
// RED-PROOF: ignore the rm error again → the create and the tar run for the volume → FAILS.
func TestR1256_H5_AVolumeThatCannotBeRemovedIsNotMergedInto(t *testing.T) {
bin := t.TempDir()
calls := filepath.Join(bin, "calls.log")
stub := "#!/bin/sh\necho \"$@\" >> " + calls + "\n" +
"case \"$*\" in 'compose version --short') echo v2.29.7;; 'volume rm -f app_busy') echo 'volume is in use' >&2; exit 1;; esac\nexit 0\n"
if err := os.WriteFile(filepath.Join(bin, "docker"), []byte(stub), 0o755); err != nil {
t.Fatal(err)
}
t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
dump := t.TempDir()
for _, n := range []string{"app_busy.tar", "app_free.tar"} {
mustWrite(t, filepath.Join(dump, n), "tar")
}
m := &Manager{logger: log.New(io.Discard, "", 0)}
n, err := m.restoreDockerVolumesFrom("app", dump)
if err == nil || n != 1 {
t.Fatalf("restored %d, err %v — want 1 and an error naming app_busy", n, err)
}
if !strings.Contains(err.Error(), "app_busy") {
t.Errorf("the error must name the volume: %v", err)
}
b, _ := os.ReadFile(calls)
for _, l := range strings.Split(string(b), "\n") {
if (strings.HasPrefix(l, "volume create") || strings.HasPrefix(l, "run ")) && strings.Contains(l, "app_busy") {
t.Fatalf("the volume that could not be removed was written into: %q", l)
}
}
}
// ---- H6: a second-drive mirror must not start between the page's refusal and the restore's own record.
// The page asked (nothing ran), then a mirror began, then the restore began: the begin itself refuses, records
// nothing, and the mirror — asked under the same lock — refuses once a restore is recorded.
// RED-PROOF: make TryBeginRestoreOp record the op without asking (the old BeginRestoreOp) → the restore begins beside
// the mirror → FAILS.
func TestR1256_H6_ARestoreCannotBeginBesideAMirrorThatStartedAfterTheCheck(t *testing.T) {
tier2ResetForTest()
defer tier2ResetForTest()
m, _ := newOffboxManager(t)
if busy, _ := m.RestoreBusy(); busy != "" {
t.Fatalf("fixture: nothing runs, got %q", busy)
}
// the window: the page's check passed; now a mirror begins
if !m.beginTier2Run("immich") {
t.Fatal("fixture: the mirror must begin while no restore is recorded")
}
if busy, app := m.TryBeginRestoreOp("restore", "immich"); busy != RestoreBusyMirror || app != "immich" {
t.Fatalf("the restore began beside a running mirror: busy=%q app=%q", busy, app)
}
if m.RestoreStatus().Running {
t.Fatal("a refused begin left a restore op recorded")
}
tier2CopyEnd("immich")
if busy, _ := m.TryBeginRestoreOp("restore", "immich"); busy != "" {
t.Fatalf("with the mirror done the restore must begin, got %q", busy)
}
if m.beginTier2Run("immich") {
t.Fatal("a mirror began while the restore of the same app is recorded")
}
// a second restore is refused while the first runs; the backup run refuses too
if busy, _ := m.TryBeginRestoreOp("restore", "other"); busy != RestoreBusyRestore {
t.Fatalf("a second restore began beside the first: %q", busy)
}
m.EndRestoreOp(true, "ok")
if err := m.AcquireRunningForTest(); err != nil {
t.Fatal(err)
}
if busy, _ := m.TryBeginRestoreOp("restore", "immich"); busy != RestoreBusyBackup {
t.Fatalf("a restore began beside a backup run: %q", busy)
}
m.ReleaseRunningForTest()
}
// ---- H8: an unused restore copy is cleaned up; a copy a hold or a pending put-back needs is never touched.
func r1256Copy(t *testing.T, m *Manager, app string, age time.Duration, now time.Time) string {
t.Helper()
dir := filepath.Join(restoreUndoDir(m.namespaceRoot(m.systemDataPath), app), now.Add(-age).UTC().Format(restoreCopyStampLayout))
mustWrite(t, filepath.Join(dir, app+"_data.tar"), "LIVE")
return dir
}
func r1256Exists(p string) bool { _, err := os.Stat(p); return err == nil }
// RED-PROOF: drop the hold check (or the marker check) from SweepUnusedRestoreCopies → the held / named copy is removed
// → FAILS; drop the age check → the young copy is removed → FAILS.
func TestR1256_H8_OnlyAnUnusedOldCopyIsRemoved(t *testing.T) {
m, sett := newOffboxManager(t)
now := time.Now()
old := 40 * 24 * time.Hour
unused := r1256Copy(t, m, "unused", old, now)
young := r1256Copy(t, m, "young", 24*time.Hour, now)
held := r1256Copy(t, m, "held", old, now)
waiting := r1256Copy(t, m, "waiting", old, now)
named := r1256Copy(t, m, "named", old, now)
if err := sett.SetRestoreHold(settings.RestoreHold{Stack: "held", At: now.Format(time.RFC3339), Reason: settings.HoldReasonRestoreMixed}); err != nil {
t.Fatal(err)
}
if err := sett.SetRestoreHold(settings.RestoreHold{Stack: "waiting", At: now.Format(time.RFC3339), Reason: settings.HoldReasonPutBackPending}); err != nil {
t.Fatal(err)
}
// a restore cut by a power loss: the marker (no longer active after a failed recovery's End) still names the copy
if err := m.appStop.Begin("unit-restore:named", ReasonUnitRestore, []string{"named"}); err != nil {
t.Fatal(err)
}
if err := m.appStop.SetUndo("named", named); err != nil {
t.Fatal(err)
}
got := m.SweepUnusedRestoreCopies(now)
if len(got) != 1 || got[0] != unused || r1256Exists(unused) {
t.Fatalf("removed %v — want exactly the unused old copy %s", got, unused)
}
for _, keep := range []string{young, held, waiting, named} {
if !r1256Exists(keep) {
t.Errorf("a needed copy was removed: %s", keep)
}
}
if r1256Exists(filepath.Dir(unused)) {
t.Error("the emptied per-app folder must go too")
}
}
// While a restore runs nothing is removed; a marker that cannot be read stops the sweep.
// RED-PROOF: drop the RestoreBusy check → the old copy goes during a restore → FAILS.
func TestR1256_H8_NothingIsRemovedDuringARestoreOrWithAnUnreadableMarker(t *testing.T) {
m, _ := newOffboxManager(t)
now := time.Now()
c := r1256Copy(t, m, "app", 40*24*time.Hour, now)
m.BeginRestoreOp("restore", "other")
if got := m.SweepUnusedRestoreCopies(now); len(got) != 0 || !r1256Exists(c) {
t.Fatalf("removed %v during a restore", got)
}
m.EndRestoreOp(true, "ok")
mustWrite(t, m.appStop.path, "{not json")
if got := m.SweepUnusedRestoreCopies(now); len(got) != 0 || !r1256Exists(c) {
t.Fatalf("removed %v with an unreadable marker", got)
}
if err := os.Remove(m.appStop.path); err != nil {
t.Fatal(err)
}
if got := m.SweepUnusedRestoreCopies(now); len(got) != 1 {
t.Fatalf("control: with nothing in the way the old copy goes, removed %v", got)
}
}
@@ -0,0 +1,133 @@
package backup
import (
"context"
"errors"
"io"
"log"
"os"
"strings"
"testing"
"gitea.dooplex.hu/admin/felhom-controller/internal/settings"
)
// R-1340: a restore_mixed hold records WHAT put it in place — which restore, which branch, which put-back step failed,
// whether the restore's failure was a database replay, and where the copy is kept — so the operator's mail
// (cmd/controller heldStoppedOperatorText, pinned by TestR1340_* there) tells the real story. Measured 2026-10-29 on
// Tester 1: Radicale (no database), its volume could not be removed, the put-back's stop failed, and the mail said its
// DATABASE restore failed and was rolled back.
//
// RED-PROOF (2026-10-29): with the R-1340 fields dropped from holdAppAfterMixedRestore's hold literal and from
// holdPutBackFailed's (the pre-R-1340 record, which carried no cause), all five tests below fail on „mixed cause """ /
// „kind """.
func holdOf(t *testing.T, m *Manager, stack string) settings.RestoreHold {
t.Helper()
if m.settings == nil {
t.Fatal("fixture: no settings wired")
}
h, ok := m.settings.GetRestoreHold(stack)
if !ok {
t.Fatalf("%s is not held", stack)
}
return h
}
// The Radicale shape: a VOLUME restore fails (no database involved), then the put-back's stop fails.
func TestR1340_AVolumeFailureWhosePutBackStopFailsRecordsTheStepAndNoDatabase(t *testing.T) {
m, vp, rig, _, notified, _ := r893PutBackFixture(t)
rig.snapReplayErr = errors.New("volume rm -f immich_pgdata: volume is in use")
p := &r1256StopFailProvider{r893Provider: vp, failAt: 2} // 1 = the restore's stop, 2 = the put-back's
m.SetStackProvider(p)
if _, err := m.ReconstituteFromOffsite(context.Background(), "immich", false); err == nil {
t.Fatal("a failed restore must be surfaced")
}
h := holdOf(t, m, "immich")
if h.Reason != settings.HoldReasonRestoreMixed || h.MixedCause != settings.MixedCausePutBack {
t.Fatalf("reason %q, mixed cause %q — want restore_mixed / put_back", h.Reason, h.MixedCause)
}
if !strings.Contains(h.FailedStep, "stopping the app before the put-back failed") || !strings.Contains(h.FailedStep, "compose down: timeout") {
t.Errorf("failed step %q — want the stop and its error", h.FailedStep)
}
if h.DBReplay {
t.Error("a volume failure must not be recorded as a database replay")
}
if h.RestoreKind != settings.RestoreKindOffsite {
t.Errorf("restore kind %q, want offsite", h.RestoreKind)
}
if h.SafetyDump == "" {
t.Error("the kept copy's folder must be recorded")
} else if _, err := os.Stat(h.SafetyDump); err != nil {
t.Errorf("the recorded copy %s is not on disk: %v", h.SafetyDump, err)
}
if *notified != 1 {
t.Errorf("hold notices %d, want 1", *notified)
}
}
// The database replay fails (option C's shape), then the put-back's stop fails: DBReplay is recorded.
func TestR1340_ADatabaseReplayFailureRecordsTheDatabase(t *testing.T) {
m, vp, _, _, _, _ := r893PutBackFixture(t)
m.SetStackProvider(&r1256StopFailProvider{r893Provider: vp, failAt: 2})
if _, err := m.ReconstituteFromOffsite(context.Background(), "immich", false); err == nil {
t.Fatal("a failed restore must be surfaced")
}
h := holdOf(t, m, "immich")
if h.MixedCause != settings.MixedCausePutBack || !h.DBReplay {
t.Fatalf("mixed cause %q, db replay %v — want put_back and true", h.MixedCause, h.DBReplay)
}
}
// R-1256 H4: the backup's definition cannot be written and the live one cannot be written back — no data moved.
func TestR1340_ADefinitionWriteFailureRecordsItsCause(t *testing.T) {
m, _, _ := r1256DefFailFixture(t, 2)
if _, err := m.ReconstituteFromOffsite(context.Background(), "immich", false); err == nil {
t.Fatal("a failed definition write must be surfaced")
}
h := holdOf(t, m, "immich")
if h.MixedCause != settings.MixedCauseDefinitionWrite || h.DBReplay {
t.Fatalf("mixed cause %q, db replay %v — want definition_write and false", h.MixedCause, h.DBReplay)
}
if !strings.Contains(h.FailedStep, "writing the live app definition back failed") {
t.Errorf("failed step %q", h.FailedStep)
}
}
// A LOCAL restore (from the app's own backup) records itself as local, never off-site.
func TestR1340_ALocalRestoreRecordsItsKind(t *testing.T) {
m, _, rig, _ := r1177Fixture(t)
if m.settings == nil {
sett, err := settings.Load(t.TempDir()+"/settings.json", log.New(io.Discard, "", 0))
if err != nil {
t.Fatal(err)
}
m.settings = sett
}
rig.unitErr = errors.New("tar: short read")
rig.putBackErr = errors.New("tar xf failed")
if _, err := m.RestoreFromRecoveryUnit("app"); err == nil {
t.Fatal("a failed put-back must be surfaced")
}
h := holdOf(t, m, "app")
if h.RestoreKind != settings.RestoreKindLocal || h.MixedCause != settings.MixedCausePutBack || h.DBReplay {
t.Fatalf("kind %q, cause %q, db %v — want local / put_back / false", h.RestoreKind, h.MixedCause, h.DBReplay)
}
if !strings.Contains(h.FailedStep, "putting the live volumes back failed") || !strings.Contains(h.FailedStep, "tar xf failed") {
t.Errorf("failed step %q", h.FailedStep)
}
}
// A restore cut by a stop whose put-back fails at the next start (R-1251 H2) records its own cause.
func TestR1340_AnInterruptedPutBackRecordsItsCause(t *testing.T) {
r := newR1251Rig(t)
r.putErr = errors.New("compose down: timeout")
r.guard().Recover()
h, ok := r.sett.GetRestoreHold("immich")
if !ok || h.Reason != settings.HoldReasonRestoreMixed || h.MixedCause != settings.MixedCauseInterruptedPutBack {
t.Fatalf("hold %+v (held %v) — want restore_mixed / interrupted_put_back", h, ok)
}
if !strings.Contains(h.FailedStep, "compose down: timeout") {
t.Errorf("failed step %q", h.FailedStep)
}
}
@@ -0,0 +1,122 @@
package backup
import (
"errors"
"io"
"log"
"path/filepath"
"sync/atomic"
"testing"
"time"
"gitea.dooplex.hu/admin/felhom-controller/internal/settings"
)
// r1342Drive registers the rig's app drive, as every drive is registered on a box, so the list and the delete see it.
func r1342Drive(t *testing.T, m *Manager) {
t.Helper()
if m.settings == nil {
sett, err := settings.Load(filepath.Join(t.TempDir(), "settings.json"), log.New(io.Discard, "", 0))
if err != nil {
t.Fatal(err)
}
m.settings = sett
}
if err := m.settings.AddStoragePath(settings.StoragePath{Path: m.GetAppDrivePath("app"), Label: "rig"}); err != nil {
t.Fatal(err)
}
}
// R-1342 (found live on Tester 1, 2026-10-29 10:39 CET): (1) while the box still watches whether a restored app runs
// stably, its restore copy is the way back — „Törlés most" must not take it (D62: never while an operation runs on the
// app); (2) an app REMOVED during that watch is not „did not start" — no operator alarm, no „the copy is kept".
// removableProvider is the stable-watch rig's provider that can answer StackRemoved.
type removableProvider struct {
*sampledProvider
removed atomic.Bool
}
func (p *removableProvider) StackRemoved(string) bool { return p.removed.Load() }
// RED-PROOF: drop the watching check from restoreCopyNeededFor / DeleteRestoreCopy → the copy is offered and deleted
// mid-watch → FAILS.
func TestR1342_ACopyUnderTheStableWatchIsNotDeletable(t *testing.T) {
withStable(t, 400*time.Millisecond, 3*time.Second)
m, rig, alarms := fixARig(t, func(int) bool { return true },
func(int) []ContainerSample { return []ContainerSample{healthy("c1", 0)} })
r1342Drive(t, m)
m.BeginRestoreOp("restore", "app")
if _, err := m.RestoreFromRecoveryUnit("app"); err != nil {
t.Fatal(err)
}
m.EndRestoreOp(true, "ok")
copies := m.RestoreCopies()
if len(copies) != 1 || copies[0].Needed != RestoreCopyNeededChecking || !copies[0].DeleteOn.IsZero() {
t.Fatalf("mid-watch the copy must read „checking\", got %+v", copies)
}
if _, err := m.DeleteRestoreCopy("app", copies[0].Stamp); !errors.Is(err, ErrRestoreCopyNeeded) {
t.Fatalf("a delete mid-watch: %v, want ErrRestoreCopyNeeded", err)
}
if left := undoCopies(t, rig.undoRoot); len(left) != 1 {
t.Fatalf("the copy must stay through the watch, found %v", left)
}
if left := waitNoCopies(t, rig.undoRoot); len(left) != 0 {
t.Fatalf("after the stable window the watch releases it, found %v", left)
}
if len(*alarms) != 0 {
t.Fatalf("no alarm: %v", *alarms)
}
if m.watchingCopy(filepath.Join(rig.undoRoot, copies[0].Stamp)) {
t.Fatal("the watch mark must go when the watch ends")
}
}
// RED-PROOF: drop the stableRemoved case → the removed app „did not run stably" → one alarm → FAILS.
func TestR1342_AnAppRemovedDuringTheWatchRaisesNoAlarm(t *testing.T) {
withStable(t, 2*time.Second, 400*time.Millisecond)
var up atomic.Bool
up.Store(true)
m, rig, alarms := fixARig(t, func(int) bool { return up.Load() },
func(int) []ContainerSample { return []ContainerSample{healthy("c1", 0)} })
rp := &removableProvider{sampledProvider: m.stackProvider.(*sampledProvider)}
m.stackProvider = rp
r1342Drive(t, m)
m.BeginRestoreOp("restore", "app")
if _, err := m.RestoreFromRecoveryUnit("app"); err != nil {
t.Fatal(err)
}
m.EndRestoreOp(true, "ok")
// the household removes the app inside the watch
up.Store(false)
rp.removed.Store(true)
time.Sleep(700 * time.Millisecond)
if len(*alarms) != 0 {
t.Fatalf("an app removed during the watch must not alarm „did not start\": %v", *alarms)
}
copies := m.RestoreCopies()
if len(copies) != 1 || copies[0].Needed != "" {
t.Fatalf("after the watch ended the copy is an unused one (sweep / Törlés most): %+v", copies)
}
_ = rig
}
// Control: an app that stays installed and never runs stably still alarms once (the R-1270 rule is unchanged).
func TestR1342_AnInstalledUnstableAppStillAlarms(t *testing.T) {
withStable(t, 2*time.Second, 400*time.Millisecond)
var up atomic.Bool
up.Store(true)
m, _, alarms := fixARig(t, func(int) bool { return up.Load() },
func(int) []ContainerSample { return []ContainerSample{healthy("c1", 0)} })
m.stackProvider = &removableProvider{sampledProvider: m.stackProvider.(*sampledProvider)}
m.BeginRestoreOp("restore", "app")
if _, err := m.RestoreFromRecoveryUnit("app"); err != nil {
t.Fatal(err)
}
m.EndRestoreOp(true, "ok")
up.Store(false)
time.Sleep(700 * time.Millisecond)
if len(*alarms) != 1 {
t.Fatalf("an installed app that never runs stably alarms once, got %v", *alarms)
}
}
@@ -0,0 +1,53 @@
package backup
import (
"io"
"log"
"testing"
"time"
"gitea.dooplex.hu/admin/felhom-controller/internal/settings"
)
// R-1347: a restore that lifts an UPDATE hold must also forget the stack manager's in-memory „last update ended held"
// flag. Left set, the crash-loop watcher does not watch the app and the night leg skips it until the controller restarts
// (D64's sibling: the operator's clear_hold already forgets it, R-1343; the restore did not).
//
// The consequence on the real flag — ObserveUnhealthy and legCandidate — is TestR1347_RestoreLiftsTheWatchersBlindSpot
// (cmd/controller), and the seam's wiring TestR1347_UpdateHeldForgetterIsWiredAtStartup.
//
// RED-PROOF (2026-11-02): seen failing before the seam existed — the build failed on SetUpdateHeldForgetter; with the
// call dropped from clearUpdateHoldAfterRestore it fails on „the flag was not forgotten".
func TestR1347_ARestoreThatLiftsAnUpdateHoldForgetsTheHeldFlag(t *testing.T) {
sett := slice4Settings(t)
m := &Manager{logger: log.New(io.Discard, "", 0), settings: sett}
forgot := map[string]int{}
m.SetUpdateHeldForgetter(func(s string) bool { forgot[s]++; return true })
_ = m.HoldAfterFailedUpdate("nextcloud", time.Now(), time.Now(), UpdateTierLocal)
m.clearUpdateHoldAfterRestore("nextcloud")
if _, held := sett.GetRestoreHold("nextcloud"); held {
t.Fatal("the update hold must be lifted")
}
if forgot["nextcloud"] != 1 {
t.Fatalf("the restore lifted the update hold, but the flag was not forgotten (calls: %v)", forgot)
}
// A RESTORE hold (R-379) stays, so nothing about it is forgotten.
_ = sett.SetRestoreHold(settings.RestoreHold{Stack: "rst", At: "2026-08-22T14:00:00Z"})
m.clearUpdateHoldAfterRestore("rst")
if _, held := sett.GetRestoreHold("rst"); !held || forgot["rst"] != 0 {
t.Fatalf("a restore hold is not lifted by a restore (held %v, forget calls %d)", held, forgot["rst"])
}
// No hold at all: nothing to forget (a plain restore of a healthy app).
m.clearUpdateHoldAfterRestore("plain")
if forgot["plain"] != 0 {
t.Fatalf("no hold was lifted, yet the flag was touched %d time(s)", forgot["plain"])
}
// nil seam: no crash (the pre-R-1347 behaviour).
m2 := &Manager{logger: log.New(io.Discard, "", 0), settings: sett}
_ = m2.HoldAfterFailedUpdate("other", time.Now(), time.Now(), UpdateTierLocal)
m2.clearUpdateHoldAfterRestore("other")
}
@@ -0,0 +1,75 @@
package backup
import (
"errors"
"strings"
"testing"
"gitea.dooplex.hu/admin/felhom-controller/internal/settings"
)
// R-1348: the restore_mixed hold written at START-UP after an interrupted put-back fails must reach the operator as the
// R-1340 mail. Recover runs long before the notifier exists (main.go), so the guard keeps the name and hands it over when
// SetHeldNotify is wired; a failure after that (a drive that returned at run time) goes out at once.
//
// RED-PROOF (2026-11-02): seen failing before the seam existed (build: SetHeldNotify); with the call dropped from
// holdPutBackFailed these fail on „no mail for a held app".
func TestR1348_AFailedPutBackAtStartupMailsOnceTheNotifierIsWired(t *testing.T) {
r := newR1251Rig(t)
r.putErr = errors.New("compose down: timeout")
g := r.guard()
if res := g.Recover(); res == nil || len(res.Held) != 1 {
t.Fatalf("recovery must hold the app: %+v", res)
}
var mailed []string
g.SetHeldNotify(func(stack string) { mailed = append(mailed, stack) })
if len(mailed) != 1 || mailed[0] != "immich" {
t.Fatalf("no mail for a held app: the hold from Recover must be handed over when the notifier is wired, got %v", mailed)
}
h, ok := r.sett.GetRestoreHold("immich")
if !ok || h.Reason != settings.HoldReasonRestoreMixed || h.MixedCause != settings.MixedCauseInterruptedPutBack ||
!strings.Contains(h.FailedStep, "compose down: timeout") {
t.Fatalf("the mail reads this record, and it is wrong: %+v", h)
}
g.SetHeldNotify(func(stack string) { mailed = append(mailed, "again:"+stack) })
if len(mailed) != 1 {
t.Fatalf("a held app is mailed once, not at every wiring: %v", mailed)
}
}
// A clean put-back, or one still waiting for its drive, is no failure: no mail.
func TestR1348_NoMailWithoutAFailedPutBack(t *testing.T) {
r := newR1251Rig(t)
g := r.guard()
g.Recover()
var mailed []string
g.SetHeldNotify(func(stack string) { mailed = append(mailed, stack) })
if len(mailed) != 0 {
t.Fatalf("a put-back that worked mailed: %v", mailed)
}
w := newR1251Rig(t)
w.unbind(t)
gw := w.guard()
gw.Recover()
gw.SetHeldNotify(func(stack string) { mailed = append(mailed, stack) })
if len(mailed) != 0 {
t.Fatalf("a put-back that waits for its drive has its own hold and reminder, not this mail: %v", mailed)
}
}
// After the wiring a failed put-back (the drive returned at run time: ResumePutBack) mails at once.
func TestR1348_AFailedResumeMailsAtOnce(t *testing.T) {
r := newR1251Rig(t)
r.unbind(t)
g := r.guard()
g.Recover() // waiting for its drive
var mailed []string
g.SetHeldNotify(func(stack string) { mailed = append(mailed, stack) })
r.bind(t)
r.putErr = errors.New("tar xf failed")
g.ResumePutBack("immich")
if len(mailed) != 1 || mailed[0] != "immich" {
t.Fatalf("a put-back that failed on resume must mail: %v", mailed)
}
}
+8 -2
View File
@@ -224,8 +224,14 @@ func (m *Manager) restoreDockerVolumesFrom(stackName, dumpDir string) (int, erro
m.logger.Printf("[INFO] [backup] Restoring Docker volume %s for %s", volName, stackName)
// Remove existing volume (ignore errors — may not exist)
dockerexec.Command("docker", "volume", "rm", "-f", volName).Run()
// Remove the existing volume. `rm -f` of a missing volume succeeds, so an error means the volume EXISTS and
// could not be removed (still in use). R-1256 H5: it used to be ignored — the `volume create` below is a no-op
// on an existing volume, and the tar was unpacked ON TOP of the old content (a merge). That volume fails now.
if out, err := dockerexec.Command("docker", "volume", "rm", "-f", volName).CombinedOutput(); err != nil {
m.logger.Printf("[ERROR] [backup] Failed to remove volume %s before the restore: %s — %v (not written into)", volName, strings.TrimSpace(string(out)), err)
failed = append(failed, volName)
continue
}
// Create fresh volume — WITH the labels compose gives its own volumes (R-658, v0.268.0). A bare
// `volume create` made a volume the update's undo (until v0.267.0) could not find, and one
@@ -0,0 +1,216 @@
package backup
import (
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"sort"
"strings"
"time"
"gitea.dooplex.hu/admin/felhom-controller/internal/settings"
)
// D62 (operator ruling 2026-10-29; `07` §6.3): the household sees its restore copies in the kept-copies list
// („Megőrzött másolatok") on the restore page — the app, the date of the restore the copy protects, its size, and the
// day the box deletes it by itself (restoreCopyUnusedAge after the restore) — and may delete one earlier with
// „Törlés most", after a warning and the app's name typed.
//
// A copy a hold or a pending put-back needs is NEVER deletable (the same three states the sweep leaves alone, R-1256
// H8): the row says why in one line and the button is off; the handler refuses it too. While any backup or restore
// operation runs on the box, a delete is refused (409). The check and the removal are ONE step under m.mu, so a
// restore cannot begin in between (the R-1256 H6 shape). Pinned by TestD62_*.
// Why a restore copy is needed — the row's one line, and the refusal's reason. "" = not needed: deletable.
const (
RestoreCopyNeededHold = "hold" // the app is held (a failed put-back keeps its copy, D20) — support decides
RestoreCopyNeededPutBack = "putback" // a put-back waits for its drive (R-1251) or a cut restore names it (D22)
RestoreCopyNeededUnknown = "unknown" // the app-stop marker cannot be read: nothing is offered (fail closed)
// RestoreCopyNeededChecking (R-1342): the box still watches whether the restored app runs stably (up to 30 minutes
// after the restore, R-1270) — the copy is the way back if it does not.
RestoreCopyNeededChecking = "checking"
)
var (
ErrRestoreCopyNotFound = errors.New("restore copy not found")
ErrRestoreCopyNeeded = errors.New("restore copy is needed by a hold or a pending put-back")
ErrRestoreCopyBusy = errors.New("a backup or restore operation runs")
)
// RestoreCopy is one restore copy (<namespace>/backups/restore-undo/<app>/<stamp>).
type RestoreCopy struct {
App string
Stamp string // the folder's name; with App, the copy's identity on the page
At time.Time // when the restore began (the stamp; the folder's time when the stamp does not parse)
SizeBytes int64
Path string
Needed string // "" or one of RestoreCopyNeeded*
DeleteOn time.Time // when the sweep removes it; zero when Needed != "" (a needed copy is never swept)
}
// restoreCopyAt is a copy's restore time: its stamp, or the folder's time when the stamp does not parse.
func restoreCopyAt(dir, name string) (time.Time, bool) {
if at, err := time.Parse(restoreCopyStampLayout, name); err == nil {
return at, true
}
fi, err := os.Stat(dir)
if err != nil {
return time.Time{}, false
}
return fi.ModTime(), true
}
// restoreCopyNeededFor is why app's copies are needed ("" = deletable). named is appStopNamedApps' answer, ok its ok.
func (m *Manager) restoreCopyNeededFor(app string, named map[string]bool, ok bool) string {
if !ok || m.settings == nil {
return RestoreCopyNeededUnknown
}
if named[app] {
return RestoreCopyNeededPutBack
}
if h, held := m.settings.GetRestoreHold(app); held {
if h.Reason == settings.HoldReasonPutBackPending {
return RestoreCopyNeededPutBack
}
return RestoreCopyNeededHold
}
return ""
}
func dirSize(dir string) int64 {
var n int64
_ = filepath.WalkDir(dir, func(_ string, d fs.DirEntry, err error) error {
if err == nil && d.Type().IsRegular() {
if fi, e := d.Info(); e == nil {
n += fi.Size()
}
}
return nil
})
return n
}
// RestoreCopies lists every restore copy on the box's drives, oldest first.
func (m *Manager) RestoreCopies() []RestoreCopy {
named, ok := m.appStopNamedApps()
var out []RestoreCopy
for _, nsRoot := range m.primaryUnitRoots() {
base := filepath.Join(nsRoot, "backups", "restore-undo")
apps, err := os.ReadDir(base)
if err != nil {
continue
}
for _, a := range apps {
if !a.IsDir() {
continue
}
app := a.Name()
needed := m.restoreCopyNeededFor(app, named, ok)
copies, err := os.ReadDir(filepath.Join(base, app))
if err != nil {
continue
}
for _, c := range copies {
if !c.IsDir() {
continue
}
dir := filepath.Join(base, app, c.Name())
at, ok := restoreCopyAt(dir, c.Name())
if !ok {
continue
}
rc := RestoreCopy{App: app, Stamp: c.Name(), At: at, SizeBytes: dirSize(dir), Path: dir, Needed: needed}
if rc.Needed == "" && m.watchingCopy(dir) {
rc.Needed = RestoreCopyNeededChecking
}
if rc.Needed == "" {
rc.DeleteOn = at.Add(restoreCopyUnusedAge)
}
out = append(out, rc)
}
}
}
sort.SliceStable(out, func(i, j int) bool { return out[i].At.Before(out[j].At) })
return out
}
// validCopyName is a single path element: no separator, not empty, not "." or "..".
func validCopyName(s string) bool {
return s != "" && s != "." && s != ".." && !strings.ContainsAny(s, `/\`) && filepath.Base(s) == s
}
// DeleteRestoreCopy removes ONE restore copy, named by its app and its folder's name, and nothing else (the path
// guard: both names are single path elements, the folder is a real directory — not a link — directly under
// <namespace>/backups/restore-undo/<app>/). Refused while any backup or restore operation runs (ErrRestoreCopyBusy)
// and for a copy a hold or a pending put-back needs (ErrRestoreCopyNeeded). The check and the removal hold m.mu, so
// no restore can begin in between. Returns the copy as it was (for the log line and the operator event).
func (m *Manager) DeleteRestoreCopy(app, stamp string) (RestoreCopy, error) {
if !validCopyName(app) || !validCopyName(stamp) {
return RestoreCopy{}, ErrRestoreCopyNotFound
}
m.mu.Lock()
defer m.mu.Unlock()
if busy, _ := m.restoreBusyLocked(); busy != "" {
return RestoreCopy{}, ErrRestoreCopyBusy
}
var found *RestoreCopy
for _, nsRoot := range m.primaryUnitRoots() {
appDir := filepath.Join(nsRoot, "backups", "restore-undo", app)
dir := filepath.Join(appDir, stamp)
fi, err := os.Lstat(dir)
if err != nil || !fi.IsDir() || fi.Mode()&os.ModeSymlink != 0 {
continue
}
if filepath.Dir(dir) != appDir || filepath.Dir(appDir) != filepath.Join(nsRoot, "backups", "restore-undo") {
continue
}
at, ok := restoreCopyAt(dir, stamp)
if !ok {
continue
}
found = &RestoreCopy{App: app, Stamp: stamp, At: at, SizeBytes: dirSize(dir), Path: dir}
break
}
if found == nil {
return RestoreCopy{}, ErrRestoreCopyNotFound
}
named, ok := m.appStopNamedApps()
if found.Needed = m.restoreCopyNeededFor(app, named, ok); found.Needed != "" {
return *found, ErrRestoreCopyNeeded
}
if m.watching[found.Path] { // R-1342: under m.mu, the same lock the watch marks its copy under
found.Needed = RestoreCopyNeededChecking
return *found, ErrRestoreCopyNeeded
}
if err := os.RemoveAll(found.Path); err != nil {
return *found, fmt.Errorf("removing the restore copy %s: %w", found.Path, err)
}
_ = os.Remove(filepath.Dir(found.Path)) // the per-app folder, when it is now empty
return *found, nil
}
// setWatching marks (on) or clears a copy a stable-start watch holds (R-1342).
func (m *Manager) setWatching(dir string, on bool) {
if dir == "" {
return
}
m.mu.Lock()
defer m.mu.Unlock()
if on {
if m.watching == nil {
m.watching = map[string]bool{}
}
m.watching[dir] = true
return
}
delete(m.watching, dir)
}
// watchingCopy reports whether a stable-start watch still holds the copy.
func (m *Manager) watchingCopy(dir string) bool {
m.mu.Lock()
defer m.mu.Unlock()
return m.watching[dir]
}
@@ -0,0 +1,130 @@
package backup
import (
"encoding/json"
"os"
"path/filepath"
"sort"
"time"
)
// R-1256 H8 (review round 2, HUNT-1): a restore copy (<namespace>/backups/restore-undo/<app>/<stamp>) that nothing
// will ever use again used to stay on the drive for good. A copy is KEPT on purpose in three states — a put-back that
// failed (the app is held, D20), a put-back waiting for its drive (the putback_pending hold, R-1251) and a restore cut
// by a power loss (the app-stop marker names it, D22) — and for 30 minutes after a restore while the box watches for a
// stable start (R-1270). Every one of those is still needed. A copy outside all of them — the app runs again, or was
// removed, and nothing names the copy — is disk the household cannot see or use.
//
// The rule (the age: operator ruling D62, 2026-10-29 — 30 days, and the household may delete a copy earlier with
// „Törlés most", restore_copies.go): a copy is removed only
// when ALL of these hold, and the sweep removes NOTHING when it cannot answer one of them:
// - it is older than restoreCopyUnusedAge (its folder's stamp; the folder's time when the stamp does not parse);
// - the app has no restore hold of any kind (held apps keep every copy — support decides);
// - the app-stop marker does not name the app (a pending put-back), and the marker is readable;
// - no restore op is in flight on the box (a new restore's copy and the stable-start watcher are left alone).
//
// Run every 6 hours from main.go (TestR1256_H8_TheSweepIsWiredAtStartup). Pinned by TestR1256_H8_*.
// restoreCopyUnusedAge is how long an unused copy stays after its restore (D62: 30 days; TestD62_AnUnusedCopyIsKept30Days).
const restoreCopyUnusedAge = 30 * 24 * time.Hour
// restoreCopyStampLayout is copyLiveVolumes' folder name.
const restoreCopyStampLayout = "20060102T150405Z"
// SweepUnusedRestoreCopies removes the restore copies no hold, no pending put-back and no running restore needs, and
// older than restoreCopyUnusedAge. Returns the folders removed.
func (m *Manager) SweepUnusedRestoreCopies(now time.Time) []string {
if busy, _ := m.RestoreBusy(); busy == RestoreBusyRestore {
m.logger.Printf("[INFO] [backup] restore-copy sweep skipped: a restore runs")
return nil
}
named, ok := m.appStopNamedApps()
if !ok {
m.logger.Printf("[WARN] [backup] restore-copy sweep skipped: the app-stop marker cannot be read — a copy it names must not go")
return nil
}
var removed []string
for _, nsRoot := range m.primaryUnitRoots() {
base := filepath.Join(nsRoot, "backups", "restore-undo")
apps, err := os.ReadDir(base)
if err != nil {
continue
}
for _, a := range apps {
if !a.IsDir() {
continue
}
app := a.Name()
if named[app] {
continue
}
if m.settings == nil {
return removed // no hold store: a held app cannot be told apart
}
if _, held := m.settings.GetRestoreHold(app); held {
continue
}
appDir := filepath.Join(base, app)
copies, err := os.ReadDir(appDir)
if err != nil {
continue
}
sort.Slice(copies, func(i, j int) bool { return copies[i].Name() < copies[j].Name() })
for _, c := range copies {
if !c.IsDir() {
continue
}
dir := filepath.Join(appDir, c.Name())
at, err := time.Parse(restoreCopyStampLayout, c.Name())
if err != nil {
fi, sErr := os.Stat(dir)
if sErr != nil {
continue
}
at = fi.ModTime()
}
if now.Sub(at) < restoreCopyUnusedAge {
continue
}
if err := os.RemoveAll(dir); err != nil {
m.logger.Printf("[WARN] [backup] %s: the unused restore copy %s could not be removed: %v", app, dir, err)
continue
}
m.logger.Printf("[INFO] [backup] %s: the unused restore copy %s (from %s) is removed — no hold, no pending put-back, older than %s (R-1256)",
app, dir, at.UTC().Format(time.RFC3339), restoreCopyUnusedAge)
removed = append(removed, dir)
}
_ = os.Remove(appDir) // the per-app folder, when it is now empty
}
}
return removed
}
// appStopNamedApps reads the app-stop marker without side effects: the apps of an ACTIVE marker and every app its Undo
// names. ok=false when the marker exists and cannot be read — the caller then touches nothing.
func (m *Manager) appStopNamedApps() (map[string]bool, bool) {
named := map[string]bool{}
if m.appStop == nil || m.appStop.path == "" {
return named, true
}
data, err := os.ReadFile(m.appStop.path)
if os.IsNotExist(err) {
return named, true
}
if err != nil {
return nil, false
}
var mk AppStopMarker
if err := json.Unmarshal(data, &mk); err != nil {
return nil, false
}
for app := range mk.Undo {
named[app] = true
}
if mk.Active {
for _, app := range mk.Stacks {
named[app] = true
}
}
return named, true
}
@@ -195,9 +195,11 @@ func (p *CrashPutBack) PutBackInterruptedRestore(stack, undoDir string) error {
if j.Stack != stack {
return fmt.Errorf("the restore copy at %s belongs to %q, not %q", undoDir, j.Stack, stack)
}
// R-1256 H5: never pour the copy back under an app that could not be stopped — a refusal here is a failed
// put-back: the guard holds the app and keeps the copy (R-1251 H2).
if p.stop != nil {
if err := p.stop(stack); err != nil {
p.logger.Printf("[WARN] [appstop] %s: stopping before the put-back failed: %v (continuing)", stack, err)
return fmt.Errorf("stopping %s before the put-back: %w", stack, err)
}
}
mgr := &Manager{logger: p.logger, volumeReplayFrom: p.volReplay, undoVolumeRemoveFn: p.volRemove}
+2 -1
View File
@@ -3,6 +3,7 @@ package backup
import (
"errors"
"fmt"
"gitea.dooplex.hu/admin/felhom-controller/internal/settings"
"gitea.dooplex.hu/admin/felhom-controller/internal/util"
"os"
"path/filepath"
@@ -530,7 +531,7 @@ func (m *Manager) RestoreFromRecoveryUnitAtWith(stackName, unitDir string, opt U
// without one (the unit holds no volume) only a database replay that began can have changed data — and with no
// copy to pour back that is the R-379 half state: held, never started (operator ruling 2026-08-22).
putBack := func(cause error, holdKey string, moved bool) (UnitRestoreResult, error) {
return res, m.putBackAfterFailedRestore(stackName, cause, liveDef, undo, moved || undo != nil, opt.FilesPlaced, restartStack, holdKey)
return res, m.putBackAfterFailedRestore(stackName, cause, liveDef, undo, moved || undo != nil, opt.FilesPlaced, restartStack, holdKey, settings.RestoreKindLocal)
}
// R-353: the count is captured even when the replay errors — a partial replay is a fact the
// customer's sentence has to be built from, and discarding it on the error path is how Scenario C
@@ -71,9 +71,14 @@ func orNone(s string) string {
// so and the kept copy is removed (the normal rule after a successful restore). A new restore of the app ends the watch
// untouched.
func (m *Manager) watchLateStart(stack, copyDir string, since time.Time, watch time.Duration) {
m.setWatching(copyDir, true) // R-1342: the copy is the way back while the app may still start
defer m.setWatching(copyDir, false)
switch m.waitStableStart(stack, since, since.Add(watch)) {
case stableAborted:
return // a new restore of this app owns it now
case stableRemoved:
m.logger.Printf("[INFO] [backup] %s: the app was removed while the box waited for it to start — the watch ends (R-1342)", stack)
return
case stableNot:
m.logger.Printf("[WARN] [backup] %s: still not running stably %s after its restore — the restore copy stays for support (%s) (R-1270)", stack, lateStartWatch, orNone(copyDir))
return
@@ -133,12 +138,26 @@ type containerSampler interface {
ContainerSamples(name string) ([]ContainerSample, error)
}
// StackRemovalReporter (R-1342) is the provider's optional answer to „was this app removed?" — true only when the app is
// known and no longer installed. A watch that sees it ends quietly: an app the household removed did not „fail to
// start". The production stackAdapter implements it (a compile-time assertion in cmd/controller/main.go).
type StackRemovalReporter interface {
StackRemoved(name string) bool
}
// stackRemoved asks the provider; a provider without the answer never reads „removed".
func (m *Manager) stackRemoved(stack string) bool {
r, ok := m.stackProvider.(StackRemovalReporter)
return ok && r.StackRemoved(stack)
}
type stableResult int
const (
stableYes stableResult = iota
stableNot
stableAborted
stableRemoved // R-1342: the app was removed during the watch
)
// stableSample is one look: ok, and the fingerprint (container id → restart count) a stable window must keep.
@@ -201,6 +220,9 @@ func (m *Manager) waitStableFor(stack string, watchFrom, deadline time.Time, win
if m.restoreBegunAfter(stack, watchFrom) {
return stableAborted
}
if m.stackRemoved(stack) {
return stableRemoved
}
ok, fp := m.stableSample(stack)
switch {
case !ok:
@@ -226,13 +248,17 @@ func (m *Manager) releaseAfterStableStart(stack, kind string, undo *liveVolumeCo
dir := undo.dir
from := time.Now() // taken HERE, before the goroutine: a restore begun after this moment is a new one
until := from.Add(stableReleaseWatch)
m.setWatching(dir, true) // R-1342: „Törlés most" refuses the copy while the watch holds it
go func() {
defer m.setWatching(dir, false)
switch m.waitStableStart(stack, from, until) {
case stableYes:
removeCopyDir(m, stack, dir)
m.logger.Printf("[INFO] [backup] %s: ran stably for %s after its %s — the restore copy is released (R-1270)", stack, stableStartWindow, kind)
case stableAborted:
m.logger.Printf("[INFO] [backup] %s: a new restore began before the %s's start was stable — its restore copy stays for support (%s)", stack, kind, dir)
case stableRemoved:
m.logger.Printf("[INFO] [backup] %s: the app was removed during the stable-start check after its %s — no alarm; the restore copy, if the remove left it, is an unused one (%s) (R-1342)", stack, kind, dir)
default:
m.logger.Printf("[ERROR] [backup] %s: did not run stably within %s after its %s — the restore copy stays for support (%s) (R-1270)", stack, stableReleaseWatch, kind, dir)
if m.restoreNotStartedNotify != nil {
@@ -262,6 +288,8 @@ func (m *Manager) restoredAppStarted(stack string) error {
return nil
case stableAborted:
return fmt.Errorf("a new restore of %s began", stack)
case stableRemoved:
return fmt.Errorf("%s was removed during the restore's start check", stack)
}
return fmt.Errorf("stack %s did not run stably for %s (it restarted or turned unhealthy) after restore", stack, verdictStableWindow)
}
@@ -674,6 +674,12 @@ func (m *Manager) clearUpdateHoldAfterRestore(stackName string) {
return
}
m.logger.Printf("[INFO] [backup] %s: restore completed — the update hold (set %s) is CLEARED", stackName, h.At)
// R-1347: the hold store and the stack manager's in-memory flag go together, as in the operator's clear (D64 = B, R-1343).
// Left set, the crash-loop watcher would not watch the restored app and the night leg would skip it until the next
// controller restart. A running update is not touched (ForgetUpdateHeld refuses it). Pinned by TestR1347_*.
if m.updateHeldForgetter != nil && m.updateHeldForgetter(stackName) {
m.logger.Printf("[INFO] [backup] %s: the restored app is watched and updated again — its update-held flag is forgotten (R-1347)", stackName)
}
// R-671 (v0.272.0): the undo copies the hold kept describe the state this restore just replaced. They
// were kept so the hold's data stayed recoverable; once the app is restored whole they are dead weight
// (measured 2026-09-24 on 9202: three nextcloud copies, ~0.9 GiB, outlived the hold and nothing named
@@ -691,6 +697,12 @@ func (m *Manager) SetUndoCopyRemover(fn func(stackName string) int) {
m.undoCopyRemover = fn
}
// SetUpdateHeldForgetter wires R-1347's seam: stacks.Manager.ForgetUpdateHeld. INIT-ONLY, main.go — pinned by
// TestR1347_UpdateHeldForgetterIsWiredAtStartup (an AST walk). The backup package cannot import stacks.
func (m *Manager) SetUpdateHeldForgetter(fn func(stackName string) bool) {
m.updateHeldForgetter = fn
}
// UpdateHeldStacks is the set of apps held stopped after a failed update (R-660, v0.268.0) — the
// FOURTH way the product stops an app on purpose, and until v0.268.0 the one `classifyRunStates` did
// not know: each hold's `app_update_held` was followed ~11 s later by an `app_start_failed` for the
+132
View File
@@ -0,0 +1,132 @@
// Package busymark writes the controller's „busy" file for the host agent (D65 = A, operator ruling 2026-10-29 15:50;
// felhom.eu `03`, `04` §6.1).
//
// WHY: the operator can reboot the guest from the hub. The agent refuses while a backup, a restore, an off-site run or
// an app update runs — but the controller's own work is invisible to the agent (it runs inside this container). So
// while any of it runs, this package keeps `<data>/ctl/busy` fresh: line 1 the time (RFC 3339, UTC), line 2 what runs.
// The agent reads it over one exact read-only grant (`pct exec <vmid> -- cat <the guest path>`), without Docker.
//
// FRESHNESS IS THE SIGNAL, NOT PRESENCE: the file is rewritten every Every (15 s) while busy and removed when idle.
// A controller that is killed or stuck mid-backup stops rewriting it, and the agent (90 s) reads the old file as „not
// busy" — a stuck controller is exactly the box a reboot is for. A file left by a previous run is removed at start.
// Pinned by busymark_test.go.
package busymark
import (
"context"
"errors"
"log"
"os"
"path/filepath"
"sync"
"time"
)
// FileName is the busy file inside the ctl directory (the directory of the hold-clear socket, 0700).
const FileName = "busy"
// DefaultEvery is the rewrite cadence while busy.
const DefaultEvery = 15 * time.Second
// Writer keeps the file in step with its probes.
type Writer struct {
Path string // <data>/ctl/busy
Every time.Duration
Now func() time.Time
Logger *log.Logger
mu sync.Mutex
probes []probe
last string // what the last tick saw ("" = idle)
}
type probe struct {
what string
busy func() bool
}
// AddProbe adds one kind of work: what is the sentence the agent shows the operator, busy says whether it runs now.
// A nil busy is ignored (a box without that component).
func (w *Writer) AddProbe(what string, busy func() bool) {
if busy == nil {
return
}
w.mu.Lock()
defer w.mu.Unlock()
w.probes = append(w.probes, probe{what: what, busy: busy})
}
// Busy returns the first running work's sentence, or "" when nothing runs.
func (w *Writer) Busy() string {
w.mu.Lock()
ps := append([]probe(nil), w.probes...)
w.mu.Unlock()
for _, p := range ps {
if p.busy() {
return p.what
}
}
return ""
}
func (w *Writer) now() time.Time {
if w.Now != nil {
return w.Now()
}
return time.Now()
}
func (w *Writer) logf(format string, args ...any) {
if w.Logger != nil {
w.Logger.Printf(format, args...)
}
}
// Tick runs one evaluation: write the file when busy, remove it when idle. Exported for the test and the start.
func (w *Writer) Tick() {
what := w.Busy()
if what == "" {
if err := os.Remove(w.Path); err != nil && !errors.Is(err, os.ErrNotExist) {
w.logf("[WARN] [busymark] the busy file could not be removed: %v — the agent reads it as busy for up to 90 s more", err)
}
if w.last != "" {
w.logf("[INFO] [busymark] idle again (was: %s) — an operator reboot of the box is no longer refused for it", w.last)
}
w.last = ""
return
}
body := w.now().UTC().Format(time.RFC3339) + "\n" + what + "\n"
if err := os.MkdirAll(filepath.Dir(w.Path), 0o700); err == nil {
tmp := w.Path + ".tmp"
if err = os.WriteFile(tmp, []byte(body), 0o600); err == nil {
err = os.Rename(tmp, w.Path)
}
if err != nil {
w.logf("[WARN] [busymark] the busy file could not be written: %v — an operator reboot is not refused for %s", err, what)
}
}
if w.last != what {
w.logf("[INFO] [busymark] busy: %s — an operator reboot of the box is refused until it ends", what)
}
w.last = what
}
// Run removes a file left by an earlier run, then ticks every Every until ctx ends (and removes the file then).
func (w *Writer) Run(ctx context.Context) {
every := w.Every
if every <= 0 {
every = DefaultEvery
}
w.Tick()
t := time.NewTicker(every)
defer t.Stop()
for {
select {
case <-ctx.Done():
_ = os.Remove(w.Path)
return
case <-t.C:
w.Tick()
}
}
}
@@ -0,0 +1,65 @@
package busymark
import (
"os"
"path/filepath"
"strings"
"testing"
"time"
)
// D65 = A: the agent refuses an operator reboot while the controller's busy file is fresh.
func newW(t *testing.T) (*Writer, *bool, *time.Time) {
t.Helper()
busy := false
now := time.Date(2026, 10, 29, 16, 0, 0, 0, time.UTC)
w := &Writer{Path: filepath.Join(t.TempDir(), "ctl", FileName), Now: func() time.Time { return now }}
w.AddProbe("a backup or a restore is running", func() bool { return busy })
return w, &busy, &now
}
// Busy → the file holds the time and the sentence; idle → gone. RED-PROOF: skip the write → no file → FAILS;
// skip the remove → the file stays → FAILS.
func TestBusyFileFollowsTheWork(t *testing.T) {
w, busy, now := newW(t)
w.Tick()
if _, err := os.Stat(w.Path); !os.IsNotExist(err) {
t.Fatalf("idle: a busy file exists (%v)", err)
}
*busy = true
w.Tick()
raw, err := os.ReadFile(w.Path)
if err != nil {
t.Fatalf("busy: no file: %v", err)
}
lines := strings.Split(strings.TrimSpace(string(raw)), "\n")
if len(lines) != 2 || lines[0] != now.Format(time.RFC3339) || lines[1] != "a backup or a restore is running" {
t.Fatalf("file %q", raw)
}
if fi, _ := os.Stat(w.Path); fi.Mode().Perm() != 0o600 {
t.Fatalf("mode %v, want 0600", fi.Mode().Perm())
}
// it is REWRITTEN while busy: freshness is the agent's signal
*now = now.Add(15 * time.Second)
w.Tick()
raw, _ = os.ReadFile(w.Path)
if !strings.HasPrefix(string(raw), now.Format(time.RFC3339)) {
t.Fatalf("not rewritten: %q", raw)
}
*busy = false
w.Tick()
if _, err := os.Stat(w.Path); !os.IsNotExist(err) {
t.Fatalf("idle again: the busy file is still there (%v) — the agent would refuse a reboot for 90 s more", err)
}
}
// The first probe that runs names the work; a nil probe is ignored.
func TestBusyNamesTheRunningWork(t *testing.T) {
w, _, _ := newW(t)
w.AddProbe("an app update is running", func() bool { return true })
w.AddProbe("ignored", nil)
if got := w.Busy(); got != "an app update is running" {
t.Fatalf("Busy() = %q", got)
}
}
@@ -0,0 +1,171 @@
// Package holdreport tells the hub which apps are held (D53, felhom.eu `08` §10).
//
// A held app is stopped on purpose and stays stopped until a person acts. Until D53 the hub knew nothing about it:
// the crash-loop stop sent one event, the other holds sent none, and demo-hp's Kimai sat held for 11 days unseen
// (R-1291). The legacy report is frozen, so the event channel carries the holds:
//
// - app_held when a hold appears or changes (stack, reason, since, the hold's sentence);
// - app_hold_cleared when it is gone — also when it went while the controller was down, because the set last
// reported is kept in settings (ReportedHolds), not in memory;
// - every hold still in place is sent again once a day and at every controller start, because an event can be
// lost. The hub treats a repeat as idempotent.
//
// ONE OBSERVER, NOT A HOOK PER WRITER. Seven code paths write a hold and four clear one. A send in each of them is
// the shape where the one path nobody found is the next silent hold; this package reads the hold store itself, so a
// new writer is covered the day it is added. Both events are severity info: the hub mails nothing on receipt. Its
// reminder after the grace per reason is the operator's mail, and it never goes to the household (D53).
//
// Pinned by holdreport_test.go.
package holdreport
import (
"log"
"sort"
"time"
"gitea.dooplex.hu/admin/felhom-controller/internal/settings"
)
// Event types — the hub's allowedEventTypes carries both (the coupling rule).
const (
EventHeld = "app_held"
EventCleared = "app_hold_cleared"
)
// ResendEvery is how often every hold still in place is sent again.
const ResendEvery = 24 * time.Hour
// Store is what the reporter needs of the settings.
type Store interface {
ListRestoreHolds() []settings.RestoreHold
GetReportedHolds() map[string]string
SetReportedHolds(map[string]string) error
}
// Push sends one event to the hub (notify.Notifier.PushEvent).
type Push func(eventType, severity, message string, details interface{})
// Details is the payload of both events.
type Details struct {
StackName string `json:"stack_name"`
Reason string `json:"reason,omitempty"`
Since string `json:"since,omitempty"`
Why string `json:"why,omitempty"`
Repeat bool `json:"repeat,omitempty"` // a daily or start-up re-send, not a new hold
}
// Reporter compares the hold store with what was last reported. Tick is called by the scheduler.
type Reporter struct {
store Store
push Push
logger *log.Logger
lastFull time.Time
// installed (R-1298) — nil = every app counts as installed.
installed func(stack string) bool
skipLogged map[string]bool
}
// New builds a reporter. The first Tick re-sends every hold (a controller start).
func New(store Store, push Push, logger *log.Logger) *Reporter {
return &Reporter{store: store, push: push, logger: logger}
}
func key(h settings.RestoreHold) string { return h.WireReason() + "|" + h.At }
// SetInstalled wires the „is this app installed?" check (R-1298). nil = every app counts as installed.
func (r *Reporter) SetInstalled(f func(stack string) bool) { r.installed = f }
// installHold is a hold that belongs to an app's INSTALL (R-704): a removal ends it. A restore hold (restore_failed,
// restore_mixed) does not — a person clears it, so it stays reported whatever the app's state (R-379).
func installHold(h settings.RestoreHold) bool {
switch h.Reason {
case settings.HoldReasonUnhealthyStop, settings.HoldReasonUpdateFailed, settings.HoldReasonPutBackPending:
return true
}
return false
}
// Tick sends what changed since the last tick, and every hold again when a day has passed.
func (r *Reporter) Tick(now time.Time) {
if r.store == nil || r.push == nil {
return
}
all := r.store.ListRestoreHolds()
sort.Slice(all, func(i, j int) bool { return all[i].Stack < all[j].Stack })
// R-1298: an install's hold of an app that is not installed any more (removed outside the product) is not a held
// app — it is skipped, and reported cleared if it was reported before. Logged once per stack per process.
holds := all[:0:0]
for _, h := range all {
if r.installed != nil && installHold(h) && !r.installed(h.Stack) {
if r.skipLogged == nil {
r.skipLogged = map[string]bool{}
}
if !r.skipLogged[h.Stack] {
r.skipLogged[h.Stack] = true
r.logf("[INFO] [holdreport] %s: a %s hold of an app that is not installed — not reported (R-1298)", h.Stack, h.WireReason())
}
continue
}
holds = append(holds, h)
}
prev := r.store.GetReportedHolds()
full := r.lastFull.IsZero() || now.Sub(r.lastFull) >= ResendEvery
cur := make(map[string]string, len(holds))
sent, cleared := 0, 0
for _, h := range holds {
k := key(h)
cur[h.Stack] = k
known, seen := prev[h.Stack]
if seen && known == k && !full {
continue
}
repeat := seen && known == k
r.push(EventHeld, "info", "App "+h.Stack+" is held: "+h.Why(),
Details{StackName: h.Stack, Reason: h.WireReason(), Since: h.At, Why: h.Why(), Repeat: repeat})
sent++
if !repeat {
r.logf("[INFO] [holdreport] %s held (%s since %s) — reported to the hub", h.Stack, h.WireReason(), h.At)
}
}
gone := make([]string, 0)
for stack := range prev {
if _, ok := cur[stack]; !ok {
gone = append(gone, stack)
}
}
sort.Strings(gone)
for _, stack := range gone {
r.push(EventCleared, "info", "App "+stack+" is no longer held", Details{StackName: stack})
cleared++
r.logf("[INFO] [holdreport] %s hold cleared — reported to the hub", stack)
}
if full {
r.lastFull = now
r.logf("[DEBUG] [holdreport] full re-send: %d hold(s) sent, %d cleared", sent, cleared)
}
if !sameMap(prev, cur) {
if err := r.store.SetReportedHolds(cur); err != nil {
// Not fatal: the next tick sends the same difference again, which the hub reads as idempotent.
r.logf("[WARN] [holdreport] could not save the reported holds: %v — the next tick repeats the difference", err)
}
}
}
func sameMap(a, b map[string]string) bool {
if len(a) != len(b) {
return false
}
for k, v := range a {
if b[k] != v {
return false
}
}
return true
}
func (r *Reporter) logf(format string, args ...interface{}) {
if r.logger != nil {
r.logger.Printf(format, args...)
}
}
@@ -0,0 +1,211 @@
package holdreport
import (
"io"
"log"
"os"
"path/filepath"
"strings"
"testing"
"time"
"gitea.dooplex.hu/admin/felhom-controller/internal/settings"
)
type fakeStore struct {
holds map[string]settings.RestoreHold
reported map[string]string
}
func (f *fakeStore) ListRestoreHolds() []settings.RestoreHold {
out := []settings.RestoreHold{}
for _, h := range f.holds {
out = append(out, h)
}
return out
}
func (f *fakeStore) GetReportedHolds() map[string]string {
out := map[string]string{}
for k, v := range f.reported {
out[k] = v
}
return out
}
func (f *fakeStore) SetReportedHolds(m map[string]string) error { f.reported = m; return nil }
type sent struct {
typ, sev string
d Details
}
func rec(out *[]sent) Push {
return func(t, sev, msg string, d interface{}) { *out = append(*out, sent{t, sev, d.(Details)}) }
}
var t0 = time.Date(2026, 10, 26, 18, 0, 0, 0, time.UTC)
// The report field (D53): a new hold is sent once as app_held with its stack, reason and since, severity info (the hub
// mails nothing on receipt; its reminder after the grace is the mail).
func TestD53_ANewHoldIsReportedWithStackReasonAndSince(t *testing.T) {
st := &fakeStore{holds: map[string]settings.RestoreHold{
"kimai": {Stack: "kimai", At: "2026-10-14T08:00:00Z", Reason: settings.HoldReasonUnhealthyStop, UnhealthyKind: "crash_loop"},
}}
var out []sent
r := New(st, rec(&out), nil)
r.Tick(t0)
if len(out) != 1 || out[0].typ != EventHeld || out[0].sev != "info" {
t.Fatalf("want one info app_held, got %+v", out)
}
d := out[0].d
if d.StackName != "kimai" || d.Reason != "unhealthy_stop" || d.Since != "2026-10-14T08:00:00Z" || d.Why == "" {
t.Fatalf("payload: %+v", d)
}
if st.reported["kimai"] != "unhealthy_stop|2026-10-14T08:00:00Z" {
t.Fatalf("reported record: %v", st.reported)
}
// The next tick inside a day sends nothing.
out = nil
r.Tick(t0.Add(time.Minute))
if len(out) != 0 {
t.Fatalf("an unchanged hold was sent again inside a day: %+v", out)
}
}
// An event can be lost: every hold still in place is sent again after a day, marked as a repeat.
func TestD53_AHoldIsSentAgainEveryDay(t *testing.T) {
st := &fakeStore{holds: map[string]settings.RestoreHold{"a": {Stack: "a", At: "2026-10-20T00:00:00Z", Reason: settings.HoldReasonUpdateFailed}}}
var out []sent
r := New(st, rec(&out), nil)
r.Tick(t0)
out = nil
r.Tick(t0.Add(ResendEvery))
if len(out) != 1 || out[0].typ != EventHeld || !out[0].d.Repeat {
t.Fatalf("want one repeat app_held after a day, got %+v", out)
}
}
// A hold cleared by a person ends it: one app_hold_cleared, then nothing.
func TestD53_AClearedHoldSendsClearedOnce(t *testing.T) {
st := &fakeStore{holds: map[string]settings.RestoreHold{"a": {Stack: "a", At: "2026-10-20T00:00:00Z", Reason: settings.HoldReasonRestoreMixed}}}
var out []sent
r := New(st, rec(&out), nil)
r.Tick(t0)
delete(st.holds, "a")
out = nil
r.Tick(t0.Add(time.Minute))
if len(out) != 1 || out[0].typ != EventCleared || out[0].d.StackName != "a" || out[0].sev != "info" {
t.Fatalf("want one info app_hold_cleared for a, got %+v", out)
}
if len(st.reported) != 0 {
t.Fatalf("the reported record still names the cleared hold: %v", st.reported)
}
out = nil
r.Tick(t0.Add(2 * time.Minute))
r.Tick(t0.Add(ResendEvery + time.Hour))
if len(out) != 0 {
t.Fatalf("a cleared hold was reported again: %+v", out)
}
}
// A hold cleared while the controller was down is still reported cleared: the record lives in settings.
func TestD53_AHoldClearedWhileDownIsReportedAtStart(t *testing.T) {
st := &fakeStore{holds: map[string]settings.RestoreHold{}, reported: map[string]string{"gone": "update_failed|2026-10-01T00:00:00Z"}}
var out []sent
New(st, rec(&out), nil).Tick(t0)
if len(out) != 1 || out[0].typ != EventCleared || out[0].d.StackName != "gone" {
t.Fatalf("want app_hold_cleared for gone at start, got %+v", out)
}
}
// A hold whose reason changes (a put-back that failed becomes a mixed restore) is a new hold for the hub.
func TestD53_AChangedReasonIsReportedAgain(t *testing.T) {
st := &fakeStore{holds: map[string]settings.RestoreHold{"a": {Stack: "a", At: "2026-10-20T00:00:00Z", Reason: settings.HoldReasonPutBackPending}}}
var out []sent
r := New(st, rec(&out), nil)
r.Tick(t0)
st.holds["a"] = settings.RestoreHold{Stack: "a", At: "2026-10-20T01:00:00Z", Reason: settings.HoldReasonRestoreMixed}
out = nil
r.Tick(t0.Add(time.Minute))
if len(out) != 1 || out[0].typ != EventHeld || out[0].d.Reason != "restore_mixed" || out[0].d.Repeat {
t.Fatalf("want a new (not repeat) app_held restore_mixed, got %+v", out)
}
}
// The legacy empty reason is a restore that failed with its rollback: the hub reads it as restore_failed.
func TestD53_TheEmptyReasonIsRestoreFailedOnTheWire(t *testing.T) {
st := &fakeStore{holds: map[string]settings.RestoreHold{"db": {Stack: "db", At: "2026-10-20T00:00:00Z"}}}
var out []sent
New(st, rec(&out), nil).Tick(t0)
if len(out) != 1 || out[0].d.Reason != "restore_failed" {
t.Fatalf("want reason restore_failed, got %+v", out)
}
}
// The seam is wired: main builds the reporter on the real settings and notifier and ticks it from the scheduler. A
// reporter nobody ticks is the inert-seam shape (four instances in this project). A commented-out line does not count.
func TestD53_TheReporterIsWiredInMain(t *testing.T) {
raw, err := os.ReadFile(filepath.Join("..", "..", "cmd", "controller", "main.go"))
if err != nil {
t.Fatalf("cannot read main.go: %v", err)
}
live := []string{}
for _, l := range strings.Split(string(raw), "\n") {
if !strings.HasPrefix(strings.TrimSpace(l), "//") {
live = append(live, l)
}
}
src := strings.Join(live, "\n")
for _, want := range []string{"holdreport.New(sett, notifier.PushEvent, logger)", `sched.Every("hold-report"`, "holdReporter.Tick(", "holdReporter.SetInstalled("} {
if !strings.Contains(src, want) {
t.Errorf("main.go lacks %q — the hold report is not wired", want)
}
}
}
// The reported record survives a restart: it is what lets a hold cleared while the controller was down be reported.
func TestD53_TheReportedRecordSurvivesAReload(t *testing.T) {
p := filepath.Join(t.TempDir(), "settings.json")
s, err := settings.Load(p, log.New(io.Discard, "", 0))
if err != nil {
t.Fatal(err)
}
if err := s.SetReportedHolds(map[string]string{"kimai": "unhealthy_stop|2026-10-14T08:00:00Z"}); err != nil {
t.Fatal(err)
}
s2, err := settings.Load(p, log.New(io.Discard, "", 0))
if err != nil {
t.Fatal(err)
}
if got := s2.GetReportedHolds()["kimai"]; got != "unhealthy_stop|2026-10-14T08:00:00Z" {
t.Fatalf("after a reload the record reads %q", got)
}
}
// R-1298: an install's hold (crash-loop stop, failed update, waiting put-back) of an app that is NOT installed any more is
// not reported — on 9202 four such holds from a hand removal would have mailed the operator weekly about apps that do not
// exist. A restore hold stays reported whatever the app's state (R-379: a person clears it). A hold reported earlier and
// now skipped is reported cleared. COMPANION RED-PROOF: without the installed check all three holds are reported.
func TestR1298_OnlyHoldsOfInstalledAppsAreReported(t *testing.T) {
st := &fakeStore{holds: map[string]settings.RestoreHold{
"gone": {Stack: "gone", At: "2026-09-24T12:16:24Z", Reason: settings.HoldReasonUnhealthyStop},
"gonedb": {Stack: "gonedb", At: "2026-09-24T12:16:24Z", Reason: settings.HoldReasonRestoreFailed},
"present": {Stack: "present", At: "2026-10-26T17:37:52Z", Reason: settings.HoldReasonUpdateFailed},
}, reported: map[string]string{"gone": "unhealthy_stop|2026-09-24T12:16:24Z"}}
var out []sent
r := New(st, rec(&out), nil)
r.SetInstalled(func(stack string) bool { return stack == "present" })
r.Tick(t0)
got := map[string]string{}
for _, s := range out {
got[s.d.StackName] = s.typ
}
if got["gone"] != EventCleared {
t.Errorf("the hold of an app that is not installed must be reported cleared, got %q", got["gone"])
}
if got["gonedb"] != EventHeld {
t.Errorf("a restore hold must stay reported even when the app is gone, got %q", got["gonedb"])
}
if got["present"] != EventHeld {
t.Errorf("an installed app's hold must be reported, got %q", got["present"])
}
}
+32 -1
View File
@@ -953,6 +953,7 @@
"dashboard.tunnel_offline_title": "The secure internet connection is not connected now, so your apps cannot be reached from outside. Check the internet connection.",
"dashboard.utolso_mentes": "Last backup:",
"dashboard.vedett": "Protected",
"dashboard.operator_reboot": "Felhom support restarted your box at %s.",
"dashboard.vezerlopult": "Dashboard",
"datapath.consequence.excluded": "This folder is temporary and is not backed up.",
"datapath.consequence.import_excluded": "Copy the files to be processed in here. The app reads them and then deletes them from here — this folder is temporary and is not backed up.",
@@ -1258,6 +1259,9 @@
"err.appexport.a_z_kotet_adata_hianyzik_a": "the data of volume %q is missing from the package",
"err.appexport.jelszo_hibas_vagy_a_fajl_serult": "wrong password, or the file is damaged",
"err.appexport.ket_adatkonyvtar_azonos_nevvel_vegzodik_es": "two data folders end in the same name (%q: %s and %s) — the package could not tell them apart",
"err.appexport.kulonleges_fajl": "%s is a special file (a pipe, socket or device) that cannot be saved — the export stopped; nothing was left out silently",
"err.appexport.import_foglalt": "a package cannot be loaded right now: another operation is working on the box (%s). Wait until it finishes and try again.",
"err.appexport.hdd_path_hibas": "the data-drive path in the package is not valid (“%s”) — the import did not start, nothing changed",
"err.appexport.visszafejtes_sikertelen": "decryption failed: %s",
"err.backup.whole_restore_space": "There is not enough room on the drive to bring the files back: %.1f GB needed, %.1f GB free. Nothing was changed.",
"err.backup.whole_restore_no_proven_copy": "The second drive holds no checked copy that can bring the app back together with its files. Nothing was changed.",
@@ -2631,6 +2635,20 @@
"kept.delete.type": "To delete it, type: %s",
"kept.delete.mismatch": "The name you typed does not match (%s), so nothing was deleted.",
"kept.deleted": "The kept data of %s is deleted.",
"restore_copy.title": "Copies from before a restore",
"restore_copy.hint": "When you restore an app, the box first saves the app’s data as it was. It deletes that copy by itself 30 days after the restore.",
"restore_copy.restored_on": "restore on %s",
"restore_copy.auto_delete": "automatically deleted on %s",
"restore_copy.needed.hold": "Cannot be deleted: the app is stopped, and this copy is its way back. Support decides about it.",
"restore_copy.needed.putback": "Cannot be deleted: an interrupted restore puts the data back from this copy.",
"restore_copy.needed.unknown": "Cannot be deleted now: the box cannot tell whether this copy is still needed.",
"restore_copy.needed.checking": "Cannot be deleted now: the box is still checking that the app started well after the restore (up to 30 minutes).",
"restore_copy.delete": "Delete now",
"restore_copy.warning": "This is the copy of %s’s data from before the restore on %s. If you delete it, the restore can no longer be undone, and this copy cannot be brought back.",
"restore_copy.app_busy": "Cannot be deleted now: an operation runs on the app. Try again when it has ended.",
"restore_copy.not_found": "This copy is no longer there, so nothing was deleted.",
"restore_copy.failed": "The copy could not be deleted: %s",
"flash.restore_copy.deleted": "The copy of %s from before its restore is deleted.",
"kept.page.title": "Kept data",
"kept.page.back": "Back",
"kept.page.intro": "Data that removed apps left on the drives. You can look at it, load it into a new install, or delete it. The server never deletes any of it by itself.",
@@ -2663,11 +2681,13 @@
"api.escrow.too_many_attempts": "Too many failed attempts, try again in 1 minute.",
"api.escrow.stage_failed": "Preparing the remote backup password for escrow failed — the process did not start. Try again.",
"api.escrow.already_running": "A code is already being created — wait until it finishes.",
"api.escrow.recovery_offer_open": "You cannot create a new recovery code right now: first open your old off-site backups with your existing code (Backups page). A new code would replace the key of the old backups.",
"api.escrow.code_not_shown": "The code was created but not shown — for security it cannot be fetched again. Start the process again: the new code replaces the old one.",
"api.escrow.no_active_job": "There is no active recovery process — start creating the code first.",
"api.escrow.confirm_expired": "The time to type the new code back has run out — your previous code still works. Start the process again.",
"api.escrow.confirm_lost": "The new code no longer waits for confirmation — your previous code still works. Start the process again.",
"api.escrow.confirm_store_failed": "The new code could not be saved — your previous code still works. Try again.",
"api.escrow.confirm_store_unknown": "We cannot tell yet whether the new code was saved — the server did not answer in time. Keep both codes (the old one and the new one) and try again.",
"api.escrow.confirm_words_mismatch": "The words do not match — check the code you wrote down.",
"api.share.form_invalid": "Invalid form — reload the page.",
"api.share.too_many_attempts": "Too many failed attempts, try again in 1 minute",
@@ -2868,5 +2888,16 @@
"err.backup.restore_image_gone": "The version of this backup (%s) cannot be downloaded: its maker no longer offers it. We did not touch the app. Choose another backup.",
"err.backup.restore_image_unreachable": "The version of this backup (%s) cannot be downloaded right now, so we did not touch the app. Try again later, or choose another backup.",
"kept.backup.future_note": "(its date is in the future — the clock of the box that made it may have been wrong)",
"kept.choice.use.future": "Note: the date of this backup (%s) is in the future. The clock of the box that made it may have been wrong. Choose it only if you are sure it is your backup."
"kept.choice.use.future": "Note: the date of this backup (%s) is in the future. The clock of the box that made it may have been wrong. Choose it only if you are sure it is your backup.",
"offsite_end.dialog": "The local backups are deleted now. The off-site copies stay for 30 more days. They are deleted on: {date}. Until then you can take this back on the Backups page.",
"offsite_end.marked": "Marked for deletion. Deleted on: %s.",
"offsite_end.keep_button": "Keep it after all",
"offsite_end.kept_before": "The off-site copies of this app were kept.",
"offsite_end.start_button": "Delete in 30 days",
"offsite_end.done": "The off-site copies were deleted on %s.",
"flash.offsite_end.kept": "The off-site copies are kept.",
"flash.offsite_end.nothing_to_keep": "The off-site copies of this app are not marked for deletion, or are already deleted.",
"flash.offsite_end.not_possible": "The off-site copies of this app cannot be marked for deletion now.",
"flash.offsite_end.failed": "This could not be saved. Try again.",
"event.offsite_end_scheduled": "%s: the off-site copies of this app are marked for deletion. They are deleted on: %s. Until then you can take this back on the Backups page with the “Keep it after all” button."
}
+32 -1
View File
@@ -948,6 +948,7 @@
"dashboard.tunnel_offline_title": "A biztonságos internetkapcsolat most nem kapcsolódik, ezért az alkalmazásaid kívülről nem érhetők el. Ellenőrizd az internetkapcsolatot.",
"dashboard.utolso_mentes": "Utolsó mentés:",
"dashboard.vedett": "Védett",
"dashboard.operator_reboot": "A Felhom ügyfélszolgálata %s-kor újraindította a dobozt.",
"dashboard.vezerlopult": "Vezérlőpult",
"datapath.consequence.excluded": "Ez a mappa átmeneti, és nem készül róla biztonsági mentés.",
"datapath.consequence.import_excluded": "Ide másold a feldolgozandó fájlokat. Az alkalmazás beolvassa, majd törli innen — ez a mappa átmeneti, és nem készül róla biztonsági mentés.",
@@ -1253,6 +1254,9 @@
"err.appexport.a_z_kotet_adata_hianyzik_a": "a(z) %q kötet adata hiányzik a csomagból",
"err.appexport.jelszo_hibas_vagy_a_fajl_serult": "jelszó hibás vagy a fájl sérült",
"err.appexport.ket_adatkonyvtar_azonos_nevvel_vegzodik_es": "két adatkönyvtár azonos névvel végződik (%q: %s és %s) — a csomag nem tudná megkülönböztetni őket",
"err.appexport.kulonleges_fajl": "a(z) %s különleges fájl (cső, foglalat vagy eszköz), ezt nem lehet menteni — az exportálás leállt, semmi nem maradt ki csendben",
"err.appexport.import_foglalt": "most nem tölthetsz vissza csomagot: egy másik művelet dolgozik a dobozon (%s). Várd meg, míg befejeződik, és próbáld újra.",
"err.appexport.hdd_path_hibas": "a csomag adatmeghajtó-útvonala hibás („%s”) — a betöltés el sem indult, semmi nem változott",
"err.appexport.visszafejtes_sikertelen": "visszafejtés sikertelen: %s",
"err.backup.whole_restore_space": "Nincs elég hely a meghajtón a fájlok visszaállításához: %.1f GB kellene, %.1f GB szabad. Semmi nem változott.",
"err.backup.whole_restore_no_proven_copy": "A második meghajtón nincs olyan ellenőrzött másolat, amely az alkalmazást a fájljaival együtt vissza tudná hozni. Semmi nem változott.",
@@ -2619,6 +2623,20 @@
"kept.delete.type": "A törléshez írd be: %s",
"kept.delete.mismatch": "A beírt név nem egyezik (%s), ezért nem töröltünk semmit.",
"kept.deleted": "A(z) %s megőrzött adatai törölve.",
"restore_copy.title": "Visszaállítás előtti másolatok",
"restore_copy.hint": "Visszaállításkor a doboz előbb elmenti az alkalmazás akkori adatait. Ezt a másolatot a visszaállítás után 30 nappal magától törli.",
"restore_copy.restored_on": "visszaállítás: %s",
"restore_copy.auto_delete": "automatikusan törlődik: %s",
"restore_copy.needed.hold": "Nem törölhető: az alkalmazás le van állítva, és ez a másolat az út vissza. Az ügyfélszolgálat dönt róla.",
"restore_copy.needed.putback": "Nem törölhető: egy félbeszakadt visszaállítás ebből a másolatból teszi vissza az adatokat.",
"restore_copy.needed.unknown": "Most nem törölhető: a doboz nem tudja eldönteni, kell-e még ez a másolat.",
"restore_copy.needed.checking": "Most nem törölhető: a doboz még figyeli, hogy az alkalmazás rendben elindult-e a visszaállítás után (legfeljebb 30 percig).",
"restore_copy.delete": "Törlés most",
"restore_copy.warning": "Ez a(z) %s adatainak másolata a %s-i visszaállítás előttről. Ha törlöd, a visszaállítás többé nem vonható vissza, és ez a másolat nem hozható vissza.",
"restore_copy.app_busy": "Most nem törölhető: az alkalmazáson éppen egy művelet fut. Próbáld újra, ha véget ért.",
"restore_copy.not_found": "Ez a másolat már nincs meg, ezért nem töröltünk semmit.",
"restore_copy.failed": "A másolatot nem sikerült törölni: %s",
"flash.restore_copy.deleted": "A(z) %s visszaállítás előtti másolata törölve.",
"kept.page.title": "Megőrzött adatok",
"kept.page.back": "Vissza",
"kept.page.intro": "Az eltávolított alkalmazások lemezen maradt adatai. Megnézheted őket, betöltheted egy új telepítésbe, vagy törölheted. Magától a szerver soha nem töröl közülük semmit.",
@@ -2651,11 +2669,13 @@
"api.escrow.too_many_attempts": "Túl sok sikertelen próbálkozás, próbáld újra 1 perc múlva.",
"api.escrow.stage_failed": "A távoli mentés jelszavának letéti előkészítése nem sikerült — a folyamat nem indult el. Próbáld újra.",
"api.escrow.already_running": "Egy kódkészítés már folyamatban van — várd meg, míg befejeződik.",
"api.escrow.recovery_offer_open": "Most nem készíthetsz új helyreállítási kódot: előbb nyisd meg a régi, házon kívüli mentéseidet a meglévő kódoddal (Mentések oldal). Egy új kód lecserélné a régi mentések kulcsát.",
"api.escrow.code_not_shown": "A kód létrejött, de nem lett megjelenítve — biztonsági okból újra nem kérhető le. Indítsd újra a folyamatot: az új kód a régit érvényteleníti.",
"api.escrow.no_active_job": "Nincs aktív helyreállítási folyamat — előbb indítsd el a kódkészítést.",
"api.escrow.confirm_expired": "Lejárt az idő az új kód visszaírására — a régi kódod továbbra is érvényes. Indítsd újra a folyamatot.",
"api.escrow.confirm_lost": "Az új kód már nem vár megerősítésre — a régi kódod továbbra is érvényes. Indítsd újra a folyamatot.",
"api.escrow.confirm_store_failed": "Az új kódot nem sikerült elmenteni — a régi kódod továbbra is érvényes. Próbáld újra.",
"api.escrow.confirm_store_unknown": "Nem tudjuk biztosan, hogy az új kód mentése sikerült-e — a központ nem válaszolt időben. Őrizd meg mindkét kódot (a régit és az újat is), és próbáld újra.",
"api.escrow.confirm_words_mismatch": "A megadott szavak nem egyeznek — ellenőrizd a felírt kódot.",
"api.share.form_invalid": "Érvénytelen űrlap — töltsd újra az oldalt.",
"api.share.too_many_attempts": "Túl sok sikertelen próbálkozás, próbáld újra 1 perc múlva",
@@ -2856,5 +2876,16 @@
"err.backup.restore_image_gone": "Ennek a mentésnek a verzióját (%s) nem lehet letölteni: a készítője már nem kínálja. Az alkalmazáshoz nem nyúltunk. Válassz egy másik mentést.",
"err.backup.restore_image_unreachable": "Ennek a mentésnek a verzióját (%s) most nem lehet letölteni, ezért az alkalmazáshoz nem nyúltunk. Próbáld újra később, vagy válassz egy másik mentést.",
"kept.backup.future_note": "(a dátuma a jövőben van — a mentést készítő doboz órája rosszul járhatott)",
"kept.choice.use.future": "Figyelem: ennek a mentésnek a dátuma (%s) a jövőben van. A mentést készítő doboz órája rosszul járhatott. Csak akkor válaszd, ha biztosan ez a ti mentésetek."
"kept.choice.use.future": "Figyelem: ennek a mentésnek a dátuma (%s) a jövőben van. A mentést készítő doboz órája rosszul járhatott. Csak akkor válaszd, ha biztosan ez a ti mentésetek.",
"offsite_end.dialog": "A helyi mentések most törlődnek. A távoli másolatok még 30 napig megmaradnak. Törlésük napja: {date} Addig a Mentések oldalon visszavonhatod.",
"offsite_end.marked": "Törlésre kijelölve. Törlés napja: %s",
"offsite_end.keep_button": "Mégis megtartom",
"offsite_end.kept_before": "Ennek az alkalmazásnak a távoli másolatai megmaradtak.",
"offsite_end.start_button": "Törlés 30 nap múlva",
"offsite_end.done": "A távoli másolatok törölve: %s",
"flash.offsite_end.kept": "A távoli másolatok megmaradnak.",
"flash.offsite_end.nothing_to_keep": "Ennek az alkalmazásnak a távoli másolatai nincsenek törlésre kijelölve, vagy már törlődtek.",
"flash.offsite_end.not_possible": "Ennek az alkalmazásnak a távoli másolatait most nem lehet törlésre kijelölni.",
"flash.offsite_end.failed": "Nem sikerült elmenteni. Próbáld újra.",
"event.offsite_end_scheduled": "%s: az alkalmazás távoli másolatai törlésre vannak kijelölve. Törlésük napja: %s Addig a Mentések oldalon a „Mégis megtartom” gombbal visszavonhatod."
}
+18 -7
View File
@@ -20,11 +20,19 @@ import (
)
// Pinned image tags — NEVER ":latest" (a floating tag breaks reproducible golden bakes and lets the
// deployed version drift). Verified to resolve on Docker Hub before baking.
// deployed version drift). Verified to resolve on Docker Hub before baking. cloudflared follows Cloudflare's security
// notices (felhom.eu `01` „Tunnel placement"): 2026.10.3 since the notice of 2026-10-20 — before 2026.10.2 the image
// trusts eight eMudhra (emSign) intermediates with weak keys; 2026.10.4 since 2026-10-27 (VULN-176088, the metrics
// server's debug endpoints). traefik v3.7.16 and the file manager 1.5.8-stable since 2026-10-27 for their security
// notices (felhom.eu R-1304, R-1305; 1.5.7-stable is skipped — it broke existing TOTP sign-ins). Each new image reaches
// a running box by the reconcile at start: TestEnsureTraefik_ANewImageRecreatesTraefik,
// TestEnsureCloudflared_ANewImageRecreatesTheTunnel, TestReconcileFileBrowserImage_MovesOnlyTheImage.
// traefik v3.7.17 since 2026-11-02: GHSA-xv5x-242w-7hf7 (high, v3.7.14–v3.7.16): an unauthenticated client with a
// Negotiate/NTLM header holds a backend transport per connection until memory runs out, NTLM backend or not.
const (
TraefikImage = "traefik:v3.7.13"
CloudflaredImage = "cloudflare/cloudflared:2026.9.3"
FileBrowserImage = "gtstef/filebrowser:1.5.6-stable"
TraefikImage = "traefik:v3.7.17"
CloudflaredImage = "cloudflare/cloudflared:2026.10.4"
FileBrowserImage = "gtstef/filebrowser:1.5.8-stable"
// FileBrowserImportMount is the in-container mount point NAME for the canonical drop-zone
// (R-75): the bind lands at /srv/<this>. ASCII and space-free on purpose — it appears in a
// container path, in the generated compose, and (percent-encoded) in the deep-link URL.
@@ -95,9 +103,12 @@ const (
ForwardedHeadersMiddleware = "felhom-forwarded-headers"
HTTPSOnlyMiddleware = "felhom-https-only"
HTTPSOnlyCatchAllRouter = "felhom-https-only-catchall"
// HSTSMaxAgeSeconds is ONE DAY on purpose (decision 244 brief): no includeSubDomains, no preload — a longer value is
// the operator's decision (register row), because a browser keeps it even if the box is ever served without https.
HSTSMaxAgeSeconds = 86400
// HSTSMaxAgeSeconds is ONE YEAR (felhom.eu `09` §3 decision 249, D2 = A, R-1050): it was one day from 2026-10-15,
// and becomes one year after a month with no https trouble (searched 2026-11-14: the open and closed registers,
// the operator's mailbox, the hub's log — none). NEVER includeSubDomains, NEVER preload: a browser keeps this value
// for the whole year even if a name is ever served without https, and those two cannot be taken back.
// Pinned by TestRenderForwardedHeaders_HTTPSOnly.
HSTSMaxAgeSeconds = 31536000
)
// TraefikData is the per-customer input for the traefik stack. ACMEEmail empty → no Let's Encrypt
+3 -2
View File
@@ -164,8 +164,9 @@ func TestRenderForwardedHeaders_HTTPSOnly(t *testing.T) {
t.Errorf("%s must be redirectScheme{scheme: https, permanent: true}, got %v", HTTPSOnlyMiddleware, mws[HTTPSOnlyMiddleware])
}
h := mws[ForwardedHeadersMiddleware].(map[string]any)["headers"].(map[string]any)
if h["stsSeconds"] != HSTSMaxAgeSeconds || HSTSMaxAgeSeconds != 86400 {
t.Errorf("HSTS must be one day (86400) until the operator rules otherwise, got %v", h["stsSeconds"])
// R-1050 (decision 249): one year since the release after 2026-11-15; it was one day (86400) for the first month.
if h["stsSeconds"] != HSTSMaxAgeSeconds || HSTSMaxAgeSeconds != 31536000 {
t.Errorf("HSTS must be one year (31536000) — decision 249 — got %v (constant %d)", h["stsSeconds"], HSTSMaxAgeSeconds)
}
if h["stsIncludeSubdomains"] != false || h["stsPreload"] != false {
t.Errorf("HSTS must not include subdomains nor preload, got %v / %v", h["stsIncludeSubdomains"], h["stsPreload"])
+7
View File
@@ -0,0 +1,7 @@
# upstream.txt — where each pin in infra.go publishes its security notices (the security watch, felhom.eu R-1303).
# One line per `*Image` const in infra.go: the const name, then its sources. The grammar lives in ONE place:
# felhom.eu/scripts/security_watch_inventory.py. A const with no line here refuses the push (gate `upstream`).
TraefikImage github:traefik/traefik
CloudflaredImage github:cloudflare/cloudflared feed:cloudflare-blog vulnnotes:cloudflared
FileBrowserImage github:gtsteffaniak/filebrowser
SambaImage self
+107
View File
@@ -0,0 +1,107 @@
package infra
import (
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"fmt"
"os"
"sort"
"time"
)
// ACMEStoreFile is Traefik's certificate store inside its stack folder (traefik.yml.tmpl: `storage:
// /etc/traefik/acme.json`, mounted from the stack folder).
const ACMEStoreFile = "acme.json"
// WebCert is one certificate of Traefik's ACME store, as the hub needs it to warn before the end date
// (felhom.eu R-1379, D77, `09` §3 decision 298). NO key material: only the certificate's own public fields.
type WebCert struct {
Domain string `json:"domain"` // the store's main name, e.g. "*.example.hu"
NotAfter string `json:"not_after"` // RFC3339 UTC — the end date
Issuer string `json:"issuer,omitempty"` // the issuer's common name
}
const (
webCertMaxStoreBytes = 4 << 20
webCertMax = 8
)
// ReadWebCerts reads the END DATES out of Traefik's ACME store. Who knows a box's web certificate date: only the
// box — the certificate is issued to Traefik in the guest and lives in this file; the household's public names end
// at Cloudflare, so nobody outside can read it. Until this nobody read it at all: when a renewal failed (Traefik
// renews by itself, 30 days before the end), the first sign was a browser warning on the end date.
//
// The store also holds the PRIVATE keys. This function decodes into a shape that has no key field, parses the
// certificate only, and returns nothing but names and dates; it never logs. Shape measured on three boxes on
// 2026-11-11 (felhom.eu audits/end-dates-list-2026-11-11/tools/guest-dates.sh): `{"<resolver>":{"Certificates":
// [{"domain":{"main":…},"certificate":"<base64 PEM>"}]}}`.
//
// A missing or EMPTY store is (nil, nil): no certificate yet (a box with no ACME e-mail serves Traefik's own
// certificate, which is not in the store). At most webCertMax entries, soonest end first. Pinned by TestReadWebCerts_*.
func ReadWebCerts(path string) ([]WebCert, error) {
st, err := os.Stat(path)
if err != nil {
if os.IsNotExist(err) {
return nil, nil
}
return nil, fmt.Errorf("web certificate store: %w", err)
}
if st.Size() == 0 {
return nil, nil
}
if st.Size() > webCertMaxStoreBytes {
return nil, fmt.Errorf("web certificate store is %d bytes — not read", st.Size())
}
raw, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("web certificate store: %w", err)
}
var store map[string]struct {
Certificates []struct {
Domain struct {
Main string `json:"main"`
} `json:"domain"`
Certificate string `json:"certificate"`
} `json:"Certificates"`
}
if err := json.Unmarshal(raw, &store); err != nil {
return nil, fmt.Errorf("web certificate store is not readable JSON") // never the content
}
var out []WebCert
for _, res := range store {
for _, c := range res.Certificates {
pemBytes, err := base64.StdEncoding.DecodeString(c.Certificate)
if err != nil {
continue
}
block, _ := pem.Decode(pemBytes) // the first block is the leaf; the rest is its chain
if block == nil || block.Type != "CERTIFICATE" {
continue
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
continue
}
name := c.Domain.Main
if name == "" {
name = cert.Subject.CommonName
}
if name == "" && len(cert.DNSNames) > 0 {
name = cert.DNSNames[0]
}
out = append(out, WebCert{Domain: name, NotAfter: cert.NotAfter.UTC().Format(time.RFC3339), Issuer: cert.Issuer.CommonName})
}
}
sort.Slice(out, func(i, j int) bool {
if out[i].NotAfter != out[j].NotAfter {
return out[i].NotAfter < out[j].NotAfter
}
return out[i].Domain < out[j].Domain
})
if len(out) > webCertMax {
out = out[:webCertMax]
}
return out, nil
}
+119
View File
@@ -0,0 +1,119 @@
package infra
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"crypto/x509/pkix"
"encoding/base64"
"encoding/json"
"encoding/pem"
"math/big"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
// acmeEntry makes one store entry the way Traefik writes it: the certificate (leaf + a second block, as a chain) and
// its PRIVATE KEY, both base64 of PEM.
func acmeEntry(t *testing.T, main string, notAfter time.Time) map[string]any {
t.Helper()
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatal(err)
}
tmpl := &x509.Certificate{SerialNumber: big.NewInt(time.Now().UnixNano()), Subject: pkix.Name{CommonName: main},
Issuer: pkix.Name{CommonName: "Test CA"}, DNSNames: []string{main}, NotBefore: notAfter.Add(-90 * 24 * time.Hour), NotAfter: notAfter}
der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
if err != nil {
t.Fatal(err)
}
leaf := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})
chain := append(append([]byte{}, leaf...), leaf...) // a second block stands in for the issuer's certificate
kb, _ := x509.MarshalECPrivateKey(key)
keyPEM := pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: kb})
return map[string]any{"domain": map[string]any{"main": main, "sans": []string{main}},
"certificate": base64.StdEncoding.EncodeToString(chain), "key": base64.StdEncoding.EncodeToString(keyPEM), "Store": "default"}
}
func writeStore(t *testing.T, entries ...map[string]any) string {
t.Helper()
p := filepath.Join(t.TempDir(), ACMEStoreFile)
b, _ := json.Marshal(map[string]any{"letsencrypt": map[string]any{
"Account": map[string]any{"Email": "household@example.hu", "PrivateKey": "QUNDT1VOVC1LRVktTVVTVC1OT1QtTEVBSw=="},
"Certificates": entries}})
if err := os.WriteFile(p, b, 0o600); err != nil {
t.Fatal(err)
}
return p
}
// felhom.eu R-1379 (D77): the box reads its web certificate's END DATE from Traefik's store so the hub can warn 14
// days before — and reads NOTHING else from a file that also holds the private keys. The consequence asserted: the
// right date per name, soonest first; and no byte of a key, the account key or the e-mail in what comes back.
// COMPANION RED-PROOFS (observed, felhom.eu audits/night-build-2026-11-14/B/redproof-controller-webcert.txt).
func TestReadWebCerts_EndDatesAndNoKeyMaterial(t *testing.T) {
soon := time.Date(2026, 11, 20, 1, 46, 0, 0, time.UTC)
later := time.Date(2027, 1, 19, 1, 46, 0, 0, time.UTC)
e1, e2 := acmeEntry(t, "*.example.hu", later), acmeEntry(t, "old.example.hu", soon)
got, err := ReadWebCerts(writeStore(t, e1, e2))
if err != nil {
t.Fatal(err)
}
if len(got) != 2 || got[0].Domain != "old.example.hu" || got[0].NotAfter != "2026-11-20T01:46:00Z" ||
got[1].Domain != "*.example.hu" || got[1].NotAfter != "2027-01-19T01:46:00Z" {
t.Fatalf("certificates = %+v, want old.example.hu 2026-11-20 first, then *.example.hu 2027-01-19", got)
}
wire, _ := json.Marshal(got)
for _, secret := range []string{e1["key"].(string), e2["key"].(string), "QUNDT1VOVC1LRVktTVVTVC1OT1QtTEVBSw==", "household@example.hu", "PRIVATE KEY"} {
if strings.Contains(string(wire), secret) || strings.Contains(string(wire), secret[:min(20, len(secret))]) {
t.Fatalf("what the box reports carries key material or the e-mail: %s", wire)
}
}
for _, c := range got {
if len(c.Domain)+len(c.NotAfter)+len(c.Issuer) > 200 {
t.Errorf("a reported certificate is %d bytes — more than a name, a date and an issuer: %+v", len(c.Domain)+len(c.NotAfter)+len(c.Issuer), c)
}
}
}
// No store, an empty store (the file the controller creates before Traefik's first run), and a store with no
// certificate yet: nothing to report and no error. A store that is not JSON: an error that does not quote the file.
func TestReadWebCerts_EmptyMissingAndBroken(t *testing.T) {
dir := t.TempDir()
if got, err := ReadWebCerts(filepath.Join(dir, "none.json")); got != nil || err != nil {
t.Errorf("a missing store: %v, %v", got, err)
}
empty := filepath.Join(dir, "empty.json")
_ = os.WriteFile(empty, nil, 0o600)
if got, err := ReadWebCerts(empty); got != nil || err != nil {
t.Errorf("an empty store: %v, %v", got, err)
}
if got, err := ReadWebCerts(writeStore(t)); len(got) != 0 || err != nil {
t.Errorf("a store with no certificate: %v, %v", got, err)
}
broken := filepath.Join(dir, "broken.json")
_ = os.WriteFile(broken, []byte(`{"letsencrypt": SECRET-LOOKING-BYTES`), 0o600)
_, err := ReadWebCerts(broken)
if err == nil || strings.Contains(err.Error(), "SECRET") {
t.Errorf("a broken store: err = %v, want an error that does not quote the file", err)
}
// an entry whose certificate is not a certificate is skipped, the good one stays
bad := map[string]any{"domain": map[string]any{"main": "bad.example.hu"}, "certificate": "bm90IGEgY2VydA=="}
got, err := ReadWebCerts(writeStore(t, bad, acmeEntry(t, "ok.example.hu", time.Date(2027, 2, 1, 0, 0, 0, 0, time.UTC))))
if err != nil || len(got) != 1 || got[0].Domain != "ok.example.hu" {
t.Errorf("a store with one unreadable entry: %+v, %v", got, err)
}
// more than the cap: the soonest ends stay
var many []map[string]any
for i := 0; i < 12; i++ {
many = append(many, acmeEntry(t, "n"+string(rune('a'+i))+".example.hu", time.Date(2027, 1, 1+i, 0, 0, 0, 0, time.UTC)))
}
got, _ = ReadWebCerts(writeStore(t, many...))
if len(got) != webCertMax || got[0].NotAfter != "2027-01-01T00:00:00Z" {
t.Errorf("cap: %d entries, first %+v", len(got), got[0])
}
}
@@ -0,0 +1,34 @@
package notify
import (
"encoding/json"
"strings"
"testing"
)
// D62 — restore_copy_deleted: info (the hub's vocabulary), the operator message only (no household sentence — the hub
// bars the type from customers too), and the details carry who, app, the restore's date and the size.
func TestD62_RestoreCopyDeletedEvent(t *testing.T) {
n := &Notifier{}
var et, sev, msg, cust string
var det []byte
n.pushFn = func(eventType, severity, message, customer string, details interface{}) {
et, sev, msg, cust = eventType, severity, message, customer
det, _ = json.Marshal(details)
}
n.NotifyRestoreCopyDeleted(RestoreCopyDeletedDetails{App: "vikunja", RestoreAt: "2026-10-29T08:00:00Z", SizeBytes: 4096,
Who: "the household (dashboard sign-in) from 192.168.0.5", Path: "/x/backups/restore-undo/vikunja/20261029T080000Z"})
if et != "restore_copy_deleted" || sev != "info" || cust != "" {
t.Fatalf("type=%q severity=%q customer=%q", et, sev, cust)
}
for _, want := range []string{"vikunja", "2026-10-29T08:00:00Z", "4096", "the household"} {
if !strings.Contains(msg, want) {
t.Fatalf("message %q lacks %q", msg, want)
}
}
for _, want := range []string{`"app":"vikunja"`, `"restore_at":"2026-10-29T08:00:00Z"`, `"size_bytes":4096`, `"who":"the household`} {
if !strings.Contains(string(det), want) {
t.Fatalf("details %s lack %s", det, want)
}
}
}
@@ -0,0 +1,71 @@
package notify
import (
"encoding/json"
"io"
"log"
"path/filepath"
"strings"
"testing"
"time"
"gitea.dooplex.hu/admin/felhom-controller/internal/settings"
)
// D84 (`09` §3 decision 309; `07-backup-architecture.md` §8.2f): the household's ONE mail at the press names the app,
// the end date and how to take it back — in the household's language, with the date in that language's form.
// RED-PROOF: felhom.eu/documentation/audits/build-release-4-2026-11-15/A/redproof-ctrl-press.txt.
func TestD84_OffsiteEndScheduledEvent(t *testing.T) {
ends := time.Date(2026, 12, 15, 10, 30, 0, 0, time.UTC)
for _, lang := range []string{"hu", "en"} {
sett, err := settings.Load(filepath.Join(t.TempDir(), "settings.json"), log.New(io.Discard, "", 0))
if err != nil {
t.Fatal(err)
}
if err := sett.SetLanguage(lang); err != nil {
t.Fatal(err)
}
n := &Notifier{settings: sett, logger: log.New(io.Discard, "", 0)}
var et, sev, msg, cust string
var det []byte
calls := 0
n.pushFn = func(eventType, severity, message, customer string, details interface{}) {
calls++
et, sev, msg, cust = eventType, severity, message, customer
det, _ = json.Marshal(details)
}
n.NotifyOffsiteEndScheduled("vikunja", "2026-11-15T10:30:00Z", "2026-12-15T10:30:00Z", ends)
if calls != 1 || et != "offsite_end_scheduled" || sev != "info" {
t.Fatalf("%s: calls=%d type=%q severity=%q", lang, calls, et, sev)
}
// the wire sentence is always Hungarian: the app, the day, the way back
for _, want := range []string{"vikunja", "2026. 12. 15.", "Mentések oldalon", "„Mégis megtartom”"} {
if !strings.Contains(msg, want) {
t.Errorf("%s: the Hungarian sentence %q lacks %q", lang, msg, want)
}
}
if strings.Contains(msg, "15..") || strings.Contains(msg, "%") {
t.Errorf("%s: the Hungarian sentence is malformed: %q", lang, msg)
}
if lang == "hu" {
if cust != "" {
t.Errorf("a Hungarian household sends nothing extra, got %q", cust)
}
} else {
for _, want := range []string{"vikunja", "2026-12-15", "Backups page", "“Keep it after all”"} {
if !strings.Contains(cust, want) {
t.Errorf("the English sentence %q lacks %q", cust, want)
}
}
if strings.Contains(cust, "2026. 12.") || strings.Contains(cust, "%") {
t.Errorf("the English sentence carries the Hungarian date form or a verb: %q", cust)
}
}
// the details: stack_name (the hub's headline names the app from it) and the press's own key
for _, want := range []string{`"stack_name":"vikunja"`, `"removed_at":"2026-11-15T10:30:00Z"`, `"ends_at":"2026-12-15T10:30:00Z"`, `"subject":"vikunja|2026-11-15T10:30:00Z"`} {
if !strings.Contains(string(det), want) {
t.Errorf("%s: details %s lack %s", lang, det, want)
}
}
}
}
+59 -1
View File
@@ -163,6 +163,8 @@ type UpdateDetails struct {
type AppDetails struct {
StackName string `json:"stack_name,omitempty"`
DisplayName string `json:"display_name,omitempty"`
// Source (app_oom only, R-528): what saw the kill — "docker" (State.OOMKilled) or "cgroup" (the host's kernel counter).
Source string `json:"source,omitempty"`
}
// CrossDriveDetails holds structured data for cross-drive backup events.
@@ -804,6 +806,12 @@ func (n *Notifier) NotifyAppStartFailures(apps []AppRunState) {
// that stays OOM-marked does not repeat. "warning" — the hub vocabulary (R-329). Operator-only
// hub-side (hub >= v0.114.0 registers it): the household sees the dashboard tag.
func (n *Notifier) NotifyAppOOM(stack, container, startedAt string, kills int64, memLimit, peak string) {
n.NotifyAppOOMFrom(stack, container, startedAt, kills, memLimit, peak, "")
}
// NotifyAppOOMFrom is NotifyAppOOM with the source that saw the kill (R-528: "docker" or "cgroup"), carried in the
// event's details. One event per container run, whichever source saw it.
func (n *Notifier) NotifyAppOOMFrom(stack, container, startedAt string, kills int64, memLimit, peak, source string) {
key := container + "|" + startedAt
n.mu.Lock()
if n.oomSeen == nil {
@@ -816,7 +824,7 @@ func (n *Notifier) NotifyAppOOM(stack, container, startedAt string, kills int64,
if first {
n.emit("app_oom", "warning",
fmt.Sprintf("Alkalmazás memóriája elfogyott: %s (%s) — egy folyamatát a memóriakorlát leállította", stack, container),
AppDetails{StackName: stack, DisplayName: container})
AppDetails{StackName: stack, DisplayName: container, Source: source})
}
if storm {
n.logger.Printf("[ERROR] [notify] %s: container %s OOM STORM — %d kills in %d min (limit %s, peak %s)",
@@ -1577,6 +1585,56 @@ func (n *Notifier) NotifyAppDefinitionRefused(app, detail string) {
n.pushEventBoth("app_definition_refused", "warning", msg, "", AppDefinitionRefusedDetails{App: app, Refused: detail})
}
// RestoreCopyDeletedDetails is restore_copy_deleted's record: who deleted which app's copy, the restore it protected,
// and its size.
type RestoreCopyDeletedDetails struct {
App string `json:"app"`
RestoreAt string `json:"restore_at"` // RFC 3339, UTC
SizeBytes int64 `json:"size_bytes"`
Who string `json:"who"`
Path string `json:"path"`
}
// NotifyRestoreCopyDeleted (D62, operator 2026-10-29): the household deleted a restore copy with „Törlés most" before
// its 30 days. Info, operator-only on the hub (registered in both of its lists, hub D62): an audit line for support,
// never a household mail. Pinned by TestD62_RestoreCopyDeletedEvent.
func (n *Notifier) NotifyRestoreCopyDeleted(d RestoreCopyDeletedDetails) {
msg := fmt.Sprintf("%s: the restore copy from before the restore of %s (%d bytes) was deleted by hand — %s. That restore can no longer be undone from this box.",
d.App, d.RestoreAt, d.SizeBytes, d.Who)
n.pushEventBoth("restore_copy_deleted", "info", msg, "", d)
}
// OffsiteEndScheduledDetails is offsite_end_scheduled's record. Subject is the press's own key (app + the record's
// time): the hub mails once per subject, so two apps removed in one hour are two mails and one press delivered twice
// is one. StackName is what the hub's mail headline names the app from.
type OffsiteEndScheduledDetails struct {
StackName string `json:"stack_name"`
RemovedAt string `json:"removed_at"` // RFC 3339, UTC
EndsAt string `json:"ends_at"` // RFC 3339, UTC
Subject string `json:"subject"`
}
// NotifyOffsiteEndScheduled (D84, `09` §3 decision 309; `07` §8.2f): the household pressed „delete backup data” for
// an app — its off-site copies end on endsOn. ONE mail per press to the household's own address, naming the app, the
// day and the way back; a receipt on the hub (never switched off by a group, never mailed to the operator). `info`:
// nothing is wrong. The day is written in each language's own date form, so both sentences are rendered here.
// Pinned by TestD84_OffsiteEndScheduledEvent.
func (n *Notifier) NotifyOffsiteEndScheduled(app, removedAt, endsAt string, endsOn time.Time) {
const key = "event.offsite_end_scheduled"
d := OffsiteEndScheduledDetails{StackName: app, RemovedAt: removedAt, EndsAt: endsAt, Subject: app + "|" + removedAt}
b, err := i18n.Shared()
if err != nil {
n.logger.Printf("[ERROR] NotifyOffsiteEndScheduled: bundle unavailable: %v", err)
n.pushEventBoth("offsite_end_scheduled", "info", key, "", d)
return
}
household := ""
if lang := n.boxLang(); lang != i18n.Default {
household = b.Msgf(lang, key, app, i18n.FormatDate(lang, endsOn))
}
n.pushEventBoth("offsite_end_scheduled", "info", b.Msgf(i18n.Default, key, app, i18n.FormatDate(i18n.Default, endsOn)), household, d)
}
// healthSeverity is the event severity a health status would be sent at (R-647): the disabled path
// names what it drops, and "warn" is a health STATUS, not a severity the hub knows.
func healthSeverity(status string) string {
@@ -0,0 +1,78 @@
package offsiteapply
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"gitea.dooplex.hu/admin/felhom-controller/internal/backup"
)
// D72 / D84 (`07-backup-architecture.md` §8.2f): the window request carries the box's due end records, the answer
// carries what the hub agreed to — and only a GRANTED window carries an agreement.
// RED-PROOF: felhom.eu/documentation/audits/build-release-4-2026-11-15/A/redproof-ctrl-window.txt.
func TestD84_WindowClient_SendsTheClaimsAndReadsTheAgreement(t *testing.T) {
var gotPath string
var gotBody map[string]json.RawMessage
answer := `{"granted":true,"window_id":9,"newest_allowed":"2026-12-20T03:00:00Z","max_remove":10,"ended_allowed":["aa","bb"],"ended_refused":[{"app":"immich","reason":"the box's newest report lists the app as installed"}]}`
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotPath = r.URL.Path
b, _ := io.ReadAll(r.Body)
gotBody = map[string]json.RawMessage{}
_ = json.Unmarshal(b, &gotBody)
_, _ = w.Write([]byte(answer))
}))
defer srv.Close()
c := HubWindowClient{Registrar: HubRegistrar{HubURL: srv.URL, CustomerID: "c1", APIKey: "k"}}
claims := []backup.OffsiteEndedClaim{{App: "vikunja", RemovedAt: "2026-11-15T10:00:00Z", EndsAt: "2026-12-15T10:00:00Z", SnapshotIDs: []string{"aa", "bb", "cc"}}}
w, err := c.Open(context.Background(), 20, claims)
if err != nil {
t.Fatal(err)
}
if gotPath != "/api/v1/offsite/window-open/c1" || string(gotBody["count_before"]) != "20" {
t.Fatalf("request: path=%q body=%v", gotPath, gotBody)
}
var sent []backup.OffsiteEndedClaim
if err := json.Unmarshal(gotBody["ended"], &sent); err != nil || len(sent) != 1 || sent[0].App != "vikunja" || strings.Join(sent[0].SnapshotIDs, ",") != "aa,bb,cc" || sent[0].RemovedAt != "2026-11-15T10:00:00Z" {
t.Fatalf("the hub did not receive the claim: %s (%v)", gotBody["ended"], err)
}
if w.AcceptsEnded {
t.Fatal("an answer WITHOUT accepts_ended (an older hub) reads as a hub that knows end records")
}
if !w.Granted || w.ID != 9 || w.MaxRemove != 10 || strings.Join(w.EndedAllowed, ",") != "aa,bb" || len(w.EndedRefused) != 1 || w.EndedRefused[0].App != "immich" {
t.Fatalf("window = %+v, want the agreement (aa,bb) and the refusal of immich", w)
}
// With no due record the body is the one an older hub always saw: no `ended` key at all.
if _, err := c.Open(context.Background(), 20, nil); err != nil {
t.Fatal(err)
}
if _, has := gotBody["ended"]; has {
t.Fatalf("a request with no claim carries `ended`: %v", gotBody)
}
// A window that is NOT granted carries no agreement, whatever the answer holds — and it does carry the hub's
// word that it reads end records (the box learns it on an ordinary night).
answer = `{"granted":false,"reason":"not due","ended_allowed":["aa","bb"],"accepts_ended":true}`
w2, err := c.Open(context.Background(), 20, claims)
if err == nil && !w2.AcceptsEnded {
t.Fatal("accepts_ended of a not-granted answer was not read")
}
if err != nil || w2.Granted || len(w2.EndedAllowed) != 0 {
t.Fatalf("not granted: %+v %v — an agreement without a window must not reach the box", w2, err)
}
// The close names the removed ids for the hub's audit.
answer = `{"closed":true}`
if err := c.Close(context.Background(), backup.OffsiteWindowResult{ID: 9, CountBefore: 20, CountAfter: 18, Removed: 2, Outcome: "pruned", RemovedForEndedApps: []string{"aa", "bb"}}); err != nil {
t.Fatal(err)
}
var removed []string
if err := json.Unmarshal(gotBody["removed_for_ended_apps"], &removed); err != nil || strings.Join(removed, ",") != "aa,bb" || gotPath != "/api/v1/offsite/window-close/c1" {
t.Fatalf("close: path=%q removed_for_ended_apps=%s", gotPath, gotBody["removed_for_ended_apps"])
}
}
+15 -3
View File
@@ -127,8 +127,14 @@ func (c HubRegistrar) MoveAside(ctx context.Context) (string, error) {
type HubWindowClient struct{ Registrar HubRegistrar }
func (c HubWindowClient) Open(ctx context.Context, countBefore int) (backup.OffsiteWindow, error) {
raw, err := c.Registrar.post(ctx, "window-open", map[string]int{"count_before": countBefore})
func (c HubWindowClient) Open(ctx context.Context, countBefore int, ended []backup.OffsiteEndedClaim) (backup.OffsiteWindow, error) {
// D72/D84: the due end records ride the same request; `ended` is left out when there is none, so the body an
// older hub sees is the one it always saw.
req := struct {
CountBefore int `json:"count_before"`
Ended []backup.OffsiteEndedClaim `json:"ended,omitempty"`
}{CountBefore: countBefore, Ended: ended}
raw, err := c.Registrar.post(ctx, "window-open", req)
if err != nil {
return backup.OffsiteWindow{}, err
}
@@ -138,17 +144,23 @@ func (c HubWindowClient) Open(ctx context.Context, countBefore int) (backup.Offs
NewestAllowed string `json:"newest_allowed"`
MaxRemove int `json:"max_remove"`
Reason string `json:"reason"`
EndedAllowed []string `json:"ended_allowed"`
EndedRefused []backup.OffsiteEndedRefusal `json:"ended_refused"`
// AcceptsEnded: this hub reads `ended` (in every answer of a hub that does, granted or not).
AcceptsEnded bool `json:"accepts_ended"`
}
if err := json.Unmarshal(raw, &r); err != nil {
return backup.OffsiteWindow{}, fmt.Errorf("hub window-open: malformed response")
}
w := backup.OffsiteWindow{Granted: r.Granted, ID: r.WindowID, MaxRemove: r.MaxRemove, Reason: r.Reason}
w := backup.OffsiteWindow{Granted: r.Granted, ID: r.WindowID, MaxRemove: r.MaxRemove, Reason: r.Reason, AcceptsEnded: r.AcceptsEnded}
if r.Granted {
t, perr := time.Parse(time.RFC3339, r.NewestAllowed)
if perr != nil {
return backup.OffsiteWindow{}, fmt.Errorf("hub window-open: bad newest_allowed")
}
w.NewestAllowed = t
// Only a GRANTED window carries an agreement.
w.EndedAllowed, w.EndedRefused = r.EndedAllowed, r.EndedRefused
}
return w, nil
}
+37
View File
@@ -6,10 +6,13 @@ import (
"fmt"
"log"
"os"
"path/filepath"
"strings"
"time"
"gitea.dooplex.hu/admin/felhom-controller/internal/backup"
"gitea.dooplex.hu/admin/felhom-controller/internal/config"
"gitea.dooplex.hu/admin/felhom-controller/internal/infra"
"gitea.dooplex.hu/admin/felhom-controller/internal/metrics"
"gitea.dooplex.hu/admin/felhom-controller/internal/monitor"
"gitea.dooplex.hu/admin/felhom-controller/internal/scheduler"
@@ -200,6 +203,8 @@ func BuildReport(
r.Offsite = backupMgr.OffboxReportStatus()
}
r.WebCerts = webCertsForReport(cfg.Paths.StacksDir, cfg.Customer.Domain, logger) // R-1379: the web certificate's end date
if debug && logger != nil {
logger.Printf("[DEBUG] [report] BuildReport: complete — containers=%d, health=%s, deployed=%d, available=%d, app_telemetry=%d",
r.Containers.Total, r.Health.Status, len(r.Stacks.Deployed), len(r.Stacks.Available), len(r.AppTelemetry))
@@ -339,3 +344,35 @@ func rootStorageEntry(sysInfo system.SystemInfo) StorageReport {
ReadFailed: !sysInfo.DiskKnown,
}
}
// webCertsForReport reads the end dates of the box's web certificates for the report (felhom.eu R-1379). A store that
// cannot be read is a WARN line and an absent field — never a failed report, and never the store's content in a log.
//
// Only certificates for the household's CURRENT domain are reported (the name itself, `*.<domain>`, or a name under
// it). Traefik's store keeps a certificate for a name the box no longer serves — after a domain change, say — and
// that one can no longer renew: reporting it would warn the operator about a name nobody uses (review, 2026-11-14).
// With no domain configured nothing can be told apart, so everything is reported.
func webCertsForReport(stacksDir, domain string, logger *log.Logger) []infra.WebCert {
if stacksDir == "" {
return nil
}
certs, err := infra.ReadWebCerts(filepath.Join(stacksDir, "traefik", infra.ACMEStoreFile))
if err != nil {
if logger != nil {
logger.Printf("[WARN] [report] web certificate end date not read: %v", err)
}
return nil
}
domain = strings.ToLower(strings.TrimSpace(domain))
if domain == "" {
return certs
}
var mine []infra.WebCert
for _, c := range certs {
name := strings.ToLower(c.Domain)
if name == domain || name == "*."+domain || strings.HasSuffix(name, "."+domain) {
mine = append(mine, c)
}
}
return mine
}
+42 -4
View File
@@ -21,9 +21,11 @@ import (
// problem, main.go). The result rides the next report as `operator_action_results: [{id, outcome,
// message}]`; the hub lists an action until its result has arrived, then stops.
//
// THE LIST IS CLOSED. Four actions, and run_job names one of four jobs. Nothing here deletes data,
// THE LIST IS CLOSED. Five actions, and run_job names one of four jobs. Nothing here deletes data,
// starts a countdown or shortens one — `03` §4 asks for a signing key only to destroy or overwrite the
// only copy, and none of these does. An unknown action, an unknown job or an argument out of range is
// only copy, and none of these does. clear_hold (D64 = B, operator ruling 2026-10-29 12:10) lifts an app's
// hold of ANY reason with no operator signature: it deletes nothing and starts nothing — the app stays
// stopped until the household (or the operator) starts it, and a waiting put-back's copy stays on disk. An unknown action, an unknown job or an argument out of range is
// answered `refused` and NOTHING is called. Pinned by TestOpActions_ClosedList (which fails when an
// entry is added, so a new action is a decision, not an edit) and TestOpActions_UnknownIsRefused.
//
@@ -38,6 +40,7 @@ const (
OpAbandonStop = "abandon_stop"
OpAbandonExtend = "abandon_extend"
OpRunJob = "run_job"
OpClearHold = "clear_hold"
OutcomeDone = "done"
OutcomeRefused = "refused"
@@ -57,7 +60,7 @@ const (
)
// operatorActionNames is THE closed list. Adding an entry fails TestOpActions_ClosedList by design.
var operatorActionNames = []string{OpOffsiteBackupNow, OpAbandonStop, OpAbandonExtend, OpRunJob}
var operatorActionNames = []string{OpOffsiteBackupNow, OpAbandonStop, OpAbandonExtend, OpRunJob, OpClearHold}
// operatorJobNames is the fixed set run_job may name — the scheduler's own job names (main.go).
var operatorJobNames = []string{"fill-watch", "offsite-integrity", "offsite-proof", "disk-health-check"}
@@ -83,6 +86,21 @@ func contains(list []string, v string) bool {
return false
}
// validHoldStack is clear_hold's argument check: the same alphabet as backup.isSafeStackName (report cannot import
// backup; REUSE.md „Safe-name validators").
func validHoldStack(s string) bool {
if s == "" || len(s) > 64 {
return false
}
for _, c := range s {
if (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-' || c == '_' {
continue
}
return false
}
return true
}
// ErrActionRefused, wrapped by a handler, turns its error into a `refused` outcome (the action could
// not START — e.g. an off-site run already in flight) instead of `failed` (it started and went wrong).
var ErrActionRefused = errors.New("refused")
@@ -101,7 +119,7 @@ type OperatorActionResult struct {
Message string `json:"message"`
}
// OperatorActionHandlers are the four doors, wired by main.go. A nil handler answers `refused`
// OperatorActionHandlers are the five doors, wired by main.go. A nil handler answers `refused`
// („not available on this box").
type OperatorActionHandlers struct {
// OffsiteBackupNow returns a refusal sentence when the run may not start (the household's
@@ -111,6 +129,9 @@ type OperatorActionHandlers struct {
AbandonExtend func(days int) (time.Time, error)
// RunJob is Scheduler.RunNow: an error = not started (unknown/running); the channel = the job's end.
RunJob func(name string) (<-chan error, error)
// ClearHold lifts the app's hold in the RUNNING controller (D64 = B, R-1343) and returns the result
// sentence. actionID names the action in the box's log. An error wrapping ErrActionRefused = nothing changed.
ClearHold func(stack string, actionID int64) (string, error)
// ResultReady sends an out-of-cycle report so a result reaches the hub in seconds (optional).
ResultReady func()
}
@@ -317,6 +338,23 @@ func (o *OperatorActions) dispatch(a OperatorAction) {
}
o.finish(a, outcomeOf(jerr), msg)
}()
case OpClearHold:
// The argument is checked HERE, before any handler is touched (the closed list's rule): one app name,
// the backup package's strict alphabet (letters, digits, '-' and '_', at most 64).
if !validHoldStack(a.Arg) {
o.finish(a, OutcomeRefused, "the argument must be one app name (letters, digits, '-' and '_')")
return
}
if o.h.ClearHold == nil {
o.finish(a, OutcomeRefused, "not available on this box")
return
}
msg, err := o.h.ClearHold(a.Arg, a.ID)
if err != nil {
o.finish(a, outcomeOf(err), err.Error())
return
}
o.finish(a, OutcomeDone, msg)
default:
o.finish(a, OutcomeRefused, "unknown action")
}
+79 -2
View File
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"reflect"
"strings"
"sync"
@@ -15,9 +16,11 @@ import (
// The list is CLOSED. This test fails when an action or a job is added, by design: a new entry is an
// operator decision (no action may delete data, start a countdown or shorten one), not an edit. The
// hub pins the same four in its own test (hub internal/store opactions_test.go).
// hub pins the same list in its own test (hub internal/store opactions_test.go).
// 2026-10-29: clear_hold added deliberately — operator ruling D64 = B (12:10): the hub's „Clear hold" works for
// every hold reason with no operator signature. It deletes nothing and starts nothing.
func TestOpActions_ClosedList(t *testing.T) {
if got, want := OperatorActionNames(), []string{"abandon_extend", "abandon_stop", "offsite_backup_now", "run_job"}; !reflect.DeepEqual(got, want) {
if got, want := OperatorActionNames(), []string{"abandon_extend", "abandon_stop", "clear_hold", "offsite_backup_now", "run_job"}; !reflect.DeepEqual(got, want) {
t.Fatalf("operator actions = %v, want exactly %v — a new action needs the operator's word (decision 185)", got, want)
}
if got, want := OperatorJobNames(), []string{"disk-health-check", "fill-watch", "offsite-integrity", "offsite-proof"}; !reflect.DeepEqual(got, want) {
@@ -56,6 +59,10 @@ func recordingHandlers(c *calls) OperatorActionHandlers {
close(ch)
return ch, nil
},
ClearHold: func(stack string, id int64) (string, error) {
c.add("clear:" + stack)
return "the hold on " + stack + " is cleared", nil
},
}
}
@@ -197,3 +204,73 @@ func TestOpActions_WireShapes(t *testing.T) {
t.Fatalf("report carried %s", b)
}
}
// clear_hold (D64 = B): the argument is one app name in the strict alphabet — never a path, never empty, never two
// names. A bad one is refused and the handler is NOT called (the closed list's rule: validate before any door).
// RED-PROOF (2026-10-29): with validHoldStack returning true, this fails on „a refused action called [clear:…]".
func TestOpActions_ClearHoldBadArgumentIsRefusedAndCallsNothing(t *testing.T) {
c := &calls{}
o := NewOperatorActions(context.Background(), recordingHandlers(c), nil)
list := []OperatorAction{
{ID: 1, Action: OpClearHold, Arg: ""},
{ID: 2, Action: OpClearHold, Arg: "../settings"},
{ID: 3, Action: OpClearHold, Arg: "immich paperless"},
{ID: 4, Action: OpClearHold, Arg: "immich/x"},
{ID: 5, Action: OpClearHold, Arg: strings.Repeat("a", 65)},
{ID: 6, Action: OpClearHold, Arg: "immich\n"},
{ID: 7, Action: OpClearHold, Arg: "."},
}
o.Reconcile(list)
if got := c.get(); len(got) != 0 {
t.Fatalf("a refused action called %v", got)
}
for _, a := range list {
if r := resultFor(t, o, a.ID); r.Outcome != OutcomeRefused || !strings.Contains(r.Message, "one app name") {
t.Errorf("#%d clear_hold(%q): %+v, want refused naming the rule", a.ID, a.Arg, r)
}
}
// control: a good name does reach the handler
o.Reconcile([]OperatorAction{{ID: 8, Action: OpClearHold, Arg: "paperless-ngx_2"}})
if got := c.get(); len(got) != 1 || got[0] != "clear:paperless-ngx_2" {
t.Fatalf("a valid name must reach the handler, calls %v", got)
}
}
// clear_hold (D64 = B): a valid name reaches the handler with the action's id, and its sentence is the result; a
// handler refusal (the app has no hold) is answered refused, an error that is not a refusal failed.
// RED-PROOF (2026-10-29): with the OpClearHold case removed from dispatch, this fails on „unknown action".
func TestOpActions_ClearHoldDoneRefusedFailed(t *testing.T) {
var gotStack string
var gotID int64
h := OperatorActionHandlers{ClearHold: func(stack string, id int64) (string, error) {
gotStack, gotID = stack, id
switch stack {
case "notheld":
return "", fmt.Errorf("%w: notheld has no hold — nothing was changed", ErrActionRefused)
case "broken":
return "", errors.New("saving settings: disk full")
}
return "the hold on " + stack + " is cleared (it was: held after a failed update)", nil
}}
o := NewOperatorActions(context.Background(), h, nil)
o.Reconcile([]OperatorAction{{ID: 7, Action: OpClearHold, Arg: "kimai"}})
if gotStack != "kimai" || gotID != 7 {
t.Fatalf("handler called with (%q, %d), want (kimai, 7)", gotStack, gotID)
}
if r := resultFor(t, o, 7); r.Outcome != OutcomeDone || r.Message != "the hold on kimai is cleared (it was: held after a failed update)" {
t.Fatalf("result %+v", r)
}
o.Reconcile([]OperatorAction{{ID: 8, Action: OpClearHold, Arg: "notheld"}, {ID: 9, Action: OpClearHold, Arg: "broken"}})
if r := resultFor(t, o, 8); r.Outcome != OutcomeRefused || !strings.Contains(r.Message, "has no hold") {
t.Errorf("not held: %+v", r)
}
if r := resultFor(t, o, 9); r.Outcome != OutcomeFailed {
t.Errorf("a save error must be failed, not refused: %+v", r)
}
// nil handler → refused, not a crash
o2 := NewOperatorActions(context.Background(), OperatorActionHandlers{}, nil)
o2.Reconcile([]OperatorAction{{ID: 1, Action: OpClearHold, Arg: "kimai"}})
if r := resultFor(t, o2, 1); r.Outcome != OutcomeRefused {
t.Errorf("nil handler: %+v", r)
}
}
+7
View File
@@ -4,6 +4,7 @@ import (
"time"
"gitea.dooplex.hu/admin/felhom-controller/internal/backup"
"gitea.dooplex.hu/admin/felhom-controller/internal/infra"
"gitea.dooplex.hu/admin/felhom-controller/internal/metrics"
"gitea.dooplex.hu/admin/felhom-controller/internal/stacks"
)
@@ -64,6 +65,12 @@ type Report struct {
// leg on this box: steps done / undone / held / failed / skipped, each skip with its reason. Absent
// until a leg has run since the controller started. Additive: the hub stores the raw report.
UpdateLeg *stacks.UpdateLegSummary `json:"update_leg,omitempty"`
// WebCerts (felhom.eu R-1379, D77) — the end dates of the box's web certificates, read from Traefik's store
// (infra.ReadWebCerts: names and dates only, no key material). The hub warns the operator 14 days before an end
// date: only the box can know it, and a renewal that fails is silent until the day. Absent when the box has no
// certificate in the store. Additive: an older hub stores the raw report and ignores it.
WebCerts []infra.WebCert `json:"web_certs,omitempty"`
}
// SystemReport holds host-level system info.
Loaded 100 of 311 files, more files were not shown because too many files have changed in this diff. Show more