Authorization
Overview
The Chainr platform implements role-based access control (RBAC) with fine-grained permissions to ensure users can only access resources they are authorized to use.
Ownership checks as implemented
The RBAC model further down is the Phase 4 design. What svc-core enforces today is ownership: every user-creatable resource has exactly one of owner_user_id / owner_organisation_id / owner_project_id, and every route checks the caller against it. The helpers live in app/dependency/resource_access.py:
| Helper | Use it for |
|---|---|
verify_resource_read | a route that only reads or references the resource, so a platform-managed row (CHAINR Bot) is admitted |
verify_owner_scope | any create (or edit) whose body names an owner — the owner is client input, so it is checked too |
verify_list_scope | list routes filtered by owner_organisation_id / owner_project_id |
verify_conversation_access | any prompt path that takes a conversation_id — continuing one loads its history into the model |
require_superuser | platform administration that acts on every user's records (/app/users except /me, /dev/*) |
Rules that are easy to miss, each of which was a real hole:
Sub-routes are gated by their parent. A route under
/{knowledge_id},/{agent_id}or/worlds/{world_id}resolves the parent through one helper (_accessible_knowledge,_accessible_agent,_accessible_world) before touching anything beneath it.A reference is a read. Granting a repository, toolkit or skillset to an agent, adding a knowledge base to a repository, naming an agent in a simulation, an evaluation variant or a dashboard tile, or a
cw_*custom worker in a skill graph all let the caller run or retrieve through the referenced resource — so each is checked like opening it directly. Evaluation and dashboard targets are resolved inside background tasks with no request, sobuild_targetscopes them to the owning evaluation or board and fails closed without one.System rows are read-only, and the default refuses them. CHAINR Bot, its guide repository and knowledge base are
is_systemrows with no owner (the one-owner check constraint admits that only when the flag is set).verify_resource_accessrefuses them outright — superusers included — so a route that has not opted in cannot change them; a route that only reads or references one (GET, prompt, list grants, history, a dashboard tile or evaluation variant naming the bot, or granting the guide repository to one's own agent) usesverify_resource_read._accessible_agent/_accessible_knowledgetakeread=Truefor the same split. Memory routes on a system agent — as on every agent — are narrowed to the caller (user_idon svc-ai's/memory), because the agent is shared and its memories are not. See chainr-bot.md and Agent memory below.A decision record is its turn's owner's, and its reviewers'.
GET /app/decisions/{id}holds a person's whole question and answer, so it is read like their conversation or skill run, with one addition. Whoever may open and resolve a flag raised on the turn may read the record too (review.may_review, the queue's own rule): a superuser, the governance editors of the organisation or project the flag is filed under, or of the organisation whose rule raised it there. The response says which (access:owner/reviewer). Anyone else gets 404, as for an id no turn has. Every reviewer read is logged (decision_reads) before the record is served, the read is refused with a 503 if it cannot be, and the log shows on the record for its owner. See decision-record.md.Owners in a request body are client input.
tests/test_owner_scope_guard.pywalks every POST route whose body acceptsowner_project_idand asserts each refuses a project the caller is not in, so a new resource type is covered the day it lands.
svc-bff forwards only app/… paths (backend_path_allowed): /monitoring and the dev router are not the browser's. svc-auth follows a login's return_to only to the platform's own hosts (app/redirects.py).
Organisation membership as implemented
Membership decides who may reach what an organisation or project owns: verify_resource_access admits a member of the owning organisation or project. Until migration 81 nothing ever wrote a membership row, so a creator was refused on the organisation they had just made (Known gap 3). The code is app/services/membership.py.
Roles are defined in code, two of them, and checked from code (ROLE_PERMISSIONS); ensure_roles writes them to the roles / permissions tables at startup for anything reading them there.
| Role | May |
|---|---|
member | what their access allows in each area, see who belongs, leave |
Access per area
A role decides who manages the organisation. What a member may do to what it owns is their access: a level in each of four areas (migration 82, access JSON on user_organisations, user_projects and membership_invites). The registry is app/services/access.py, served to fe-core by GET /app/access/catalogue.
| Area | Kinds |
|---|---|
knowledge | knowledge sources, repositories, uploaded documents |
governance | rules, datasets, evaluations, simulation worlds; the review queue |
dashboards | dashboards |
| Level | May |
|---|---|
writer | also create, and change or delete what they created |
editor | change or delete anything in the area |
An admin is an editor everywhere, whatever their row says (
access.effective).Rules need a governance editor, to create as well as to change: a rule changes every member's use of the organisation's agents, so having written it is not enough (
ResourceKind.create_level/change_own_level)."What they created" is the actor on the resource's first edit-history version (
resource_access.creator_of). A resource moved in from personal work counts as its mover's.Reading never needs a level.
verify_resource_readadmits any member;verify_resource_access(change) andverify_owner_scope(..., model=)(create, and each item of a move) check the level. A 403 names the level held and the one needed.Projects and conversations are outside the areas. A project inside an organisation is managed by the organisation's admins; a conversation is its owner's.
tests/test_access.pyfails on an ownable model that is in neither the areas norOUTSIDE_AREAS, and on aGEThandler that calls a change check.Defaults. An invite carries access (fe-core starts it from the Builder preset: editor of agents, knowledge and dashboards, reader of governance); one that names none grants reader everywhere. Migration 82 gave existing members editor everywhere except governance, where they became writers: close to what they had, without the right to change the organisation's rules they lost the same day. An admin stepping down keeps editor everywhere until someone narrows it.
Superusers pass every check, as before.
An organisation always keeps an admin. The last admin can neither step down nor leave (409); they make someone else an admin first.
Creators join as admin. Creating an organisation or a project adds its creator in the same transaction. Migration 81 backfilled existing ones from each
createdversion's actor (a project without one falls back to its owning user).Every change is a version of the organisation, with its members and pending invites in
children_snapshotandmembers/invitesinchanged_fields, the way a grant versions an agent.
Invites are links, because the stack sends no email. An admin makes one for an email address and passes it on themselves.
The token is 32 random bytes, returned once; only its SHA-256 is stored (
membership_invites.token_hash).The link carries the token in its fragment (
/user/invite#<token>), which browsers never send to a server, and fe-core posts it in a request body (POST /app/invites/preview,/accept), so it is in no access log.It admits only a signed-in user whose email is the one it names, once, for seven days. A new invite for the same address withdraws the old one. Someone already a member consumes the link and keeps their role.
The preview shows the invited address masked (
a***@example.com), so a leaked link reveals little.
Limits worth knowing:
The email match trusts the email on the session. If Auth0 allows email/password sign-up without verification, require verified email there.
On the hosted platform Cloudflare Access sits in front of every hostname. An invite does not get anyone past it: the Access policy must admit the invitee too.
Projects work the same way. register_membership_routes (app/router/app/membership_routes.py) mounts one set of member and invite routes on each router, and a project admin holds project:update where an organisation admin holds org:members / org:invite.
Route ({base} is /organisations/id/{id} or /projects/{id}) | Who |
|---|---|
PATCH {base}/members/{user_id} (role, access) | admin |
DELETE {base}/members/{user_id} | admin, or the member leaving |
GET / POST {base}/invites | admin |
DELETE {base}/invites/{invite_id} | admin |
PUT / DELETE /organisations/id/{id} | admin |
POST /invites/preview, POST /invites/accept | any signed-in user |
Workspaces
Every owner is a workspace (app/services/workspace.py), and every page shows exactly one:
| Workspace | Owns | Parent | URL |
|---|---|---|---|
| Organisation | owner_organisation_id | — | /organisation/<id>/… |
| Personal project | owner_project_id, project owned by a user | the user's Personal | /project/<id>/… |
| Org project | owner_project_id, project owned by an organisation | the organisation | /project/<id>/… |
Projects are one level deep (ck_projects_not_nested, migration 83).
Requests name it. fe-core sends
?workspace=personal | organisation:<id> | project:<id>on every request. Lists return exactly that workspace's rows — its own, what it inherits, and built-ins — each marked with why it is there (origin:own/inherited/required/built_in) and whose it is (home_workspace). Naming none is Personal: there is no mixed listing.GET /workspaceslists the caller's workspaces for the switcher;GET /workspaces/resolvechecks one.Creates land in it. A create that names no owner is given the request's workspace (
app/dependency/workspace.pyowner_for), after the membership and create-level checks.Membership. An organisation's admins are admins of every one of its projects by position, and a personal project's owner of theirs (
membership.implicit_admin; listed as "Admin (via Acme)" / "Owner"). Everyone else joins a project explicitly, and an org project admits only the organisation's members (409 "Invite them to Acme first"); leaving the organisation leaves its projects.Inheritance, by reference. A project declares what it inherits from its parent (
workspace_inheritance,GET/POST/DELETE /projects/{id}/inheritance): a whole kind, future ones included, or one resource — agents, skillsets (with their skills), repositories (with their sources), knowledge, rules, datasets, dashboards. Inherited work is read and used in the project and changed only in the parent. Declaring needs an editor of the kind's area in the project (or an admin) who can read the parent; from a personal parent, only its owner may declare, so a member of someone's personal project cannot expose their other work. Each declaration versions the project. A person's work is readable by the members of their personal projects that inherit it.Required rules. A parent's governance editor can mark a rule Required for all projects; it, and a parent rule pinned to one project, apply in the project with no declaration. A project can add stricter rules of its own, never leave these out.
Governance follows the workspace an invocation happens in. Its own rules apply, plus what it inherits or is required. A person's rules no longer follow them into an organisation's agent. An organisation's quota is one budget for it and its projects, and a review flag lands in the queue of the workspace it was raised in. See
docs/guides/governance.md#whose-rules-apply.References stay inside a workspace. An agent may be granted, and a skillset or repository may bundle, only what its workspace has: its own, inherited, or built-in (
inheritance.require_visible, 422 otherwise). At run time an agent reads only its workspace's knowledge.Copies (
POST /ownership/copy,app/services/copying.py): an agent, skill, skillset, rule, dataset or dashboard can be copied from a project's parent into the project — an editable copy of its own, withcloned_from_id/cloned_from_version— or duplicated in place. What a copied agent uses follows by reference: the project inherits it. Knowledge is inherit-only.Moves.
POST /ownership/previewand/ownership/movemove personal work, with the personal work it depends on, into an organisation or project the mover can create in; refused while anything someone else owns is among it. fe-core offers it from Personal only.Evidence. The evaluation gate and Assurance count an agent's home workspace's evaluations, and the evaluations of the workspace it is used in.
Nothing on a page comes from another workspace. Lists are not the only reads: every record and figure a page shows is the request's workspace's (
app/dependency/workspace.pyrequest_workspace), so a member's personal work never appears in their organisation's pages, nor the other way round. Each kind of record carries the workspace it belongs to and is read by it:What Filed by Read with Uploaded documents owner columns, like any resource (migration 88); the uploader is the actor on the createdversionin_scope— the library list, and the documents a chat may attach (app/services/uploads.py)Conversations, skill runs, generation runs workspace_organisation_id/workspace_project_id(migrations 85, 87)Workspace.made_here, and the personThe change feed each version's snapshot of its resource's owner activity/router.py_in_workspaceUsage ledger, governance activity the workspace stamp ( ledger_stamp)Workspace.stamped— breakdowns, cost cardssvc-ai's traces workspaceon each row (svc-ai migration 22), from theX-Workspaceheader svc-core sends/stats/*?workspace=— Overview cards, usage tiles, Activity's invocationsNetwork tiles, rule targets, pickers, generative catalogues the resources' owners in_scopeWork with no request behind it names its workspace itself (
ai_client.in_workspace): a skill run its run's, an evaluation its experiment's (each cell, since the pool's threads start empty), a tile refresh its board's, a crawl its source's, a chat socket the workspace in its first frame. Every agent's memory routes — an organisation's, a project's, CHAINR Bot, and a personal agent's too — show and clear only the caller's own (Agent memory).
Agent memory
What an agent remembers of a person (svc-ai agent_memories, Memory) is that person's, in that agent's workspace, and nobody else's:
Scoped at storage and at recall. Every row is keyed by agent and user and stamped with the workspace the work was done in. Every read filters on all three (a row from before workspaces were stamped stays with its agent); every write that names a stored row — a correction, a request to forget — acts only on the scope's own rows, and ids never come from a model.
No memory without an agent. A run that names no agent — a stored skill run, a model evaluated with tools — keeps none (
graph_based._memory_store). Before October 2026 such runs, and every agent whose skill graph was on (svc-ai'sSkillEnginedropped the agent's id), used a namespace of the person alone, which recalled what every one of their agents remembered — in every workspace — into whatever ran.Only conversations remember. Evaluations and dashboard tiles run with memory off (
targets.AgentTarget): a tile runs as its board's creator, so on an organisation's board the creator's memories were recalled into what every member saw.Each person manages their own. Every memory route is narrowed to the caller (
_memory_owner), the network views to the viewer (_memory_user); a personal agent's owner no longer sees its project members' memories.Redacted like the answer. What memory keeps passes the run's Output
redact_piirules, and what it recalls the Inputredact_piirules (rules.output_redactor/input_redactor): memory used to store the answer before any Output rule ran.Gone with its owner. Deleting an agent clears its memory once the deletion has committed; deleting an account, an organisation or a project clears what their agents remembered, and an account's deletion everything any agent remembered of them (
services/memory_lifecycle.py).
Platform roles
Membership roles (above) say what a person may do inside an organisation or project. Platform roles say what they may do on CHAIN-R itself, and are assigned in Auth0, not in the app (auth-flow.md):
superuserisusers.is_superuser, the flag every access check above reads first: it passes them all, so a superuser sees and changes every user's resources (built-inis_systemrows still refuse them). Kept in step from Auth0 once its Action sends roles.developerunlocks developer tools (scenario runs) and changes no access check: a developer's pages show only what their membership shows.require_role(PlatformRole.developer)(app/dependency/user/context.py) guards such a route; a superuser holds it too.
The registry is app/services/platform_roles.py; adding a role is one entry there, the role in Auth0, and the route that asks for it.
Authorization Model
Roles
System Roles
admin: Full system access
user: Standard user access
guest: Limited read-only access
Project Roles
owner: Full project control
editor: Read/write project access
viewer: Read-only project access
Permissions
User Permissions
user:read- View user profilesuser:write- Update user profilesuser:delete- Delete user accounts
Project Permissions
project:create- Create new projectsproject:read- View project detailsproject:write- Modify project settingsproject:delete- Delete projectsproject:share- Manage project sharing
Document Permissions
document:create- Upload documentsdocument:read- View documentsdocument:write- Edit document metadatadocument:delete- Delete documentsdocument:download- Download documents
Workflow Permissions
workflow:create- Create workflowsworkflow:read- View workflowsworkflow:write- Modify workflowsworkflow:execute- Run workflowsworkflow:delete- Delete workflows
Permission Checking
Middleware Implementation
def check_permission(required_permission: str):
def decorator(func):
@wraps(func)
async def wrapper(*args, **kwargs):
user = get_current_user()
if not user.has_permission(required_permission):
raise HTTPException(
status_code=403,
detail="Insufficient permissions"
)
return await func(*args, **kwargs)
return wrapper
return decorator
@app.get("/api/projects")
@check_permission("project:read")
async def list_projects():
# Implementation
Database Schema
CREATE TABLE user_roles (
user_id UUID REFERENCES users(id),
role_name VARCHAR(50) NOT NULL,
assigned_at TIMESTAMP DEFAULT NOW(),
assigned_by UUID REFERENCES users(id),
PRIMARY KEY (user_id, role_name)
);
CREATE TABLE role_permissions (
role_name VARCHAR(50),
permission VARCHAR(100),
PRIMARY KEY (role_name, permission)
);
CREATE TABLE project_members (
project_id UUID REFERENCES projects(id),
user_id UUID REFERENCES users(id),
role VARCHAR(50) NOT NULL,
added_at TIMESTAMP DEFAULT NOW(),
added_by UUID REFERENCES users(id),
PRIMARY KEY (project_id, user_id)
);
Access Control Logic
Resource Ownership
Users own their own resources
Project owners control project resources
System admins override ownership rules
Hierarchical Permissions
Higher roles inherit lower role permissions
admin > user > guest
owner > editor > viewer
Context-Aware Access
Project-specific permissions
Time-based access (future)
IP-based restrictions (future)
API Authorization
Protected Endpoints
# Project endpoints
GET /api/projects # project:read
POST /api/projects # project:create
GET /api/projects/{id} # project:read + ownership
PUT /api/projects/{id} # project:write + ownership
DELETE /api/projects/{id} # project:delete + ownership
# Document endpoints
POST /api/documents # document:create + project membership
GET /api/documents/{id} # document:read + project membership
PUT /api/documents/{id} # document:write + project membership
DELETE /api/documents/{id} # document:delete + project membership
Authorization Headers
Authorization: Bearer <jwt_token>
X-Project-ID: <project_uuid> # For project-scoped operations
Permission Management
Role Assignment
Self-service role requests
Admin approval workflow
Automatic role assignment (project creation)
Permission Auditing
Permission change logging
Access attempt logging
Regular permission reviews
Security Considerations
Principle of Least Privilege
Users get minimum required permissions
Permission escalation requires approval
Regular permission cleanup
Secure Defaults
New users start with basic permissions
Explicit permission grants required
Permission revocation on role changes
Testing Authorization
Unit Tests
def test_user_cannot_delete_other_projects():
user = create_test_user()
project = create_test_project(owner=other_user)
with pytest.raises(HTTPException) as exc:
delete_project(project.id, user=user)
assert exc.value.status_code == 403
Integration Tests
End-to-end permission testing
Role transition testing
Permission inheritance testing