Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 4 additions & 12 deletions novem/code/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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)
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand Down
16 changes: 4 additions & 12 deletions novem/job/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand Down
93 changes: 74 additions & 19 deletions novem/sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
"""
Expand All @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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("/")
Expand Down Expand Up @@ -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}")
Expand All @@ -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():
Expand Down Expand Up @@ -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("")
Expand All @@ -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

Expand Down
26 changes: 10 additions & 16 deletions novem/vis/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)}"

Expand Down Expand Up @@ -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}")
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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}")
Expand Down
39 changes: 28 additions & 11 deletions tests/test_api_relpath.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
18 changes: 13 additions & 5 deletions tests/test_code.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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):
Expand Down
Loading