Files
LLeMbas/src/lembas/security/permissions.py
T
Jaroslav Beneš 21001f2eb8 Knowledge, notes, memory and skills, and a harness to make them used
Four places a model can reach for, differing in who writes a record and how it
gets in front of the model.

**Knowledge** is uploaded by a person and searched by the model. It goes through
`services/files.py:prepare` — the same pipeline as a chat attachment — so the
same PDF produces the same text whichever way it arrived, and `Document` carries
the same content columns as `Attachment` for the same reason.

**Notes** are written by the model and edited by you. Too long to inject, so
they are searched.

**Memory** is short facts, and every one of them goes into every request. That
single decision is where the rest of its design comes from: records are capped
short, the block has a budget, there is no search tool because the model is
already looking at them, and they are not shareable — a record about a person is
not content to hand round.

**Skills** are saved procedures. Only the name and description are injected; the
body is fetched when the model decides one applies, which is what makes a
hundred skills affordable. A model may write and revise its own — the safety
story is not a gate but a record: every revision is kept, attributed and
revertible. A model that has just read a hostile page can save a skill that
outlives the conversation, and the honest mitigation is that it is visible and
undoable rather than that it was prevented.

**The harness** is why any of it gets used. A model handed a tools array
ignores it and answers from recall, because nothing in the request suggests
otherwise. `services/harness.py` assembles a preamble from what this chat
actually has: when to reach for each tool, the memories, the skill index.

This is an exception to "system prompts are precedence, not concatenation", and
a deliberate one. That rule governs the three *authored* layers and is
untouched — exactly one still wins. The harness is a different axis: it
describes the machinery rather than the behaviour, nobody authored it, and there
is nothing for it to disagree with. It is prepended to whichever authored prompt
won, in one system message, since several endpoints reject a second.

Supporting changes:

- **Sharing**, in one helper. `visible_to()` is the only definition of who can
  see a library item and every listing and tool goes through it. Sharing grants
  *reading*; two people editing one note with no history and no merge is worse
  than copying it. **Administrators do not bypass this** — they bypass
  permissions elsewhere because an admin can grant themselves those anyway, but
  reading somebody's private notes is a different act.
- **FTS5**, created by `db/migrations.py:ensure_fts` with the triggers an
  external-content index needs. Idempotent, like the column sync beside it.
  Terms are ANDed and then ORed: the caller is usually a model writing a whole
  question, and requiring every word loses the match on one absent term.
- **The attach button is a menu** — file, image, a web page, or a document from
  the library. Attaching a document copies it, because history must not change
  when a document is edited later.
- **A URL fetcher with an SSRF guard.** This server can reach the router, the
  other services on the box and LLeMbas itself, and the address can come from a
  model. Private ranges are refused *after resolution* and redirects are followed
  by hand so every hop is checked. An admin can open it deliberately.
- **Model capabilities split** into protocol support and a toggle per built-in
  tool. Rows predating the split have no `tool_*` keys, and absent counts as on
  when `tools` is on — otherwise an upgrade silently takes web search away from
  every model already configured for it.

Also fixes the test fixture, which built the schema with `create_all` and so ran
against a database without the FTS tables production has; it now runs
`sync_schema`, the same path startup takes.

430 tests, ruff clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-21 19:43:57 +02:00

222 lines
6.6 KiB
Python

"""Permission vocabulary and resolution.
The model is deliberately small: a flat set of named booleans, granted by an
instance-wide baseline and widened by group membership. Permissions are a union
across groups -- being in a second group can only ever grant more, never take
away. That is the behaviour people expect, and the alternative (a deny that
wins) makes "why can this user not do X" unanswerable without simulating every
group.
Administrators bypass the whole thing. There is no permission that can be
withheld from an admin, because an admin can grant it back to themselves in two
clicks; pretending otherwise would be theatre.
Model *access* is separate and lives in models_visible_to(): a permission says
what a user may do, model access says which models they may do it with.
"""
from __future__ import annotations
from dataclasses import dataclass
from sqlalchemy import select
from sqlalchemy.orm import Session as DBSession
from lembas.db.models import Connection, Model, User
@dataclass(frozen=True)
class PermissionDef:
key: str
label: str
description: str
default: bool
group: str
# The order here is the order they render in the admin UI.
PERMISSION_DEFS: tuple[PermissionDef, ...] = (
PermissionDef(
"chat.create", "Start chats", "Create new conversations.", True, "Chat"
),
PermissionDef(
"chat.delete", "Delete chats", "Delete their own conversations.", True, "Chat"
),
PermissionDef(
"chat.system_prompt",
"Set system prompts",
"Give an individual chat its own system prompt.",
True,
"Chat",
),
PermissionDef(
"chat.params",
"Adjust sampling",
"Change temperature, top-p and similar per chat.",
False,
"Chat",
),
PermissionDef(
"chat.model_select",
"Choose the model",
"Switch a chat to a different model. Without this, chats use the default.",
True,
"Chat",
),
PermissionDef(
"folder.manage",
"Manage folders",
"Create, rename, nest and delete folders.",
True,
"Workspace",
),
PermissionDef(
"files.upload",
"Attach files",
"Attach images, PDFs and text files to a message. Images only reach "
"models marked as having vision.",
True,
"Workspace",
),
PermissionDef(
"tools.web_search",
"Search the web",
"Let a model look things up while it answers. Only offered to models "
"marked as supporting tools, and only when web search is configured.",
True,
"Chat",
),
PermissionDef(
"audio.transcribe",
"Dictate messages",
"Speak a message instead of typing it. Needs a transcription endpoint.",
True,
"Audio",
),
PermissionDef(
"audio.listen",
"Play replies aloud",
"Have a reply read out. Needs a speech endpoint.",
True,
"Audio",
),
PermissionDef(
"library.use",
"Use the library",
"Keep knowledge documents, notes, memories and skills of their own.",
True,
"Library",
),
PermissionDef(
"library.share",
"Share library items",
"Give other people, or a group, access to their documents, notes and "
"skills. Sharing grants reading only.",
False,
"Library",
),
PermissionDef(
"tools.knowledge",
"Search their knowledge",
"Let a model search the documents this user has collected.",
True,
"Library",
),
PermissionDef(
"tools.notes",
"Read and write notes",
"Let a model keep its own notes for this user, and read them back later.",
True,
"Library",
),
PermissionDef(
"tools.memory",
"Remember things",
"Let a model record short facts about this user, shown to it on every "
"turn.",
True,
"Library",
),
PermissionDef(
"tools.skills",
"Use and write skills",
"Let a model follow saved instructions, and write new ones. Every "
"change is recorded and can be rolled back.",
True,
"Library",
),
)
PERMISSION_KEYS = tuple(d.key for d in PERMISSION_DEFS)
DEFAULT_PERMISSIONS = {d.key: d.default for d in PERMISSION_DEFS}
def permission_groups() -> dict[str, list[PermissionDef]]:
"""Definitions bucketed by their UI section, preserving declaration order."""
grouped: dict[str, list[PermissionDef]] = {}
for definition in PERMISSION_DEFS:
grouped.setdefault(definition.group, []).append(definition)
return grouped
def baseline_permissions(db: DBSession) -> dict[str, bool]:
"""Instance-wide permissions for a user in no group at all."""
from lembas.services import settings_store
stored = settings_store.get(db, "default_permissions") or {}
return {key: bool(stored.get(key, DEFAULT_PERMISSIONS[key])) for key in PERMISSION_KEYS}
def resolve(db: DBSession, user: User | None) -> dict[str, bool]:
"""Effective permissions for a user."""
if user is None:
return dict.fromkeys(PERMISSION_KEYS, False)
if user.is_admin:
return dict.fromkeys(PERMISSION_KEYS, True)
effective = baseline_permissions(db)
for group in user.groups:
granted = group.permissions_json or {}
for key in PERMISSION_KEYS:
# Union: a group can only widen. Absent means "no opinion", not
# "deny", so a group need only list what it adds.
if granted.get(key):
effective[key] = True
return effective
def has(db: DBSession, user: User | None, key: str) -> bool:
return resolve(db, user).get(key, False)
def models_visible_to(db: DBSession, user: User | None) -> list[Model]:
"""Models a user may start a chat with, in display order.
A model is visible when it is enabled, its connection is enabled, and
either it is public or the user belongs to one of its groups.
"""
query = (
select(Model)
.join(Connection)
.where(Model.enabled.is_(True), Connection.enabled.is_(True))
.order_by(Model.position, Model.model_id)
)
candidates = list(db.scalars(query))
if user is not None and user.is_admin:
return candidates
if user is None:
return []
member_of = {group.id for group in user.groups}
return [
model
for model in candidates
if model.public or member_of.intersection({g.id for g in model.groups})
]
def can_use_model(db: DBSession, user: User | None, model_id: str) -> bool:
return any(model.model_id == model_id for model in models_visible_to(db, user))