From 108652b6e7cce1ee6dccaccac074d8bc51dd0a6b Mon Sep 17 00:00:00 2001 From: Adeel Ahmad Date: Mon, 5 Oct 2026 01:33:37 +0000 Subject: [PATCH] feat(storage): keep Lens's own files on this machine or any rclone connection MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit blobs.py keeps files where Settings → Storage (the files section) says: data_dir/objects, or a storage connection (S3, Drive, Dropbox, OneDrive, SFTP, SMB, WebDAV, a folder) under a folder, optionally wrapped in rclone crypt. Files are encrypted with their namespace's key before they leave the machine. Each file records where it went, so changing the setting strands nothing. A check route and the assistant's file_storage tool test it; change_settings files always waits for approval. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01XZQXJtCvJgbG1Z2H312KcS --- DEVLOG.md | 10 +- docs/storage.md | 29 +++ fastapi_backend/app/api/v1/routes/admin.py | 21 +- fastapi_backend/app/domain/blobs.py | 240 ++++++++++++++++++ fastapi_backend/app/domain/ops_tools.py | 30 ++- fastapi_backend/app/domain/settings.py | 18 ++ fastapi_backend/app/domain/store.py | 3 + fastapi_backend/app/schemas/admin.py | 18 +- fastapi_backend/tests/api/test_file_store.py | 154 +++++++++++ nextjs-frontend/app/openapi-client/index.ts | 7 + nextjs-frontend/app/openapi-client/sdk.gen.ts | 22 ++ .../app/openapi-client/types.gen.ts | 81 ++++++ nextjs-frontend/openapi.json | 154 +++++++++++ 13 files changed, 781 insertions(+), 6 deletions(-) create mode 100644 docs/storage.md create mode 100644 fastapi_backend/app/domain/blobs.py create mode 100644 fastapi_backend/tests/api/test_file_store.py diff --git a/DEVLOG.md b/DEVLOG.md index d758e615f..fa918f67e 100644 --- a/DEVLOG.md +++ b/DEVLOG.md @@ -213,8 +213,14 @@ Todo: - [ ] Self-organising, next: nest notes without a click when the fit is clear (decision model, like PARA filing) - [x] # topics move to the SKOS topics once the graph thread splits them from entities (#135) - [ ] Attachments on a page, encrypted through the keyring -- [ ] Object storage (S3, or an rclone remote served as S3) in the setup wizard, no local storage; a downloadable - 256-bit storage key. Design proposal waiting on Adeel (changes existing installs) +- [x] The file store (blobs.py, docs/storage.md): this machine or any storage connection through rclone (S3, Drive, + Dropbox, OneDrive, SFTP, SMB, WebDAV, a folder), keyring-encrypted before it leaves, optional rclone crypt; the + `files` settings, a check, the assistant's file_storage tool. Adeel said go 2026-10-05, with rclone and crypt +- [ ] Settings → Storage and the setup wizard step (pick a connection, folder, crypt, check); new installs choose +- [ ] Attachments on notes in the file store; BlockSuite images and files +- [ ] Moving uploads and recordings' media to the file store (pipelines need local copies: a cache) +- [ ] A downloadable storage key (the server secret; opens every namespace that isn't a passkey vault) +- [ ] File storage over MCP (admins) ## 2026-10-04 · The graph, end to end diff --git a/docs/storage.md b/docs/storage.md new file mode 100644 index 000000000..e5a0ffc3e --- /dev/null +++ b/docs/storage.md @@ -0,0 +1,29 @@ +# Where Lens keeps its files + +Status: **built**: the file store (this machine, or any storage connection through rclone, optionally wrapped in rclone +crypt), its settings, a check, and the assistant's `file_storage` tool. **In progress**: Settings → Storage and the +setup wizard step, notes' attachments. **Planned**: moving uploads and recordings' media there too, and a downloadable +storage key. + +The files Lens makes its own, starting with notes' attachments, go where **Settings → Storage** (the `files` section) +says: + +| Setting | | +|---|---| +| `store` | `local`: `data_dir/objects` on this machine (the default). `connection`: a storage connection | +| `connection` | the id of a storage connection (Settings → Sources): S3 or S3-compatible (AWS, MinIO, Backblaze, R2 ...), Google Drive, Dropbox, OneDrive, SFTP, SMB, WebDAV, or a folder on this machine inside `sources.local_roots` | +| `folder` | where on it: a path; for S3, the bucket and a path (`my-bucket/lens`); for a folder on this machine, its full path | +| `crypt` | also wrap it in an [rclone crypt](https://rclone.org/crypt/) remote, which hides the names and sizes of what is kept there | + +Everything goes through rclone, so any remote it reaches works the same way. A file going to a connection is +encrypted with its namespace's key ([Encryption](encryption.md)) before it leaves the machine: the remote only ever +holds ciphertext, whether `crypt` is on or not. crypt's password is made by Lens the first time it's needed and kept +sealed like any setting's secret: there's nothing to type or remember. + +Each file records where it went, so changing these settings never strands what is already stored: older files are read +from wherever they were written, and new ones go to the new place. + +`POST /api/v1/settings/files/test` writes a small file there, reads it back and removes it: what is saved, or a +`{store, connection, folder, crypt}` given in the body, to check before saving. The assistant (for admins) has +`file_storage`, which says where files go and which connections could take them, and checks it with `check`; it +changes it with `change_settings files`, which always waits for approval. diff --git a/fastapi_backend/app/api/v1/routes/admin.py b/fastapi_backend/app/api/v1/routes/admin.py index 66eaf6e1f..78c827dcc 100644 --- a/fastapi_backend/app/api/v1/routes/admin.py +++ b/fastapi_backend/app/api/v1/routes/admin.py @@ -13,7 +13,7 @@ from app import email from app.api.deps import AdminReader, AdminWriter, Cfg, Db, domain_errors from app.core.middleware import host_name -from app.domain import auth, bridge, decide, jobs, llm, local_llm, semantic, settings, sources, speech, store, telemetry, tunnel +from app.domain import auth, blobs, bridge, decide, jobs, llm, local_llm, semantic, settings, sources, speech, store, telemetry, tunnel from app.schemas.admin import ( AuditEntry, BridgeStatus, @@ -21,6 +21,8 @@ DecisionStatus, DecisionTestResult, EmbedTestResult, + FileStoreTestResult, + FileStoreTry, Health, IndexQueued, LlmTestResult, @@ -93,6 +95,23 @@ async def test_mail(user: AdminWriter, cfg: Cfg) -> MailTestResult: return MailTestResult(ok=True, to=user.email) +@router.post("/settings/files/test") +def test_file_store(user: AdminWriter, cfg: Cfg, db: Db, body: FileStoreTry | None = None) -> FileStoreTestResult: + """Write a small file where Lens would keep files, read it back and remove it: what is saved, or what is given + (to check a connection and folder before saving them).""" + where = None + if body and body.store == "connection": + if not body.connection: + return FileStoreTestResult(ok=False, store="connection", error="choose a storage connection") + try: + where = {"store": "connection", "connection": body.connection, "folder": blobs._folder(body.folder), "crypt": body.crypt} + except ValueError as e: + return FileStoreTestResult(ok=False, store="connection", error=str(e)) + elif body and body.store == "local": + where = {"store": "local"} + return FileStoreTestResult(**blobs.test(db, cfg, where)) + + @router.get("/settings/bridge") def bridge_status(user: AdminReader, cfg: Cfg, db: Db) -> BridgeStatus: """How the assistant's chat-room bridge (Matterbridge) is doing.""" diff --git a/fastapi_backend/app/domain/blobs.py b/fastapi_backend/app/domain/blobs.py new file mode 100644 index 000000000..d828ce835 --- /dev/null +++ b/fastapi_backend/app/domain/blobs.py @@ -0,0 +1,240 @@ +"""Where Lens keeps the files it makes its own, such as a note's attachments (docs/storage.md): on this machine, or on +any storage connection (S3 or S3-compatible, Google Drive, Dropbox, OneDrive, SFTP, SMB, WebDAV, a folder), through rclone. + +Settings → Storage (the `files` section) chooses it: `store` is "local" (data_dir/objects, the default) or +"connection" (`connection`, a storage source of sources.py, under its `folder`). Files going to a connection are +encrypted with their namespace's key (keyring.py) before they leave the machine, so the remote only ever holds +ciphertext. `crypt` wraps the connection in an rclone crypt remote too, which also hides the names and sizes of what is +kept there; its password is made here, kept sealed, and never needs typing. + +Each file records where it went (`where`, from put()), so changing the setting never strands what is already stored: +older files are read from wherever they were written. +""" + +from __future__ import annotations + +import contextlib +import os +import pathlib +import re +import secrets +import shutil +import subprocess +import tempfile +import time + +from . import feeds, keyring, settings, sources, store + +R = store.R +KEY_RX = re.compile(r"^[a-z0-9][a-z0-9._-]{0,80}(/[a-z0-9][a-z0-9._-]{0,80}){0,8}$") +CRYPT = "lenscrypt" +TIMEOUT = 3600 # seconds one copy may take + + +def _key(key): + if not KEY_RX.match(key or ""): + raise ValueError(f"not a storage key: {key!r}") + return key + + +def _local_root(cfg): + return pathlib.Path(cfg["data_dir"]) / "objects" + + +def _tmp(cfg): + d = pathlib.Path(cfg["data_dir"]) / "tmp" + d.mkdir(parents=True, exist_ok=True, mode=0o700) + return d + + +def target(db, cfg): + """Where new files go, from the `files` settings: {"store": "local"} or {"store": "connection", ...}.""" + f = cfg.get("files") or {} + if f.get("store") != "connection": + return {"store": "local"} + if not f.get("connection"): + raise RuntimeError("Settings → Storage keeps files on a connection, but none is chosen") + return {"store": "connection", "connection": int(f["connection"]), "folder": _folder(f.get("folder")), "crypt": bool(f.get("crypt"))} + + +def _folder(folder): + folder = str(folder or "").strip().rstrip("/") # a leading / stays: a folder on this machine is a full path + if ".." in pathlib.PurePosixPath(folder).parts or "\n" in folder: + raise ValueError("the folder can't contain .. or line breaks") + return folder + + +def check_connection(db, sid): + """ValueError unless `sid` is a storage connection files can be kept on (not an email account or a calendar).""" + try: + src = sources.get(db, int(sid)) + except (KeyError, TypeError, ValueError): + raise ValueError("that connection doesn't exist") from None + if feeds.handles(src): + raise ValueError(f"{sources.BACKENDS[src['type']]['label']} isn't storage: choose a storage connection") + return src + + +# ---------- the crypt remote's password ---------- +def _crypt_secrets(db, cfg): + """rclone crypt's two passwords, made the first time they are needed and kept sealed like any setting's secret.""" + row = db.one("SELECT sealed FROM $r", r=R("app_setting", "files_crypt")) or {} + sealed = row.get("sealed") or {} + if not sealed.get("password"): + sealed = {k: settings.seal(cfg, secrets.token_urlsafe(32), f"files:crypt:{k}") for k in ("password", "salt")} + db.q("UPSERT $r CONTENT $d", r=R("app_setting", "files_crypt"), d={"data": "{}", "sealed": sealed, "updated_at": store.now()}) + return {k: settings.unseal(cfg, sealed[k], f"files:crypt:{k}") for k in ("password", "salt")} + + +# ---------- rclone ---------- +@contextlib.contextmanager +def _remote(db, cfg, where): + """A private rclone config for `where`, and the remote prefix files go under ("name:folder/" or "lenscrypt:").""" + src = check_connection(db, where["connection"]) + folder = where.get("folder") or "" + if src["type"] == "local": + folder = sources.check_path(cfg, src, folder) # only inside sources.local_roots + else: + folder = folder.lstrip("/") + name, text = sources._config(cfg, src) + base = f"{name}:{folder}" + if where.get("crypt"): + pw = _crypt_secrets(db, cfg) + text += ( + f"[{CRYPT}]\ntype = crypt\nremote = {sources._one_line(base)}\n" + f"password = {sources.obscure(cfg, pw['password'])}\npassword2 = {sources.obscure(cfg, pw['salt'])}\n" + ) + prefix = f"{CRYPT}:" + else: + prefix = base.rstrip("/") + "/" if folder else base + d = tempfile.mkdtemp(prefix="la-rclone-") + conf = os.path.join(d, "rclone.conf") + fd = os.open(conf, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + with os.fdopen(fd, "w") as f: + f.write(text) + try: + yield conf, prefix + sources._writeback(db, cfg, src, conf) + finally: + shutil.rmtree(d, ignore_errors=True) + + +def _missing(err): + m = str(err).lower() + return "not found" in m or "doesn't exist" in m or "does not exist" in m or "nosuchkey" in m + + +def _rclone(cfg, conf, *argv, timeout=TIMEOUT): + out = subprocess.run( + [sources._bin(cfg), "--config", conf, "--retries", "2", "--low-level-retries", "3", *argv], + capture_output=True, + text=True, + timeout=timeout, + ) + if out.returncode: + raise RuntimeError(sources._clean_err(out.stderr) or f"rclone exited with {out.returncode}") + return out.stdout + + +# ---------- files ---------- +def _send(db, cfg, where, key, path): + """Copy the bytes at `path` to `key` as they are.""" + if where["store"] == "local": + dest = _local_root(cfg) / key + dest.parent.mkdir(parents=True, exist_ok=True) + tmp = dest.with_name(f".{dest.name}.{secrets.token_hex(4)}") + try: + shutil.copyfile(path, tmp) + os.replace(tmp, dest) + finally: + with contextlib.suppress(OSError): + tmp.unlink() + return + with _remote(db, cfg, where) as (conf, prefix): + _rclone(cfg, conf, "copyto", str(path), prefix + key) + + +def _fetch(db, cfg, where, key, dest): + """Copy what is kept at `key` to `dest` as it is. KeyError when it isn't there.""" + if where.get("store", "local") == "local": + p = _local_root(cfg) / key + if not p.is_file(): + raise KeyError(key) + shutil.copyfile(p, dest) + return + with _remote(db, cfg, where) as (conf, prefix): + try: + _rclone(cfg, conf, "copyto", prefix + key, str(dest)) + except RuntimeError as e: + if _missing(e): + raise KeyError(key) from None + raise + + +@contextlib.contextmanager +def _scratch(cfg): + fd, tmp = tempfile.mkstemp(dir=_tmp(cfg)) + os.close(fd) + try: + yield tmp + finally: + with contextlib.suppress(OSError): + os.unlink(tmp) + + +def put(db, cfg, sid, key, path, where=None): + """Keep the file at `path` (left as it is) under `key` for namespace `sid`, where the settings say (or at + `where`). Returns where it went, to keep beside the file's row. On this machine it is encrypted as Lens's other + files are (keyring.protect); going to a connection, always. A vault nobody has unlocked raises keyring.Locked.""" + key, where = _key(key), where or target(db, cfg) + with _scratch(cfg) as tmp: + shutil.copyfile(path, tmp) + if where["store"] == "local": + keyring.protect(db, cfg, sid, tmp) + else: + keyring.encrypt_file(db, cfg, sid, tmp, force=True) # it leaves the machine: only ever as ciphertext + _send(db, cfg, where, key, tmp) + return where + + +@contextlib.contextmanager +def open_file(db, cfg, where, key): + """The plain bytes of a kept file, as a file to read. KeyError when it isn't there.""" + key, where = _key(key), where or {"store": "local"} + with _scratch(cfg) as tmp: + _fetch(db, cfg, where, key, tmp) + with keyring.open_plain(db, cfg, tmp) as f: + yield f + + +def delete(db, cfg, where, key): + """Remove a kept file; one already gone is fine.""" + key, where = _key(key), where or {"store": "local"} + if where.get("store", "local") == "local": + with contextlib.suppress(FileNotFoundError): + (_local_root(cfg) / key).unlink() + return + with _remote(db, cfg, where) as (conf, prefix): + try: + _rclone(cfg, conf, "deletefile", prefix + key, timeout=120) + except RuntimeError as e: + if not _missing(e): + raise + + +def test(db, cfg, where=None): + """Write a small file where files would go, read it back and remove it: {ok, store, seconds} or {ok, store, error}.""" + t0, probe, store_ = time.monotonic(), secrets.token_bytes(64), None + try: + where = where or target(db, cfg) + store_, key = where["store"], f"lens-check/{secrets.token_hex(8)}" + with _scratch(cfg) as tmp, _scratch(cfg) as back: + pathlib.Path(tmp).write_bytes(probe) + _send(db, cfg, where, key, tmp) + _fetch(db, cfg, where, key, back) + delete(db, cfg, where, key) + if pathlib.Path(back).read_bytes() != probe: + raise RuntimeError("what was read back isn't what was written") + except (RuntimeError, ValueError, KeyError, OSError, subprocess.TimeoutExpired) as e: + return {"ok": False, "store": store_, "error": str(e)[:300] or type(e).__name__} + return {"ok": True, "store": store_, "seconds": round(time.monotonic() - t0, 2)} diff --git a/fastapi_backend/app/domain/ops_tools.py b/fastapi_backend/app/domain/ops_tools.py index 16c4e38a5..a78480bcc 100644 --- a/fastapi_backend/app/domain/ops_tools.py +++ b/fastapi_backend/app/domain/ops_tools.py @@ -9,7 +9,7 @@ from __future__ import annotations -from . import auth, decide, jobs, llm, metadata, settings, setup, store, uploads +from . import auth, blobs, decide, feeds, jobs, llm, metadata, settings, setup, sources, store, uploads R = store.R _S = {"type": "string"} @@ -26,6 +26,7 @@ "graph", "video", "uploads", + "files", "ai", "reports", "notifications", @@ -38,7 +39,7 @@ "telemetry", "sensors", ) -ALWAYS_ASK = {"telemetry", "sensors"} # sensors open ports on the network +ALWAYS_ASK = {"telemetry", "sensors", "files"} # sensors open ports on the network; files moves where new files go ADMIN_TOOLS = [ ( @@ -71,6 +72,16 @@ ["section", "changes"], True, ), + ( + "file_storage", + "Where Lens keeps the files it makes its own (notes' attachments): this machine, or a storage connection (S3, " + "Google Drive, Dropbox, OneDrive, SFTP, SMB, WebDAV) under a folder, optionally wrapped in rclone crypt; and the " + "connections it could use. check: write, read back and remove a small file there. Change it with change_settings " + "files {store: local|connection, connection, folder, crypt}; a new connection is added in Settings → Sources.", + {"check": {"type": "boolean"}}, + [], + False, + ), ( "create_namespace", "Create a namespace: a separate set of recordings, documents and images with its own people and access. " @@ -210,6 +221,21 @@ def t_change_settings(self, section, changes): what = ", ".join(f"{k} = {v}" for k, v in shown.items()) return self._change("change_settings", {"section": section, "changes": changes}, f"Set {section}: {what}") + def t_file_storage(self, check=False): + f = self.cfg.get("files") or {} + out = { + "store": f.get("store", "local"), + "connection": f.get("connection"), + "folder": f.get("folder"), + "crypt": bool(f.get("crypt")), + "connections": [ + {"id": s["id"], "name": s["name"], "type": s["type"]} for s in sources.list_sources(self.db) if not feeds.handles(s) + ], + } + if check: + out["check"] = blobs.test(self.db, self.cfg) + return out, "Checked where files are kept" + (": " + ("it works" if out["check"]["ok"] else "it failed") if check else "") + def t_create_namespace(self, name, graph="shared"): name = name.strip().lower() if not store.NS_RX.match(name): diff --git a/fastapi_backend/app/domain/settings.py b/fastapi_backend/app/domain/settings.py index 4f45af240..7b50efd99 100644 --- a/fastapi_backend/app/domain/settings.py +++ b/fastapi_backend/app/domain/settings.py @@ -85,6 +85,7 @@ ), "server": ("embed_frame_ancestors", "max_upload_mb", "allowed_hosts", "session_hours", "secure_cookies", "trusted_proxies"), "uploads": None, + "files": None, "tokens": None, "auth": ("passwords",), # the LibreOffice and Chromium paths are startup settings only (the web app can't choose what the server runs) @@ -121,6 +122,7 @@ ("mail", "security"): {"starttls", "ssl", "none"}, ("bridge", "answer"): {"mention", "all"}, ("tunnel", "mode"): {"off", "quick", "token", "managed"}, + ("files", "store"): {"local", "connection"}, } # Settings the environment (.env) sets, which win over archive.yaml and the app and show as locked there: the # break-glass allowed hosts, the model provider so an install can be configured without the setup wizard, and @@ -400,6 +402,16 @@ def _check(section, key, value, default): if not (isinstance(value, int) and not isinstance(value, bool) and lo <= value <= hi): raise ValueError(f"documents.{key} is a whole number from {lo} to {hi}") return value + if section == "files" and key == "connection": + if value is not None and not (isinstance(value, int) and not isinstance(value, bool) and value > 0): + raise ValueError("files.connection is a storage connection's id") + return value + if (section, key) == ("files", "folder"): + from . import blobs + + if not isinstance(value, str) or len(value) > 200: + raise ValueError("files.folder is a folder (a bucket and path for S3), up to 200 characters") + return blobs._folder(value) if (section, key) == ("video", "object_min_score"): if not (isinstance(value, (int, float)) and not isinstance(value, bool) and 0.05 <= value <= 0.95): raise ValueError("video.object_min_score is a number from 0.05 to 0.95") @@ -879,6 +891,12 @@ def save(db, base, section, changes, user=None): "SELECT VALUE id FROM passkey WHERE account IN (SELECT VALUE record::id(id) FROM account WHERE admin = true AND disabled != true) LIMIT 1" ): raise ValueError("add a passkey for an admin before turning passwords off, or nobody could administer Lens") + if section == "files" and data.get("store") == "connection": + from . import blobs + + if not data.get("connection"): + raise ValueError("choose the storage connection files are kept on") + blobs.check_connection(db, data["connection"]) if section == "tunnel": from . import tunnel diff --git a/fastapi_backend/app/domain/store.py b/fastapi_backend/app/domain/store.py index 3a88f5327..f60075328 100644 --- a/fastapi_backend/app/domain/store.py +++ b/fastapi_backend/app/domain/store.py @@ -205,6 +205,9 @@ def labels(): }, # audio, video, documents and images uploaded in the web app, in pieces (docs/configuration.md); transcript files use # server.max_upload_mb + # where Lens keeps the files it makes its own, such as notes' attachments (blobs.py, docs/storage.md): "local" + # (data_dir/objects) or "connection" (a storage source, under its folder); crypt wraps it in rclone crypt too + "files": {"store": "local", "connection": None, "folder": "lens", "crypt": False}, "uploads": {"max_mb": 4096, "extensions": list(MEDIA_EXT + DOCUMENT_EXT + IMAGE_EXT), "chunk_mb": 8, "expire_hours": 24}, # documents and images (docs/configuration.md): how large their pages are drawn, when a page is read by OCR, and # how many pages are read at most diff --git a/fastapi_backend/app/schemas/admin.py b/fastapi_backend/app/schemas/admin.py index 8321a0620..4a1261ef4 100644 --- a/fastapi_backend/app/schemas/admin.py +++ b/fastapi_backend/app/schemas/admin.py @@ -6,7 +6,7 @@ from pydantic import Field -from app.schemas.common import Ok, ResponseModel +from app.schemas.common import Ok, RequestModel, ResponseModel class Started(Ok): @@ -190,6 +190,22 @@ class TelemetryTestResult(ResponseModel): ms: int | None = None +class FileStoreTry(RequestModel): + """Where to try keeping files, before saving it (Settings → Storage); nothing given tries what is saved.""" + + store: Literal["local", "connection"] | None = None + connection: int | None = Field(None, description="a storage connection's id") + folder: str | None = Field(None, max_length=200, description="the folder on it (for S3, the bucket and a path)") + crypt: bool = Field(False, description="wrap it in rclone crypt too") + + +class FileStoreTestResult(ResponseModel): + ok: bool + store: Literal["local", "connection"] | None = None + seconds: float | None = None + error: str | None = None + + class AuditEntry(ResponseModel): at: str email: str | None = None diff --git a/fastapi_backend/tests/api/test_file_store.py b/fastapi_backend/tests/api/test_file_store.py new file mode 100644 index 000000000..ea3f603d3 --- /dev/null +++ b/fastapi_backend/tests/api/test_file_store.py @@ -0,0 +1,154 @@ +"""Where Lens keeps its own files (blobs.py): this machine, or a storage connection through rclone, optionally crypt.""" + +from __future__ import annotations + +import json +import shutil +import socket +import subprocess +import time + +import pytest + +from app.domain import ai_tools, blobs, keyring, store +from tests.helpers import login, make_user + +needs_rclone = pytest.mark.skipif(not shutil.which("rclone"), reason="rclone is not installed") + + +def _roundtrip(db, cfg, sid, where, folder, name="note.txt", data=b"the quarterly numbers\n" * 50): + src = folder / name + src.write_bytes(data) + key = f"notes/{sid}/1/{name}" + got = blobs.put(db, cfg, sid, key, src, where) + assert src.read_bytes() == data # the original is left as it was + with blobs.open_file(db, cfg, got, key) as f: + assert f.read() == data + return key, got + + +def test_on_this_machine(client, db, cfg, folder): + pods = store.ns_id(db, "pods") + key, where = _roundtrip(db, cfg, pods, None, folder) + assert where == {"store": "local"} + kept = folder / "data" / "objects" / key + assert kept.read_bytes().startswith(b"the quarterly") # plain, like Lens's other files while encryption.files is off + blobs.delete(db, cfg, where, key) + assert not kept.exists() + blobs.delete(db, cfg, where, key) # already gone: fine + with pytest.raises(KeyError), blobs.open_file(db, cfg, where, key): + pass + with pytest.raises(ValueError): + blobs.put(db, cfg, pods, "../escape", folder / "note.txt") + assert blobs.test(db, cfg)["ok"] + + +def test_settings(client, db, cfg, folder): + make_user(db, "root@x.io", "root password 1", admin=True) + h = login(client, "root@x.io", "root password 1") + put = lambda body: client.put("/api/v1/settings/files", headers=h, json=body) # noqa: E731 + assert put({"store": "connection"}).status_code == 400 # which connection? + assert put({"store": "cloud"}).status_code == 400 + assert put({"folder": "a/../b"}).status_code == 400 + assert put({"store": "connection", "connection": 999}).status_code == 400 + cal = client.post("/api/v1/sources", headers=h, json={"name": "cal", "type": "ical", "params": {"url": "https://example.org/a.ics"}}) + if cal.status_code == 200: # a calendar isn't somewhere files can be kept + assert put({"store": "connection", "connection": cal.json()["id"]}).status_code == 400 + r = client.post("/api/v1/settings/files/test", headers=h) + assert r.json()["ok"] and r.json()["store"] == "local", r.text + r = client.post("/api/v1/settings/files/test", headers=h, json={"store": "connection"}) + assert (r.json()["ok"], r.json()["error"]) == (False, "choose a storage connection") + files = client.get("/api/v1/settings", headers=h).json()["files"]["values"] + assert files == {"store": "local", "connection": None, "folder": "lens", "crypt": False} + + +def _free_port(): + s = socket.socket() + s.bind(("127.0.0.1", 0)) + port = s.getsockname()[1] + s.close() + return port + + +@needs_rclone +def test_on_a_connection(client, db, cfg, folder): + make_user(db, "root@x.io", "root password 1", admin=True) + h = login(client, "root@x.io", "root password 1") + pods = store.ns_id(db, "pods") + (folder / "inbox" / "kept").mkdir(parents=True) + disk = client.post("/api/v1/sources", headers=h, json={"name": "disk", "type": "local"}).json()["id"] + + # a folder on this machine, through rclone: it only ever holds ciphertext + where = {"store": "connection", "connection": disk, "folder": str(folder / "inbox" / "kept"), "crypt": False} + key, got = _roundtrip(db, cfg, pods, where, folder) + assert got == where + raw = (folder / "inbox" / "kept" / key).read_bytes() + assert raw.startswith(keyring.MAGIC) and b"quarterly" not in raw + # with crypt, not even the names show + crypt = {**where, "crypt": True} + ckey, _ = _roundtrip(db, cfg, pods, crypt, folder, name="secret-plan.txt") + names = [p.name for p in (folder / "inbox" / "kept").rglob("*")] + assert "secret-plan.txt" not in names and len(names) > 3 + # the crypt password is made once, kept sealed, and the same the next time + assert blobs._crypt_secrets(db, cfg) == blobs._crypt_secrets(db, cfg) + blobs.delete(db, cfg, crypt, ckey) + with pytest.raises(KeyError), blobs.open_file(db, cfg, crypt, ckey): + pass + # outside sources.local_roots: refused + with pytest.raises(ValueError): + blobs.put(db, cfg, pods, "x/y", folder / "note.txt", {**where, "folder": "/etc"}) + + # saved, then checked from Settings → Storage and by the assistant + r = client.put( + "/api/v1/settings/files", + headers=h, + json={"store": "connection", "connection": disk, "folder": str(folder / "inbox" / "kept"), "crypt": True}, + ) + assert r.status_code == 200, r.text + r = client.post("/api/v1/settings/files/test", headers=h) + assert r.json()["ok"] and r.json()["store"] == "connection", r.text + r = client.post("/api/v1/settings/files/test", headers=h, json={"store": "connection", "connection": disk, "folder": "/etc"}) + assert not r.json()["ok"] and "local_roots" in r.json()["error"] + current = client.app.state.archive.current() + uid = db.one("SELECT record::id(id) AS id FROM account WHERE email = 'root@x.io'")["id"] + box = ai_tools.Toolbox(db, current, {"id": uid, "email": "root@x.io", "admin": True}, {pods}, {pods}, {}, None, admin=True) + out = json.loads(box.call("file_storage", {"check": True})[0]) + assert out["store"] == "connection" and out["crypt"] and out["check"]["ok"], out + assert [c["name"] for c in out["connections"]] == ["disk"] + # what was kept before the setting changed is still read from where it went + with blobs.open_file(db, cfg, got, key) as f: + assert f.read().startswith(b"the quarterly") + + # S3, through rclone's own S3 server + root = folder / "s3" + (root / "bucket").mkdir(parents=True) + port = _free_port() + srv = subprocess.Popen( + ["rclone", "serve", "s3", str(root), "--addr", f"127.0.0.1:{port}", "--auth-key", "AKTEST,SK-plain-123"], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + try: + for _ in range(50): + try: + socket.create_connection(("127.0.0.1", port), timeout=0.2).close() + break + except OSError: + time.sleep(0.2) + s3 = client.post( + "/api/v1/sources", + headers=h, + json={ + "name": "bucket", + "type": "s3", + "secrets": {"secret_access_key": "SK-plain-123"}, + "params": {"provider": "Other", "endpoint": f"http://127.0.0.1:{port}", "access_key_id": "AKTEST"}, + }, + ).json()["id"] + s3where = {"store": "connection", "connection": s3, "folder": "bucket/lens", "crypt": False} + key, _ = _roundtrip(db, cfg, pods, s3where, folder, name="s3.txt") + assert (root / "bucket" / "lens" / key).read_bytes().startswith(keyring.MAGIC) + assert blobs.test(db, cfg, {**s3where, "crypt": True})["ok"] + finally: + srv.terminate() + srv.wait() diff --git a/nextjs-frontend/app/openapi-client/index.ts b/nextjs-frontend/app/openapi-client/index.ts index 505153dc4..3f80db4ea 100644 --- a/nextjs-frontend/app/openapi-client/index.ts +++ b/nextjs-frontend/app/openapi-client/index.ts @@ -754,6 +754,8 @@ export type { FieldValuesUpdate, FileLine, FileLines, + FileStoreTestResult, + FileStoreTry, FileUpdate, FindGraphPathData, FindGraphPathError, @@ -2337,6 +2339,11 @@ export type { TestExtensionErrors, TestExtensionResponse, TestExtensionResponses, + TestFileStoreData, + TestFileStoreError, + TestFileStoreErrors, + TestFileStoreResponse, + TestFileStoreResponses, TestLlmData, TestLlmResponse, TestLlmResponses, diff --git a/nextjs-frontend/app/openapi-client/sdk.gen.ts b/nextjs-frontend/app/openapi-client/sdk.gen.ts index 3a9f91946..490823c19 100644 --- a/nextjs-frontend/app/openapi-client/sdk.gen.ts +++ b/nextjs-frontend/app/openapi-client/sdk.gen.ts @@ -1131,6 +1131,9 @@ import type { TestExtensionData, TestExtensionErrors, TestExtensionResponses, + TestFileStoreData, + TestFileStoreErrors, + TestFileStoreResponses, TestLlmData, TestLlmResponses, TestMailData, @@ -2260,6 +2263,25 @@ export class Admin { }); } + /** + * Test File Store + * + * Write a small file where Lens would keep files, read it back and remove it: what is saved, or what is given + * (to check a connection and folder before saving them). + */ + public static testFileStore( + options?: Options, + ): RequestResult { + return (options?.client ?? client).post({ + url: "/api/v1/settings/files/test", + ...options, + headers: { + "Content-Type": "application/json", + ...options?.headers, + }, + }); + } + /** * Bridge Status * diff --git a/nextjs-frontend/app/openapi-client/types.gen.ts b/nextjs-frontend/app/openapi-client/types.gen.ts index 5f4cb8ef7..0868fe9f3 100644 --- a/nextjs-frontend/app/openapi-client/types.gen.ts +++ b/nextjs-frontend/app/openapi-client/types.gen.ts @@ -4586,6 +4586,59 @@ export type FileLines = { [key: string]: unknown; }; +/** + * FileStoreTestResult + */ +export type FileStoreTestResult = { + /** + * Ok + */ + ok: boolean; + /** + * Store + */ + store?: "local" | "connection" | null; + /** + * Seconds + */ + seconds?: number | null; + /** + * Error + */ + error?: string | null; + [key: string]: unknown; +}; + +/** + * FileStoreTry + * + * Where to try keeping files, before saving it (Settings → Storage); nothing given tries what is saved. + */ +export type FileStoreTry = { + /** + * Store + */ + store?: "local" | "connection" | null; + /** + * Connection + * + * a storage connection's id + */ + connection?: number | null; + /** + * Folder + * + * the folder on it (for S3, the bucket and a path) + */ + folder?: string | null; + /** + * Crypt + * + * wrap it in rclone crypt too + */ + crypt?: boolean; +}; + /** * FileUpdate */ @@ -17297,6 +17350,34 @@ export type TestMailResponses = { export type TestMailResponse = TestMailResponses[keyof TestMailResponses]; +export type TestFileStoreData = { + /** + * Body + */ + body?: FileStoreTry | null; + path?: never; + query?: never; + url: "/api/v1/settings/files/test"; +}; + +export type TestFileStoreErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type TestFileStoreError = TestFileStoreErrors[keyof TestFileStoreErrors]; + +export type TestFileStoreResponses = { + /** + * Successful Response + */ + 200: FileStoreTestResult; +}; + +export type TestFileStoreResponse = TestFileStoreResponses[keyof TestFileStoreResponses]; + export type BridgeStatusData = { body?: never; path?: never; diff --git a/nextjs-frontend/openapi.json b/nextjs-frontend/openapi.json index 23b09a31c..5ddcd81de 100644 --- a/nextjs-frontend/openapi.json +++ b/nextjs-frontend/openapi.json @@ -2263,6 +2263,55 @@ } } }, + "/api/v1/settings/files/test": { + "post": { + "tags": [ + "admin" + ], + "summary": "Test File Store", + "description": "Write a small file where Lens would keep files, read it back and remove it: what is saved, or what is given\n(to check a connection and folder before saving them).", + "operationId": "test_file_store", + "requestBody": { + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/FileStoreTry" + }, + { + "type": "null" + } + ], + "title": "Body" + } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/FileStoreTestResult" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, "/api/v1/settings/bridge": { "get": { "tags": [ @@ -30211,6 +30260,111 @@ ], "title": "FileLines" }, + "FileStoreTestResult": { + "properties": { + "ok": { + "type": "boolean", + "title": "Ok" + }, + "store": { + "anyOf": [ + { + "type": "string", + "enum": [ + "local", + "connection" + ] + }, + { + "type": "null" + } + ], + "title": "Store" + }, + "seconds": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ], + "title": "Seconds" + }, + "error": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Error" + } + }, + "additionalProperties": true, + "type": "object", + "required": [ + "ok" + ], + "title": "FileStoreTestResult" + }, + "FileStoreTry": { + "properties": { + "store": { + "anyOf": [ + { + "type": "string", + "enum": [ + "local", + "connection" + ] + }, + { + "type": "null" + } + ], + "title": "Store" + }, + "connection": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Connection", + "description": "a storage connection's id" + }, + "folder": { + "anyOf": [ + { + "type": "string", + "maxLength": 200 + }, + { + "type": "null" + } + ], + "title": "Folder", + "description": "the folder on it (for S3, the bucket and a path)" + }, + "crypt": { + "type": "boolean", + "title": "Crypt", + "description": "wrap it in rclone crypt too", + "default": false + } + }, + "additionalProperties": false, + "type": "object", + "title": "FileStoreTry", + "description": "Where to try keeping files, before saving it (Settings \u2192 Storage); nothing given tries what is saved." + }, "FileUpdate": { "properties": { "role": {