Owner jobs and guests' own scheduled jobs are the cron-jobs live plugin's (forms move-ai-agent-cron-jobs-into-a-plugin_u0wa6b, cron-scheduled-in-the-cli-and-mcp_x4nk83). Gone: backend/cron/, schemas/cron.py, /api/cron*, /api/me/cron*, the cron scheduler thread, Settings → Cron and the guests' Tâches planifiées pages, `ai-agent cron` (now a pointer), MCP run_cron_job / set_cron_job / browse cron, the scheduled-jobs core skill, guestDefaults.cronLimits. The core keeps thin contracts: - runs.guest bridge (runs/guestjob.py): a guest's job run as that guest, confined by the core from their record; the plugin only names it. - runs.start's cron stamp → meta.cron. - delivery of a guest job's result (push, mail, mailHtml) off the stamp. - « Discuter »: POST /api/cron-runs/discuss. - runs.cron provider readers (plugins/cron_bridge.py): budget, auto-archive, agents catalog, the agents page's Schedule. - core/cronexpr.py, agents/runconfig.py; context.write create for a new agent definition; ui.pages[].unless; setRoute keeps a Settings page under /settings/p/. - carryover.cron_jobs: /data/cron-jobs.json → the plugin's jobs.json, cronLimits → limits.json, guests' qwen jobs → sonnet (PR #23's decision, superseded). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
326 lines
16 KiB
Python
326 lines
16 KiB
Python
"""Roles, overrides and credential scopes (authz/, docs/permissions.md): the
|
|
catalog holds together, a person is their role plus their overrides, the old
|
|
switches migrate to exactly what they allowed, scopes only narrow, the gate
|
|
refuses by permission (and logs it), and loopback without the host token is
|
|
written down.
|
|
|
|
Imports ``main`` against throwaway paths (no startup event → no threads)."""
|
|
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import tempfile
|
|
import unittest
|
|
from unittest import mock
|
|
|
|
TMP = pathlib.Path(tempfile.mkdtemp())
|
|
for k, v in {"DB_PATH": TMP / "x.db", "TRANSCRIPTS_DIR": TMP / "t",
|
|
"WORKSPACE": TMP, "REPO_DIR": TMP, "ARCHIVE_DIR": TMP / "arch",
|
|
"META_PATH": TMP / "meta.json", "WORKERS_PATH": TMP / "w.json",
|
|
"PROFILES_PATH": TMP / "profiles.json",
|
|
"WORKERS_TRANSCRIPTS_DIR": TMP / "mirror",
|
|
"CRON_PATH": TMP / "cron.json", "NOTIFY_PATH": TMP / "n.json",
|
|
"FORMS_PATH": TMP / "f.json", "UI_STATE_PATH": TMP / "ui.json",
|
|
"NOTIF_READ_PATH": TMP / "nr.json",
|
|
"MAIL_TRIGGER_SENDERS_PATH": TMP / "mt.json",
|
|
"USERS_PATH": TMP / "users.json", "AUTH_PATH": TMP / "auth.json",
|
|
"ROLES_PATH": TMP / "roles.json",
|
|
"SECURITY_LOG_PATH": TMP / "sec.jsonl", "SECURITY_STATE_PATH": TMP / "sec.json",
|
|
"PROJECTS_DIR": TMP / "projects",
|
|
"INTERNAL_API_TOKEN": "tok", "GUEST_HOSTS": "guest.example.test",
|
|
"OWNER_USERS": "gabriel", "READONLY_USERS": "bot",
|
|
"READONLY_API_KEY": "phonekey",
|
|
"SIDECAR_TOKEN": "", "PI_TRANSCRIPTS_DIR": ""}.items():
|
|
os.environ[k] = str(v)
|
|
(TMP / "projects" / "film").mkdir(parents=True)
|
|
|
|
from fastapi.testclient import TestClient # noqa: E402
|
|
|
|
import main # noqa: E402
|
|
from authz import catalog as cat, policy, roles # noqa: E402
|
|
from authz.routes import PUBLIC, TABLE, matcher # noqa: E402
|
|
from security import service # noqa: E402
|
|
from users.caller import OWNER, SESSION_COOKIE, guest_from_record # noqa: E402
|
|
from users.store import UsersStore # noqa: E402
|
|
|
|
DEPS = main.app.state.ai
|
|
ADMIN = "https://admin.example.test"
|
|
EDGE = frozenset({"testclient"})
|
|
OWNER_H = {"X-Internal-Auth": "tok"}
|
|
|
|
|
|
def _reset():
|
|
for u in DEPS.users.all():
|
|
DEPS.users.delete(u["id"])
|
|
roles.store()._data = {"roles": {}}
|
|
roles.store()._save()
|
|
DEPS.security_state.set_locked(False)
|
|
DEPS.security_log.path.unlink(missing_ok=True)
|
|
for seen in (service._denied_seen, service._loopback_seen):
|
|
seen.clear()
|
|
|
|
|
|
class Catalog(unittest.TestCase):
|
|
def test_every_route_permission_is_in_the_catalog(self):
|
|
used = set(TABLE.values()) - {PUBLIC}
|
|
self.assertEqual(used - cat.ALL, set())
|
|
# a route permission no route needs is dead weight; a feature one has none
|
|
self.assertEqual(cat.ROUTE_PERMS - used, set())
|
|
self.assertEqual(cat.FEATURE_PERMS & used, set())
|
|
|
|
def test_tiers_nest_and_the_host_is_the_operators(self):
|
|
self.assertTrue(cat.PERSON_PERMS < cat.ADMIN_PERMS < cat.ALL)
|
|
self.assertEqual(cat.ALL - cat.ADMIN_PERMS, cat.HOST_PERMS)
|
|
self.assertTrue(cat.CORE <= cat.PERSON_PERMS)
|
|
for rid, b in roles.BUILTIN.items():
|
|
self.assertTrue(b["perms"] <= b["ceiling"], rid)
|
|
|
|
|
|
class Roles(unittest.TestCase):
|
|
def setUp(self):
|
|
_reset()
|
|
|
|
def test_built_ins(self):
|
|
s = roles.store()
|
|
self.assertEqual(s.get("operator")["perms"], cat.ALL)
|
|
self.assertFalse(s.get("admin")["perms"] & cat.HOST_PERMS)
|
|
self.assertFalse(s.assignable("operator") or s.assignable("admin"))
|
|
self.assertTrue(all(s.assignable(r) for r in ("member", "guest", "viewer")))
|
|
g = s.get("guest")["perms"]
|
|
self.assertIn("cli.use", g)
|
|
self.assertNotIn("mcp.connect", g)
|
|
self.assertNotIn("runs.start", s.get("viewer")["perms"])
|
|
|
|
def test_edit_within_the_ceiling_only(self):
|
|
s = roles.store()
|
|
with self.assertRaises(ValueError):
|
|
s.update("guest", perms=[*s.get("guest")["perms"], "users.manage"])
|
|
with self.assertRaises(ValueError):
|
|
s.update("operator", perms=["self"])
|
|
with self.assertRaises(ValueError):
|
|
s.update("admin", perms=["accounts.manage"])
|
|
r = s.update("guest", perms=["conversations.read"])
|
|
self.assertEqual(r["perms"], cat.CORE | {"conversations.read"}) # core stays
|
|
self.assertTrue(r["edited"])
|
|
self.assertEqual(s.reset("guest")["perms"], roles.GUEST_DEFAULT | cat.CORE)
|
|
|
|
def test_a_clone_stays_in_the_person_tier(self):
|
|
s = roles.store()
|
|
r = s.clone("admin", "Co-admin")
|
|
self.assertTrue(r["assignable"])
|
|
self.assertEqual(r["perms"], cat.PERSON_PERMS)
|
|
self.assertEqual(r["id"], "co-admin")
|
|
with self.assertRaises(ValueError):
|
|
s.clone("guest", "co-admin")
|
|
s.delete("co-admin")
|
|
self.assertIsNone(s.get("co-admin"))
|
|
|
|
|
|
class People(unittest.TestCase):
|
|
def setUp(self):
|
|
_reset()
|
|
|
|
def test_role_plus_overrides(self):
|
|
u = DEPS.users.create("dom@example.com", "Dom")
|
|
self.assertEqual(policy.role_of(u), "guest")
|
|
self.assertEqual(policy.effective(u), roles.GUEST_DEFAULT | cat.CORE)
|
|
u = DEPS.users.update(u["id"], {"allow": ["mcp.connect"], "deny": ["cli.use", "self"]})
|
|
eff = policy.effective(u)
|
|
self.assertIn("mcp.connect", eff)
|
|
self.assertNotIn("cli.use", eff)
|
|
self.assertIn("self", eff) # a core one can't be denied
|
|
u = DEPS.users.update(u["id"], {"role": "viewer"})
|
|
self.assertNotIn("runs.start", policy.effective(u))
|
|
self.assertIn("mcp.connect", policy.effective(u)) # overrides follow them
|
|
for bad in ({"role": "admin"}, {"role": "operator"}, {"role": "nope"},
|
|
{"allow": ["users.manage"]}, {"allow": ["accounts.manage"]}):
|
|
with self.assertRaises(ValueError, msg=bad):
|
|
DEPS.users.update(u["id"], bad)
|
|
|
|
def test_an_old_switch_is_an_override_relative_to_the_role(self):
|
|
u = DEPS.users.create("dom@example.com", "Dom", cli=False, mcp=True,
|
|
computers={"enabled": True, "max": 5})
|
|
self.assertEqual((u["allow"], u["deny"]), (["mcp.connect", "computers.pair"],
|
|
["cli.use"]))
|
|
self.assertEqual(u["computers"], {"max": 5})
|
|
u = DEPS.users.update(u["id"], {"cli": True, "mcp": False})
|
|
self.assertEqual((u["allow"], u["deny"]), (["computers.pair"], []))
|
|
for k in ("cli", "mcp", "scratchBash", "codeMode", "createProjects"):
|
|
self.assertNotIn(k, u)
|
|
|
|
def test_the_stores_migration_keeps_every_switch(self):
|
|
path = TMP / "old-users.json"
|
|
old = {"dom": {"id": "dom", "email": "d@x.y", "role": "guest", "cli": True,
|
|
"mcp": True, "createProjects": True, "scratchBash": False,
|
|
"computers": {"enabled": True, "max": 4}},
|
|
"eve": {"id": "eve", "email": "e@x.y", "role": "guest"}}
|
|
path.write_text(json.dumps({"users": old}))
|
|
before = {uid: policy.legacy_switches(u) for uid, u in old.items()}
|
|
store = UsersStore(str(path))
|
|
for uid, want in before.items():
|
|
u = store.get(uid)
|
|
self.assertEqual(u["authz"], 1)
|
|
eff = policy.effective(u)
|
|
self.assertEqual({p: p in eff for p in want}, want, uid)
|
|
self.assertEqual(store.get("dom")["computers"], {"max": 4})
|
|
self.assertTrue(list(TMP.glob("old-users.json.bak-authz-*")))
|
|
# a second load changes nothing
|
|
raw = path.read_text()
|
|
UsersStore(str(path))
|
|
self.assertEqual(path.read_text(), raw)
|
|
|
|
def test_a_hand_made_record_reads_its_old_switches(self):
|
|
self.assertIn("runs.codemode", policy.effective({}))
|
|
self.assertNotIn("runs.codemode", policy.effective({"codeMode": False}))
|
|
self.assertIn("mcp.connect", policy.effective({"mcp": True}))
|
|
|
|
|
|
class Scopes(unittest.TestCase):
|
|
def setUp(self):
|
|
_reset()
|
|
|
|
def test_a_scope_only_narrows(self):
|
|
dom = guest_from_record(DEPS.users.create("dom@example.com", "Dom", allow=["mcp.connect"]))
|
|
cli = dom.narrowed("cli")
|
|
self.assertTrue(cli.perms <= dom.perms)
|
|
self.assertTrue(cli.read_perms <= dom.perms)
|
|
self.assertTrue(cli.has("mcp.connect")) # features ride along
|
|
self.assertFalse(cli.allows("inbox.answer", "POST")) # the human answers
|
|
self.assertFalse(cli.allows("self", "GET")) # no devices, drafts, settings
|
|
self.assertTrue(cli.allows("whoami", "GET"))
|
|
self.assertFalse(cli.allows(PUBLIC, "POST")) # a credential doesn't sign in
|
|
viewer = guest_from_record(DEPS.users.create("v@example.com", "V", role="viewer"))
|
|
self.assertFalse(viewer.narrowed("cli").allows("runs.start", "POST"))
|
|
|
|
def test_the_owners_read_only_credentials(self):
|
|
import core.auth as auth
|
|
self.assertTrue(auth.OWNER_PHONE.allows("notifications.ledger", "GET"))
|
|
self.assertFalse(auth.OWNER_PHONE.allows("conversations.read", "GET"))
|
|
self.assertTrue(auth.OWNER_BOT.allows("conversations.read", "GET"))
|
|
self.assertFalse(auth.OWNER_BOT.allows("conversations.read", "POST"))
|
|
for p in ("users.manage", "security.manage", "accounts.manage", "workers.manage"):
|
|
self.assertFalse(auth.OWNER_BOT.allows(p, "GET"), p)
|
|
self.assertTrue(OWNER.allows(None, "POST")) # an unmapped route: operator only
|
|
self.assertFalse(auth.OWNER_BOT.allows(None, "GET"))
|
|
|
|
|
|
class Gate(unittest.TestCase):
|
|
def setUp(self):
|
|
_reset()
|
|
self.pushes = []
|
|
for target, repl in (
|
|
("notifications.service._create_notify",
|
|
lambda deps, d: self.pushes.append(d) or d),
|
|
("core.auth._resolved", lambda: (EDGE | {"127.0.0.1"}, EDGE))):
|
|
p = mock.patch(target, repl)
|
|
p.start()
|
|
self.addCleanup(p.stop)
|
|
self.c = TestClient(main.app, base_url=ADMIN)
|
|
# the owner's host calls: loopback, with the host token
|
|
self.o = TestClient(main.app, base_url="http://127.0.0.1:8096", client=("127.0.0.1", 5000))
|
|
|
|
def guest(self, **fields):
|
|
u = DEPS.users.create("dom@example.com", "Dom", projects={"film": "chat"}, **fields)
|
|
g = TestClient(main.app, base_url="https://guest.example.test")
|
|
g.cookies.set(SESSION_COOKIE, DEPS.auth.open_session(u["id"]))
|
|
return u, g
|
|
|
|
def kinds(self):
|
|
return [e["kind"] for e in DEPS.security_log.events()]
|
|
|
|
def test_a_viewer_reads_and_starts_nothing(self):
|
|
u, g = self.guest(role="viewer")
|
|
self.assertEqual(g.get("/api/conversations").status_code, 200)
|
|
r = g.post("/api/spawn", json={"prompt": "x", "projects": ["film"]})
|
|
self.assertEqual(r.status_code, 403)
|
|
ev = [e for e in DEPS.security_log.events() if e["kind"] == "perm_denied"]
|
|
self.assertEqual(ev[0]["who"], u["id"])
|
|
self.assertEqual(ev[0]["data"]["perm"], "runs.start")
|
|
me = g.get("/api/me").json()
|
|
self.assertEqual(me["roleId"], "viewer")
|
|
self.assertNotIn("runs.start", me["perms"])
|
|
|
|
def test_everyone_reads_the_hubs_name(self):
|
|
# what the app calls the local runner (core/config.HUB_LABEL)
|
|
from core.config import HUB_LABEL
|
|
_, g = self.guest(role="viewer")
|
|
self.assertEqual(g.get("/api/me").json()["hubName"], HUB_LABEL)
|
|
self.assertEqual(self.o.get("/api/me", headers=OWNER_H).json()["hubName"], HUB_LABEL)
|
|
|
|
def test_the_readonly_bot_is_told_what_it_may_read(self):
|
|
# the app draws a page for a permission held for reading too
|
|
# (frontend business/users/access.ts) — else the screenshot bot is
|
|
# sent home from every guarded page
|
|
from core.auth import OWNER_BOT
|
|
from users.routes import _me
|
|
me = _me(DEPS, OWNER_BOT)
|
|
self.assertTrue(me["readonly"])
|
|
self.assertNotIn("lab.settings", me["perms"])
|
|
self.assertIn("self", me["readPerms"])
|
|
self.assertIn("lab.settings", me["readPerms"])
|
|
self.assertNotIn("users.manage", me["readPerms"])
|
|
self.assertNotIn("accounts.manage", me["readPerms"])
|
|
self.assertEqual(self.o.get("/api/me", headers=OWNER_H).json()["readPerms"], [])
|
|
|
|
def test_a_role_edit_reaches_its_people_at_once(self):
|
|
_, g = self.guest()
|
|
# cron.own: « Discuter » on one of their jobs' runs (an empty body: 422
|
|
# once through the gate, 403 when the gate refuses)
|
|
same = {"Origin": "https://guest.example.test"}
|
|
self.assertEqual(g.post("/api/cron-runs/discuss", json={}, headers=same).status_code, 422)
|
|
r = self.o.put("/api/roles/guest", headers=OWNER_H,
|
|
json={"perms": sorted(roles.GUEST_DEFAULT - {"cron.own"})})
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertEqual(g.post("/api/cron-runs/discuss", json={}, headers=same).status_code, 403)
|
|
|
|
def test_the_roles_api(self):
|
|
r = self.o.get("/api/roles", headers=OWNER_H).json()
|
|
self.assertEqual([x["id"] for x in r["roles"]][:5], list(roles.ORDER))
|
|
self.assertTrue({p["id"] for p in r["permissions"]} == cat.ALL)
|
|
DEPS.users.create("dom@example.com", "Dom")
|
|
self.assertEqual(next(x for x in r["roles"] if x["id"] == "guest")["members"], 0)
|
|
r = self.o.post("/api/roles", headers=OWNER_H, json={"clonedFrom": "guest", "name": "Team"})
|
|
self.assertEqual(r.status_code, 200, r.text)
|
|
self.assertEqual(r.json()["clonedFrom"], "guest")
|
|
DEPS.users.update("dom", {"role": "team"})
|
|
self.assertEqual(self.o.delete("/api/roles/team", headers=OWNER_H).status_code, 409)
|
|
DEPS.users.update("dom", {"role": "guest"})
|
|
self.assertEqual(self.o.delete("/api/roles/team", headers=OWNER_H).status_code, 200)
|
|
self.assertEqual(self.o.put("/api/roles/operator", headers=OWNER_H,
|
|
json={"perms": []}).status_code, 400)
|
|
g = TestClient(main.app, base_url="https://guest.example.test")
|
|
g.cookies.set(SESSION_COOKIE, DEPS.auth.open_session("dom"))
|
|
self.assertEqual(g.get("/api/roles").status_code, 403)
|
|
|
|
def test_the_user_view_carries_role_and_switches(self):
|
|
u = DEPS.users.create("dom@example.com", "Dom", allow=["mcp.connect"])
|
|
r = self.o.get("/api/users", headers=OWNER_H).json()["users"][0]
|
|
self.assertEqual((r["role"], r["allow"], r["deny"]), ("guest", ["mcp.connect"], []))
|
|
self.assertIs(r["mcp"], True)
|
|
self.assertIs(r["cli"], True)
|
|
self.assertIn("mcp.connect", r["perms"])
|
|
r = self.o.put(f"/api/users/{u['id']}", headers=OWNER_H, json={"cli": False}).json()
|
|
self.assertEqual(r["deny"], ["cli.use"])
|
|
self.assertIs(r["cli"], False)
|
|
|
|
def test_loopback_without_the_token_is_written_down_once(self):
|
|
lo = TestClient(main.app, base_url="http://127.0.0.1:8096", client=("127.0.0.1", 5000))
|
|
for _ in range(3):
|
|
self.assertEqual(lo.get("/api/conversations").status_code, 200)
|
|
self.assertEqual(self.kinds().count("loopback_tokenless"), 1)
|
|
lo.get("/api/conversations", headers=OWNER_H)
|
|
lo.get("/api/projects", headers={"Authorization": "Bearer tok"})
|
|
self.assertEqual(self.kinds().count("loopback_tokenless"), 1)
|
|
self.assertEqual(self.pushes, []) # logged, never pushed
|
|
|
|
def test_the_phone_key_reads_its_notifications_only(self):
|
|
h = {"X-API-Key": "phonekey"} # the phone: a host-network container
|
|
self.assertEqual(self.o.get("/api/notifications/unread", headers=h).status_code, 200)
|
|
self.assertEqual(self.o.get("/api/conversations", headers=h).status_code, 403)
|
|
self.assertEqual(self.o.post("/api/notifications/state", headers=h, json={}).status_code,
|
|
403)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|