Add CLI for managing SFTP recording backups
Android checks / cli (push) Canceled after 0s
Android checks / verify (push) Canceled after 0s

This commit is contained in:
Meghdad committed 2026-10-16 16:04:53 +03:30
1 parent 27cf823959
commit 8588c2f3ad
21 files changed
+1732 -2

No files matched your search

+31
View File
@@ -13,6 +13,37 @@ concurrency:
cancel-in-progress: true
jobs:
cli:
runs-on: ubuntu-24.04
timeout-minutes: 10
steps:
- name: Check out source
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
with:
persist-credentials: false
- name: Install isolated CLI and build tools
run: |
python3 -m venv /tmp/remember-cli-ci
/tmp/remember-cli-ci/bin/python -m pip install 'setuptools>=77' build .
- name: Test CLI and disposable loopback SFTP integration
run: /tmp/remember-cli-ci/bin/python -m unittest discover -s tests/cli -v
- name: Build and smoke-test CLI distributions
run: |
/tmp/remember-cli-ci/bin/python -m build --no-isolation
/tmp/remember-cli-ci/bin/python -m pip install --force-reinstall --no-deps dist/*.whl
/tmp/remember-cli-ci/bin/remember --help
- name: Upload CLI distributions
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7
with:
name: remember-backup-cli
path: dist/
if-no-files-found: error
retention-days: 14
verify:
runs-on: ubuntu-24.04
timeout-minutes: 25
+7
View File
@@ -32,3 +32,10 @@ signing.properties
*.wav
*.mp3
*.pending
# Optional Python backup CLI
__pycache__/
*.py[cod]
*.egg-info/
.venv/
dist/
+9
View File
@@ -88,6 +88,15 @@ The connected-test task can target every connected device. Verify device identit
Two recording-limit integration tests capture for a real minute. Keep meaningful coverage for pause exclusion, screen-off/background behavior, stop/split boundaries, playable output, bookmarks, and preference persistence when those behaviors change. Compile device tests even when no suitable emulator is available, and report that execution remains unverified. For UI changes, inspect scrolling, round-screen clipping, large multi-digit minutes, rotary input, and accessibility descriptions. Documentation-only edits do not need an Android rebuild.
## Optional Desktop Backup CLI
- `tools/remember_cli/` is a separate Python 3.10+ package (`pyproject.toml`) with the `remember` command; `tools/remember` is its checkout launcher. Keep SFTP/local destinations explicit (`user@host:/root` or local path), without a required Remember config file. Do not add Python dependencies to the APK.
- Preserve version-1 watch manifests, stable IDs, titles, millisecond bookmarks, unknown fields, and the 500 MB per-file bound. Metadata remains the completion marker. Validate/bound untrusted metadata and escape terminal control sequences. Never derive local paths or commands from titles.
- Use required known-host or explicit SHA256 verification before SSH authentication; never add a skip-verification mode or expose private keys/passwords in arguments, output, or fixtures. Keep SFTP-only operation, one connection, bounded buffers, and no remote shell/checksum dependency. SSH agents and optional common SSH configuration may be reused.
- Downloads verify size and SHA-256 before publication, retain safe resumable partials, and preserve old local audio on failure. Sync never propagates remote deletion locally. Respect the destination lock and reject linked/special files.
- CLI server mutations are explicitly supported separately from the watch UI: title edits preserve other metadata and require atomic replacement, `rm` uses recoverable `.remember-trash`, restore verifies audio and refuses conflicts, and permanent purge requires confirmation/`--yes` for an explicit selection. Do not recursively delete unknown paths or follow symlinks. Preserve diagnostics/recovery for interrupted moves; document races with watch uploads and never claim a cross-client transaction.
- Run `python -m unittest discover -s tests/cli -v` in an isolated environment. Network tests use only `tools/sftp_fixture.py` on loopback with disposable keys/files. Build with `python -m build`; verify wheel installation. No Android rebuild is needed for CLI-only changes. Update `docs/cli.md`, backup/privacy documentation, and notices as relevant.
## Commit & Pull Request Guidelines
Use concise, descriptive commit subjects. Keep PRs focused, explain behavior changes, and report validation. Include round-screen screenshots for UI changes and link relevant issues when applicable. Use disposable recordings for screenshots. Report which checks ran, any failures or skipped device tests, and remaining physical-watch limitations. Do not commit or push unless the user asks; preserve their staging and unrelated changes.
+4
View File
@@ -29,3 +29,7 @@ Recording-service changes also need the device tests. Use a disposable emulator:
- Do not introduce app accounts, additional network services, or analytics without discussing the change first.
Do not include local IDE/device configuration, credentials, signing keys, build output, or personal audio in a pull request. Avoid attaching private recordings or identifying information to issues. Contributions are covered by the repository's [MIT license](LICENSE).
## Optional desktop CLI
The Python package in `tools/remember_cli` is independent of the watch APK. With Python 3.10+, use an isolated environment, install with `python -m pip install -e . build`, and run `python -m unittest discover -s tests/cli -v`. The network tests start only the included loopback SFTP fixture with temporary files and generated keys. Never point tests at personal backup servers. Build distributables with `python -m build`. CLI-only changes do not require an Android rebuild; preserve the watch manifest schema, SHA-256 checks, SSH host verification, bounded transfers, non-destructive sync, and confirmation/trash behavior. Read [docs/cli.md](docs/cli.md) before changing mutations or partial-transfer recovery.
+3
View File
@@ -0,0 +1,3 @@
include tools/remember tools/sftp_fixture.py
include docs/backup.md THIRD_PARTY_NOTICES.md
recursive-include tests/cli *.py
+2
View File
@@ -16,3 +16,5 @@ Remember records audio only after the user starts capture and grants microphone
- Uninstalling the app removes local recordings, preferences, playback cache, and the stored SSH identity. It does not delete server backups. You will need to authorize a new watch public key after reinstalling. Restoring backups into the local library and phone transfer are not implemented.
Developer tools and test runs can access the debug app's files. Use disposable emulator recordings for testing, and do not publish private audio or logs in issues or pull requests.
The optional desktop `remember` CLI connects directly to the SSH/SFTP destination supplied on its command line, using the computer's SSH identity/agent or an explicitly prompted password. It verifies server identities through SSH known-hosts or an explicit fingerprint; first-use interactive trust may add an approved key to the computer's known-hosts file. It sends no data to an application account, analytics service, or third-party storage. Downloads create local audio/metadata copies; playback uses a verified temporary copy removed after the player exits. Explicit CLI title edits affect server metadata; deletion moves server copies into a hidden trash folder, while explicit purge permanently removes selected trash entries. These actions do not alter recordings on the watch. See [the CLI guide](docs/cli.md).
+14
View File
@@ -164,6 +164,20 @@ Uploads use one SFTP connection at a time and bounded buffers, without a databas
The watch's private SSH key is encrypted using Android Keystore. SSH encrypts transport; audio and metadata on your server are **not encrypted at rest**. End-to-end encryption, exact-time scheduling, bandwidth caps, remote deletion, and restoration into the local library are not implemented. Automatic backup checks periodically for finished clips; saving a clip does not force an immediate upload. Interrupted jobs retain partial files for a later retry, subject to the configured retry limit.
## Backup CLI
The optional **`remember` CLI** works with backup folders over SFTP or on your computer, without a Remember config file or server software. Install it once with `pipx install .` (Python 3.10+), then pass the SSH destination and root directly:
```sh
remember ls backup@backup.example:/srv/remember --search meeting
remember info backup@backup.example:/srv/remember latest
remember sync backup@backup.example:/srv/remember ./recordings
remember verify backup@backup.example:/srv/remember
remember play backup@backup.example:/srv/remember latest
```
It supports bookmarks, JSON output, resumable verified downloads, incremental sync, title edits, recoverable server-side trash, restore, and explicit permanent purge. Host-key checks are required; your computer uses its own SSH key or agent. Sync never propagates remote deletions into local recordings. Pause watch uploads while changing server backups; those edits do not update watch-local titles or receipts. See the [CLI guide](docs/cli.md) for installation alternatives, every command, and safety/compatibility details. This is a separate desktop tool; Python is not added to the watch APK.
## Tests and automated checks
Local checks:
+1 -1
View File
@@ -30,4 +30,4 @@ Android APIs, Kotlin runtime libraries, the Android Gradle Plugin, and test libr
The app uses Android's installed system fonts. No Samsung font, watch-face asset, or wallpaper is bundled. The Spatial Number appearance is referenced as design inspiration; the numeral paths and other app artwork are drawn in project code. Screenshots in `docs/` show the app running in an emulator.
The optional Python SFTP test fixture uses separately installed Paramiko and cryptography packages under their upstream licenses. These development-only packages are not bundled in the Android app.
The optional Python backup CLI and SFTP test fixture use separately installed [Paramiko 5.x](https://pypi.org/project/paramiko/5.0.0/) (LGPL-2.1) and its dependencies, including cryptography, under their upstream licenses. These packages are installed by Python packaging tools, not vendored into this repository or bundled in the Android app. The CLI's original source is MIT; this does not relicense its dependencies.
+3 -1
View File
@@ -46,7 +46,9 @@ Verification requires downloading the uploaded audio once, so account for both d
Server recordings downloads a selected file into a single temporary playback cache and verifies its checksum before playback. At least the full recording size plus 16 MB free space is required. The browser loads up to 1,000 manifests per folder. Files created by other applications or unsupported/corrupt manifests are ignored.
SSH protects transfers but does not encrypt the audio and metadata stored on the server. Restore into the local library, client-side backup encryption, remote deletion, bandwidth limits, and exact-clock-time scheduling are future work.
SSH protects transfers but does not encrypt the audio and metadata stored on the server. Restore into the watch's local library, client-side backup encryption, remote deletion from the watch, bandwidth limits, and exact-clock-time scheduling are future work.
For desktop backup management, use the separate [Remember CLI](cli.md). It accepts `user@host:/backup/root` directly, lists/searches recordings, shows bookmarks, verifies/downloads audio, and supports explicit server-title edits and recoverable trash/restore/purge. Pause watch uploads while changing server files. CLI changes do not change the watch's local recordings or receipts, and a later watch re-upload can recreate files or replace a CLI-edited title.
## Testing
+131
View File
@@ -0,0 +1,131 @@
# Remember backup CLI
`remember` manages the recorder's existing backups over **SFTP** or in a local folder. Pass the destination directly, like `scp`; no Remember config file, account, database, server process, or phone app is needed. It works with the SFTP-only server account described in [backup setup](backup.md).
## Install
Python 3.10+ is required. From this repository:
```sh
pipx install .
remember --help
```
Alternatively use a Python virtual environment:
```sh
python3 -m venv .venv
.venv/bin/python -m pip install .
.venv/bin/remember --help
```
On Windows use `.venv\Scripts\python` and `.venv\Scripts\remember`. `python -m remember_cli` is equivalent to `remember`. The checkout launcher `tools/remember` also works when its Python environment has the dependencies installed. The CLI is separate from the watch APK.
## Connect without configuration
```sh
remember ls backup@backup.example:/srv/remember
remember ls backup@backup.example:/srv/remember -P 2222 -i ~/.ssh/id_ed25519
remember ls 'sftp://backup@backup.example:2222/srv/remember'
remember ls 'backup@[2001:db8::10]:/srv/remember'
remember ls ./downloaded-backups
```
Quote the entire source if its path contains spaces. Relative remote paths and `~/...` are relative to the SFTP account's home; absolute paths are as seen inside its chroot. The root directory must already exist.
Authorize **your computer's SSH public key** for the same backup account, or use `--password` for an interactive password prompt if your server permits it. The watch's private key stays on the watch and is not needed. SSH-agent identities and normal private-key files are supported. Load encrypted keys with `ssh-add` first, or use `-i KEYFILE --ask-passphrase`.
Standard OpenSSH `known_hosts` is honored. An unknown host requires explicit interactive approval of its SHA-256 fingerprint **before authentication**. For scripts, supply an independently verified fingerprint:
```sh
remember ls backup@backup.example:/srv/remember --host-key 'SHA256:VERIFIED_FINGERPRINT'
```
There is no insecure/skip-verification option. Changed known host keys are rejected. `--known-hosts FILE` selects a trust file; this is optional SSH trust storage, not application configuration. An explicit fingerprint is a per-command pin and is not saved. If the server offers several host-key types, ensure the pin matches the negotiated key; your watch may pin a different type.
SSH aliases can reuse `HostName`, `User`, `Port`, `IdentityFile`, and `ProxyCommand` from `~/.ssh/config` when present. This is not a complete OpenSSH client: `ProxyJump`, certificates, hardware-token providers, arbitrary `ssh -o` settings, and every SSH-config directive are not implemented. A reachable alias or trusted local `ProxyCommand` can supply a jump connection. No remote shell commands are executed. `--timeout SECONDS` bounds connection and socket waits.
## Find and inspect recordings
```sh
remember ls backup@backup.example:/srv/remember
remember ls backup@backup.example:/srv/remember --search meeting --marked
remember ls backup@backup.example:/srv/remember --since 2026-10-01 --until 2026-11-01
remember ls backup@backup.example:/srv/remember --sort duration --reverse --limit 10
remember info backup@backup.example:/srv/remember latest
remember marks backup@backup.example:/srv/remember 12ab34cd
remember stats backup@backup.example:/srv/remember
remember ls backup@backup.example:/srv/remember --json
```
Use full IDs, unambiguous ID prefixes (at least four characters), or `latest`. Displayed dates are UTC. `--until` is exclusive; a date denotes midnight UTC. Filters also work with `stats` and `sync`. Human output escapes terminal control characters from server filenames and titles. `--json` gives clean JSON on stdout; diagnostics/progress go to stderr. Commands exit `0` on success, `1` on failed/incomplete operations, `2` on argument errors, and `130` on interruption.
`ls` shows only completed version-1 manifests with regular audio of the declared size. Listing does **not** read every audio checksum. Corrupt/unsupported manifests, linked files, missing audio, and incomplete uploads produce warnings; use `doctor` to inspect them. It is not limited to the watch browser's 1,000 manifests.
## Download and sync
```sh
remember get backup@backup.example:/srv/remember latest -o ./recordings
remember get backup@backup.example:/srv/remember 12ab34cd 56ef78ab -o ./recordings
remember sync backup@backup.example:/srv/remember ./recordings --dry-run
remember sync backup@backup.example:/srv/remember ./recordings
remember sync backup@backup.example:/srv/remember ./meetings --search meeting --marked
```
Downloads retain `<id>.m4a` and `<id>.json`, including titles and millisecond bookmark timestamps. Stable IDs keep files compatible with the watch backup format and avoid unsafe title-derived paths. `info` and `marks` make the metadata readable.
Each file is streamed through a bounded buffer and verified against its manifest's size and SHA-256 before publication. Audio is replaced atomically; metadata follows. Interrupted downloads keep hidden `.part` files and their snapshot receipts for the next run. Corrupt resumed prefixes restart once from zero. Use `--no-resume` to restart explicitly. A small `.remember-lock` remains in the destination; its OS lock is automatically released after crashes.
`sync` hashes existing local audio before skipping it and refreshes metadata. It **never deletes local recordings**, including when backups were removed remotely. Differing local audio is preserved unless you supply `--force`; even then a failed download preserves the previous audio. Metadata mirrors the selected server snapshot. Free space for both the existing and replacement audio is needed when replacing a file. No restore/import into the watch's private library is provided.
## Verify and diagnose
```sh
remember verify backup@backup.example:/srv/remember
remember verify backup@backup.example:/srv/remember latest 12ab34cd --json
remember doctor backup@backup.example:/srv/remember
```
Verification streams the audio to your computer without storing it; budget download bandwidth. `doctor` reports incomplete uploads, orphaned audio, invalid manifests, leftover CLI metadata writes, and partial/damaged trash. It never deletes or repairs files automatically. `.upload` files may belong to an active watch transfer; leave them alone until that transfer finishes.
## Listen
```sh
remember play backup@backup.example:/srv/remember latest
remember play backup@backup.example:/srv/remember 12ab34cd --player 'mpv --no-video'
```
The complete audio is downloaded and verified into a private temporary directory before playback. It is removed after the player exits. The default player is the first available of `ffplay`, `mpv`, or macOS `afplay`. A custom player command must block until playback finishes; shell operators are not interpreted. Audio is not streamed before verification and is never sent to a third-party service.
## Rename, trash, restore, and purge
Pause watch uploads while editing backups. There is no server transaction or shared lock with the watch: concurrent uploads can change files, recreate a trashed recording, or replace a CLI-edited title. The tool checks snapshots before changes and refuses detected conflicts, but this cannot eliminate every race with another client. Changes affect **server copies only**, not the watch's local titles, recordings, or backup receipts.
```sh
remember rename backup@backup.example:/srv/remember 12ab34cd 'Interview with Alex' --dry-run
remember rename backup@backup.example:/srv/remember 12ab34cd 'Interview with Alex'
remember rm backup@backup.example:/srv/remember 12ab34cd --dry-run
remember rm backup@backup.example:/srv/remember 12ab34cd
remember trash backup@backup.example:/srv/remember
remember restore backup@backup.example:/srv/remember TRASH_ID_PREFIX
remember purge backup@backup.example:/srv/remember TRASH_ID_PREFIX --dry-run
remember purge backup@backup.example:/srv/remember TRASH_ID_PREFIX --yes
```
`rename` changes only the title (1–200 characters) in metadata and preserves IDs, checksums, bookmarks, and unknown fields. Remote title replacement requires the SFTP server's `posix-rename@openssh.com` extension. If atomic replacement is unavailable, the tool fails without deleting the original manifest.
`rm` asks for confirmation and **moves** the selected pair into `.remember-trash/<trash-id>/` on the same server. It does not download/copy the audio and does not free disk space yet. `--yes` approves the explicit selection for scripts; there is no implicit all/wildcard removal. Completion metadata is hidden before moving audio. A small entry record makes interrupted two-file moves visible in `trash` and `doctor`.
`restore` verifies quarantined audio, moves audio first and metadata last, and refuses to overwrite existing backups. Interrupted moves can be resumed using the same trash ID when their matching pieces remain available. `purge` permanently removes only the selected trash entry's validated files and requires confirmation or `--yes`; it cannot be undone. Partial/damaged entries with unknown or linked files require manual inspection. Trash is not automatically expired. Linked backup files and trash entries are refused; an explicitly chosen local root/destination resolves to its target.
These operations also work on local backup directories. A watch re-upload after CLI deletion may recreate the recording; deleting its server copy does not mark/delete the watch's local file.
## Development and validation
```sh
python -m pip install -e . build
python -m unittest discover -s tests/cli -v
python -m build
```
Unit tests use temporary local recordings. The network integration test starts the included loopback-only disposable SFTP fixture, generates test identities, and removes its files afterwards. It never connects to a personal backup server. The Android APK does not include Python or Paramiko. Windows behavior and physical server resource consumption still require validation on the intended systems.
+20
View File
@@ -0,0 +1,20 @@
[build-system]
requires = ["setuptools>=77"]
build-backend = "setuptools.build_meta"
[project]
name = "remember-backup"
version = "0.1.0"
description = "Config-free SFTP and local backup tools for the Remember watch recorder"
readme = "docs/cli.md"
requires-python = ">=3.10"
license = "MIT"
license-files = ["LICENSE"]
dependencies = ["paramiko>=5.0,<6"]
[project.scripts]
remember = "remember_cli.cli:main"
[tool.setuptools]
package-dir = {"" = "tools"}
packages = ["remember_cli"]
+273
View File
@@ -0,0 +1,273 @@
import contextlib
import hashlib
import io
import json
import os
import sys
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
from remember_cli.cli import main, parser
from remember_cli.model import Clip, Error, json_bytes, safe
from remember_cli.repository import Repository, download, exclusive_file
from remember_cli.store import Source, Store
FIRST = "aaaaaaaa-1111-4111-8111-111111111111"
SECOND = "bbbbbbbb-2222-4222-8222-222222222222"
def manifest(clip_id=FIRST, audio=b"synthetic audio fixture", **changes):
return {"version": 1, "id": clip_id, "title": "Meeting / notes", "created": 1_790_000_000_000,
"duration": 90000, "marks": [1000, 12000], "bytes": len(audio),
"sha256": hashlib.sha256(audio).hexdigest(), **changes}
class CliTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory(prefix="remember-cli-test-")
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name) / "server"
self.root.mkdir()
self.target = Path(self.temp.name) / "downloads"
self.audio = b"synthetic audio fixture" * 6000
self.doc = manifest(audio=self.audio, future_field={"preserve": True})
self.seed(self.doc, self.audio)
self.store = Store(Source.parse(str(self.root)))
self.repo = Repository(self.store)
def seed(self, doc, audio):
(self.root / (doc["id"] + ".m4a")).write_bytes(audio)
(self.root / (doc["id"] + ".json")).write_bytes(json_bytes(doc))
def call(self, *arguments):
stdout, stderr = io.StringIO(), io.StringIO()
with contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr), patch("sys.stdin", io.StringIO()):
code = main(list(arguments))
return code, stdout.getvalue(), stderr.getvalue()
def test_source_scp_urls_ipv6_local_paths_and_no_password_urls(self):
for value in ["me@box:/backups with spaces", "sftp://me@box/backups%20with%20spaces"]:
parsed = Source.parse(value)
self.assertEqual((parsed.host, parsed.user, parsed.root), ("box", "me", "/backups with spaces"))
self.assertEqual(Source.parse("me@[::1]:/backup").host, "::1")
self.assertEqual(Source.parse("ssh://me@[::1]:2222/backup").port, 2222)
self.assertIsNone(Source.parse("./backup:notes").host)
with self.assertRaises(Error):
Source.parse("sftp://me:secret@host/backup")
with self.assertRaises(Error):
Source.parse("https://host/backup")
def test_global_options_work_before_or_after_command(self):
for argv in [["--json", "-P", "2222", "ls", str(self.root)], ["ls", str(self.root), "--json", "-P", "2222"]]:
args = parser().parse_args(argv)
self.assertTrue(args.json)
self.assertEqual(args.port, 2222)
def test_list_filters_bookmarks_machine_json_and_terminal_escape(self):
code, stdout, stderr = self.call("ls", str(self.root), "--marked", "--search", "NOTES", "--json")
self.assertEqual(code, 0, stderr)
self.assertEqual(json.loads(stdout)[0]["future_field"], {"preserve": True})
code, stdout, _ = self.call("marks", str(self.root), "aaaa", "--json")
self.assertEqual(json.loads(stdout)[1], {"number": 2, "milliseconds": 12000, "time": "00:00:12"})
self.assertNotIn("\x1b", safe("title\x1b[31m\n"))
def test_missing_ambiguous_and_short_ids_never_select_arbitrarily(self):
doc = manifest("aaaaaaaa-2222-4222-8222-222222222222", b"second")
self.seed(doc, b"second")
for selector in ["", "a", "aaaa", "ffff"]:
code, _, error = self.call("info", str(self.root), selector)
self.assertEqual(code, 1, selector)
self.assertTrue(error)
def test_malformed_oversized_duplicate_and_traversal_metadata_fail_closed(self):
invalid = [json_bytes({**self.doc, "id": "../../private"}),
b'{"version":1,"version":1}', b"[1,2]", b"x" * (128 * 1024 + 1),
json_bytes({**self.doc, "bytes": True}), json_bytes({**self.doc, "version": True}),
json_bytes({**self.doc, "sha256": "bad"})]
for payload in invalid:
(self.root / (FIRST + ".json")).write_bytes(payload)
clips, issues = self.repo.inventory()
self.assertEqual(clips, [])
self.assertTrue(issues)
with self.assertRaises(Error):
Clip.parse(b'{"version": NaN}', FIRST)
def test_doctor_reports_upload_orphan_and_bad_manifest_without_removing(self):
(self.root / (SECOND + ".m4a")).write_bytes(b"interrupted")
(self.root / (SECOND + ".m4a.upload")).write_bytes(b"partial")
code, stdout, _ = self.call("doctor", str(self.root), "--json")
self.assertEqual(code, 1)
self.assertEqual(len(json.loads(stdout)["issues"]), 2)
self.assertTrue((self.root / (SECOND + ".m4a.upload")).exists())
def test_verified_download_and_metadata_only_incremental_sync(self):
clip = self.repo.clip(FIRST)
result = download(self.store, clip, self.target)
self.assertEqual(result["status"], "downloaded")
self.assertEqual((self.target / (FIRST + ".m4a")).read_bytes(), self.audio)
self.repo.rename_title(clip, "Updated title")
result = download(self.store, self.repo.clip(FIRST), self.target)
self.assertEqual(result["status"], "unchanged")
local = json.loads((self.target / (FIRST + ".json")).read_bytes())
self.assertEqual(local["title"], "Updated title")
self.assertEqual(local["marks"], self.doc["marks"])
self.assertEqual(local["future_field"], self.doc["future_field"])
def test_resume_interruption_and_repair_corrupt_prefix(self):
clip = self.repo.clip(FIRST)
original_open = self.store.open
class Interrupted(io.BytesIO):
def read(self, count=-1):
if self.tell() >= 65536:
raise OSError("simulated disconnect")
return super().read(count)
with patch.object(self.store, "open", return_value=Interrupted(self.audio)):
with self.assertRaises(OSError):
download(self.store, clip, self.target)
partial = self.target / ("." + FIRST + ".m4a.part")
self.assertEqual(partial.stat().st_size, 65536)
partial.write_bytes(b"wrong prefix" * 100)
download(self.store, clip, self.target)
self.assertEqual((self.target / (FIRST + ".m4a")).read_bytes(), self.audio)
def test_checksum_failure_never_replaces_existing_audio_even_with_force(self):
self.target.mkdir()
local = self.target / (FIRST + ".m4a")
local.write_bytes(b"precious previous local audio")
with self.assertRaises(Error):
download(self.store, self.repo.clip(FIRST), self.target)
(self.root / (FIRST + ".m4a")).write_bytes(b"X" * len(self.audio))
with self.assertRaises(Error):
download(self.store, self.repo.clip(FIRST), self.target, force=True)
self.assertEqual(local.read_bytes(), b"precious previous local audio")
@unittest.skipIf(os.name == "nt", "symlink creation requires extra privileges on Windows")
def test_symlinked_audio_and_local_partial_are_not_followed(self):
outside = Path(self.temp.name) / "outside"
outside.write_bytes(b"keep")
self.target.mkdir()
(self.target / ("." + FIRST + ".m4a.part")).symlink_to(outside)
with self.assertRaises((Error, OSError)):
download(self.store, self.repo.clip(FIRST), self.target)
self.assertEqual(outside.read_bytes(), b"keep")
(self.root / (FIRST + ".m4a")).unlink()
(self.root / (FIRST + ".m4a")).symlink_to(outside)
clips, issues = self.repo.inventory()
self.assertEqual(clips, [])
self.assertTrue(issues)
def test_rename_preserves_all_other_fields_and_rejects_changed_snapshot(self):
clip = self.repo.clip(FIRST)
updated = self.repo.rename_title(clip, "New name")
self.assertEqual(updated, {**self.doc, "title": "New name"})
with self.assertRaises(Error):
self.repo.rename_title(clip, "stale update")
self.assertEqual(self.repo.clip(FIRST).title, "New name")
def test_mutations_refuse_active_uploads(self):
clip = self.repo.clip(FIRST)
(self.root / (FIRST + ".json.upload")).write_bytes(b"busy")
with self.assertRaises(Error):
self.repo.remove(clip)
with self.assertRaises(Error):
self.repo.rename_title(clip, "new")
self.assertTrue((self.root / (FIRST + ".json")).exists())
def test_trash_restore_and_purge_are_explicit_and_preserve_original_audio(self):
code, stdout, _ = self.call("rm", str(self.root), "aaaa", "--dry-run", "--json")
self.assertEqual(code, 0)
self.assertTrue(json.loads(stdout)[0]["dry_run"])
code, _, _ = self.call("rm", str(self.root), "aaaa")
self.assertEqual(code, 1)
self.assertTrue((self.root / (FIRST + ".m4a")).exists())
entry = self.repo.remove(self.repo.clip(FIRST))
self.assertFalse((self.root / (FIRST + ".json")).exists())
saved = self.repo.trash()[0]
self.assertEqual(saved["state"], "complete")
self.repo.restore(saved)
self.assertEqual((self.root / (FIRST + ".m4a")).read_bytes(), self.audio)
entry = self.repo.remove(self.repo.clip(FIRST))
code, _, _ = self.call("purge", str(self.root), entry["trash_id"], "--json")
self.assertEqual(code, 1)
code, _, error = self.call("purge", str(self.root), entry["trash_id"], "--yes", "--json")
self.assertEqual(code, 0, error)
self.assertEqual(self.repo.trash(), [])
def test_trash_failure_retains_recoverable_entry_and_original_backup(self):
rename = self.store.rename
def fail_audio(old, new):
if old == FIRST + ".m4a":
raise OSError("simulated move failure")
rename(old, new)
with patch.object(self.store, "rename", side_effect=fail_audio):
with self.assertRaises(Error):
self.repo.remove(self.repo.clip(FIRST))
self.assertEqual(self.repo.clip(FIRST).raw, self.doc)
entry = self.repo.trash()[0]
self.assertEqual(entry["state"], "partial")
self.repo.restore(entry)
self.assertEqual(self.repo.trash(), [])
def test_interrupted_restore_can_resume_without_overwrite(self):
self.repo.remove(self.repo.clip(FIRST))
entry = self.repo.trash()[0]
rename = self.store.rename
def fail_metadata(old, new):
if new == FIRST + ".json":
raise OSError("simulated restore failure")
rename(old, new)
with patch.object(self.store, "rename", side_effect=fail_metadata):
with self.assertRaises(OSError):
self.repo.restore(entry)
self.repo.restore(self.repo.trash()[0])
self.assertEqual(self.repo.clip(FIRST).raw, self.doc)
def test_restore_conflict_and_unknown_trash_files_fail_closed(self):
entry = self.repo.remove(self.repo.clip(FIRST))
self.seed(self.doc, self.audio)
with self.assertRaises(Error):
self.repo.restore(self.repo.trash()[0])
folder = self.root / ".remember-trash" / entry["trash_id"]
(folder / "important-other-file").write_bytes(b"keep")
self.assertEqual(self.repo.trash()[0]["state"], "damaged")
code, _, _ = self.call("purge", str(self.root), entry["trash_id"], "--yes")
self.assertEqual(code, 1)
self.assertTrue((folder / "important-other-file").exists())
def test_sync_does_not_propagate_deletions_and_dry_run_creates_nothing(self):
code, _, error = self.call("sync", str(self.root), str(self.target), "--dry-run", "--json")
self.assertEqual(code, 0, error)
self.assertFalse(self.target.exists())
self.call("sync", str(self.root), str(self.target), "--json")
self.repo.remove(self.repo.clip(FIRST))
code, _, error = self.call("sync", str(self.root), str(self.target), "--json")
self.assertEqual(code, 0, error)
self.assertEqual((self.target / (FIRST + ".m4a")).read_bytes(), self.audio)
def test_play_uses_verified_private_temporary_audio_without_a_shell(self):
paths = []
def play(argv, **kwargs):
self.assertIsInstance(argv, list)
self.assertNotIn("shell", kwargs)
path = Path(argv[-1])
self.assertEqual(path.read_bytes(), self.audio)
paths.append(path)
with patch("remember_cli.cli.subprocess.run", side_effect=play):
code, stdout, error = self.call("play", str(self.root), "latest", "--player", sys.executable, "--json")
self.assertEqual(code, 0, error)
self.assertTrue(json.loads(stdout)["played"])
self.assertTrue(paths)
self.assertFalse(paths[0].exists())
def test_destination_lock_refuses_competing_downloads(self):
self.target.mkdir()
with exclusive_file(self.target / ".remember-lock"):
with self.assertRaises(Error):
download(self.store, self.repo.clip(FIRST), self.target)
self.assertFalse((self.target / (FIRST + ".m4a")).exists())
if __name__ == "__main__":
unittest.main()
+128
View File
@@ -0,0 +1,128 @@
"""Real SSH/SFTP protocol tests against a disposable loopback-only server, never personal storage."""
import contextlib
import io
import json
import os
import socket
import subprocess
import sys
import tempfile
import time
import unittest
import paramiko
from pathlib import Path
from unittest.mock import patch
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
from cryptography.hazmat.primitives.serialization import Encoding, NoEncryption, PrivateFormat
from remember_cli.cli import main
from remember_cli.model import Error, json_bytes
from remember_cli.repository import Repository, download
from remember_cli.store import Source, Store
from test_cli import FIRST, manifest
class SftpTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.temp = tempfile.TemporaryDirectory(prefix="remember-cli-sftp-test-")
cls.folder = Path(cls.temp.name)
cls.identity = cls.folder / "id_ed25519"
cls.identity.write_bytes(Ed25519PrivateKey.generate().private_bytes(Encoding.PEM, PrivateFormat.OpenSSH, NoEncryption()))
cls.identity.chmod(0o600)
with socket.socket() as listener:
listener.bind(("127.0.0.1", 0))
cls.port = listener.getsockname()[1]
cls.state = cls.folder / "state.json"
cls.log = (cls.folder / "fixture.log").open("w+")
fixture = Path(__file__).resolve().parents[2] / "tools/sftp_fixture.py"
cls.server = subprocess.Popen([sys.executable, str(fixture), "--port", str(cls.port), "--state-file", str(cls.state)], stdout=cls.log, stderr=cls.log)
deadline = time.monotonic() + 10
while not cls.state.exists() and time.monotonic() < deadline and cls.server.poll() is None:
time.sleep(.05)
if not cls.state.exists():
cls.log.seek(0)
cls.server.terminate(); cls.server.wait(timeout=5)
raise RuntimeError(cls.log.read())
cls.pin = json.loads(cls.state.read_text())["fingerprint"]
cls.source_text = f"backup-test@127.0.0.1:/remember"
cls.source = Source.parse(cls.source_text)
@classmethod
def tearDownClass(cls):
cls.server.terminate(); cls.server.wait(timeout=10)
cls.log.close(); cls.temp.cleanup()
def connect(self, pin=None):
return Store(self.source, port=self.port, identity=str(self.identity), host_key=pin or self.pin, timeout=5)
def test_identity_rejection_precedes_authentication_and_known_hosts_reuse(self):
before = json.loads(self.state.read_text())["auth_attempts"]
with self.assertRaises(Error):
with self.connect("SHA256:" + "a" * 43):
pass
self.assertEqual(json.loads(self.state.read_text())["auth_attempts"], before)
with patch("sys.stdin", io.StringIO()):
with self.assertRaises(Error):
Store(self.source, port=self.port, identity=str(self.identity), known_hosts=str(self.folder / "empty-known-hosts"), timeout=5)
self.assertEqual(json.loads(self.state.read_text())["auth_attempts"], before)
class Terminal(io.StringIO):
def isatty(self):
return True
approved = self.folder / "approved-known-hosts"
with patch("sys.stdin", Terminal("yes\n")), contextlib.redirect_stderr(io.StringIO()):
with Store(self.source, port=self.port, identity=str(self.identity), known_hosts=str(approved), timeout=5):
pass
self.assertIn(f"[127.0.0.1]:{self.port}", approved.read_text())
with self.connect() as store:
key = store.client.get_transport().get_remote_server_key()
hosts = self.folder / "known-hosts"
hosts.write_text(f"[127.0.0.1]:{self.port} {key.get_name()} {key.get_base64()}\n")
with Store(self.source, port=self.port, identity=str(self.identity), known_hosts=str(hosts), timeout=5) as store:
self.assertEqual(list(store.entries()), [])
before = json.loads(self.state.read_text())["auth_attempts"]
wrong = paramiko.Ed25519Key.from_private_key_file(str(self.identity))
hosts.write_text(f"[127.0.0.1]:{self.port} {wrong.get_name()} {wrong.get_base64()}\n")
with self.assertRaises(paramiko.BadHostKeyException):
Store(self.source, port=self.port, identity=str(self.identity), known_hosts=str(hosts), timeout=5)
self.assertEqual(json.loads(self.state.read_text())["auth_attempts"], before)
def test_real_sftp_list_download_atomic_title_trash_restore_and_purge(self):
audio = b"disposable recording bytes" * 5000
doc = manifest(audio=audio)
with self.connect() as store:
store.atomic_write(FIRST + ".m4a", audio)
store.atomic_write(FIRST + ".json", json_bytes(doc))
repo = Repository(store)
clips, issues = repo.inventory()
self.assertEqual(issues, [])
self.assertEqual(len(clips), 1)
repo.verify(clips[0])
result = download(store, clips[0], self.folder / "download")
self.assertEqual(Path(result["file"]).read_bytes(), audio)
with patch.object(store.sftp, "posix_rename", side_effect=OSError("Unsupported extension")):
with self.assertRaises(Error):
repo.rename_title(clips[0], "Must not replace the original")
self.assertEqual(store.read(FIRST + ".json"), clips[0].encoded)
repo.rename_title(clips[0], "Edited from the CLI")
self.assertEqual(repo.clip(FIRST).title, "Edited from the CLI")
repo.remove(repo.clip(FIRST))
entry = repo.trash()[0]
self.assertEqual(entry["state"], "complete")
self.assertEqual(repo.inventory()[0], [])
repo.restore(entry)
repo.verify(repo.clip(FIRST))
repo.remove(repo.clip(FIRST))
repo.purge(repo.trash()[0])
self.assertEqual(repo.trash(), [])
stdout, stderr = io.StringIO(), io.StringIO()
with contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr):
result = main(["stats", self.source_text, "-P", str(self.port), "-i", str(self.identity), "--host-key", self.pin, "--json"])
self.assertEqual(result, 0, stderr.getvalue())
self.assertEqual(json.loads(stdout.getvalue())["recordings"], 0)
if __name__ == "__main__":
unittest.main()
Executable
+12
View File
@@ -0,0 +1,12 @@
#!/usr/bin/env python3
"""Run from a checkout after `python3 -m pip install .`, or use the installed `remember` command."""
import sys
if sys.version_info < (3, 10):
sys.exit("Remember CLI requires Python 3.10 or newer.")
try:
from remember_cli.cli import main
except ModuleNotFoundError as error:
sys.exit(f"Missing CLI dependency ({error.name}). Install with: pipx install . (or python3 -m pip install .)")
raise SystemExit(main())
+3
View File
@@ -0,0 +1,3 @@
"""Remember backup CLI. No watch, account, or application config file required."""
__version__ = "0.1.0"
+3
View File
@@ -0,0 +1,3 @@
from .cli import main
raise SystemExit(main())
+358
View File
@@ -0,0 +1,358 @@
"""The `remember` command. All destinations are explicit; no remembered server/config file."""
import argparse
import json
import os
import re
import shlex
import shutil
import subprocess
import sys
import tempfile
import time
from datetime import datetime, timezone
from pathlib import Path
import paramiko
from . import __version__
from .model import Error, date, duration, safe
from .repository import Repository, download
from .store import Source, Store
def parser():
common = argparse.ArgumentParser(add_help=False)
for flags, kwargs in [
(("-P", "--port"), dict(type=int, help="SSH port (like scp -P)")),
(("-i", "--identity"), dict(help="SSH private-key file; otherwise use SSH agent/default keys")),
(("--host-key",), dict(help="verified SHA256:... host fingerprint instead of known_hosts")),
(("--known-hosts",), dict(help="OpenSSH known_hosts file (default: ~/.ssh/known_hosts)")),
(("--password",), dict(action="store_true", help="prompt for an SSH password (never place it in arguments)")),
(("--ask-passphrase",), dict(action="store_true", help="prompt for an encrypted private key's passphrase")),
(("--timeout",), dict(type=int, help="connection and socket timeout in seconds (default: 30)")),
(("--json",), dict(action="store_true", help="machine-readable JSON on stdout; diagnostics on stderr")),
]:
common.add_argument(*flags, default=argparse.SUPPRESS, **kwargs)
root = argparse.ArgumentParser(prog="remember", parents=[common], description="Work with Remember backups over SFTP or on disk. No application config file required.",
epilog="Example: remember ls user@server:/backups/remember --search meeting\nRemote paths also accept sftp://user@host:2222/path and [user@][IPv6]:/path.",
formatter_class=argparse.RawDescriptionHelpFormatter)
root.add_argument("--version", action="version", version=f"remember-backup {__version__}")
commands = root.add_subparsers(dest="command", required=True)
def command(name, help, aliases=()):
child = commands.add_parser(name, aliases=aliases, parents=[common], help=help, description=help)
child.add_argument("source", metavar="SOURCE", help="[user@]host:/backup/root, SSH URL, or local directory")
return child
def filters(child):
child.add_argument("--search", help="case-insensitive title/ID search")
child.add_argument("--since", type=parse_date, help="created on/after this UTC date or ISO timestamp")
child.add_argument("--until", type=parse_date, help="created before this UTC date or ISO timestamp (exclusive)" )
child.add_argument("--marked", action="store_true", help="only recordings with bookmarks")
child.add_argument("--sort", choices=["created", "title", "duration", "bytes"], default="created")
child.add_argument("--reverse", action="store_true", help="reverse the default sort (created: newest first)")
child.add_argument("--limit", type=positive, help="maximum number of matched recordings")
filters(command("ls", "List and search completed recordings", aliases=["list"]))
filters(command("stats", "Summarize completed recordings, audio bytes, time, and bookmarks"))
child = command("info", "Show metadata, SHA-256, and bookmarks", aliases=["stat"])
child.add_argument("id", help="full recording ID or unambiguous prefix; 'latest' selects newest")
child = command("marks", "Show a recording's bookmarks as timestamps")
child.add_argument("id")
child = command("get", "Download selected audio + metadata; verify before publishing", aliases=["cp"])
child.add_argument("ids", nargs="+", help="recording IDs/prefixes or latest")
child.add_argument("-o", "--output", required=True, metavar="DIRECTORY")
transfer_options(child)
child = command("sync", "Incrementally download backups; never propagate server deletions locally")
child.add_argument("output", metavar="DIRECTORY")
filters(child); transfer_options(child)
child = command("verify", "Read audio and check every size and SHA-256 (uses download bandwidth)", aliases=["check"])
child.add_argument("ids", nargs="*", help="IDs/prefixes; omit to verify every completed recording")
command("doctor", "Report invalid manifests, missing/orphaned audio, uploads, and damaged trash")
child = command("play", "Verify a temporary local copy, then play with ffplay, mpv, or afplay")
child.add_argument("id")
child.add_argument("--player", help="blocking player command, e.g. 'mpv --no-video'; no shell is used")
child = command("rename", "Rename a backup's title in metadata; never rename its stable file ID")
child.add_argument("id"); child.add_argument("title")
child.add_argument("--dry-run", action="store_true")
child = command("rm", "Move selected backups to server-side trash (reversible)", aliases=["remove"])
child.add_argument("ids", nargs="+")
child.add_argument("-y", "--yes", action="store_true", help="confirm the explicitly selected recordings without prompting")
child.add_argument("--dry-run", action="store_true")
command("trash", "List recoverable trash entries, including interrupted moves")
child = command("restore", "Restore a trash entry, verify its audio, and refuse existing-file conflicts")
child.add_argument("id", help="trash ID or unambiguous prefix")
child.add_argument("--dry-run", action="store_true")
child = command("purge", "Permanently delete explicitly selected trash entries; cannot be undone")
child.add_argument("ids", nargs="+", help="trash IDs/prefixes (no implicit 'all')")
child.add_argument("-y", "--yes", action="store_true")
child.add_argument("--dry-run", action="store_true")
return root
def positive(value):
try:
result = int(value)
if result > 0:
return result
except ValueError:
pass
raise argparse.ArgumentTypeError("must be a positive integer")
def parse_date(value):
try:
parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
return int(parsed.replace(tzinfo=timezone.utc).timestamp() * 1000) if parsed.tzinfo is None else int(parsed.timestamp() * 1000)
except (ValueError, OverflowError) as exc:
raise argparse.ArgumentTypeError("use YYYY-MM-DD or an ISO timestamp") from exc
def transfer_options(child):
child.add_argument("--force", action="store_true", help="replace differing local audio only after successful verification")
child.add_argument("--no-resume", action="store_true", help="restart this tool's partial downloads from zero")
child.add_argument("--dry-run", action="store_true", help="show selected transfers without writing local files")
def selected(clips, selectors):
result = []
for selector in selectors:
if selector == "latest":
matches = clips[:1]
else:
if not re.fullmatch(r"[a-fA-F0-9-]{4,36}", selector):
raise Error("Use a full recording ID, a prefix of at least four characters, or latest")
exact = [clip for clip in clips if clip.id == selector]
matches = exact or [clip for clip in clips if clip.id.lower().startswith(selector.lower())]
if len(matches) != 1:
raise Error(f"{safe(selector)}: {'ambiguous prefix; use more of the ID' if matches else 'no completed recording found'}")
if matches[0].id not in {clip.id for clip in result}:
result.append(matches[0])
return result
def filtered(clips, args):
result = [clip for clip in clips if
(not args.search or args.search.casefold() in (clip.title + " " + clip.id).casefold()) and
(args.since is None or clip.raw["created"] >= args.since) and
(args.until is None or clip.raw["created"] < args.until) and
(not args.marked or clip.marks)]
key = (lambda clip: clip.title.casefold()) if args.sort == "title" else (lambda clip: clip.raw[args.sort])
result.sort(key=lambda clip: (key(clip), clip.id), reverse=(args.sort == "created") != args.reverse)
return result[:args.limit] if args.limit else result
def output(value, args):
if getattr(args, "json", False):
print(json.dumps(value, ensure_ascii=False, allow_nan=False))
elif isinstance(value, str):
print(safe(value))
else:
print(json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False))
def table(headers, rows):
rows = [[safe(value) for value in row] for row in rows]
if not rows:
print("No matching recordings.")
return
widths = [max(len(header), *(len(row[i]) for row in rows)) for i, header in enumerate(headers)]
for row in [headers, *rows]:
print(" ".join(value.ljust(width) for value, width in zip(row, widths)).rstrip())
def human_bytes(value):
amount = float(value)
for unit in ("B", "KiB", "MiB", "GiB", "TiB"):
if amount < 1024 or unit == "TiB":
return f"{amount:.1f} {unit}" if unit != "B" else f"{value} B"
amount /= 1024
def download_progress(clip_id, args):
last = [0.0]
def report(done, total):
now = time.monotonic()
if sys.stderr.isatty() and not getattr(args, "json", False) and (now - last[0] >= .5 or done == total):
last[0] = now
print(f"\r{clip_id[:12]} {done / total:6.1%} {human_bytes(done)} / {human_bytes(total)}", end="\n" if done == total else "", file=sys.stderr, flush=True)
return report
def confirm(args, message):
if args.dry_run or args.yes:
return
if getattr(args, "json", False) or not sys.stdin.isatty():
raise Error("Confirmation required: review with --dry-run, then pass --yes")
print(message, file=sys.stderr)
print("Type yes to continue: ", file=sys.stderr, end="", flush=True)
if input().strip() != "yes":
raise Error("Cancelled; no changes made")
def trash_selection(entries, selectors):
chosen = []
for selector in selectors:
if not re.fullmatch(r"[a-f0-9]{4,32}", selector):
raise Error("Use a trash ID or a prefix of at least four characters")
matches = [item for item in entries if item["trash_id"].startswith(selector)]
if len(matches) != 1:
raise Error(f"Trash ID {safe(selector)} is missing or ambiguous")
entry = matches[0]
if entry["state"] == "damaged":
raise Error(f"Trash entry requires manual inspection: {safe(entry.get('error'))}")
if entry not in chosen:
chosen.append(entry)
return chosen
def player_command(value):
if value:
result = shlex.split(value, posix=os.name != "nt")
if result:
return result
raise Error("Player command is empty")
for executable, options in [("ffplay", ["-nodisp", "-autoexit"]), ("mpv", ["--no-video"]), ("afplay", [])]:
if shutil.which(executable):
return [executable, *options]
raise Error("Install ffplay/mpv, or pass --player 'your blocking audio player'")
def run(args):
options = {key: getattr(args, key) for key in ("port", "identity", "host_key", "known_hosts", "password", "ask_passphrase", "timeout") if hasattr(args, key)}
if options.get("timeout", 30) <= 0:
raise Error("Timeout must be positive")
source = Source.parse(args.source)
with Store(source, **options) as store:
repo = Repository(store)
command = {"list": "ls", "stat": "info", "cp": "get", "check": "verify", "remove": "rm"}.get(args.command, args.command)
if command in ("trash", "restore", "purge"):
entries = repo.trash()
if command == "trash":
if getattr(args, "json", False):
output(entries, args)
else:
table(["TRASH ID", "STATE", "DELETED (UTC)", "TITLE"], [[item["trash_id"], item["state"], date(item.get("deleted", 0)), item.get("manifest", {}).get("title", item.get("error", ""))] for item in entries])
return 1 if any(item["state"] != "complete" for item in entries) else 0
chosen = trash_selection(entries, [args.id] if command == "restore" else args.ids)
if command == "purge":
confirm(args, "Permanently delete these trash entries (cannot be undone):\n" + "\n".join(item["trash_id"] + " " + safe(item["manifest"]["title"]) for item in chosen))
results = []
for entry in chosen:
result = {"trash_id": entry["trash_id"], "id": entry["manifest"]["id"], "action": command, "dry_run": args.dry_run}
try:
if not args.dry_run:
repo.restore(entry) if command == "restore" else repo.purge(entry)
except (Error, OSError) as exc:
result["error"] = str(exc)
results.append(result)
output(results, args)
return 1 if any("error" in result for result in results) else 0
clips, issues = repo.inventory()
if command == "doctor":
trash = repo.trash()
trash_issues = [entry for entry in trash if entry["state"] != "complete"]
output({"completed": len(clips), "issues": issues, "trash_issues": trash_issues}, args)
return 1 if issues or trash_issues else 0
for issue in issues:
print(f"warning: {safe(issue['file'])}: {safe(issue['problem'])}", file=sys.stderr)
if command in ("ls", "stats", "sync"):
clips = filtered(clips, args)
elif command in ("info", "marks", "play", "rename"):
clips = selected(clips, [args.id])
elif command in ("get", "rm") or command == "verify" and args.ids:
clips = selected(clips, args.ids)
if command == "ls":
if getattr(args, "json", False):
output([clip.summary() for clip in clips], args)
else:
table(["ID", "CREATED (UTC)", "DURATION", "SIZE", "MARKS", "TITLE"], [[clip.id, date(clip.raw["created"]), duration(clip.raw["duration"]), human_bytes(clip.raw["bytes"]), len(clip.marks), clip.title] for clip in clips])
elif command == "stats":
result = {"recordings": len(clips), "bytes": sum(clip.raw["bytes"] for clip in clips), "duration_ms": sum(clip.raw["duration"] for clip in clips), "bookmarks": sum(len(clip.marks) for clip in clips), "invalid_or_incomplete": len(issues)}
if getattr(args, "json", False):
output(result, args)
else:
print(f"Recordings: {result['recordings']}\nAudio: {human_bytes(result['bytes'])}\nDuration: {duration(result['duration_ms'])}\nBookmarks: {result['bookmarks']}\nIssues: {result['invalid_or_incomplete']}")
elif command == "info":
clip = clips[0]
if getattr(args, "json", False):
output(clip.summary(), args)
else:
print(f"Title: {safe(clip.title)}\nID: {clip.id}\nCreated: {date(clip.raw['created'])}\nDuration: {duration(clip.raw['duration'])}\nAudio: {human_bytes(clip.raw['bytes'])} ({clip.raw['bytes']} bytes)\nSHA-256: {clip.raw['sha256']}\nBookmarks: {len(clip.marks)}")
for i, mark in enumerate(clip.marks, 1):
print(f" {i:3d} {duration(mark)} ({mark} ms)")
elif command == "marks":
marks = [{"number": i + 1, "milliseconds": mark, "time": duration(mark)} for i, mark in enumerate(clips[0].marks)]
if getattr(args, "json", False):
output(marks, args)
else:
table(["MARK", "TIME", "MILLISECONDS"], [[item["number"], item["time"], item["milliseconds"]] for item in marks])
elif command == "verify":
results = []
for clip in clips:
try:
repo.verify(clip)
results.append({"id": clip.id, "ok": True})
except (Error, OSError) as exc:
results.append({"id": clip.id, "ok": False, "error": str(exc)})
output(results, args)
return 1 if any(not item["ok"] for item in results) or issues else 0
elif command in ("get", "sync"):
results = []
for clip in clips:
if args.dry_run:
results.append({"id": clip.id, "bytes": clip.raw["bytes"], "action": "download or verify existing", "dry_run": True})
continue
try:
result = download(store, clip, args.output, force=args.force, resume=not args.no_resume, progress=download_progress(clip.id, args))
results.append(result)
if not getattr(args, "json", False):
print(f"{result['status']}: {safe(result['file'])}", file=sys.stderr)
except (Error, OSError) as exc:
results.append({"id": clip.id, "status": "failed", "error": str(exc)})
output(results, args)
return 1 if any(item.get("status") == "failed" for item in results) or issues else 0
elif command == "play":
player = player_command(args.player)
with tempfile.TemporaryDirectory(prefix="remember-play-") as folder:
result = download(store, clips[0], folder, progress=download_progress(clips[0].id, args))
# Server titles never form commands or local paths. Keep the verified file until the player exits.
subprocess.run([*player, result["file"]], check=True, stdout=sys.stderr)
output({"id": clips[0].id, "played": True}, args)
elif command == "rename":
if not 1 <= len(args.title.strip()) <= 200:
raise Error("Title must contain 1–200 characters")
value = {**clips[0].raw, "title": args.title.strip()} if args.dry_run else repo.rename_title(clips[0], args.title)
output({"id": clips[0].id, "title": value["title"], "dry_run": args.dry_run}, args)
elif command == "rm":
confirm(args, "Move these recordings to recoverable trash:\n" + "\n".join(clip.id + " " + safe(clip.title) for clip in clips))
# Validate all selections before making the first change.
for clip in clips:
repo.unchanged(clip)
results = []
for clip in clips:
result = {"id": clip.id, "title": clip.title, "action": "trash", "dry_run": args.dry_run}
try:
if not args.dry_run:
result["trash_id"] = repo.remove(clip)["trash_id"]
except (Error, OSError) as exc:
result["error"] = str(exc)
results.append(result)
output(results, args)
return 1 if any("error" in result for result in results) else 0
return 0
def main(argv=None):
args = parser().parse_args(argv)
try:
return run(args)
except KeyboardInterrupt:
print("Interrupted; unverified downloads remain resumable. Inspect trash for interrupted moves.", file=sys.stderr)
return 130
except BrokenPipeError:
return 0
except (Error, OSError, ValueError, EOFError, paramiko.SSHException, subprocess.SubprocessError) as exc:
if getattr(args, "json", False):
print(json.dumps({"error": str(exc)}, ensure_ascii=False), file=sys.stderr)
else:
print("remember: " + safe(exc), file=sys.stderr)
return 1
+117
View File
@@ -0,0 +1,117 @@
"""The watch's version-1 completion manifest, never a source of filesystem paths."""
import hashlib
import json
import re
from dataclasses import dataclass
from datetime import datetime, timezone
MAX_METADATA = 128 * 1024
MAX_AUDIO = 500 * 1024 * 1024
CHUNK = 64 * 1024
ID = re.compile(r"[a-fA-F0-9-]{36}\Z")
class Error(Exception):
"""An actionable CLI error, without a traceback or credential dump."""
def safe(value):
"""Do not let remote titles/filenames inject terminal control sequences."""
return "".join(c if c.isprintable() else ascii(c)[1:-1] for c in str(value))
def _object(pairs):
result = {}
for key, value in pairs:
if key in result:
raise Error(f"Duplicate metadata field: {safe(key)}")
result[key] = value
return result
def load_json(data):
if len(data) > MAX_METADATA:
raise Error("Metadata exceeds 128 KiB")
try:
def constant(_):
raise Error("Non-finite JSON numbers are not supported")
return json.loads(data, object_pairs_hook=_object, parse_constant=constant)
except (ValueError, UnicodeError, RecursionError) as exc:
raise Error("Invalid JSON metadata") from exc
def json_bytes(value):
data = (json.dumps(value, ensure_ascii=False, separators=(",", ":"), allow_nan=False) + "\n").encode("utf-8")
if len(data) > MAX_METADATA:
raise Error("Metadata exceeds 128 KiB")
return data
def integer(value, name, low=-(2**63), high=2**63 - 1):
if type(value) is not int or not low <= value <= high:
raise Error(f"Invalid {name}")
return value
@dataclass(frozen=True)
class Clip:
id: str
raw: dict
encoded: bytes
@classmethod
def parse(cls, data, expected_id):
doc = load_json(data)
if not isinstance(doc, dict) or type(doc.get("version")) is not int or doc["version"] != 1:
raise Error("Unsupported manifest version")
if not ID.fullmatch(expected_id) or doc.get("id") != expected_id:
raise Error("Manifest ID does not match its filename")
if not isinstance(doc.get("title"), str):
raise Error("Invalid title")
integer(doc.get("created"), "creation timestamp")
integer(doc.get("duration"), "duration", 0)
integer(doc.get("bytes"), "audio size", 1, MAX_AUDIO)
digest = doc.get("sha256")
if not isinstance(digest, str) or not re.fullmatch(r"[a-f0-9]{64}", digest):
raise Error("Invalid SHA-256")
marks = doc.get("marks", [])
if not isinstance(marks, list) or len(marks) > 10000:
raise Error("Invalid bookmarks")
for mark in marks:
integer(mark, "bookmark timestamp")
return cls(expected_id, doc, data)
@property
def title(self):
return self.raw["title"][:200]
@property
def marks(self):
return [min(max(mark, 0), self.raw["duration"]) for mark in self.raw.get("marks", [])]
def summary(self):
return {**self.raw, "title": self.title, "marks": self.marks}
def duration(milliseconds):
seconds = milliseconds // 1000
return f"{seconds // 3600:02d}:{seconds // 60 % 60:02d}:{seconds % 60:02d}"
def date(milliseconds):
try:
return datetime.fromtimestamp(milliseconds / 1000, timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z")
except (OverflowError, OSError, ValueError):
return str(milliseconds)
def hash_stream(stream, maximum=None):
digest = hashlib.sha256()
size = 0
while chunk := stream.read(CHUNK):
size += len(chunk)
if maximum is not None and size > maximum:
raise Error("Audio exceeds its declared size")
digest.update(chunk)
return size, digest.hexdigest()
+298
View File
@@ -0,0 +1,298 @@
"""Versioned backup operations, verified downloads, and recoverable server-side trash."""
import contextlib
import hashlib
import os
import re
import stat
import time
import uuid
from pathlib import Path
from .model import CHUNK, ID, MAX_METADATA, Clip, Error, hash_stream, integer, json_bytes, load_json, safe
TRASH = ".remember-trash"
class Repository:
def __init__(self, store):
self.store = store
def clip(self, clip_id):
if not isinstance(clip_id, str) or not ID.fullmatch(clip_id):
raise Error("Invalid recording ID")
clip = Clip.parse(self.store.read(f"{clip_id}.json"), clip_id)
audio = self.store.stat(f"{clip_id}.m4a")
if not stat.S_ISREG(audio.st_mode) or audio.st_size != clip.raw["bytes"]:
raise Error("Missing, linked, or wrong-size audio")
return clip
def inventory(self):
clips, issues, names = [], [], set()
for name, attrs in self.store.entries():
names.add(name)
if not re.fullmatch(r"[a-fA-F0-9-]{36}\.json", name):
continue
try:
if not stat.S_ISREG(attrs.st_mode):
raise Error("Not a regular manifest")
clips.append(self.clip(name[:-5]))
except (Error, OSError, ValueError, TypeError) as exc:
issues.append({"file": name, "problem": str(exc)})
valid = {clip.id for clip in clips}
for name in sorted(names):
if name.endswith(".upload"):
issues.append({"file": name, "problem": "incomplete upload (may still be active)"})
elif re.fullmatch(r"[a-fA-F0-9-]{36}\.m4a", name) and name[:-4] not in valid:
issues.append({"file": name, "problem": "audio without a valid completion manifest"})
elif name.startswith(".remember-") and name.endswith(".tmp"):
issues.append({"file": name, "problem": "unfinished CLI metadata write"})
clips.sort(key=lambda item: (item.raw["created"], item.id), reverse=True)
return clips, issues
def unchanged(self, clip):
if self.store.read(f"{clip.id}.json") != clip.encoded:
raise Error("Manifest changed; refresh and retry")
audio = self.store.stat(f"{clip.id}.m4a")
if not stat.S_ISREG(audio.st_mode) or audio.st_size != clip.raw["bytes"]:
raise Error("Audio changed; refresh and retry")
if any(self.store.exists(clip.id + suffix) for suffix in (".m4a.upload", ".json.upload")):
raise Error("An upload for this recording may be active; wait before modifying it")
def verify(self, clip):
with self.store.open(f"{clip.id}.m4a") as stream:
size, digest = hash_stream(stream, clip.raw["bytes"])
if size != clip.raw["bytes"] or digest != clip.raw["sha256"]:
raise Error("Audio size/SHA-256 verification failed")
def rename_title(self, clip, title):
title = title.strip()
if not 1 <= len(title) <= 200:
raise Error("Title must contain 1–200 characters")
self.unchanged(clip)
updated = {**clip.raw, "title": title}
self.store.atomic_write(f"{clip.id}.json", json_bytes(updated), expected=clip.encoded)
return updated
def _trash_directory(self, trash_id):
if not isinstance(trash_id, str) or not re.fullmatch(r"[a-f0-9]{32}", trash_id):
raise Error("Invalid trash ID")
return f"{TRASH}/{trash_id}"
def trash(self):
if not self.store.exists(TRASH):
return []
entries = []
for name, attrs in self.store.entries(TRASH):
try:
if not stat.S_ISDIR(attrs.st_mode):
raise Error("Not a regular trash directory")
entry = self.trash_entry(name)
entries.append(entry)
except (Error, OSError, ValueError, TypeError) as exc:
entries.append({"trash_id": name, "state": "damaged", "error": str(exc)})
return sorted(entries, key=lambda item: item.get("deleted", 0), reverse=True)
def trash_entry(self, trash_id):
base = self._trash_directory(trash_id)
record = load_json(self.store.read(f"{base}/entry.json"))
if not isinstance(record, dict) or type(record.get("version")) is not int or record["version"] != 1 or record.get("trash_id") != trash_id:
raise Error("Invalid trash entry")
integer(record.get("deleted"), "trash timestamp", 0)
original = record.get("manifest")
if not isinstance(original, dict):
raise Error("Invalid saved manifest")
clip_id = original.get("id")
if not isinstance(clip_id, str):
raise Error("Invalid saved recording ID")
Clip.parse(json_bytes(original), clip_id)
names = {name for name, _ in self.store.entries(base)}
expected = {"entry.json", f"{clip_id}.m4a", f"{clip_id}.json"}
if names - expected:
raise Error("Trash entry contains unknown files; manual inspection required")
for name in names:
if not stat.S_ISREG(self.store.stat(f"{base}/{name}").st_mode):
raise Error("Trash entry contains a linked or special file")
# Interrupted two-file moves remain visible and can be restored or purged explicitly.
complete = expected <= names
return {**record, "state": "complete" if complete else "partial", "files": sorted(names)}
def remove(self, clip):
self.unchanged(clip)
if not self.store.exists(TRASH):
self.store.mkdir(TRASH)
trash_id = uuid.uuid4().hex
base = self._trash_directory(trash_id)
self.store.mkdir(base)
record = {"version": 1, "trash_id": trash_id, "deleted": time.time_ns() // 1_000_000, "manifest": clip.raw}
self.store.atomic_write(f"{base}/entry.json", json_bytes(record))
# Remove the completion marker first; never expose a completed backup with missing audio.
self.store.rename(f"{clip.id}.json", f"{base}/{clip.id}.json")
try:
self.store.rename(f"{clip.id}.m4a", f"{base}/{clip.id}.m4a")
except BaseException as exc:
# If a concurrent watch upload published a new manifest, never overwrite it.
if not self.store.exists(f"{clip.id}.json"):
self.store.rename(f"{base}/{clip.id}.json", f"{clip.id}.json")
if isinstance(exc, (KeyboardInterrupt, SystemExit)):
raise
raise Error(f"Trash move interrupted. Inspect/restore trash entry {trash_id}") from None
return record
def restore(self, entry):
base = self._trash_directory(entry["trash_id"])
manifest = entry["manifest"]
clip_id = manifest["id"]
# Resolve interrupted removal/restoration using the saved hash, never by filename alone.
for suffix in (".m4a", ".json"):
name = clip_id + suffix
there, here = self.store.exists(f"{base}/{name}"), self.store.exists(name)
if there and here:
raise Error(f"Restore would overwrite {name}; existing backups are preserved")
if not there and not here:
raise Error(f"Neither trash nor backup root contains {name}; cannot restore")
if suffix == ".m4a":
with self.store.open(f"{base}/{name}" if there else name) as stream:
size, digest = hash_stream(stream, manifest["bytes"])
if size != manifest["bytes"] or digest != manifest["sha256"]:
raise Error("Trash audio verification failed; nothing restored")
else:
candidate = Clip.parse(self.store.read(f"{base}/{name}" if there else name), clip_id)
if candidate.raw != manifest:
raise Error("Trash manifest changed; nothing restored")
# Audio first, completion marker last. A repeated restore safely resumes an interrupted move.
for suffix in (".m4a", ".json"):
name = clip_id + suffix
if self.store.exists(f"{base}/{name}"):
self.store.rename(f"{base}/{name}", name)
self.store.remove(f"{base}/entry.json")
self.store.rmdir(base)
return manifest
def purge(self, entry):
base = self._trash_directory(entry["trash_id"])
# Only the exact, validated entry files. Never recursively remove arbitrary server paths.
current = self.trash_entry(entry["trash_id"])
if current["manifest"] != entry["manifest"]:
raise Error("Trash entry changed; refresh and retry")
for suffix in (".json", ".m4a"):
name = f"{base}/{entry['manifest']['id']}{suffix}"
if self.store.exists(name):
self.store.remove(name)
self.store.remove(f"{base}/entry.json")
self.store.rmdir(base)
@contextlib.contextmanager
def exclusive_file(path):
"""OS releases the lock on crashes; the small lock file deliberately remains in the mirror."""
descriptor = os.open(path, os.O_CREAT | os.O_RDWR | getattr(os, "O_NOFOLLOW", 0), 0o600)
stream = os.fdopen(descriptor, "r+b")
try:
if not stat.S_ISREG(os.fstat(descriptor).st_mode) or os.fstat(descriptor).st_nlink != 1:
raise Error("Unsafe local lock file")
try:
if os.name == "nt":
import msvcrt
if os.fstat(descriptor).st_size == 0:
stream.write(b"0"); stream.flush(); stream.seek(0)
msvcrt.locking(descriptor, msvcrt.LK_NBLCK, 1)
else:
import fcntl
fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB)
except OSError as exc:
raise Error("Another CLI process is using this destination") from exc
yield
finally:
stream.close()
def _regular(path):
try:
info = path.lstat()
except FileNotFoundError:
return False
if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:
raise Error(f"Refusing linked or special local file: {safe(path)}")
return True
def _atomic_local(path, data):
temporary = path.parent / (".remember-" + uuid.uuid4().hex + ".tmp")
try:
with temporary.open("xb") as stream:
os.chmod(temporary, 0o600)
stream.write(data); stream.flush(); os.fsync(stream.fileno())
os.replace(temporary, path)
finally:
temporary.unlink(missing_ok=True)
def download(store, clip, directory, *, force=False, resume=True, progress=lambda *_: None):
"""One bounded stream, checked SHA-256, atomic publication; no local audio is overwritten implicitly."""
directory = Path(directory).expanduser().resolve()
directory.mkdir(mode=0o700, parents=True, exist_ok=True)
final = directory / f"{clip.id}.m4a"
metadata = directory / f"{clip.id}.json"
partial = directory / f".{clip.id}.m4a.part"
receipt = directory / f".{clip.id}.part.json"
snapshot = {key: clip.raw[key] for key in ("id", "bytes", "sha256")}
with exclusive_file(directory / ".remember-lock"):
if _regular(final):
size, digest = final.stat().st_size, None
if size == clip.raw["bytes"]:
with final.open("rb") as stream:
size, digest = hash_stream(stream, clip.raw["bytes"])
if size == clip.raw["bytes"] and digest == clip.raw["sha256"]:
_regular(metadata)
_atomic_local(metadata, clip.encoded)
return {"id": clip.id, "status": "unchanged", "file": str(final), "bytes": size}
if not force:
raise Error(f"Local audio differs: {safe(final)}. Use --force to replace it")
_regular(metadata)
offset = 0
if _regular(partial) and _regular(receipt) and resume:
try:
if receipt.stat().st_size <= MAX_METADATA and load_json(receipt.read_bytes()) == snapshot:
offset = partial.stat().st_size
except Error:
pass
if offset > clip.raw["bytes"]:
offset = 0
_regular(receipt)
_atomic_local(receipt, json_bytes(snapshot))
# Retry a corrupt resumed prefix once from zero; never publish unverified audio.
for attempt in range(2):
descriptor = os.open(partial, os.O_CREAT | os.O_RDWR | getattr(os, "O_NOFOLLOW", 0), 0o600)
with os.fdopen(descriptor, "r+b") as output:
if os.fstat(output.fileno()).st_nlink != 1 or not stat.S_ISREG(os.fstat(output.fileno()).st_mode):
raise Error("Unsafe partial download")
output.truncate(offset); output.seek(offset)
transferred = offset
with store.open(f"{clip.id}.m4a") as remote:
remote.seek(offset)
while chunk := remote.read(min(CHUNK, clip.raw["bytes"] - transferred + 1)):
transferred += len(chunk)
if transferred > clip.raw["bytes"]:
raise Error("Server audio exceeds its manifest; previous local audio retained")
output.write(chunk)
progress(transferred, clip.raw["bytes"])
output.flush(); os.fsync(output.fileno())
if transferred != clip.raw["bytes"]:
raise Error("Incomplete download; partial retained for resume")
output.seek(0)
size, digest = hash_stream(output, clip.raw["bytes"])
if size == clip.raw["bytes"] and digest == clip.raw["sha256"]:
break
partial.unlink(missing_ok=True)
if not offset or attempt:
receipt.unlink(missing_ok=True)
raise Error("SHA-256 mismatch; previous local audio retained")
offset = 0
# Refuse a concurrently created destination unless replacement was explicitly requested.
if final.exists() and not force:
raise Error("Local destination appeared during download; verified partial retained")
os.replace(partial, final)
_atomic_local(metadata, clip.encoded)
receipt.unlink(missing_ok=True)
return {"id": clip.id, "status": "downloaded", "file": str(final), "bytes": clip.raw["bytes"]}
+285
View File
@@ -0,0 +1,285 @@
"""Bounded SFTP/file operations. No remote shell, recursive traversal, or glob expansion."""
import base64
import getpass
import hashlib
import hmac
import os
import posixpath
import re
import stat
import sys
import uuid
from dataclasses import dataclass
from pathlib import Path
from urllib.parse import unquote, urlsplit
import paramiko
from .model import Error, MAX_METADATA, safe
@dataclass(frozen=True)
class Source:
host: str | None
user: str | None
port: int | None
root: str
@classmethod
def parse(cls, value):
if not value or any(ord(c) < 32 or ord(c) == 127 for c in value):
raise Error("Source must be a directory or [user@]host:/backup/path")
if value.startswith(("sftp://", "ssh://")):
try:
uri = urlsplit(value)
if uri.password is not None or uri.query or uri.fragment or not uri.hostname or not uri.path:
raise Error("Use ssh://[user@]host[:port]/backup/path; passwords do not belong in URLs")
path = unquote(uri.path)
user = unquote(uri.username) if uri.username else None
if any(ord(c) < 32 or ord(c) == 127 for c in path + (user or "")):
raise Error("SSH paths and usernames cannot contain control characters")
return cls(uri.hostname, user, uri.port, path)
except ValueError as exc:
raise Error("Invalid SSH URL") from exc
if re.match(r"^[a-zA-Z][a-zA-Z0-9+.-]*://", value):
raise Error("Only sftp:// and ssh:// URLs are supported")
match = re.fullmatch(r"(?:(?P<user>[^/@:]+)@)?(?:\[(?P<ipv6>[^\]]+)\]|(?P<host>[^/:]+)):(?P<root>.+)", value)
if match and not re.match(r"^[A-Za-z]:[\\/]", value):
return cls(match["ipv6"] or match["host"], match["user"], None, match["root"])
return cls(None, None, None, str(Path(value).expanduser()))
def fingerprint(key):
return "SHA256:" + base64.b64encode(hashlib.sha256(key.asbytes()).digest()).decode().rstrip("=")
class Trust(paramiko.MissingHostKeyPolicy):
def __init__(self, pin, known_hosts):
self.pin = pin
self.known_hosts = known_hosts
def missing_host_key(self, client, hostname, key):
actual = fingerprint(key)
if self.pin:
if not hmac.compare_digest(self.pin, actual):
raise Error(f"Server identity mismatch for {safe(hostname)} (received {actual}); authentication blocked")
return
if not sys.stdin.isatty():
raise Error(f"Unknown SSH host {safe(hostname)} ({actual}). Verify this fingerprint, then pass --host-key {actual} or trust the host with SSH first")
print(f"Unknown SSH host: {safe(hostname)}\n{key.get_name()} {actual}\nCompare this fingerprint through a trusted channel.", file=sys.stderr)
print("Trust and remember this host? Type yes: ", file=sys.stderr, end="", flush=True)
if input().strip() != "yes":
raise Error("Host was not approved; authentication blocked")
path = self.known_hosts
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
# Append preserves unrelated OpenSSH host entries/comments. No auto-trust policy.
with path.open("a", encoding="utf-8") as output:
output.write(f"\n{hostname} {key.get_name()} {key.get_base64()}\n")
os.chmod(path, 0o600)
client.get_host_keys().add(hostname, key.get_name(), key)
def checked_path(name):
parts = name.split("/")
if not name or any(part in ("", ".", "..") or "\\" in part or "\x00" in part for part in parts):
raise Error("Unsafe backup filename")
return parts
def regular(mode):
return isinstance(mode, int) and stat.S_ISREG(mode)
def is_directory(mode):
return isinstance(mode, int) and stat.S_ISDIR(mode)
class Store:
def __init__(self, source, *, port=None, identity=None, host_key=None, known_hosts=None, password=False, ask_passphrase=False, timeout=30):
self.source = source
self.client = None
self.sftp = None
self.proxy = None
if source.host is None:
self.root = Path(source.root).resolve(strict=True)
if not self.root.is_dir():
raise Error("Local backup root is not a directory")
return
self.root = source.root
try:
config_path = Path.home() / ".ssh/config"
config = {}
if config_path.is_file():
with config_path.open() as stream:
config = paramiko.SSHConfig.from_file(stream).lookup(source.host)
if config.get("proxyjump") not in (None, "none") and not config.get("proxycommand"):
raise Error("ProxyJump is not supported yet; use a reachable SSH alias with ProxyCommand instead")
host = config.get("hostname", source.host)
user = source.user or config.get("user", getpass.getuser())
ssh_port = port if port is not None else source.port if source.port is not None else int(config.get("port", 22))
if not 1 <= ssh_port <= 65535:
raise Error("SSH port must be between 1 and 65535")
keys = [str(Path(identity).expanduser())] if identity else config.get("identityfile")
path = Path(known_hosts).expanduser() if known_hosts else Path.home() / ".ssh/known_hosts"
client = self.client = paramiko.SSHClient()
if not host_key:
client.load_system_host_keys()
if path.is_file():
client.load_host_keys(str(path))
client.set_missing_host_key_policy(Trust(host_key, path))
proxy = config.get("proxycommand")
if proxy and proxy != "none":
self.proxy = paramiko.ProxyCommand(proxy)
# Prompting for a password is explicit, but transmitting credentials always follows host verification.
secret = getpass.getpass("SSH password: ") if password else None
passphrase = getpass.getpass("SSH key passphrase: ") if ask_passphrase else None
client.connect(host, port=ssh_port, username=user, key_filename=keys, password=secret,
passphrase=passphrase,
allow_agent=not password, look_for_keys=not password, timeout=timeout,
banner_timeout=timeout, auth_timeout=timeout, channel_timeout=timeout,
sock=self.proxy, compress=False)
self.sftp = client.open_sftp()
self.sftp.get_channel().settimeout(timeout)
if self.root == "~" or self.root.startswith("~/"):
self.root = posixpath.join(self.sftp.normalize("."), self.root[2:] if self.root != "~" else "")
self.root = self.sftp.normalize(self.root)
if not is_directory(self.sftp.lstat(self.root).st_mode):
raise Error("Remote backup root is not a directory")
except BaseException:
self.close()
raise
def _path(self, name):
parts = checked_path(name)
# Inspect every intermediate component, including trash directories, without following symlinks.
current = self.root
for part in parts[:-1]:
current = posixpath.join(current, part) if self.sftp else current / part
mode = self.sftp.lstat(current).st_mode if self.sftp else current.lstat().st_mode
if not is_directory(mode):
raise Error("Backup path contains a symlink or non-directory")
return posixpath.join(self.root, name) if self.sftp else self.root.joinpath(*parts)
def entries(self, directory=None):
base = self.root if directory is None else self._path(directory)
if directory and not is_directory(self.stat(directory).st_mode):
raise Error("Backup directory is not a regular directory")
if self.sftp:
for item in self.sftp.listdir_iter(base, read_aheads=1):
yield item.filename, item
else:
with os.scandir(base) as iterator:
for item in iterator:
yield item.name, item.stat(follow_symlinks=False)
def stat(self, name):
path = self._path(name)
return self.sftp.lstat(path) if self.sftp else path.lstat()
def exists(self, name):
try:
self.stat(name)
return True
except FileNotFoundError:
return False
def open(self, name):
path = self._path(name)
if not regular(self.stat(name).st_mode):
raise Error(f"Not a regular file: {safe(name)}")
if self.sftp:
return self.sftp.open(path, "rb", bufsize=65536)
descriptor = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0))
return os.fdopen(descriptor, "rb")
def read(self, name):
size = self.stat(name).st_size
if type(size) is not int or not 0 <= size <= MAX_METADATA:
raise Error("Metadata exceeds 128 KiB")
with self.open(name) as stream:
data = stream.read(MAX_METADATA + 1)
if len(data) > MAX_METADATA:
raise Error("Metadata exceeds 128 KiB")
return data
def mkdir(self, name):
path = self._path(name)
if self.sftp:
self.sftp.mkdir(path, mode=0o700)
else:
path.mkdir(mode=0o700)
def rename(self, old, new):
if self.exists(new):
raise Error(f"Refusing to replace {safe(new)}")
if not regular(self.stat(old).st_mode):
raise Error("Refusing to move a non-regular file")
if self.sftp:
self.sftp.rename(self._path(old), self._path(new))
else:
# Link/unlink gives no-clobber semantics on a single local filesystem.
os.link(self._path(old), self._path(new), follow_symlinks=False)
self._path(old).unlink()
def remove(self, name):
if not regular(self.stat(name).st_mode):
raise Error("Refusing to remove a non-regular file")
path = self._path(name)
self.sftp.remove(path) if self.sftp else path.unlink()
def rmdir(self, name):
if not is_directory(self.stat(name).st_mode):
raise Error("Refusing to remove a non-directory")
path = self._path(name)
self.sftp.rmdir(path) if self.sftp else path.rmdir()
def atomic_write(self, name, data, expected=None):
path = self._path(name)
temporary = posixpath.join(posixpath.dirname(name), ".remember-" + uuid.uuid4().hex + ".tmp")
temporary_path = self._path(temporary)
try:
if self.sftp:
with self.sftp.open(temporary_path, "wx") as stream:
self.sftp.chmod(temporary_path, 0o600)
stream.write(data); stream.flush()
else:
descriptor = os.open(temporary_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(descriptor, "wb") as stream:
stream.write(data); stream.flush(); os.fsync(stream.fileno())
if expected is not None and self.read(name) != expected:
raise Error("Manifest changed during this operation; refresh and retry")
if expected is None and self.exists(name):
raise Error(f"Refusing to replace {safe(name)}")
if self.sftp:
if expected is None:
self.sftp.rename(temporary_path, path)
else:
# OpenSSH extension: never remove the committed manifest as a fallback.
try:
self.sftp.posix_rename(temporary_path, path)
except OSError as exc:
raise Error("Server could not atomically replace the manifest; original retained. OpenSSH posix-rename support is required") from exc
else:
if expected is None:
os.link(temporary_path, path)
temporary_path.unlink()
else:
os.replace(temporary_path, path)
finally:
if self.exists(temporary):
self.remove(temporary)
def close(self):
if self.sftp:
self.sftp.close()
if self.client:
self.client.close()
if self.proxy:
self.proxy.close()
def __enter__(self):
return self
def __exit__(self, *_):
self.close()
+30
View File
@@ -117,11 +117,41 @@ def main():
def rename(self, old, new):
try:
if self.local(new).exists():
raise FileExistsError(17, "Target exists")
self.local(old).rename(self.local(new))
return paramiko.SFTP_OK
except OSError as error:
return paramiko.SFTPServer.convert_errno(error.errno)
def posix_rename(self, old, new):
try:
self.local(old).replace(self.local(new))
return paramiko.SFTP_OK
except OSError as error:
return paramiko.SFTPServer.convert_errno(error.errno)
def mkdir(self, path, attr):
try:
self.local(path).mkdir(mode=0o700)
return paramiko.SFTP_OK
except OSError as error:
return paramiko.SFTPServer.convert_errno(error.errno)
def rmdir(self, path):
try:
self.local(path).rmdir()
return paramiko.SFTP_OK
except OSError as error:
return paramiko.SFTPServer.convert_errno(error.errno)
def chattr(self, path, attr):
try:
paramiko.SFTPServer.set_file_attr(self.local(path), attr)
return paramiko.SFTP_OK
except OSError as error:
return paramiko.SFTPServer.convert_errno(error.errno)
transports = []
threads = []