Files
DeepTutor/deeptutor/multi_user/grants.py
Bingxi Zhao (Frank) bd80a4d28a release: v1.5.17
Partners stop being a deployment-wide admin resource and become
per-user: three nested rights (manage / use / neither) replace the
blanket admin gate on the router, each member can build and own their
own, and every person's conversations with a partner stay private to
their account. Grants keep working and now offer only admin-managed
partners. Channel runtime state moves from one directory per channel to
one per partner — copied, not moved, and only when its owner is
unambiguous — so two partners can finally run the same channel.

Around that: a knowledge base can track GitHub repositories and re-sync
their Markdown (#903); Antigravity CLI joins My Agents now that Gemini
CLI is retired (#828); personal WeChat signs in from a QR code drawn in
the browser instead of the server log (#951); a chat account can be
linked to a DeepTutor account with /link; containers re-apply the extras
they declare instead of losing them at compose down (#762); and
`deeptutor doctor` answers whether a workspace is ready to run (#959).

Reliability, largely from community PRs: embeddings survive a
rate-limited provider through key rotation, a retry budget and a global
throttle (#962); MinerU parsing and code execution work on Windows
(#844, #964); indexing fails bounded instead of hanging (#946); MinerU
page-layout blocks stop being indexed as content (#949); voice uploads
carry a MIME the transcription API accepts (#945); and reasoning effort
can be overridden per conversation (#641).

Release plumbing: notes in assets/releases/ver1-5-17.md, v1.5.13
archived, __version__ 1.5.17, README Releases row and all eleven
translations synced.

Two defects found by the release gate and fixed here:

- Six partner routes — the four channel-onboarding endpoints and both
  WeChat QR endpoints — kept the _auth-only mount they had inherited
  from the blanket admin gate, so any signed-in account could start a
  QR login for someone else's partner and write a bot token into its
  channel config. All six now declare _MANAGEABLE, and a sweep test
  asserts no {partner_id} route is left ungated.
- A configured api_key became `str | list[str]` when key rotation
  landed, but ten call sites pass it somewhere that takes one key; a
  list would have rendered into an Authorization header verbatim.
  keypool.primary_api_key reduces at each boundary.

Gates: pre-commit (all 15 hooks), ruff check + format, pytest
5276 passed, web 605 node tests, docs build.
2026-08-25 02:24:35 +08:00

139 lines
5.5 KiB
Python

"""Logical resource grants for non-admin users."""
from __future__ import annotations
from copy import deepcopy
import json
from pathlib import Path
from typing import Any
from .identity import get_user_by_id
from .paths import SYSTEM_ROOT, ensure_system_dirs
GRANTS_DIR = SYSTEM_ROOT / "grants"
def empty_grant(user_id: str) -> dict[str, Any]:
return {
"version": 2,
"user_id": user_id,
"models": {"llm": []},
"knowledge_bases": [],
"skills": [],
# Partners an admin has lent this user. People build their own partners
# now, so a grant is only about someone *else's*: it lets the user talk
# to the named partners — never configure them — and their side of each
# conversation stays private to their account. Same shape as ``skills``
# (``[{"partner_id": ...}]``).
"partners": [],
# Tool whitelists share the partner-config semantics for built-ins:
# ``enabled_tools=None`` means "default" (every tool in the pool),
# ``[]`` means none, a list is an explicit whitelist. MCP tools can
# proxy host-side capabilities, so non-admin runtime access treats
# ``mcp_tools=None`` as deny-by-default until an admin grants explicit
# names. ``cli_apps`` is the same posture for installed CLI apps, keyed
# by app id: each one is third-party code executing in the sandbox, so
# an absent grant is no access rather than all of them.
# ``exec_enabled`` is a tri-state override on top of the
# deployment exec policy: ``None`` follows the policy, ``False`` always
# denies, ``True`` is only honored where the sandbox can actually
# isolate users (SYSTEM isolation).
"enabled_tools": None,
"mcp_tools": None,
"cli_apps": None,
"exec_enabled": None,
}
def _normalize_tool_list(value: Any) -> list[str] | None:
if value is None:
return None
if not isinstance(value, list):
return None
return [str(item).strip() for item in value if str(item).strip()]
def grant_path(user_id: str) -> Path:
ensure_system_dirs()
return GRANTS_DIR / f"{user_id}.json"
def normalize_grant(user_id: str, payload: dict[str, Any] | None) -> dict[str, Any]:
"""Coerce any stored/submitted grant payload into the v2 shape.
v1 grants normalize losslessly for everything that was ever enforced:
``models.embedding`` / ``models.search`` / ``spaces`` had no runtime
consumers and are dropped; absent v2 fields default to unrestricted.
"""
base = empty_grant(user_id)
if not isinstance(payload, dict):
return base
base["user_id"] = user_id
models = payload.get("models") if isinstance(payload.get("models"), dict) else {}
items = models.get("llm") if isinstance(models, dict) else []
if not isinstance(items, list):
items = []
base["models"]["llm"] = [dict(item) for item in items if isinstance(item, dict)]
for key in ("knowledge_bases", "skills", "partners"):
# Read once, then narrow. Two separate ``.get`` calls cannot be narrowed
# together — nothing promises they return the same object — so the
# inline-conditional form left this iterating a possible ``None``.
raw = payload.get(key)
values = raw if isinstance(raw, list) else []
base[key] = [dict(item) for item in values if isinstance(item, dict)]
for key in ("enabled_tools", "mcp_tools", "cli_apps"):
base[key] = _normalize_tool_list(payload.get(key))
exec_enabled = payload.get("exec_enabled")
base["exec_enabled"] = bool(exec_enabled) if isinstance(exec_enabled, bool) else None
return base
def load_grant(user_id: str) -> dict[str, Any]:
path = grant_path(user_id)
if not path.exists():
return empty_grant(user_id)
try:
return normalize_grant(user_id, json.loads(path.read_text(encoding="utf-8")))
except Exception:
return empty_grant(user_id)
def save_grant(user_id: str, payload: dict[str, Any]) -> dict[str, Any]:
user_record = get_user_by_id(user_id)
if user_record is None:
raise ValueError(f"Unknown user id: {user_id}")
_username, record = user_record
if str(record.get("role") or "user") == "admin":
raise ValueError("Admin users use the main workspace and cannot receive assignments.")
grant = normalize_grant(user_id, payload)
validate_grant(grant)
path = grant_path(user_id)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(grant, indent=2, ensure_ascii=False), encoding="utf-8")
return grant
def validate_grant(grant: dict[str, Any]) -> None:
"""Reject accidental secret/path material in grants.
Grants carry logical ids only. Runtime resolution happens server-side.
"""
forbidden = {"api_key", "secret", "password", "token", "path", "base_url"}
def walk(value: Any, trail: str = "grant") -> None:
if isinstance(value, dict):
for key, child in value.items():
lowered = str(key).lower()
if lowered in forbidden or lowered.endswith("_key"):
raise ValueError(f"Grants must not contain secret/path field: {trail}.{key}")
walk(child, f"{trail}.{key}")
elif isinstance(value, list):
for index, child in enumerate(value):
walk(child, f"{trail}[{index}]")
walk(grant)
def public_grant(user_id: str) -> dict[str, Any]:
return deepcopy(load_grant(user_id))