# OxiCloud ReBAC — Permissions, Grants, and Cascading
## Context
OxiCloud currently has a binary authorization model: the owner of a folder/file has every permission, every non-owner has none. The only user-to-user sharing is via anonymous token links (`storage.shares`) with three coarse flags (read/write/reshare). There is no way for a user to grant a named user fine-grained access to a folder, and no way to list resources others have shared with them.
This plan introduces a Relationship-Based Access Control (ReBAC) model:
- 6 named permissions: `read`, `create`, `share`, `comment`, `delete`, `update`
- Cascading: a grant on a folder applies to all descendants (sub-folders + files) via the existing `storage.folders.lpath` ltree
- Subjects: `user` (v1), `group` (future placeholder in schema), `token` (anonymous links — unified with existing `storage.shares`), `external` (future in schema for federated identities: Open Cloud Mesh / external OIDC)
- Pluggable engine: a single `AuthorizationEngine` trait, default implementation in PostgreSQL, ready for an `OpenFgaEngine` later
- **Roles** (Viewer, Commenter, Editor, Manager, Admin) as a UX/DTO sugar layer that the server expands into the underlying permission rows — storage and engine know nothing about roles
User decisions confirmed in conversation:
1.**Implicit owner** — owners have no rows in `access_grants`; the engine short-circuits when the caller is the resource's owner.
2.**`share` permission lets the holder grant to other named users** via `POST /api/grants` (not just create anonymous links).
3.**`GET /api/grants/incoming` returns direct grants only** — one row per resource explicitly granted to the caller. UI drills in via existing listing endpoints.
4.**Unify anonymous link shares under `access_grants`** with `subject_type='token'`. `storage.shares` retains token-lifecycle metadata (password, expiry, access count) only; the permission flags move to `access_grants`. One-time data migration.
5.**Roles in v1, implication chains deferred** — roles bundle the 6 raw permissions at the DTO layer (no schema impact). The storage keeps one row per granted permission. Permission implication (e.g., `update` ⊃ `comment` ⊃ `read`) is a Future optimization that compresses storage but doesn't change observable behavior.
6.**6 permissions are final for v1** — `read`, `create`, `share`, `comment`, `delete`, `update`. `download` (preview-only vs full-bytes) is a candidate for v2 if a "view-only" feature is added; trivial ALTER on the CHECK constraint then.
7.**Schema reserves `subject_type='external'` for federated identities** (Open Cloud Mesh / external OIDC). v1 adds the enum value and the `Subject::External(Uuid)` variant; the lookup table `auth.external_subjects` and the federation middleware are deferred.
8.**Architectural rule: AuthZ lives in the service layer, never in handlers.** All permission checks go through `AuthorizationEngine` via service methods. HTTP handlers (REST, WebDAV, NextCloud, CalDAV, CardDAV) authenticate the caller and pass `caller_id` into the service — they do NOT perform their own ownership/permission checks. This rule must be documented in `CLAUDE.md`.
9.**Per-row storage, not bitmap.** One row per `(subject, resource, permission)` rather than a single row with a packed bitmap. Preserves per-permission `granted_at` and `granted_by` (audit value), keeps future per-grant `expires_at` an easy addition, and maps 1:1 to OpenFGA tuples. Storage cost at OxiCloud's scale is acceptable and not on a hot path — micro-optimization deferred indefinitely. Matches the per-tuple shape used by Zanzibar, SpiceDB, OpenFGA, Permify.
Out-of-scope (deferred):
- Group creation & membership UI (the schema reserves `subject_type='group'`, but no group CRUD endpoints in this plan)
- External-user federation (`subject_type='external'` reserved in schema; `auth.external_subjects` table + OCM/OIDC federation middleware come later)
- Permission implication graph (`update` ⊃ `comment` ⊃ `read`, etc.) — storage compression with no observable behavior change
- Negative grants / deny rules (model stays additive — union of all applicable grants)
- Grant expiry per-row (token expiry stays on `storage.shares`)
- Comment feature itself (the `comment` permission is reserved; the comments table is a future feature)
-`download` permission (separation of preview-only from full-bytes export)
`granted_by` is always a user (group cannot grant). No FK to `auth.users` on `subject_id` or `granted_by` — those tables are in a different schema and the values are polymorphic.
### Cleanup of `storage.shares`
The permission columns move to `access_grants`. `storage.shares` keeps token-lifecycle metadata.
```sql
-- After data migration (below):
ALTERTABLEstorage.shares
DROPCOLUMNpermissions_read,
DROPCOLUMNpermissions_write,
DROPCOLUMNpermissions_reshare;
```
### Data migration (one-off, in the same migration file)
Each existing share becomes one or more rows in `access_grants` with `subject_type='token'`, `subject_id=shares.id`:
`storage.files.folder_id REFERENCES storage.folders(id) ON DELETE CASCADE` already exists — when a folder is permanently deleted, the file trigger fires for each cascaded child. No need to walk the ltree subtree manually.
### Application-layer cleanup (explicit hooks)
The trait gains two cleanup methods so the application layer can invoke cleanup explicitly. This matters because a future cache layer (see Future section) needs to see the invalidation event at the engine boundary — DB triggers happen below the cache:
```rust
/// Removes all grants targeting this resource. Returns count removed.
DB triggers stay as defense-in-depth — they catch anything the application forgets, and they catch bulk maintenance operations. The application-layer hook is the canonical path; the trigger is the safety net.
### File lifecycle hook integration
There's an existing `FileDeletedHook` trait in `src/application/ports/file_lifecycle.rs` that already fires after permanent file deletion (used today for blob-ref-count decrement). Implement an additional hook:
Register it in `common/di.rs` alongside the existing hooks. The folder/user/token cases get inline calls in their respective services (no hook trait for those yet — adding one if it's needed for a third caller is a future refactor).
### Verification — lifecycle scenarios in `grants.hurl`
1.**Resource delete clears grants**
- Alice creates folder F, grants Bob read, then permanently deletes F (via empty trash)
- Bob's `GET /api/grants/incoming` returns 0 entries containing F
- Direct SQL check (in a debug endpoint or via a test fixture): `SELECT COUNT(*) FROM access_grants WHERE resource_id = F` is 0
2.**Trash retains grants**
- Alice grants Bob read on F, moves F to trash, then restores F
- Bob still has `read` access after restore (regression: before any lifecycle change, this must continue to work)
3.**User delete clears subject grants but preserves granter**
- Alice grants Bob and Carol read on F. Admin deletes Bob.
- Carol's grant on F survives; her `granted_by=alice` still references Alice (intact)
- Bob's row is gone
4.**Token delete clears token grants**
- Alice creates a public share link on F → `access_grants` has rows with `subject_type='token'`
- Alice deletes the share link → token rows in `access_grants` are gone
5.**Orphan invariant (post-test SQL)**
```sql
SELECT COUNT(*) FROM storage.access_grants g
WHERE (g.resource_type = 'folder'
AND NOT EXISTS (SELECT 1 FROM storage.folders WHERE id = g.resource_id))
OR (g.resource_type = 'file'
AND NOT EXISTS (SELECT 1 FROM storage.files WHERE id = g.resource_id));
```
Must always be 0 after every Hurl run.
---
## Domain types
New module `src/domain/services/authorization.rs`:
Wired into `AppState` in `src/common/di.rs` as `pub authorization: Arc<dyn AuthorizationEngine>`. The factory selects the implementation from `OXICLOUD_AUTHZ_ENGINE` env var (default: `postgres`).
---
## PgAclEngine implementation
New file `src/infrastructure/services/pg_acl_engine.rs`. Holds `Arc<DbPools>`, `Arc<FolderDbRepository>`, `Arc<FileBlobReadRepository>` (for owner lookups).
Each `*_with_perms` method already calls `verify_owner`. Replace the call with `authz.require(...)`. The semantics broaden (grants count, not just ownership) but the signature and error mapping stay the same.
### Folder permission mapping (folder_service.rs)
| Method | Permission(s) checked |
|---|---|
| `create_folder_with_perms(dto, caller)` | `Create` on `Folder(parent_id)` |
| `get_folder_with_perms(id, caller)` | `Read` on `Folder(id)` |
| `rename_folder_with_perms(id, dto, caller)` | `Update` on `Folder(id)` |
| `move_folder_with_perms(id, dto, caller)` | `Update` on `Folder(id)` AND `Create` on `Folder(new_parent)` |
| `delete_folder_with_perms(id, caller)` | `Delete` on `Folder(id)` |
`get_file_owned`, `list_files_owned`, `get_file_stream_owned`, `get_file_optimized_owned`, `get_file_range_stream_owned`, `list_files_batch_for_owner` → each becomes `authz.require(caller, Read, File(id))` before delegating to the unchecked variant.
`folder_service::get_folder_by_path(path)` and `file_retrieval_service::get_file_by_path(path)` resolve a path then return the resource without any check. After this plan: resolve, then `authz.require(caller, Read, …)`. This closes a known IDOR documented in the previous plan's "Out of scope" section.
### Owner short-circuit ensures zero behavior change for current users
Because every existing user-vs-own-resource interaction is an owner check, the engine's owner short-circuit makes those calls equivalent to the current `verify_owner`. No grant lookups on the hot path until a real cross-user grant exists.
---
## REST endpoints
New handler `src/interfaces/api/handlers/grant_handler.rs`. Registered under `/api/grants`.
### `POST /api/grants` — create a grant
```json
{
"subject": { "type": "user", "id": "<uuid>" },
"resource": { "type": "folder", "id": "<uuid>" },
"permissions": ["read", "comment"]
}
```
Behavior:
1. Authenticated caller required.
2. `authz.require(caller, Share, resource)` — caller must have `share` on the resource (owners always pass via short-circuit).
3. For each permission in the list: `authz.grant(caller_id, subject, perm, resource)`. UNIQUE constraint makes repeats no-ops.
4. Returns 201 with the list of created/existing grants.
### `DELETE /api/grants/{id}` — revoke a grant
1. Look up the grant.
2. Allow if caller is the grant's `granted_by` user OR caller has `share` on the underlying resource.
3. `authz.revoke(id)`.
4. Returns 204.
### `GET /api/grants/incoming?permission=read&type=folder` — what others have shared with me
Direct grants only (per user decision). Subject is the authenticated caller's `User(id)`. Optional filters by permission and resource type.
Resource name/path is enriched via a JOIN to `storage.folders` / `storage.files`.
### `GET /api/grants?resource_type=folder&resource_id={id}` — list grants on a resource
Requires `authz.require(caller, Share, resource)` (you can see who has access only if you can manage sharing).
Returns the same shape as incoming, but for the specified resource.
### `GET /api/grants/outgoing` — grants I have created
Filtered by `granted_by = caller_id`. Useful for "Manage all my shares" UI.
---
## Roles (UX / DTO layer)
Roles are **preset bundles of permissions** that the API exposes for UI convenience. The server expands a role into its underlying permission list before writing rows; storage and engine know nothing about roles.
The DTO uses `#[serde(untagged)]` or two separate fields with server-side validation that exactly one is provided. Server expands `role` → permission list, then writes the rows.
### `PUT /api/grants/role` — reconcile a subject's role on a resource
```json
{ "subject": { "type": "user", "id": "<uuid>" },
"resource": { "type": "folder", "id": "<uuid>" },
"role": "manager" }
```
Behavior:
1. `authz.require(caller, Share, resource)`.
2. Read the current set of permissions held by `subject` on `resource`.
3. Compute the diff vs `role.expand()`: which permissions to INSERT, which to DELETE.
4. Apply both in one transaction.
5. Returns 200 with the new full set.
This is the canonical way for a UI to set "Bob is now Editor of /Photos" — the frontend doesn't track which specific rows exist.
### Why roles are pure DTO sugar (not stored)
- **Roles can evolve without schema migrations** — adding "Reviewer" tomorrow is a code change, no ALTER.
- **Mixing is allowed** — a future UI can start from "Editor" and add `share` manually; the result is a custom mixture, not "Editor + share".
- **OpenFGA migration unaffected** — tuples are per-permission regardless of how they were granted.
- **Revocation is granular** — removing a single permission doesn't require touching a "role" abstraction.
---
## File changes
### New files
- `migrations/2026MMDDHHMMSS_rebac_access_grants.sql` — table + indexes + data migration from `storage.shares`
- `src/application/dtos/grant_dto.rs` — request/response DTOs including `Role` enum + `Role::expand()`
### Modified
- `CLAUDE.md` — add a section under the Backend Architecture documenting the rule: **AuthZ is enforced exclusively in the application service layer. HTTP handlers (REST, WebDAV, NextCloud, CalDAV, CardDAV) only authenticate the caller and pass `caller_id` to the service. Never duplicate permission checks at the exposition layer.** This prevents drift between layers and matches the existing pattern of `*_with_perms` methods.
- `src/common/di.rs` — wire `authz` into `AppState`; inject into Folder/FileManagement/FileRetrieval services
- `src/application/services/folder_service.rs` — replace `verify_owner` calls with `authz.require`; add path-based check to `get_folder_by_path`
- `src/application/services/file_management_service.rs` — same; remove the private `verify_target_folder_owner` wrapper (engine does both)
- `src/application/services/share_service.rs` — on `create_shared_link`, also write the corresponding `access_grants` rows so that token-based access goes through the engine uniformly
- Alice grants `POST /api/grants` with `role: "editor"` for Bob on a new folder
- Bob can read AND rename a file inside (Editor includes `update`)
- Bob CANNOT delete the folder (Editor excludes `delete`) → 404
- Alice calls `PUT /api/grants/role` with `role: "admin"` for Bob
- Bob can now delete the folder → 200
- Alice calls `PUT /api/grants/role` with `role: "viewer"` for Bob
- Bob loses update/delete/comment/create/share; can only read → rename returns 404
7. **Token unification (regression)**
- `permissions.hurl` already covers existing share-link flows. After migration, those still pass — the engine reads from `access_grants` for token subjects, transparently.
### Unit tests
- New tests in `src/application/services/idor_protection_test.rs`:
- `engine.check(non_owner, Read, file)` with no grant → false
- `engine.check(grantee, Read, file)` after `grant()` → true
- Cascade: grant on parent folder → child file check returns true
- Revoke removes the row → next check returns false
- Tests use a stub repo for owners and an in-memory grant store, OR run against the real PG via the existing test harness.
### Storage growth sanity check (manual)
- Before migration: count rows in `storage.shares`.
- After migration: count rows in `storage.access_grants` with `subject_type='token'` ≈ shares × {1 + flag count}.
- Confirm no owner-self rows were created (validates implicit-owner choice).
---
## Rollout sequencing
1. **PR 1** — migration + schema (creates `access_grants`, migrates `storage.shares` permission flags). No code changes yet. Deploy and verify the migration runs cleanly.
2. **PR 2** — `AuthorizationEngine` trait + `PgAclEngine` + DI wiring. No services changed yet — engine is built but unused.
3. **PR 3** — service integration. Replace `verify_owner` with `authz.require` in `*_with_perms` methods. Add path-based checks. Hurl integration: `permissions.hurl` must still pass (engine's owner short-circuit ensures no behavior change for existing flows).
5. **PR 5** — `share_service` writes `access_grants` rows for new token shares (so token authz goes through the engine). At this point `storage.shares.permissions_*` columns are no longer read from anywhere — drop them.
Each PR is independently mergeable and the system stays functional throughout. PR 1-3 ship with zero observable change to users; PR 4 introduces the new feature; PR 5 retires the dead columns.
---
## Future: caching layer (in-process + Redis)
### Why
Every mutating service operation calls `authz.require(...)` at least once. The cascading SQL (`gf.lpath @> target.lpath` joined against `access_grants`) is O(log N) per check thanks to the GiST index, but at scale these costs compound:
- A batch delete of 1000 files = 1000 checks
- WebDAV PROPFIND on a deep folder may call `read` for every descendant
- A user with many active sessions hammers the same `(subject, perm, resource)` repeatedly
- Cascading means even a "no" answer requires walking the full ancestor chain — short-circuited only when the GiST index returns empty
A cache changes the cost of repeat checks from "JOIN + ltree GiST lookup" to "HashMap get" (L1) or "Redis GET" (L2). For mostly-read workloads, hit rate should be very high.
### Architecture — decorator over the trait
The `AuthorizationEngine` trait is unchanged. A `CachedAuthorizationEngine` wraps any underlying engine:
let key = DecisionKey { subject, permission: perm, resource };
// L1: in-process
if let Some(decision) = self.l1.get(&key).await { return Ok(decision); }
// L2: Redis
if let Some(l2) = &self.l2
&& let Some(decision) = l2.get(&key).await? {
self.l1.insert(key.clone(), decision).await;
return Ok(decision);
}
// Miss — query the underlying engine and backfill
let decision = self.inner.check(subject, perm, resource).await?;
self.l1.insert(key.clone(), decision).await;
if let Some(l2) = &self.l2 {
l2.set(&key, decision, CACHE_TTL).await?;
}
Ok(decision)
}
async fn grant(...) -> Result<Grant, _> {
let g = self.inner.grant(...).await?;
self.invalidate_for(g.subject, g.resource).await;
Ok(g)
}
async fn revoke(...) -> Result<(), _> {
self.inner.revoke(...).await?;
// need the affected (subject, resource) — revoke() takes only grant_id today,
// so the trait gains a small helper or returns the deleted grant for invalidation.
Ok(())
}
}
```
### Three tiers worth distinguishing
1. **Per-request cache** (cheapest to ship). A `HashMap<DecisionKey, bool>` lives in a request extension. Cleared at request end. Avoids repeat checks during a single batch op (e.g., a 1000-file delete only hits the DB once per unique `(subject, perm, file)`). No invalidation problem — request scope.
2. **In-process L1** (`moka::future::Cache`). Bounded LRU with TTL. Per-server-instance. Hit on hot resources, no network. Invalidated on local `grant`/`revoke`.
3. **Distributed L2** (Redis). Shared across multiple OxiCloud server instances. Worth adding only when running multi-instance (HA / horizontal scale). Cross-instance invalidation via Redis pub/sub or short TTL.
### Invalidation — the hard part
Cascading makes per-key invalidation hard. When Alice grants Bob `read` on folder F:
- Bob's `read` on F becomes true → invalidate `(bob, read, F)`
- Bob's `read` on every descendant of F also becomes true (live cascade) → invalidate `(bob, read, child)` for every child
There's no efficient way to enumerate all descendants and invalidate each entry. Three pragmatic options:
| **Subject-scoped flush** | All cached entries for `subject` regardless of resource | Cheap (one `bucket -> drop`) | Coarse — bob's checks on unrelated resources also dropped |
| **Resource-scoped flush** | All entries on `resource` and its descendants | Need to walk ltree on invalidation OR mark a "version" on the folder root | More targeted but more code |
| **Short TTL + eventual consistency** | None — wait for TTL | Trivial | Stale `true` after revoke for up to TTL seconds (bad), stale `false` after grant for up to TTL seconds (mildly annoying) |
Recommendation when this lands: subject-scoped flush as the simple default; switch to resource-scoped flush if subject churn is too painful for cache hit rate.
### Cache key normalization for cascading
Important detail: the cached entry for "bob can read folder F" doesn't need a separate entry per descendant. The engine's `check(bob, read, child)` would still go through the SQL because the cache key is `(bob, read, child)`, distinct from `(bob, read, F)`. So caching gives no descendant boost UNLESS we:
- Pre-resolve to "bob's effective grants" once (list all `(subject_id, permission, resource_id)` rows for bob) and cache that bundle, then evaluate any `check()` against the in-memory bundle. This is a classic Zanzibar-style "user list" cache.
That's a separate L1 design: cache the **bundle** of bob's grants, not individual decisions. Hit rate is high (one cached blob per active user). Invalidation is per-subject (when bob receives/loses a grant). The check becomes "is the requested resource an ltree descendant of any folder in bob's grant bundle?" — done in process, no DB round-trip.
This is probably the right L1 shape for OxiCloud given the cascade semantics.
The engine selection in `common/di.rs` wraps the underlying `PgAclEngine` based on this config. Disabled by default to keep v1 minimal.
### Why this is a clean follow-up, not v1
- The `AuthorizationEngine` trait is unchanged → the cache is a pure decorator
- Owner short-circuit already avoids the DB for the most common case (caller acting on own resources) — caching's marginal value is highest only once cross-user grants are common
- Adding caching too early hides whether the uncached SQL is actually slow at production scale; better to measure first
- Redis adds a new infrastructure dependency; introducing it before there's measured pressure is premature
### When to revisit
Add per-request cache when batch ops show repeated DB checks in tracing. Add L1 in-process cache when single-instance `check` p99 latency exceeds a threshold under cross-user workloads. Add L2 Redis only when running multi-instance and cross-instance cache coherence becomes a hit-rate problem.
---
## Future (v2): extend ReBAC to calendars, address books, playlists
Three resource types already have user-to-user sharing implemented as bespoke per-feature tables. After v1 proves the engine shape on files/folders, absorb them in a follow-up plan per resource type.
DROP CONSTRAINT access_grants_resource_type_check,
ADD CONSTRAINT access_grants_resource_type_check
CHECK (resource_type IN ('folder', 'file', 'calendar', 'address_book', 'playlist'));
```
2. **Domain** — extend `Resource` enum with `Calendar(Uuid)`, `AddressBook(Uuid)`, `Playlist(Uuid)`.
3. **Engine** — no cascading needed (these are flat containers, not trees). The `check()` SQL becomes a simple direct lookup with no ltree join for these branches.
4. **Service refactor** — remove the bespoke `share_calendar` / `share_address_book` / `share_playlist` methods. Sharing goes through `POST /api/grants` uniformly.
5. **Cleanup triggers** — add AFTER DELETE triggers on `caldav.calendars`, `carddav.address_books`, `audio.playlists` (same pattern as v1 triggers on `storage.folders`/`storage.files`).
WHEN 'write' THEN ARRAY['read','update','create','delete']
WHEN 'owner' THEN ARRAY['read','update','create','delete','share']
END) AS perm
) p;
-- Same shape for address_book_shares (FALSE → ['read'], TRUE → ['read','update','create','delete'])
-- Same shape for playlist_shares.
```
7. **Protocol mapping** (CalDAV / CardDAV only) — the WebDAV sharing properties (`<DAV:share-access>`, `<oc:invite>`) need to be re-implemented on top of the new grants. This is the largest unknown and the main reason for deferral.
### Why deferred, not in v1
- v1 must prove the `AuthorizationEngine` trait shape works before three more services land on it. If the trait needs an adjustment after running it on files, fixing it before three more migrations is much cheaper.
- The CalDAV/CardDAV protocol layer expects sharing semantics expressed via WebDAV properties — that's its own piece of work decoupled from the v1 grant table.
- Calendars/playlists are niche compared to file sharing — low migration risk if deferred.
- The 6-permission model already accommodates these without extension; the change is mechanical, just not yet.
3. On every `grant()`, also write the tuple to OpenFGA.
4. On `check()`, query OpenFGA's `/check` endpoint.
The `AuthorizationEngine` trait shape is identical, so swapping engines is a configuration change. The PG engine remains the source of truth for `storage.access_grants` rows; OpenFGA becomes an indexed read cache.