Commit Graph
25 Commits
Author SHA1 Message Date
flan 0b597387bd Add cmd_verify prompt to install output; fix --insecure docs
- install.sh: print 'verify' command immediately after successful restart
  so users know to confirm the backend patch loaded before creating tasks
- README: correct --insecure description; it controls TLS to the TrueNAS
  API (where the API key is transmitted), not the S3 endpoint — previous
  wording implied it was safe to use for S3 self-signed certs
2026-06-15 16:14:35 +00:00
flan 13b61a8ece Merge audit/exhaustive-review: 9 quality/safety fixes from exhaustive review
All findings from four consecutive full-codebase audit passes plus an
adversarial iXsystems-perspective audit. No new candidates surfaced in
the final clean-pass — branch declared complete.

Fixes:
- apply.sh: gate sitecustomize.py install on backup success; a failed
  backup cp previously fell through and could destroy the vendor file
- apply.sh: correct comment (keeps two prior log generations, not one)
- patch_ui.py: catch OSError on bundle backup with specific diagnostic
- patch_ui.py: find_bundle now matches MARKER so already-patched files
  return 'UI already patched' instead of misleading 'pattern not found'
- install.sh: early guard detects pipe-install (bash <(curl ...)) and
  exits with a clear error pointing to the git clone workflow
- install.sh: scope WARNING grep to current run only (record log offset
  before apply.sh, tail -c +N to read only new bytes)
- install.sh: systemctl restart failure now surfaces a recovery hint
- create_task.py: add MITM risk warning to --insecure flag help text
- create_task.py: handle unexpected 2xx response schema in cmd_create
- uninstall.sh: add import-middlewared verification after Python detection
- uninstall.sh: mv failure in JS bundle restore loop no longer aborts
  under set -e before cleanup; emits WARNING and continues
- uninstall.sh: add sync comment on find paths to match WEBUI_CANDIDATES
2026-06-15 16:12:00 +00:00
flan 9481bf55f0 Fix three findings from final clean-pass audit
- apply.sh: gate sitecustomize.py install on backup success; a failed
  backup cp (disk full, read-only mount) previously fell through and
  overwrote the vendor file with no recovery path
- create_task.py: handle unexpected 2xx response schema in cmd_create;
  bare KeyError on result['id'] is replaced with a diagnostic print
- uninstall.sh: mv inside while loop had no error handling; under
  set -euo pipefail a failed mv aborted the script before rm -rf PATCH_DIR,
  leaving the system in partial-uninstall limbo
2026-06-15 16:10:09 +00:00
flan 8f64e4964c Fix two findings from adversarial IX-perspective audit
- create_task.py: add MITM risk warning to --insecure flag help text;
  common home-user pattern (self-signed cert) exposes API key in transit
- install.sh: replace bare systemctl restart with explicit failure check
  that prints a recovery hint when middlewared fails to start post-install
2026-06-15 16:06:26 +00:00
flan 7c9aa7159a Fix two confirmed findings from full codebase audit
- patch_ui.py: wrap shutil.copy2 backup in try/except OSError so a
  permission or read-only filesystem error prints a specific diagnostic
  instead of crashing the script with a generic 'exited non-zero' message
- install.sh: add early guard that detects pipe-install (bash <(curl ...))
  and exits with a clear error pointing to the git clone workflow
2026-06-15 16:03:19 +00:00
flan 2a3b15b4b2 Fix two findings from full codebase audit
- apply.sh: correct comment from 'one prior generation' to 'two prior
  generations (.1 and .2)' — rotation has always kept three log files
- uninstall.sh: add sync comment on find paths to match WEBUI_CANDIDATES
  in patch/patch_ui.py, preventing silent drift if a new path is added
2026-06-15 15:58:29 +00:00
flan cbd85af2a3 Fix six quality findings from iterative code review
- patch_ui.py: find_bundle now matches MARKER so already-patched files
  return early and print 'UI already patched' instead of the misleading
  'filterByProviders pattern not found' warning
- install.sh: scope warning grep to current run only (record log offset
  before apply.sh, tail -c +N to read only new bytes)
- install.sh: fix misleading 'before continuing' wording on warning banner
- install.sh: fix grep anchor (^WARNING: missed [truecloud-patch] WARNING: lines)
- uninstall.sh: add import-middlewared verification after Python detection,
  matching apply.sh fallback logic
2026-06-15 15:53:06 +00:00
flan 0ce2083c71 Remove speculative AttributeError guard in URL-fix wrapper 2026-06-15 15:10:16 +00:00
flan cc43b2831d Fix five quality findings from second re-review
sitecustomize.py: when find_spec resolves real_spec as None (module absent
after a TrueNAS update), record a FAIL status and mark the module done so
hook_status.json is still written and cmd_verify shows a diagnostic FAIL
instead of the ambiguous "no status file found".

sitecustomize.py: the AttributeError fallback in the URL-fix wrapper now
writes a WARNING to stderr before returning the unmodified result, making
the unexpected ResticConfig type visible in journalctl.

apply.sh: after falling back to bare python3, verify that python3 can also
import middlewared; if not, emit a second warning so the operator knows the
backend patch may be installed in the wrong site-packages directory.

patch_ui.py: abort (return without writing) when FIND.subn produces a count
other than 1, instead of committing a doubly-patched bundle and having
subsequent runs silently accept it via the MARKER check.

uninstall.sh: when a vendor sitecustomize.py backup exists, use mv to
atomically overwrite our file rather than rm-then-mv; eliminates the window
where a read-only /usr causes rm to fail under set -e, aborting before the
backup is restored.
2026-06-15 04:07:16 +00:00
flan 8829fbb9d4 Fix four quality findings from re-review
sitecustomize.py: exec_module now records a FAIL status when the underlying
module load raises, instead of leaving hook_status.json unwritten. cmd_verify
will now show a diagnostic FAIL rather than the misleading "no status file".

sitecustomize.py: URL-fix loop covers --repository and --repository= in
addition to --repo/--repo=/-r; these are documented restic synonyms.

sitecustomize.py: _replace fallback now catches AttributeError in addition
to TypeError so an unrecognised ResticConfig return type silently falls back
to returning the unmodified result rather than crashing the backup job.

patch_ui.py: warns when FIND.subn produces a count other than 1, making
unexpected multi-replacement visible in the apply log.

uninstall.sh: find for JS bundle restore now includes /usr/share/truenas-ui,
matching all three entries in patch_ui.py's WEBUI_CANDIDATES.
2026-06-15 03:58:06 +00:00
flan 91c607a707 Improve log rotation, early-exit find_bundle, fix uninstall orphaned backup
apply.sh: preserve two log generations (.1 and .2) on rotation so the
last two boots are always available for diagnosis.

patch_ui.py: find_bundle returns on the first matching JS file instead of
collecting all matches. The multi-match warning was dead weight — the Angular
Ivy compiler produces exactly one bundle and the WARNING path was unreachable
in practice.

uninstall.sh: restore an orphaned sitecustomize.py.pre-truecloud-patch when
sitecustomize.py itself has already been removed (e.g. manual deletion while
the backup survived). Prevents leaving ghost vendor files in site-packages.
2026-06-15 03:43:03 +00:00
flan 49bd775d42 Fix five quality findings from adversarial code review
sitecustomize.py — _install():
- Scope hook to middlewared service process only via sys.argv[0] check;
  previously any tool in the same venv (midclt, debug scripts) would also
  get its imports of the two target modules intercepted.
- Exec-chain a displaced sitecustomize.py: if apply.sh backed up a
  pre-existing sitecustomize.py to .pre-truecloud-patch, run it in a
  sandboxed namespace before installing our hook so any startup code
  (path additions, codec registrations) still takes effect.

sitecustomize.py — _b2_restic_config():
- Validate expected credential fields ("account", "key") before accessing
  them; raise a named KeyError listing what is missing and what is present
  so a schema change produces an attributable error at backup time rather
  than a bare KeyError with no indication this patch is involved.

sitecustomize.py — get_restic_config wrapper:
- Extend URL fix to cover all three flag forms restic accepts:
    -r <url>      (existing)
    --repo <url>  (long two-element form, now checked)
    --repo=<url>  (long single-element form, now handled)
  Without this, a restic CLI change from -r to --repo would silently make
  the fix a no-op while verify still reported the patch as OK.

patch_ui.py — find_bundle():
- Remove UnicodeDecodeError from except clause; errors="replace" in the
  open() call means the exception can never be raised, and its presence
  suggested the error parameter was not understood.
2026-06-15 03:37:26 +00:00
flan 686aa8e8d3 Remove unused sys import from patch_ui.py 2026-06-15 03:25:56 +00:00
flan 2c9adc1ce5 Fix five quality findings; expand recovery and restore documentation
patch_ui.py:
- Write Angular bundle atomically via tmp + os.replace, matching the pattern
  already used by _record_status. Prevents a corrupt bundle if the write is
  interrupted mid-boot.

sitecustomize.py:
- Tighten _record_status count barrier comment to name _Finder._targets as
  the canonical count, making the coupling visible to future editors.

uninstall.sh:
- Verify middlewared restarted cleanly after uninstall, with journalctl
  guidance on failure — matching recover.sh's existing pattern.

apply.sh:
- Change second line of site-packages error block from WARNING: prefix
  (misleading for an instructional message) to a plain Run: hint.

create_task.py:
- Guard __doc__ against None in epilog extraction so -OO does not crash.

README.md:
- Split Emergency recovery into three named subsections: middlewared won't
  start, web UI is blank or broken (corrupt bundle recovery), and backend
  verify shows FAIL. Each gives direct commands and escalation steps.
- Add Restoring from a TrueCloud Backup section: finding the restic binary,
  gathering credentials, provider-specific env var setup for B2 and S3,
  listing and restoring snapshots, and operational notes on restore hygiene.
- Clarify that hook_status.json is written once both target modules have
  loaded (not necessarily at the instant middlewared starts).
2026-06-15 03:23:31 +00:00
flan bee405bd52 Fix six quality findings from code review
sitecustomize.py:
- Restore _record_status count barrier: write the status file only after all
  patches have reported. middlewared.plugins.cloud_backup.restic is imported
  lazily (only when a backup task runs), so without this barrier verify would
  declare "all patches active" based solely on the B2 patch that fires at
  startup. Barrier now gates on _Finder._targets rather than the removed
  _PATCHES dict.
- Add comment in exec_module noting the if/elif must stay in sync with
  _Finder._targets, making the coupling visible.

patch_ui.py:
- Merge find_webui into find_bundle: previously find_bundle(None) would crash
  with os.walk(None) if main()'s guard were removed. Merged function returns
  a 3-tuple (webui_dir, path, content); webui_dir=None means no candidate
  directory found, path=None means directory found but pattern absent.
  main() still produces distinct messages for each failure mode.

create_task.py:
- Split triple-chained .get() in cmd_list_tasks into two lines; the or {}
  handling for None credentials was buried inside a one-liner.

uninstall.sh:
- Fix find loop: replace "for x in $(find ...)" with "while IFS= read -r"
  to handle paths containing spaces or newlines.
- Add #!/usr/bin/env shebang form to Python detection, matching apply.sh.
  Without this, uninstall on a system where middlewared uses the env form
  would silently leave sitecustomize.py in the wrong site-packages.
2026-06-15 03:15:08 +00:00
flan ebca3f99cc Reduce accidental complexity across three files
sitecustomize.py:
- Replace _PATCHES dispatch dict with if/elif in exec_module; removes
  coupling between dispatch and _record_status's count barrier
- Drop _record_status count barrier entirely; both patches fire within
  milliseconds during the same import sequence, write-on-every-call is safe
- Replace _broken_url regex with str.partition + startswith checks; same
  semantics, no regex knowledge required to read
- Replace @staticmethod decorator inside plain function with explicit
  staticmethod() assignment; decorator form creates a descriptor object,
  not a callable, which confuses readers expecting class-body usage

apply.sh:
- Inline warn/ok helpers; each was one echo with a prefix, the indirection
  cost more than the abstraction saved
- Collapse patch_ui.py if/else (whose if branch was a no-op comment) to
  a single || fallback line

create_task.py:
- Remove vestigial (_client, _args) params from cmd_verify; it was pulled
  out of dispatch, the params were never used
- Replace 3-entry dispatch dict with if/elif; dict implied a uniform calling
  convention that verify already broke
2026-06-15 03:08:52 +00:00
flan 4b07ce459a Fix six audit findings: dead code, missing status records, missing fallback, unsafe JSON read
create_task.py:
- Remove dead make_client() call before the verify branch; it was called
  unconditionally with host=None/key=None, creating a broken client that was
  immediately discarded or overwritten.
- Remove "verify" from the dispatch dict; it was never reached through dispatch
  (the if/cmd==verify branch above it handled it). Dispatch now only contains
  commands that actually use a client.
- Wrap json.load() in try/except (OSError, JSONDecodeError) so a corrupt or
  partially-written status file produces a useful message instead of a traceback.

sitecustomize.py:
- Call _record_status() on the early-return paths in both _patch_b2 and
  _patch_restic. Without this, if TrueNAS natively supports B2 or the patch
  is already applied, the status file was never written and `verify` always
  reported failure even when everything was fine.
- Add idempotency guard to _record_status(): first call wins; duplicate calls
  for the same module are ignored so the entry count stays accurate.
- Make B2 get_restic_config a @staticmethod. The method never used self; the
  noqa comment was suppressing the evidence of a design mismatch. Removing the
  unused parameter makes the intent explicit.
- Add NamedTuple._replace() fallback after dataclasses.replace() in the restic
  wrapper. If ResticConfig is ever refactored to a NamedTuple, the TypeError
  from dataclasses.replace() would have surfaced as a backup job failure rather
  than a graceful recovery.
2026-06-15 02:59:57 +00:00
flan 06de1e15c0 Wrap original get_restic_config instead of replacing it; add hook status file
sitecustomize.py: _patch_restic no longer reimplements get_restic_config.
It now wraps the original: calls _orig(cloud_backup) to get a ResticConfig,
then post-processes only the -r argument to fix "b2:/bucket" → "b2:bucket"
when the URL contains a stray leading slash (the stock bug for empty-hostname
providers). Uses dataclasses.replace() to build the corrected result so new
ResticConfig fields added in future TrueNAS versions pass through unchanged.
This eliminates the transfer_setting gap, env dict mutation, and frozen-copy
drift that would occur over time.

Also adds a status file mechanism: sitecustomize.py writes
/data/truecloud-patch/hook_status.json atomically after both patches have
reported success or failure. This gives a machine-readable signal that the
hook fired correctly — without requiring log scraping.

create_task.py: new "verify" subcommand reads the status file and prints a
human-readable summary. Does not require --host or --api-key. --host and
--api-key are now optional at the parser level and validated only for
subcommands that actually need an API connection.

README: update troubleshooting to use "create_task.py verify" instead of
the manual Python introspection one-liner.
2026-06-15 02:47:59 +00:00
flan 78f943a71b Fix kill switch not cleared on reinstall; guard midclt delete; tighten sitecustomize imports
install.sh: running install.sh after a recover.sh left /data/truecloud-patch/disabled
in place, so apply.sh silently skipped all patching and middlewared restarted
without the patch. Clear the kill switch file before running apply.sh.

uninstall.sh: midclt initshutdownscript.delete was unguarded under set -euo pipefail,
so a delete failure (already-removed entry, transient API error) aborted the script
before sitecustomize.py was cleaned up or /data/truecloud-patch/ was removed. Now
guarded with an if/else that warns and continues.

sitecustomize.py: move importlib.machinery/.util imports inside the if block in
find_spec so they only execute when intercepting our two target modules, not on
every module import across the whole process. In _install(), import os before
importlib.util so the kill switch check (cheap) runs before the importlib import
(slightly heavier on first use). Remove the unused orig variable in _patch_restic.

patch_ui.py: add explicit encoding="utf-8" to both open() calls. errors="replace"
on read so malformed bytes in a bundle don't silently skip a candidate file.
2026-06-15 02:39:34 +00:00
flan 48cf3a5601 recover.sh: verify middlewared started cleanly before claiming success 2026-06-15 02:37:04 +00:00
flan 8f24725078 Add kill switch and recover.sh for emergency recovery
If the patch ever prevents middlewared from starting, users now have a
clear escape hatch that requires no knowledge of Python internals:

  bash /data/truecloud-patch/recover.sh

Or at a bare shell prompt:

  touch /data/truecloud-patch/disabled
  systemctl restart middlewared

sitecustomize.py checks for /data/truecloud-patch/disabled at Python
startup and skips the import hook entirely when the file exists.
apply.sh does the same so the PREINIT script also does nothing on reboot.

recover.sh is copied to /data/truecloud-patch/ by install.sh so it is
available even without the original repo directory.

README gains an "Emergency recovery" section above Troubleshooting.
2026-06-15 02:35:55 +00:00
flan 2d32c81485 Fix infinite recursion in import hook and stdout contamination in apply.sh
sitecustomize.py: exec_module was calling importlib.util.find_spec(fullname)
after Python had already added the module to sys.modules. find_spec
short-circuits to sys.modules[name].__spec__, which is our own wrapper spec,
so real_spec.loader.exec_module(module) immediately called exec_module again
— infinite recursion. Fix: resolve the real file spec in find_spec (before
sys.modules is populated) and store it on the Loader. exec_module now uses
the stored spec directly with no find_spec call.

Also move _mark_done into the finally block so a module that fails to load
doesn't trigger infinite retry loops on subsequent import attempts.

apply.sh: warn() writes to stdout. Inside $(find_mw_python), stdout is
captured by the command substitution, so any warn() call folded its text
into $PYTHON — causing every subsequent "$PYTHON" invocation to fail. Fix:
emit the fallback warning to stderr (>&2) so it goes to the log without
being captured.
2026-06-15 02:25:51 +00:00
flan 01bf5f8603 Update README.md 2026-06-14 22:14:30 -04:00
flan 0a54bcba9d Harden for Python 3.12+, add disclaimer, audit for robustness
- sitecustomize.py: replace deprecated find_module/load_module with
  find_spec/exec_module (required for Python 3.12+ / TrueNAS SCALE 25.x)
- apply.sh: remove set -e (PREINIT must not fail catastrophically);
  detect middlewared's actual Python binary instead of assuming python3;
  log rotation to avoid unbounded growth; independent failure per step
- patch_ui.py: detect multiple bundle matches; include TrueNAS version
  in pattern-not-found warning; better MARKER specificity
- uninstall.sh: mirror Python detection logic from apply.sh
- README: lead with Storj $5→$50 price context; prominent unsupported
  disclaimer; Python version compatibility matrix; post-update checklist
- Add MIT LICENSE
2026-06-15 02:13:24 +00:00
flan 21b9333324 Initial implementation: extend TrueCloud Backup to S3 and B2 providers
Patches middlewared at runtime via sitecustomize.py (no file edits to /usr/)
and widens the UI credential dropdown from Storj-only to S3+B2+Storj.
Persists across TrueNAS updates via PREINIT initshutdownscript stored in DB.
2026-06-15 02:02:17 +00:00