aboutsummaryrefslogtreecommitdiffstats
path: root/packages/meshbay-node/src/meshbay_node/ops
diff options
context:
space:
mode:
Diffstat (limited to 'packages/meshbay-node/src/meshbay_node/ops')
-rw-r--r--packages/meshbay-node/src/meshbay_node/ops/chat.py2
-rw-r--r--packages/meshbay-node/src/meshbay_node/ops/groups.py30
-rw-r--r--packages/meshbay-node/src/meshbay_node/ops/node_toml.py59
-rw-r--r--packages/meshbay-node/src/meshbay_node/ops/roots.py25
-rw-r--r--packages/meshbay-node/src/meshbay_node/ops/settings.py6
5 files changed, 90 insertions, 32 deletions
diff --git a/packages/meshbay-node/src/meshbay_node/ops/chat.py b/packages/meshbay-node/src/meshbay_node/ops/chat.py
index 469e907..539284b 100644
--- a/packages/meshbay-node/src/meshbay_node/ops/chat.py
+++ b/packages/meshbay-node/src/meshbay_node/ops/chat.py
@@ -17,7 +17,7 @@ log = logging.getLogger("meshbay_node.ops")
#
# The key a group's chat archive is encrypted under. Generated here, by the
# node, and never by a member — the C5b rule is about key material arriving from
-# outside, and this is the same rule that lets `gek_rotate` be a signed
+# outside, and this is the same rule that lets a group key rotation be an
# instruction rather than a delivery.
#
# An *epoch* rather than a rotation, and the distinction is the whole design:
diff --git a/packages/meshbay-node/src/meshbay_node/ops/groups.py b/packages/meshbay-node/src/meshbay_node/ops/groups.py
index 1d8003c..ac14c3a 100644
--- a/packages/meshbay-node/src/meshbay_node/ops/groups.py
+++ b/packages/meshbay-node/src/meshbay_node/ops/groups.py
@@ -9,7 +9,7 @@ from meshbay_common.crypto import generate_gek, wrap_gek_aes
from meshbay_node.config import DEFAULT_CONFIG_PATH
from meshbay_node.ops.core import OpError, _config, _group_ctx, _hub
-from meshbay_node.ops.node_toml import _find_group_range
+from meshbay_node.ops.node_toml import _find_group_range, toml_string
log = logging.getLogger("meshbay_node.ops")
@@ -142,17 +142,28 @@ async def list_groups(state: dict) -> dict:
return {"groups": out, "operator_paired": has_operator, "settings": settings}
+JOIN_POLICIES = ("invite", "open")
+
+
async def attach_group(state: dict, name: str, shared_dir: str,
- writable: bool = True) -> dict:
+ writable: bool = True, join_policy: str = "invite") -> dict:
"""
Write a new [[groups]] block into node.toml.
The name-to-id lookup happens here because this process is the one logged
into the hub. Nothing is created on the hub: the group already exists, this
only tells the node to host it.
+
+ `join_policy` is the operator's, given with this request, and `invite`
+ unless they say otherwise. The hub's own record of the group is not read
+ for it: a hub that could declare a group open would be handed its key by
+ anyone it sent. The hub's value is returned beside it, so a caller can say
+ when the two differ.
"""
if not name or not shared_dir:
raise OpError("name and shared_dir are required")
+ if join_policy not in JOIN_POLICIES:
+ raise OpError(f"join_policy must be one of {', '.join(JOIN_POLICIES)}")
config = _config(state)
hub = _hub(state)
try:
@@ -182,12 +193,12 @@ async def attach_group(state: dict, name: str, shared_dir: str,
raise OpError(f"Cannot create {path}: {e}") from e
conf_path = Path(state.get("config_path") or DEFAULT_CONFIG_PATH)
- join_policy = group.get("join_policy", "invite")
+ visibility = "public" if join_policy == "open" else "private"
block = (f'\n[[groups]]\n'
- f'id = "{group["id"]}"\n'
- f'name = "{group["name"]}"\n'
- f'visibility = "{group.get("visibility", "private")}"\n'
- f'join_policy = "{join_policy}"\n')
+ f'id = {toml_string(group["id"])}\n'
+ f'name = {toml_string(group["name"])}\n'
+ f'visibility = {toml_string(visibility)}\n'
+ f'join_policy = {toml_string(join_policy)}\n')
# No `upload_dir` here. `GroupConfig.__post_init__` still *reads* it, so an
# existing node.toml keeps working — but what it does on read is force every
# other root read-only and append that path as the one writable one, which
@@ -198,7 +209,7 @@ async def attach_group(state: dict, name: str, shared_dir: str,
block += (f'\n [[groups.roots]]\n'
# Forward slashes: a Windows path in a TOML basic string is a
# parse error (`\U`, `\a`, ... are escapes). pathlib reads `/`.
- f' path = "{path.as_posix()}"\n'
+ f' path = {toml_string(path.as_posix())}\n'
f' writable = {"true" if writable else "false"}\n')
try:
with conf_path.open("a", encoding="utf-8", newline="\n") as f:
@@ -208,7 +219,8 @@ async def attach_group(state: dict, name: str, shared_dir: str,
result = {"group_id": group["id"], "name": group["name"],
"shared_dir": str(path), "config": str(conf_path),
- "writable": writable,
+ "writable": writable, "join_policy": join_policy,
+ "hub_join_policy": group.get("join_policy", "invite"),
"note": "restart the node to pick it up"}
return result
diff --git a/packages/meshbay-node/src/meshbay_node/ops/node_toml.py b/packages/meshbay-node/src/meshbay_node/ops/node_toml.py
index f711f26..2407722 100644
--- a/packages/meshbay-node/src/meshbay_node/ops/node_toml.py
+++ b/packages/meshbay-node/src/meshbay_node/ops/node_toml.py
@@ -3,14 +3,50 @@
from __future__ import annotations
import re
+import tomllib
from pathlib import Path
from meshbay_node.ops.core import OpError
+def toml_string(value: str) -> str:
+ """A TOML basic string holding `value` exactly, quotes included.
+
+ Every string written into node.toml goes through here. A value with a quote
+ or a newline in it — a group name, a folder name, any of them chosen by
+ someone else — would otherwise end the string and write lines of its own.
+ """
+ out = ['"']
+ for ch in str(value):
+ if ch == '"':
+ out.append('\\"')
+ elif ch == "\\":
+ out.append("\\\\")
+ elif ord(ch) < 0x20 or ord(ch) == 0x7F:
+ out.append(f"\\u{ord(ch):04x}")
+ else:
+ out.append(ch)
+ out.append('"')
+ return "".join(out)
+
+
+def _string_value(line: str, key: str) -> str | None:
+ """The string `key` holds on this line, unescaped — or None.
+
+ Read as TOML, not by pattern: a value written by `toml_string` may carry an
+ escaped quote or backslash, which a `"([^"]*)"` pattern would cut short.
+ """
+ if not re.match(r"^\s*" + re.escape(key) + r"\s*=", line):
+ return None
+ try:
+ value = tomllib.loads(line.strip()).get(key)
+ except tomllib.TOMLDecodeError:
+ return None
+ return value if isinstance(value, str) else None
+
+
def _find_group_range(lines: list[str], group_id: str) -> tuple[int, int] | None:
"""Line range of a [[groups]] block by id: (start, end_exclusive)."""
- id_re = re.compile(r'^\s*id\s*=\s*"([^"]*)"')
block_starts: list[int] = []
for i, line in enumerate(lines):
if line.strip() == "[[groups]]":
@@ -24,8 +60,7 @@ def _find_group_range(lines: list[str], group_id: str) -> tuple[int, int] | None
boundary = k
break
for k in range(start + 1, boundary):
- m = id_re.match(lines[k])
- if m and m.group(1) == group_id:
+ if _string_value(lines[k], "id") == group_id:
return (start, boundary)
return None
@@ -61,8 +96,10 @@ def _update_node_toml(conf_path: Path, updates: dict) -> None:
if isinstance(value, bool):
return f"{key} = {'true' if value else 'false'}"
if isinstance(value, list):
- items = ", ".join(f'"{v}"' for v in value)
+ items = ", ".join(toml_string(v) for v in value)
return f"{key} = [{items}]"
+ if isinstance(value, str):
+ return f"{key} = {toml_string(value)}"
return f"{key} = {value}"
remaining = dict(updates)
@@ -115,7 +152,6 @@ def _remove_roots_block(conf_path: Path, group_id: str,
raise OpError(f"Group {group_id[:8]} not found in {conf_path}")
start, end = rng
- path_re = re.compile(r'^\s*path\s*=\s*"([^"]*)"')
roots_starts: list[int] = []
for i in range(start + 1, end):
if lines[i].strip() == "[[groups.roots]]":
@@ -124,10 +160,10 @@ def _remove_roots_block(conf_path: Path, group_id: str,
for j, rs in enumerate(roots_starts):
rs_end = roots_starts[j + 1] if j + 1 < len(roots_starts) else end
for k in range(rs, rs_end):
- m = path_re.match(lines[k])
- if m:
+ raw = _string_value(lines[k], "path")
+ if raw is not None:
try:
- p = str(Path(m.group(1)).expanduser().resolve())
+ p = str(Path(raw).expanduser().resolve())
except OSError:
continue
if p == resolved_path:
@@ -153,7 +189,6 @@ def _update_root_field(conf_path: Path, group_id: str,
raise OpError(f"Group {group_id[:8]} not found in {conf_path}")
start, end = rng
- path_re = re.compile(r'^\s*path\s*=\s*"([^"]*)"')
writable_re = re.compile(r'^\s*(writable|upload)\s*=')
removable_re = re.compile(r'^\s*removable\s*=')
roots_starts: list[int] = []
@@ -165,10 +200,10 @@ def _update_root_field(conf_path: Path, group_id: str,
rs_end = roots_starts[j + 1] if j + 1 < len(roots_starts) else end
found_path = False
for k in range(rs, rs_end):
- m = path_re.match(lines[k])
- if m:
+ raw = _string_value(lines[k], "path")
+ if raw is not None:
try:
- p = str(Path(m.group(1)).expanduser().resolve())
+ p = str(Path(raw).expanduser().resolve())
except OSError:
continue
if p == resolved_path:
diff --git a/packages/meshbay-node/src/meshbay_node/ops/roots.py b/packages/meshbay-node/src/meshbay_node/ops/roots.py
index e3e2781..9dbade4 100644
--- a/packages/meshbay-node/src/meshbay_node/ops/roots.py
+++ b/packages/meshbay-node/src/meshbay_node/ops/roots.py
@@ -8,7 +8,12 @@ from pathlib import Path
from meshbay_node.config import DEFAULT_CONFIG_PATH
from meshbay_node.ops.core import OpError, _config, _group_ctx, _roster
-from meshbay_node.ops.node_toml import _insert_roots_block, _remove_roots_block, _update_root_field
+from meshbay_node.ops.node_toml import (
+ _insert_roots_block,
+ _remove_roots_block,
+ _update_root_field,
+ toml_string,
+)
from meshbay_node.roots import RootError, RootSet, off_disk
log = logging.getLogger("meshbay_node.ops")
@@ -46,11 +51,11 @@ async def add_root(state: dict, group_id: str, path: str, *,
raise OpError(f"Cannot create {added.path}: {e}") from e
conf_path = Path(state.get("config_path") or DEFAULT_CONFIG_PATH)
- root_block = f' [[groups.roots]]\n path = "{added.path.as_posix()}"'
+ root_block = f' [[groups.roots]]\n path = {toml_string(added.path.as_posix())}'
if name:
- root_block += f'\n name = "{added.name}"'
+ root_block += f'\n name = {toml_string(added.name)}'
if kind != "generic":
- root_block += f'\n kind = "{added.kind}"'
+ root_block += f'\n kind = {toml_string(added.kind)}'
if writable:
root_block += '\n writable = true'
if removable:
@@ -169,11 +174,14 @@ async def update_root(state: dict, group_id: str, root_name: str, *,
writable=match.writable, removable=match.removable)
# Update the live RootSet so GET /api/groups returns correct data
- # immediately, without waiting for the async reload to finish.
+ # immediately, without waiting for the async reload to finish — and the
+ # indexer's, which is normally the same object but need not be, since it
+ # is the one the table pushed to every peer is read from.
live_roots: RootSet | None = state.get("groups_ctx", {}).get(
group_id, {}).get("roots")
- if live_roots:
- for lr in live_roots.roots:
+ indexer = state.get("indexers", {}).get(group_id)
+ for rootset in {id(x): x for x in (live_roots, indexer and indexer.roots) if x}.values():
+ for lr in rootset.roots:
lr_name = lr.name or str(Path(lr.path).name)
if fold(lr_name) == target:
if writable is not None:
@@ -182,6 +190,9 @@ async def update_root(state: dict, group_id: str, root_name: str, *,
lr.removable = removable
break
+ if indexer:
+ await indexer.publish_roots()
+
# Built from config when there is no live set, never returned empty: an
# empty list is a *valid answer* meaning "this group has no directories",
# and the client cannot tell it from "the node could not say". It would
diff --git a/packages/meshbay-node/src/meshbay_node/ops/settings.py b/packages/meshbay-node/src/meshbay_node/ops/settings.py
index eade6ca..906cd03 100644
--- a/packages/meshbay-node/src/meshbay_node/ops/settings.py
+++ b/packages/meshbay-node/src/meshbay_node/ops/settings.py
@@ -182,9 +182,9 @@ async def set_transfer_limits(state: dict, group_id: str,
Same shape as every other operator setting: lives on the node (roster.db,
not the hub and not node.toml, for the reason change 5 gives — a hub that
- decided this would have authority over someone else's machine), signed
- (webrtc_server checks the caller's admin authority before this runs), and
- live, so the pools are updated in place rather than at the next restart.
+ decided this would have authority over someone else's machine), set on the
+ node's own machine (loopback API, CLI), and live, so the pools are updated
+ in place rather than at the next restart.
"""
roster = _roster(state)
ctx = _group_ctx(state, group_id)