Permissions (row-level / table-level / storage and complex authorization)
Overview and use cases
Agentbase's authorization model: permission actions × roles → $permissions strings, configured separately on tables (Table), rows (Row), and buckets / files, and taking effect together with the rowSecurity / fileSecurity switches. When to use: implementing access control such as "users can only access their own data", "team sharing", "admin visibility"; as well as complex scenarios where authorization must be granted to others under Client SDK constraints.
Prerequisites
Table structure and bucket configuration are delivered by the server side (API Key) or the Console; the API Key is never given to browsers / mobile clients.
The SDK's
Permission/Rolehelper classes (Permission.read(Role.user(id))form in JS; Java / Python are isomorphic).
Permission model
Actions and mount points
| Action | Table $permissions | Row $permissions | Effect |
|---|---|---|---|
read | Yes | Yes | Read all rows of a table / read specified rows |
create | Yes (required to create rows) | Meaningless | Who can create rows in the table |
update / delete | Yes | Yes | Modify / delete any rows / specified rows |
write | Yes | Yes | create+update+delete (excluding read) shortcut |
Decision model (rowSecurity)
| Operation | rowSecurity: false (default) | rowSecurity: true |
|---|---|---|
| Create row | Must have table-level create | Still must have table-level create |
| Read / modify / delete row | Table-level permission only | Table-level or that row's permission (canRead(row) = table.read OR row.read) |
Table-level permission is a "grant", not a "restriction": after table-level read(Role.users()) is configured, all session users can read all rows, and row-level $permissions no longer constrains anything. enabled: false disables the whole table for ordinary users, while the API Key can still manage it.
Role constant quick reference
| Role | Meaning | Typical use |
|---|---|---|
Role.any() | Any request (including visitors without a session) | Public reads; use cautiously for writes |
Role.guests() | Visitor without a session | Pre-login exclusive content |
Role.users() | Any user with a session (including anonymous sessions) | Resources available after login |
Role.user(userId) | Specified user | Row owner |
Role.team(teamId[, role]) | Team (member role can be restricted) | Team sharing |
Role.member(membershipId) | Specified membership relation | Fine-grained team authorization |
Role.label(labelId) | Users with labels | Admins / reviewers |
Permissions are a union of allows; there are no "explicit deny" rules.
Usage workflow (recommended pattern: creator exclusive)
Grant only
createwhen creating the table:createTable({ permissions: [Permission.create(Role.users())], rowSecurity: true, enabled: true }); do not add ordinary users' table-levelread/update/delete/write, otherwise row-level isolation is bypassed.Omit
permissionswhen the client creates rows: the server automatically writes the creator'sread/update/delete; business fields such asownerIdcan be added, but they are not the permission boundary.When explicit expression is needed:
permissions: [Permission.read(Role.user(自己)), Permission.update(Role.user(自己)), Permission.delete(Role.user(自己))]; do not accept arbitraryownerIdwrapped inRole.user()from page parameters.Creating rows on behalf of users on the server: API Key requests have no "current end user"; omitting
permissionsyields empty row permissions—you must first obtain the user ID from a trusted session / JWT, then explicitly grant that user.Team collaboration: use
Role.team(teamId)instead of the uploader's personalupdate/deletefor files / rows, avoiding the 403 where "only the uploader can delete".
Key boundary: Client SDK hasRole constraint
When the Client SDK creates / updates rows, every Role in permissions must pass authorization.hasRole(role):
✅
Role.user(自己的 ID), joinedRole.team(...),Role.any()/Role.users();❌
Role.user(别人的 ID), unjoined teams → 401;Role.label('admin')only if you actually have that label;The Server SDK (API Key) skips this whole set of checks and can authorize freely.
Therefore the Client SDK cannot grant row-level permissions to others; when needed, go through a Function proxy:
The frontend creates rows containing only itself.
When sharing is needed, call a Function; inside the Function, use the Server SDK to read the row's
$permissions, verify the caller is indeed the row owner (x-appwrite-user-id), merge the target user / label permissions,updateRowsubmit the full set, and leave an audit trail.Optionally configure an authorization record table (
resourceId/granteeId/accessLevel/grantedBy); the frontend directly queries "what am I authorized for", while changes are still done by the Function.
Key boundary: updateRow full replacement
When updateRow is passed with permissions, it is a full replacement, not an incremental append: passing only new permissions loses all original permissions. The correct approach is to first use getRow to read $permissions, add and remove on a copy, then submit the whole set. If permissions is not passed, the original permissions are kept.
Storage permissions (bucket / file)
Two-layer model: bucket level is the "front gate", and file level is the "room door" when
fileSecurity: true; bucket-level permission grants directly, otherwise decisions fall back to file-level$permissions.Insufficient permission returns 404 (
file_not_found), not 403—a security design that hides file existence; when troubleshooting, check permissions first.fileSecurity: false: judged by bucket level only; no match means 401.For handling "looks like 404" caused by lost cookies in cross-domain
<img>scenarios (Blob URL / File Token), see storage.md.The Function proxy likewise applies to granting bucket files to other users / teams.
Errors and boundaries
401
Permissions must be one of: (any, users, user:xxx, user:xxx/unverified, users/unverified): the Client SDK used a row-level role that does not belong to you or is unsupported.Table-level
write(Role.users())unexpectedly opens update/delete to everyone; do not usewriteas "open both read and write".Anonymous sessions count toward
Role.users(); for fully anonymous writes useRole.any()and guard against abuse yourself.Permission changes take effect immediately; row lists already cached on the client are not automatically invalidated.
SDK Category Differences
Client SDK: subject to the
hasRoleconstraint (see above); everyday row / file reads and writes, and querying data visible to yourself.Server SDK: skips
hasRole; configure table / bucket baseline permissions, authorize on behalf of users, bulk governance.Console SDK: does not handle business authorization; configure baselines only in the Console UI.
Difference entry points: client-sdk/web.md,
server-sdk/nodejs.md.
Example Guide
Examples by language are centralized in the language tree
examples/; for the complete Function proxy code, the permission table schema, and multiple scenarios (partial users can read, authorize by role, revoke), seeskills/ob-agentbase/references/client-sdk-complex-permissions.mdandskills/ob-agentbase/references/database-permissions.md.
Examples by language
The following provides examples by language, item by item along the usage workflow; each card can switch languages (synced across the page).
Table creation baseline: grant only create (server side)
Under rowSecurity: true anyone can create rows but can only see (or modify, delete) their own rows; do not add ordinary users' table-level read/update/delete/write. No Web tab: creating tables is a server-side action (the Console configures baselines in the UI).
- Node.js (Server)
- Java
- Python
- Go
- REST (curl)
import { Client, TablesDB, Permission, Role } from 'agentbase-node-sdk';
const client = new Client()
.setEndpoint(process.env.APPBASE_ENDPOINT!) // Must include /v1
.setProject(process.env.APPBASE_PROJECT_ID!)
.setKey(process.env.APPBASE_API_KEY!);
const tablesDB = new TablesDB(client);
await tablesDB.createTable({
databaseId: 'main',
tableId: 'private_notes',
name: 'Private notes',
permissions: [Permission.create(Role.users())],
rowSecurity: true,
enabled: true,
});
// Do not add table-level read/update/delete/write(Role.users()) on top — it would bypass row-level isolationimport io.agentbase.Permission;
import io.agentbase.Role;
import io.agentbase.services.TablesDB;
TablesDB tablesDB = new TablesDB(client); // For client initialization, see server-sdk/java.md
tablesDB.createTable("main", "private_notes", "Private notes",
List.of(Permission.create(Role.users())), // Permission string create("users")
true, // rowSecurity
true, // enabled
null, null, null);
// Do not add table-level read/update/delete/write(Role.users()) on top — it would bypass row-level isolationfrom agentbase.permission import Permission
from agentbase.role import Role
from agentbase.services.tables_db import TablesDB
tables_db = TablesDB(client) # client initialization see examples/python.md
tables_db.create_table(
database_id='main', table_id='private_notes', name='Private notes',
permissions=[Permission.create(Role.users())], # Or pass a permission string directly: 'create("users")' (grammar same as REST permission strings)
row_security=True,
enabled=True,
)
# Do not add table-level read/update/delete/write(Role.users()) on top — it would bypass row-level isolationtables := agentbase.NewTablesDB(cl) // facade constructor; cl is a Client already loaded with an API Key
_, err := tables.CreateTable("main", "private_notes", "Private notes",
tables.WithCreateTablePermissions([]string{"create(\"users\")"}), // Array of permission strings; semantics same as REST
tables.WithCreateTableRowSecurity(true),
tables.WithCreateTableEnabled(true))
// Do not add table-level read/update/delete/write(Role.users()) on top — it would bypass row-level isolationcurl -sS -X POST "$APPBASE_ENDPOINT/tablesdb/main/tables" \
-H 'Content-Type: application/json' \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID" \
-H "X-Appwrite-Key: $APPBASE_API_KEY" \
-d '{
"tableId": "private_notes",
"name": "Private notes",
"rowSecurity": true,
"permissions": ["create(\"users\")"]
}'
# Table-level permissions are "allow", not "restrict": after configuring read("users"), everyone can read all rowsClient-side row creation: creator exclusive by default
When the Client SDK omits permissions, the server automatically writes the creator's read/update/delete; the Server SDK (API Key) has no "current end user", so it must grant explicitly.
- Node.js (Server)
- Web (user session)
- Java
- Python
- Go
- REST (curl)
import { ID, Permission, Role } from 'agentbase-node-sdk';
// Omitting permissions in the API Key request yields empty row permissions:
// First obtain the user ID from a trusted session / JWT, then explicitly grant it to that user
const userId = '<从已验证会话 / JWT 取得>';
await tablesDB.createRow({
databaseId: 'main',
tableId: 'private_notes',
rowId: ID.unique(),
data: { title: 'My note' },
permissions: [
Permission.read(Role.user(userId)),
Permission.update(Role.user(userId)),
Permission.delete(Role.user(userId)),
],
});import { Account, ID, Permission, Role } from 'agentbase-web-sdk'; // User is logged in
// Recommended: omit permissions; the server automatically grants the creator read/update/delete
await tablesDB.createRow({
databaseId: 'main',
tableId: 'private_notes',
rowId: ID.unique(),
data: { title: 'My note' },
});
// Explicit equivalent form (every Role must pass hasRole, otherwise 401):
const user = await new Account(client).get();
await tablesDB.createRow({
databaseId: 'main',
tableId: 'private_notes',
rowId: ID.unique(),
data: { title: 'My note' },
permissions: [
Permission.read(Role.user(user.$id)),
Permission.update(Role.user(user.$id)),
Permission.delete(Role.user(user.$id)),
],
});import io.agentbase.ID;
// Server SDK (API Key) bypasses the client-side hasRole check; omitting permissions yields empty row permissions,
// First obtain the user ID from a trusted session / JWT, then explicitly grant it to that user
String userId = "<从已验证会话 / JWT 取得>";
tablesDB.createRow("main", "private_notes", ID.unique(),
Map.of("title", "My note"),
List.of(Permission.read(Role.user(userId)),
Permission.update(Role.user(userId)),
Permission.delete(Role.user(userId))),
null);from agentbase.id import ID
from agentbase.permission import Permission
from agentbase.role import Role
# Server SDK (API Key): omitting permissions yields empty row permissions; first obtain the user ID from a trusted session / JWT, then explicitly grant it to that user
user_id = '<从已验证会话 / JWT 取得>'
tables_db.create_row(
database_id='main', table_id='private_notes', row_id=ID.unique(),
data={'title': 'My note'},
permissions=[Permission.read(Role.user(user_id)),
Permission.update(Role.user(user_id)),
Permission.delete(Role.user(user_id))],
)// Omitting permissions in the API Key request yields empty row permissions: obtain the user ID from a trusted session / JWT first, then explicitly grant it to that user
userId := "<从已验证会话 / JWT 取得>"
_, err = tables.CreateRow("main", "private_notes", id.Unique(), map[string]interface{}{"title": "My note"},
tables.WithCreateRowPermissions([]string{
"read(\"user:" + userId + "\")", "update(\"user:" + userId + "\")", "delete(\"user:" + userId + "\")",
})) // data is the 4-th positional parameter; permissions takes an array of permission strings, same semantics as RESTcurl -sS -X POST "$APPBASE_ENDPOINT/tablesdb/main/tables/private_notes/rows" \
-H 'Content-Type: application/json' \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID" \
-H "X-Appwrite-Key: $APPBASE_API_KEY" \
-d '{
"rowId": "note-001",
"data": {"title": "My note"},
"permissions": [
"read(\"user:66a9d8ef00f21\")",
"update(\"user:66a9d8ef00f21\")",
"delete(\"user:66a9d8ef00f21\")"
]
}'Team collaboration sharing and full replacement (updateRow / Role.team)
Passing permissions to updateRow is a full replacement: first use getRow to read $permissions, add and remove on a copy, then submit the whole set; if omitted, the original permissions are kept. The Client SDK cannot grant row-level permissions to others (the hasRole constraint); sharing goes through the Function proxy (see above).
- Node.js (Server)
- Web (user session)
- Java
- Python
- Go
- REST (curl)
import { Permission, Role } from 'agentbase-node-sdk';
const row = await tablesDB.getRow({ databaseId: 'main', tableId: 'private_notes', rowId: '<rowId>' });
const next = [...row.$permissions, Permission.read(Role.team('dev'))];
await tablesDB.updateRow({
databaseId: 'main',
tableId: 'private_notes',
rowId: '<rowId>',
permissions: next, // Passing only new permissions loses all original permissions
});// The Client SDK cannot authorize on behalf of others (hasRole constraint): call a Function when sharing is needed—
// Inside a Function, use the Server SDK to verify the caller is the row owner, then merge permissions and submit the full updateRow, keeping an audit trailvar row = tablesDB.getRow("main", "private_notes", "<rowId>", null, null); // Read $permissions first
var next = new java.util.ArrayList<Object>(row.getPermissions()); // Append to the copy and submit the whole set
next.add(Permission.read(Role.team("dev")));
tablesDB.updateRow("main", "private_notes", "<rowId>", null, next, null); // Passing only new permissions loses all original permissionsrow = tables_db.get_row(database_id='main', table_id='private_notes', row_id='<rowId>') # Read $permissions first (the Row model's .permissions attribute)
# Append read("team:dev") on the replica and commit the whole group; passing permissions in update_row is a full replacement
next_permissions = list(row.permissions) + ['read("team:dev")']
tables_db.update_row(database_id='main', table_id='private_notes', row_id='<rowId>',
permissions=next_permissions)row, err := tables.GetRow("main", "private_notes", "<rowId>") // Read $permissions first (row.Decode for raw JSON)
// Append read("team:dev") to the copy and submit the whole set; UpdateRow's permissions is a full replacement—passing only new permissions loses all original permissions
_, err = tables.UpdateRow("main", "private_notes", "<rowId>",
tables.WithUpdateRowPermissions([]string{
"read(\"user:66a9d8ef00f21\")", // Original permissions (from the $permissions copy)
"read(\"team:dev\")", // New: team sharing
}))# First GET the row to read $permissions, merge, then submit the whole set (PATCH's permissions semantics match the SDK updateRow)
curl -sS -X PATCH "$APPBASE_ENDPOINT/tablesdb/main/tables/private_notes/rows/note-001" \
-H 'Content-Type: application/json' \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID" \
-H "X-Appwrite-Key: $APPBASE_API_KEY" \
-d '{"permissions": ["read(\"user:66a9d8ef00f21\")", "read(\"team:dev\")"]}'