File size: 13,552 Bytes
9ad4b87 c72f0a1 cf09724 c72f0a1 9ad4b87 cf09724 c72f0a1 cf09724 c72f0a1 cf09724 c72f0a1 cf09724 c72f0a1 cf09724 c72f0a1 cf09724 c72f0a1 cf09724 c72f0a1 cf09724 c72f0a1 cf09724 c72f0a1 cf09724 c72f0a1 9ad4b87 868b75a 9ad4b87 c72f0a1 9ad4b87 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 | """Saved View actions through the existing permission checks."""
import copy
import re
from fastapi import HTTPException
from core import external_tools
from . import legacy_action
# One line per refusal: why it was refused, then the call that would succeed.
SHARE_REFUSALS = {
"not_owner": "You cannot change who sees this View, so ask its owner or an Administrator to share it.",
"audience_not_allowed": ("Sharing with everyone is a choice a person makes on screen, "
"so name each person in entries instead."),
"blank_user": "An entry has an empty user, so set user to the username of an active person in this workspace.",
"grants_changed": ("This View's audience changed after it was read, "
"so call views share again without expect and confirm the new preview."),
"grant_exceeds_role": ("Can edit is above your own access to this View, "
"so set role to view for each new editor or ask its owner to grant edit."),
"grant_exceeds_audience": ("Only this View's owner or an Administrator can share it with everyone, "
"so name each person in entries instead."),
"revoke_not_yours": ("You can remove only people you added to this View, "
"so keep everyone else in entries and share again."),
"field_not_shared": ("This View shows a field that is still private to its creator, "
"so hide that field in the View or ask its creator to share it, then share again."),
"unknown_people": ("A person in entries has no active account in this workspace, "
"so set user to a username, not a display name or email."),
"forbidden": "Your account cannot share this View, so ask its owner or an Administrator to share it.",
"view_share_failed": "This View's access could not be saved, so send the same share call again.",
}
_SHARE_FIELDS = ("database", "view_id", "entries", "expect")
_CALL_FIELDS = ("action", "arguments", "intent", "about", "purpose")
def _share_refusal(code, status=403):
"""Raise the one-line refusal for a share code."""
import routes_shares
raise routes_shares.err(status, code, SHARE_REFUSALS[code])
def _listed(names):
names = list(names)
if len(names) < 2:
return "".join(names)
return ", ".join(names[:-1]) + " and " + names[-1]
def share_arguments_fix(call):
"""Name the first wrong part of a views share call and the shape that succeeds."""
shape = "each entry is user (a username) and role (view or edit)"
if not isinstance(call, dict):
return "The call is not an object, so send action share with arguments database, view_id and entries."
stray = [str(key) for key in call if key not in _CALL_FIELDS]
if stray:
return (_listed(stray) + (" sit" if len(stray) > 1 else " sits") + " beside action, so move "
+ ("them" if len(stray) > 1 else "it") + " inside arguments, which holds database, view_id, entries and optional expect.")
args = call.get("arguments")
if not isinstance(args, dict):
return "arguments is missing or not an object, so send arguments with database, view_id and entries."
unknown = [key for key in args if key not in _SHARE_FIELDS]
if unknown:
return (_listed(map(str, unknown)) + (" are not share arguments" if len(unknown) > 1 else " is not a share argument") + ", so send only database, view_id, "
"entries and optional expect, where " + shape + ".")
missing = [key for key in ("database", "view_id", "entries") if key not in args]
if missing:
return ("arguments has no " + " or ".join(missing) + ", so add " + ("them" if len(missing) > 1 else "it") + ": database and view_id are text, "
"and entries is a list where " + shape + ".")
for key in ("database", "view_id"):
if not isinstance(args[key], str) or not args[key].strip() or key == "view_id" and len(args[key]) > 120:
return key + " is not a usable id, so set it to the text id that the View list returns."
for key in ("entries", "expect"):
rows = args.get(key)
if key not in args:
continue
if not isinstance(rows, list):
return key + " is not a list, so send a list where " + shape + ", or [] to make the View private."
if len(rows) > 200:
return key + " names more than 200 people, so share with at most 200 people in one call."
for row in rows:
if not isinstance(row, dict):
return key + " holds a plain value, so send objects where " + shape + "."
extra = [name for name in row if name not in ("user", "role")]
if extra or "user" not in row or "role" not in row:
return (key + " has an entry with " + (_listed(map(str, extra)) or "a missing field")
+ ", so give every entry exactly user (a username) and role (view or edit).")
if not isinstance(row["user"], str) or not 1 <= len(row["user"]) <= 120:
return key + " has a user that is not a username, so set user to a username of 1 to 120 characters."
if row["role"] not in ("view", "edit"):
return key + " has a role other than view or edit, so set role to view for Can view or edit for Can edit."
return "The share arguments do not match, so send database, view_id and entries, where " + shape + "."
def _share_source(session, args):
"""Resolve source ownership on a detached canonical workspace before revealing the audience."""
import routes_external
import routes_shares
from core import shares
routes_external._assert_database_scope(session, args["database"])
snapshot = routes_shares._FieldReadSnapshot(session.runtime)
topic, source_owner, view = routes_shares._find_view_record(
session, args["view_id"], _snapshot=snapshot)
workspace = routes_shares._field_storage_keys(args["database"])[0]
# A missing View and another person's View read the same, so the refusal reveals nothing.
if not view or not source_owner or f"{topic}_table_workspace" != workspace:
_share_refusal("not_owner")
rec = shares.grants("view", args["view_id"], st=session.runtime)
if rec["owner"]:
allowed = shares.may_administer(
"view", args["view_id"], session.uname, is_admin=session.admin, st=session.runtime)
else:
allowed = session.admin or source_owner == session.uname
if not allowed:
_share_refusal("not_owner")
return snapshot, topic, source_owner, view, rec
def _receipt_access(ctx, args):
"""Check current source ownership and share authority without consuming workspace corrections."""
_share_source(ctx.session, args)
return True
def _unknown_people_refusal(unknown, people):
"""Name each unknown username and, for an exact display name match, the username to use."""
import routes_shares
names = {}
for username, row in people.items():
label = str(row.get("name") or "").strip().lower()
if label:
names.setdefault(label, []).append(username)
hints = [names[who][0] + " for " + str(people[names[who][0]].get("name"))
for who in unknown if len(names.get(who, ())) == 1]
fix = ("set user to " + ", ".join(hints)
+ (", and to a username for the rest" if len(hints) < len(unknown) else "")
if hints else "set user to a username, not a display name or email")
raise routes_shares.err(400, "unknown_people", "No active person in this workspace has the username "
+ ", ".join(unknown) + ", so " + fix + ".")
def share(ctx, args):
"""Replace a named audience through the on-screen share writer and its permission ceiling."""
import routes_external
import routes_shares
try:
return _share(ctx, args)
except HTTPException as exc:
error = (exc.detail.get("error") or {}) if isinstance(exc.detail, dict) else {}
code = error.get("code")
# A 403 without a published code reaches the AI as forbidden. It names the share fix.
if code == "forbidden" or (exc.status_code == 403 and code not in SHARE_REFUSALS
and code not in routes_external.MCP_RESULT_CODES):
raise routes_shares.err(403, "forbidden", SHARE_REFUSALS["forbidden"]) from exc
raise
def _share(ctx, args):
import routes_external
import routes_shares
from core import shares
session = ctx.session
routes_external._assert_write_scope(session, "views", {"action": "share", "arguments": args})
snapshot, topic, source_owner, view, rec = _share_source(session, args)
entries = copy.deepcopy(args["entries"])
if any(row["user"].strip().lower() in {shares.EVERYONE, "everyone"} for row in entries):
_share_refusal("audience_not_allowed", 400)
if any(not row["user"].strip() for row in entries):
raise routes_shares.err(400, "unknown_people", SHARE_REFUSALS["blank_user"])
people = {row["username"].strip().lower(): row for row in routes_shares._people(session.tenant)}
unknown = sorted({row["user"].strip().lower() for row in entries} - people.keys())
if unknown:
_unknown_people_refusal(unknown, people)
keys = routes_shares._view_field_keys(view)
definitions = routes_shares._view_field_definitions(
session, f"{topic}_table_workspace", keys, _snapshot=snapshot)
defs = {key: row[0] or {"key": key, "label": key} for key, row in definitions.items()}
receivers = {row["user"].strip().lower(): row["user"].strip().lower() for row in entries}
blocked = routes_shares._admin_walled(
session, routes_shares._field_storage_keys(f"{topic}_table_workspace")[2], defs, receivers)
try:
out = routes_shares._put_share(
"view", args["view_id"], {"entries": entries}, session,
_view_snapshot=snapshot, _source_owner=source_owner, _expect=args.get("expect"),
_notify=False)
except HTTPException as exc:
code = (exc.detail.get("error") or {}).get("code")
if code == "view_share_failed":
reference = re.search(r"\bVS-[0-9A-F]{8}\b", str((exc.detail.get("error") or {}).get("message") or ""))
raise routes_shares.err(exc.status_code, code, SHARE_REFUSALS[code] + (
" If it fails again, report reference " + reference[0] + "." if reference else "")) from exc
if code in SHARE_REFUSALS:
raise routes_shares.err(exc.status_code, code, SHARE_REFUSALS[code]) from exc
raise
name = str(view.get("name") or "A View")
audience = [{"user": row["user"], "name": people[row["user"]].get("name") or row["user"],
"role": row["role"], "hiddenFields": [
{"key": key, "name": str(defs[key].get("label") or key)}
for key, who in blocked.items() if row["user"] in who]}
for row in out["entries"]]
warnings = []
for row in audience:
role = "Can edit" if row["role"] == "edit" else "Can view"
hidden = ", ".join(field["name"] for field in row["hiddenFields"])
warnings.append(f"{row['name']} will have {role} on {name}"
+ (f" with hidden fields {hidden}." if hidden else "."))
if not audience:
warnings.append(f"{name} will be private.")
return {"view_id": args["view_id"], "view": {"id": args["view_id"], "name": name,
"database": args["database"], "owner": out["owner"]}, "audience": audience,
"current_entries": rec["entries"], "entries": out["entries"], "warnings": warnings}
_ENTRIES = {"type": "array", "maxItems": 200, "items": {"type": "object", "properties": {
"user": {"type": "string", "minLength": 1, "maxLength": 120},
"role": {"type": "string", "enum": ["view", "edit"]}},
"required": ["user", "role"], "additionalProperties": False}}
GROUP = {
"name": "views", "title": "Views",
"guide": "Create, change, delete or share Views with named people. Share returns a preview, and confirm_change applies it. An empty audience makes a View private. A person chooses sharing with everyone on screen. "
"Upsert preserves config.filters groups using conj and nodes, or a list with conj and children groups. "
"Root filterConj selects and or or for a list. Unsupported or lossy filter shapes refuse before saving.",
"actions": {
"upsert": legacy_action("view_upsert"),
"delete": legacy_action("view_delete", destructive=True),
"share_preview": legacy_action("view_share_preview"),
"share": {"read": False, "destructive": False, "confirm": True,
"schema": {"type": "object", "properties": {
"database": {"type": "string", "minLength": 1},
"view_id": {"type": "string", "minLength": 1, "maxLength": 120},
"entries": _ENTRIES, "expect": _ENTRIES},
"required": ["database", "view_id", "entries"], "additionalProperties": False},
"handler": share, "receipt_access": _receipt_access},
**{"view." + action: legacy_action(
"view_object", action=action,
read=action in external_tools._OBJECT_READ_ACTIONS["view_object"],
destructive=action == "delete") for action in external_tools._VIEW_ACTIONS},
},
}
|