runloopable / api /tool_groups /members.py
fsanyoto's picture
Deploy AIOS web (React glide grid + FastAPI slice)
8133df9 verified
Raw History Blame Contribute Delete
8.55 kB
"""Member data permissions for administrators, through the on-screen permission writer."""
import copy
from fastapi import HTTPException
FORBIDDEN = "Only an administrator can read or change a member's data permissions."
WIDENING_WARNING = ("This change removes the business unit restriction on {database}, "
"so confirm_change needs the confirmation phrase.")
def _require_admin(session):
"""Refuse a caller without the administrator role before any account is read."""
import routes_admin
from deps import err
try:
routes_admin.admin_gate(session)
except HTTPException as exc:
raise err(403, "forbidden", FORBIDDEN) from exc
def _account(session, username):
"""Read an active account strictly within this session's workspace."""
import routes_admin
from core import store
from deps import err
uname = str(username).strip().lower()
tenant = str(session.runtime.tenant.slug).strip().lower()
if routes_admin._tenant_of(session.user) != tenant:
raise err(403, "forbidden", FORBIDDEN)
rec = (store.get("users", fresh=True) or {}).get(uname)
if not isinstance(rec, dict) or not rec.get("active", True) or routes_admin._tenant_of(rec) != tenant:
raise err(404, "no_such_user", "That account is not active in this workspace.")
return uname, rec
def read_permissions(ctx, args):
"""Return the member's database blocks without running the editor's write-on-read cleanup."""
import routes_admin
import routes_external
from core import external_access, perm_scope, perms, users
from deps import err
session = ctx.session
_require_admin(session)
database = args.get("database")
uname, rec = _account(session, args["username"])
member = users._public(uname, rec)
is_admin = perms.is_admin(member)
scope = routes_external._key_scope(session)[1]
rows = []
for module in routes_admin._perm_modules(session):
key = module["key"]
if database not in (None, key) or not external_access.database_allowed(scope, key):
continue
entry = perm_scope.entry(member, key) or {}
rows.append({"database": key, "label": module.get("label") or key,
"access": perm_scope.may_read(member, key, st=session.runtime),
"filter": None if is_admin else copy.deepcopy(entry.get("filter")),
"hiddenFields": [] if is_admin else list(entry.get("hiddenFields") or [])})
if database is not None and not rows:
raise err(404, "no_database", "That database is not available in this workspace.")
return {"username": uname, "is_admin": is_admin,
"access_state": routes_admin.database_access_token(rec), "rows": rows, "count": len(rows)}
def _plan(session, args):
"""Validate one database block in the writer's order and diff it, writing nothing."""
import routes_admin
import routes_external
from core import users
from deps import err
uname, rec = _account(session, args["username"])
key = str(args["database"]).strip()
entry = args["entry"]
if uname == session.uname:
raise err(400, "self_perms", "Ask another administrator to change your access.")
governed = {row["key"] for row in routes_admin._perm_modules(session)}
if key not in governed:
raise err(404, "no_database", "That database is not available in this workspace.")
token = routes_admin.database_access_token(rec)
if args.get("expect") not in (None, token):
# The confirm replays this plan with the pinned expect, so a changed account reads as stale.
raise err(409, "confirmation_stale", "This member's access changed. Read it again and preview the change again.")
submitted = {field: copy.deepcopy(entry[field]) for field in users.DATABASE_ENTRY_KEYS if field in entry}
cleaned = routes_admin._clean_perms({key: submitted}, governed_keys=governed, session=session,
stored=rec.get("perms"))
folded = routes_admin._fold_legacy_scope(rec, cleaned)
try:
routes_admin._guard_bu_widening(rec, folded, False)
widening = False
except HTTPException as exc:
if ((exc.detail or {}).get("error") or {}).get("code") != "bu_widening":
raise
widening = True
candidate = {field: copy.deepcopy(folded[key][field]) for field in users.DATABASE_ENTRY_KEYS}
stored = (rec.get("perms") or {}).get(key)
before = copy.deepcopy(stored) if isinstance(stored, dict) else None
after = {**(before or {}), **candidate}
diff, _ = routes_external._diff_documents(
{f"members/{uname}/perms/{key}": {"before": before, "after": after}}, limit=None)
return {"diff": diff, "warnings": [WIDENING_WARNING.format(database=key)] if widening else [],
"affected": {"ids": [uname, key], "count": len(diff), "ranges": []},
"revision": {"account": uname, "access_state": token},
"expect": token, "widening": widening,
"username": uname, "database": key, "before": before, "after": after}
def set_permissions(ctx, args):
"""Preview a database block, then apply it through the editor's compare-and-set on confirm."""
import routes_admin
import routes_external
session = ctx.session
_require_admin(session)
if isinstance(session.runtime, routes_external._PreviewRuntime):
return _plan(session, args)
out = routes_admin.set_database_block(
session, args["username"], args["database"], args["entry"],
expect=args.get("expect"), confirm_widen=bool(args.get("confirm_widen")))
return {**out, "revision": {"account": out["username"], "access_state": out["access_state"]}}
def _receipt_access(ctx, args):
"""A committed change stays readable to an administrator of this workspace."""
_require_admin(ctx.session)
_account(ctx.session, args["username"])
return True
_FILTER = {"type": ["object", "null"],
"description": "Row filter as conj and nodes, where each node is a colId, op and value leaf. null removes it."}
_ENTRY = {"type": "object", "properties": {
"access": {"type": "boolean"},
"filter": _FILTER,
"hiddenFields": {"type": "array", "maxItems": 500, "items": {"type": "string", "minLength": 1, "maxLength": 200}}},
"required": ["access"], "additionalProperties": False}
_USERNAME = {"type": "string", "minLength": 1, "maxLength": 120}
_DATABASE = {"type": "string", "minLength": 1, "maxLength": 200}
GROUP = {
"name": "members", "title": "Members",
"guide": "Administrators read and set a member's data permissions per database: access, row filter and hidden fields. "
"set_permissions returns a preview with the before and after block, and confirm_change applies it. "
"A change that removes a business unit restriction needs the confirmation phrase. "
"You cannot change your own permissions.",
"actions": {
"permissions": {"read": True, "destructive": False, "confirm": False,
"schema": {"type": "object", "properties": {
"username": _USERNAME, "database": _DATABASE},
"required": ["username"], "additionalProperties": False},
"handler": read_permissions,
"example": {"username": "<username>", "database": "<database>"}},
"set_permissions": {"read": False, "destructive": False, "confirm": True,
"schema": {"type": "object", "properties": {
"username": _USERNAME, "database": _DATABASE, "entry": _ENTRY,
"expect": {"type": "string", "minLength": 1, "maxLength": 128,
"description": "access_state from permissions. The preview sets it."},
"confirm_widen": {"type": "boolean",
"description": "The preview sets it when the change removes a business unit restriction."}},
"required": ["username", "database", "entry"], "additionalProperties": False},
"handler": set_permissions, "receipt_access": _receipt_access,
"example": {"username": "<username>", "database": "<database>",
"entry": {"access": True, "filter": None, "hiddenFields": []}}},
},
}