diff --git a/novem/code/__init__.py b/novem/code/__init__.py index 8e1ab93..4f177a2 100644 --- a/novem/code/__init__.py +++ b/novem/code/__init__.py @@ -181,10 +181,7 @@ def api_delete(self, relpath: str) -> None: relpath: relative path to the resource baseline, /config/type for the type file in the config folder """ - if self.user: - print(f"You cannot modify another user's {self._label}") - return - + # another user's resource: the server's share permissions decide path = self._path(relpath) if self._debug: @@ -206,7 +203,8 @@ def api_create(self, relpath: str) -> None: relpath: relative path to the resource baseline """ if self.user: - print(f"You cannot modify another user's {self._label}") + # gaia refuses every create in another user's namespace, whatever + # the shares grant, so don't send it return path = self._path(relpath) @@ -236,10 +234,7 @@ def api_write(self, relpath: str, value: str) -> None: for the type file in the config folder value: the value to write to the file """ - if self.user: - print(f"You cannot modify another user's {self._label}") - return - + # another user's resource: the server's share permissions decide path = self._path(relpath) if self._debug: @@ -337,9 +332,6 @@ def _sync_base(self, user_aware: bool) -> str: # _path() is already user-aware return self._path() - def _sync_label(self) -> str: - return self._label - def api_tree(self, colors: bool = False, relpath: str = "/") -> str: """ Iterate over the current resource and print a "pretty" ascii tree diff --git a/novem/job/__init__.py b/novem/job/__init__.py index 7f9d114..08d3936 100644 --- a/novem/job/__init__.py +++ b/novem/job/__init__.py @@ -144,10 +144,7 @@ def api_delete(self, relpath: str) -> None: for the type file in the config folder value: the value to write to the file """ - if self.user: - print("You cannot modify another user's job") - return - + # another user's resource: the server's share permissions decide path = self._path(relpath) if self._debug: @@ -180,7 +177,8 @@ def api_create(self, relpath: str) -> None: value: the value to write to the file """ if self.user: - print("You cannot modify another user's job") + # gaia refuses every create in another user's namespace, whatever + # the shares grant, so don't send it return path = self._path(relpath) @@ -210,10 +208,7 @@ def api_write(self, relpath: str, value: str) -> None: for the type file in the config folder value: the value to write to the file """ - if self.user: - print("You cannot modify another user's job") - return - + # another user's resource: the server's share permissions decide path = self._path(relpath) if self._debug: @@ -487,9 +482,6 @@ def _sync_base(self, user_aware: bool) -> str: # _path() is already user-aware return self._path() - def _sync_label(self) -> str: - return "job" - def api_tree(self, colors: bool = False, relpath: str = "/") -> str: """ Iterate over the current job and print a "pretty" ascii tree diff --git a/novem/sync.py b/novem/sync.py index 2776f3b..287fc1c 100644 --- a/novem/sync.py +++ b/novem/sync.py @@ -3,6 +3,31 @@ import requests +# Written at the root of a dump that may not hold every managed file, so a +# later load knows not to delete what the dump merely could not see. +PARTIAL_MARKER = ".novem-partial" + +# Files with a DELETE verb that the sync still must not manage. DELETE on +# `notifications` resets the caller's own preference to the default rather +# than removing a stored file (novem-code/gaia#8068), so restoring a dump +# that lacks it would silently reset the preference. +_UNMANAGED = frozenset({"/notifications"}) + +_TRUE = frozenset({"yes", "true"}) +_FALSE = frozenset({"no", "false"}) + + +def _same_value(a: str, b: str) -> bool: + """True when two file contents mean the same thing. + + Switches read back as yes/no, while older dumps hold true/false, so + those spellings compare by value instead of as text. + """ + if a == b: + return True + a, b = a.strip().lower(), b.strip().lower() + return (a in _TRUE and b in _TRUE) or (a in _FALSE and b in _FALSE) + class NovemTreeSync: """ @@ -12,22 +37,23 @@ class NovemTreeSync: walks that tree to disk; load treats a dumped folder as the desired state and syncs the remote tree to match it (create / overwrite / delete). - Concrete classes mix this in and provide two hooks plus the usual + Concrete classes mix this in and provide one hook plus the usual ``self._session`` / ``self.user`` attributes: * ``_sync_base(user_aware)`` - the resource's base URL WITHOUT a trailing slash (e.g. ``.../vis/plots/myplot``). When ``user_aware`` is true and - the resource belongs to another user, return that user-scoped path so - dump can read it. - * ``_sync_label()`` - a noun for the "cannot modify another user's X" - message (e.g. ``"plots"`` / ``"job"``). + the resource belongs to another user, return that user-scoped path. Only real, round-trippable files are synced. The directory listing reports every leaf as ``type="file"``, so selection keys on the DELETE verb in each node's ``actions``: read-only files (no DELETE) and virtual/computed files like ``notifications`` (POST but no DELETE) are excluded. Shares - (``/shared/``) round-trip as links created via PUT; tags (``/tags/``) are - excluded entirely (managed via the -t CLI flag). + (``/shared/``) round-trip as links created via PUT; tags (``/tags/``) and + ``notifications`` are excluded entirely. + + A listing gives each caller its own actions, so a dump of another user's + resource can omit files its owner could delete. Such a dump is marked + partial (see ``PARTIAL_MARKER``) and loading it never deletes. """ # supplied by the concrete NovemAPI subclass @@ -37,9 +63,6 @@ class NovemTreeSync: def _sync_base(self, user_aware: bool) -> str: # pragma: no cover - hook raise NotImplementedError - def _sync_label(self) -> str: # pragma: no cover - hook - raise NotImplementedError - # Directories a walk lists but does not descend into, mapped to a short # reason. Set by a resource whose children under that path are generated # per-entry rather than stored, so descending costs a full subtree per @@ -81,6 +104,22 @@ def api_dump(self, outpath: str) -> None: """ read_root = f"{self._sync_base(user_aware=True)}/" out = Path(outpath) + marker = out / PARTIAL_MARKER + + # Our own resource lists every action we hold, so its dump is a full + # snapshot. Another user's resource lists only what our share grants, + # so files its owner could delete may be missing from the dump. + partial = bool(self.user) + if partial: + out.mkdir(parents=True, exist_ok=True) + marker.write_text( + "This dump was taken through another user's share and may omit files.\n" + "Loading it creates and overwrites files but never deletes any.\n", + encoding="utf-8", + ) + print(f"Partial dump: {marker}") + elif marker.exists(): + marker.unlink() def write_file(api_path: str, content: str) -> None: fp = out / api_path.lstrip("/") @@ -126,6 +165,9 @@ def rec_tree(path: str) -> None: if r["type"] in ["file", "link"] and "DELETE" not in r.get("actions", []): continue + if child_path in _UNMANAGED: + continue + skip = self._walk_skip("", child_path) if skip: print(f"Skipping {skip}: {child_path}") @@ -147,6 +189,9 @@ def walk(full: Path, api_path: str) -> None: if api_path == "/tags" or api_path.startswith("/tags/"): return + if api_path == f"/{PARTIAL_MARKER}": + return + if full.is_file(): files[api_path] = full.read_text(encoding="utf-8") elif full.is_dir(): @@ -206,6 +251,9 @@ def rec_tree(path: str) -> None: if r["type"] in ["file", "link"] and "DELETE" not in r.get("actions", []): skipped.add(child_path) continue + if child_path in _UNMANAGED: + skipped.add(child_path) + continue rec_tree(child_path) rec_tree("") @@ -218,30 +266,37 @@ def api_load(self, inpath: str, dry_run: bool = False) -> None: * files that don't exist remotely are created * files whose content differs are overwritten - * remote files no longer present locally are deleted - * unchanged files are left untouched + * remote files no longer present locally are deleted, unless the + dump is partial (see ``PARTIAL_MARKER``) + * unchanged files are left untouched; yes/no and true/false + spellings of a switch count as unchanged + + For another user's resource the server's share permissions decide each + write; a refused write is reported as a failure. With dry_run=True no state-changing requests are sent; the actions that would be taken are printed instead. """ - if self.user: - print(f"You cannot modify another user's {self._sync_label()}") - return - - base = self._sync_base(user_aware=False) + base = self._sync_base(user_aware=True) read_root = f"{base}/" prefix = "[dry-run] " if dry_run else "" + partial = (Path(inpath) / PARTIAL_MARKER).is_file() local = self._collect_local_files(inpath) remote, skipped = self._collect_remote_files(read_root) # don't (re)create local copies of paths the sync doesn't manage # (virtual/read-only files like `notifications`) to_create = sorted(p for p in local if p not in remote and p not in skipped) - to_overwrite = sorted(p for p in local if p in remote and local[p] != remote[p]) + to_overwrite = sorted(p for p in local if p in remote and not _same_value(local[p], remote[p])) # delete deepest paths first so we don't strand children to_delete = sorted((p for p in remote if p not in local), reverse=True) - unchanged = sum(1 for p in local if p in remote and local[p] == remote[p]) + unchanged = sum(1 for p in local if p in remote and _same_value(local[p], remote[p])) + + if partial and to_delete: + # the dump could not see everything, so absence proves nothing + print(f"{prefix}Partial dump: keeping {len(to_delete)} remote file(s) it does not contain") + to_delete = [] created = overwritten = deleted = failed = 0 diff --git a/novem/vis/__init__.py b/novem/vis/__init__.py index f30c7c7..8809697 100644 --- a/novem/vis/__init__.py +++ b/novem/vis/__init__.py @@ -151,14 +151,13 @@ def _sync_base(self, user_aware: bool) -> str: return f"{self._api_root}users/{self.user}/vis/{self._vispath}/{self.id}" return f"{self._api_root}vis/{self._vispath}/{self.id}" - def _sync_label(self) -> str: - return self._vispath or "vis" - def _path(self, relpath: str = "", user_aware: bool = False) -> str: """URL for a path relative to this vis. - Only GET supports the custom user pathing, so user_aware is opt-in - rather than inferred from self.user. + Reads and writes (POST, DELETE) go to the user-scoped path for + another user's vis; creates (PUT) never do, since the server refuses + any create in another user's namespace. Hence opt-in rather than + inferred from self.user. """ return f"{self._sync_base(user_aware)}{norm_relpath(relpath)}" @@ -318,11 +317,8 @@ def api_delete(self, relpath: str) -> None: for the type file in the config folder value: the value to write to the file """ - if self.user: - print(f"You cannot modify another user's {self._vispath}") - return - - path = self._path(relpath) + # another user's vis: the server's share permissions decide + path = self._path(relpath, user_aware=True) if self._debug: print(f"DELETE: {path}") @@ -354,7 +350,8 @@ def api_create(self, relpath: str) -> None: value: the value to write to the file """ if self.user: - print(f"You cannot modify another user's {self._vispath}") + # gaia refuses every create in another user's namespace, whatever + # the shares grant, so don't send it (and never PUT our own path) return path = self._path(relpath) @@ -384,11 +381,8 @@ def api_write(self, relpath: str, value: str) -> None: for the type file in the config folder value: the value to write to the file """ - if self.user: - print(f"You cannot modify another user's {self._vispath}") - return - - path = self._path(relpath) + # another user's vis: the server's share permissions decide + path = self._path(relpath, user_aware=True) if self._debug: print(f"POST: {path}") diff --git a/tests/test_api_relpath.py b/tests/test_api_relpath.py index 8558de3..6453303 100644 --- a/tests/test_api_relpath.py +++ b/tests/test_api_relpath.py @@ -73,14 +73,31 @@ def test_empty_relpath_addresses_the_resource_root(job, requests_mock): assert job._path("") == f"{API_ROOT}code/jobs/res" -def test_vis_user_path_is_get_only(requests_mock): - """Reads may target another user; writes are refused rather than retargeted.""" - p = mk(Plot, user="other") - - requests_mock.register_uri("GET", rm_mod.ANY, text="", status_code=200) - p.api_read("config/type") - assert requests_mock.last_request.url == f"{API_ROOT}users/other/vis/plots/res/config/type" - - before = requests_mock.call_count - p.api_write("config/type", "value") - assert requests_mock.call_count == before, "a write against another user must not reach the API" +@pytest.mark.parametrize("cls,base", [(Plot, "vis/plots/res"), (Job, "code/jobs/res"), (Space, "code/spaces/res")]) +def test_other_user_writes_go_to_user_path(requests_mock, cls, base): + """Reads, writes and deletes on another user's resource target their namespace; + the server's share permissions decide. Creates are never sent.""" + obj = mk(cls, user="other") + requests_mock.register_uri(rm_mod.ANY, rm_mod.ANY, text="", status_code=200) + + obj.api_read("config/type") + obj.api_write("config/type", "value") + obj.api_delete("config/type") + obj.api_create("") + + sent = [(r.method, r.url) for r in requests_mock.request_history] + url = f"{API_ROOT}users/other/{base}/config/type" + assert sent == [("GET", url), ("POST", url), ("DELETE", url)] + + +@pytest.mark.parametrize("cls", [Plot, Job, Space]) +def test_other_user_write_refused_by_server_raises(requests_mock, cls): + from novem.exceptions import Novem403 + + obj = mk(cls, user="other") + requests_mock.register_uri(rm_mod.ANY, rm_mod.ANY, status_code=403, json={"message": "no write share"}) + + with pytest.raises(Novem403): + obj.api_write("config/type", "value") + with pytest.raises(Novem403): + obj.api_delete("config/type") diff --git a/tests/test_code.py b/tests/test_code.py index de7c7ce..1143096 100644 --- a/tests/test_code.py +++ b/tests/test_code.py @@ -9,7 +9,10 @@ import os from contextlib import redirect_stdout +import pytest + from novem import Computer, Image, Space +from novem.exceptions import Novem403 BASE = os.path.dirname(os.path.abspath(__file__)) CONFIG_FILE = f"{BASE}/test.conf" @@ -68,11 +71,16 @@ def test_space_user_scoped_reads(requests_mock): s = Space("team", user="other", create=False, config_path=CONFIG_FILE) assert s.name == "Team space" - # writes to another user's resource are refused client-side - f = io.StringIO() - with redirect_stdout(f): - s.name = "nope" - assert "another user's space" in f.getvalue() + # writes go to the user-scoped path and the server's shares decide + post = requests_mock.register_uri("post", f"{api_root}users/other/code/spaces/team/name", text="") + s.name = "renamed" + assert post.last_request.text == "renamed" + + requests_mock.register_uri( + "post", f"{api_root}users/other/code/spaces/team/description", status_code=403, json={"message": "denied"} + ) + with pytest.raises(Novem403, match="denied"): + s.description = "nope" def test_computer_status_and_config(requests_mock): diff --git a/tests/test_load_sync.py b/tests/test_load_sync.py index 8b341e3..15dfc85 100644 --- a/tests/test_load_sync.py +++ b/tests/test_load_sync.py @@ -3,6 +3,7 @@ from pathlib import Path from novem import Plot +from novem.sync import PARTIAL_MARKER config_file = str(Path(__file__).resolve().parent / "test.conf") @@ -63,10 +64,11 @@ def delete(self, url, **kwargs): return FakeResp(status_code=404 if path in self.fail_paths else 200) -def _make_plot_with_remote(tree, fail_paths=None): - p = Plot(id="test_plot", create=False, config_path=config_file) - read_prefix = f"{p._api_root}vis/plots/{p.id}/" - write_prefix = f"{p._api_root}vis/plots/{p.id}" +def _make_plot_with_remote(tree, fail_paths=None, user=None): + p = Plot(id="test_plot", create=False, user=user, config_path=config_file) + scope = f"users/{user}/" if user else "" + read_prefix = f"{p._api_root}{scope}vis/plots/{p.id}/" + write_prefix = f"{p._api_root}{scope}vis/plots/{p.id}" session = FakeSession(tree, read_prefix, write_prefix, fail_paths=fail_paths) p._session = session return p, session @@ -286,3 +288,97 @@ def test_load_sync_ignores_tags(tmp_path): assert not any("tags" in c for c in all_calls) assert all_calls == [] assert "0 created, 0 overwritten, 0 deleted, 1 unchanged" in out.getvalue() + + +def _flat_tree(files, actions=None): + """A root listing of plain files, each with FILE_ACTIONS unless overridden.""" + actions = actions or {} + listing = [ + {"name": name, "type": "file", "permissions": "rw", "actions": actions.get(name, FILE_ACTIONS)} + for name in files + ] + tree = {"": ("dir", listing)} + tree.update({f"/{name}": ("file", content) for name, content in files.items()}) + return tree + + +def _load(p, path): + out = StringIO() + with redirect_stdout(out): + p.api_load(inpath=str(path)) + return out.getvalue() + + +def test_load_sync_compares_switch_spellings_by_value(tmp_path): + # gaia reads switches back as yes/no; a dump from before holds true/false + tree = _flat_tree({"a": "yes", "b": "no", "c": "yes", "d": "true"}) + p, session = _make_plot_with_remote(tree) + _write_local(str(tmp_path), {"a": "true", "b": "False\n", "c": "no", "d": "true"}) + + summary = _load(p, tmp_path) + + assert session.posts == ["/c"] # only a real change is written + assert "0 created, 1 overwritten, 0 deleted, 3 unchanged" in summary + + +def test_load_sync_leaves_resettable_notifications_alone(tmp_path): + # once notifications gains DELETE (a reset to default), it still must not be + # managed: a dump without it must not reset the caller's preference, and a + # stale copy must not be written back + tree = _flat_tree({"name": "x", "notifications": "important"}) + p, session = _make_plot_with_remote(tree) + + _write_local(str(tmp_path / "old"), {"name": "x"}) + _load(p, tmp_path / "old") + _write_local(str(tmp_path / "stale"), {"name": "x", "notifications": "info"}) + _load(p, tmp_path / "stale") + + assert session.puts + session.posts + session.deletes == [] + + +def test_load_sync_partial_dump_never_deletes(tmp_path): + tree = _flat_tree({"name": "old", "logo": "owner-only"}) + p, session = _make_plot_with_remote(tree) + _write_local(str(tmp_path), {"name": "new", PARTIAL_MARKER: "partial"}) + + summary = _load(p, tmp_path) + + assert session.deletes == [] + assert session.posts == ["/name"] # the marker itself is never uploaded + assert session.puts == [] + assert "keeping 1 remote file(s)" in summary + assert "0 created, 1 overwritten, 0 deleted, 0 unchanged" in summary + + +def test_dump_of_another_users_resource_is_partial_and_round_trips(tmp_path): + # a reader's listing carries no DELETE, so the reader's dump omits `logo` + reader_tree = _flat_tree({"name": "x", "logo": "img"}, actions={"name": FILE_ACTIONS, "logo": RO_ACTIONS}) + reader, _ = _make_plot_with_remote(reader_tree, user="owner") + with redirect_stdout(StringIO()): + reader.api_dump(outpath=str(tmp_path)) + + assert (tmp_path / PARTIAL_MARKER).is_file() + assert not (tmp_path / "logo").exists() + + # the owner loading that dump keeps `logo` + owner, session = _make_plot_with_remote(_flat_tree({"name": "x", "logo": "img"})) + _load(owner, tmp_path) + assert session.puts + session.posts + session.deletes == [] + + # a later full dump into the same folder drops the stale marker + with redirect_stdout(StringIO()): + owner.api_dump(outpath=str(tmp_path)) + assert not (tmp_path / PARTIAL_MARKER).exists() + + +def test_load_into_another_users_resource_targets_their_namespace(tmp_path): + # the FakeSession only answers the users/owner/... prefix, so a load that + # fell back to the caller's own plot would read nothing and create `name` + p, session = _make_plot_with_remote(_flat_tree({"name": "old"}), user="owner") + _write_local(str(tmp_path), {"name": "new"}) + + summary = _load(p, tmp_path) + + assert session.posts == ["/name"] + assert session.puts == [] + assert "0 created, 1 overwritten" in summary