Build tenant-safe sharing
Maya and Ken belong to one tenant. Maya creates a private post, shares it with Ken, and lets comments inherit the post's access. A user with the same local ID in a different tenant must never gain access to that post.
Define the schema
This SQLite schema keeps each identity local to its tenant. Choose your application's database in the datasource when using a server database.
datasource db {
provider = "sqlite"
}
tenancy {
scope = "required"
field = "tenant_id"
}
access {
subjects = [User]
}
model User {
tenant_id String
id String
name String
posts Post[]
comments Comment[]
@@id([tenant_id, id])
}
model Post {
tenant_id String
id String
title String
body String
author_id String
author User @relation(fields: [tenant_id, author_id], references: [tenant_id, id]) @rent.creator
comments Comment[]
@@id([tenant_id, id])
}
model Comment {
tenant_id String
id String
body String
post_id String
author_id String
post Post @relation(fields: [tenant_id, post_id], references: [tenant_id, id], onDelete: Cascade)
author User @relation(fields: [tenant_id, author_id], references: [tenant_id, id]) @rent.creator
@@id([tenant_id, id])
}
permissions User {
read = anyone
create, update, delete = nobody
}
permissions Post {
editor = [User] or author
viewer = [User] or editor
read = viewer
create = anyone
update = editor
delete = author
manage_grants = author
}
permissions Comment {
read = post.viewer
create = post.viewer
update = author and post.viewer
delete = author and post.viewer or post.editor
}editor, viewer, author, and post are names you define. The bracket expression
[User] enables direct assignments to individual users. It does not make every user
an editor. The author relationship also grants the creator editing rights.
@rent.creator stamps the authenticated subject on creation and makes authorship
immutable. The tenant and author come from the trusted request context.
Bind a tenant and a person
After authenticating the request, construct a viewer from the complete user identity:
let ken = base.clone().with_viewer(
Viewer::of(User::subject(UserId {
tenant_id: "acme".into(),
id: "ken".into(),
}))
.tenant("acme"),
);Use that scoped client in request handlers. Ordinary reads return only posts Ken can read in Acme. Counts, permission flags, related comments, and pagination retain the same boundary. A local user named Ken in another tenant has a different identity.
Share a post without changing the schema
Only the author can manage grants in this policy. Using Maya's scoped client,
assign Ken the post's editor rule through grant_editor. Remove the assignment
through revoke_editor. These are data changes, so they need no RSL edit or code
generation. See the typed grant examples
for complete resource and subject keys.
Ken can now read and edit the post, but cannot delete it or share it with someone else. An independent viewer grant allows reading without editing. Removing one grant does not remove access supplied by another relationship or assignment.
Let comments follow their post
Comment.read and Comment.create follow post.viewer. Editing a comment requires
both authorship and continued access to its post. Deleting is allowed for an author
who still has access, or for a post editor acting as a moderator.
If Maya revokes Ken's only route to the post, Ken also loses access to its comments,
including comments he authored. A comment cannot be moved to another tenant because
its parent and author relationships include tenant_id in both foreign keys.
Choose the opt-ins your application needs
Tenancy and permissions are independent. Use ordinary models without either feature,
require tenancy without relationship permissions, or combine them as shown here.
Even broad rules such as read = public remain inside a required tenant boundary.
Continue with permission badges, a sharing dialog, or permission fixtures for your application.
Complete example
Download this project, or copy the files below into an empty directory.
Replace RENT_REPOSITORY_URL in Cargo.toml with the URL supplied with your preview access. Use the matching Rent CLI release.
Use a separate local database for this example:
export DATABASE_URL='sqlite://lesson.db?mode=rwc'
rent generate
rent migrate dev --name initial
cargo runRun the included test with cargo nextest run. It creates an isolated temporary database.
Cargo.toml
[package]
name = "rent-lesson-27-tenant-safe-sharing"
version = "0.1.0"
edition = "2024"
[workspace]
[[bin]]
name = "rent-lesson-27-tenant-safe-sharing"
path = "main.rs"
[dependencies]
rent = { git = "RENT_REPOSITORY_URL", tag = "v0.7.2", default-features = false, features = ["sqlite", "migrate", "extensions"] }
anyhow = "1.0.104"
tokio = { version = "1.53.1", features = ["full"] }
uuid = { version = "1.26.0", features = ["serde", "v4", "v7"] }
tempfile = "3.27.0"rent.toml
schema = "schema.rsl"
generated = "generated"
migrations = "migrations"
[database]
dialect = "sqlite"
backends = ["sqlite"]schema.rsl
datasource db {
provider = "sqlite"
}
tenancy {
scope = "required"
field = "tenant_id"
}
access {
subjects = [User]
}
model User {
tenant_id String
id String
name String
posts Post[]
comments Comment[]
@@id([tenant_id, id])
}
model Post {
tenant_id String
id String
title String
body String
author_id String
author User @relation(fields: [tenant_id, author_id], references: [tenant_id, id]) @rent.creator
comments Comment[]
@@id([tenant_id, id])
}
model Comment {
tenant_id String
id String
body String
post_id String
author_id String
post Post @relation(fields: [tenant_id, post_id], references: [tenant_id, id], onDelete: Cascade)
author User @relation(fields: [tenant_id, author_id], references: [tenant_id, id]) @rent.creator
@@id([tenant_id, id])
}
permissions User {
read = anyone
create, update, delete = nobody
}
permissions Post {
editor = author or [User]
viewer = editor or [User]
read = viewer
create = anyone
update = editor
delete, manage_grants = author
}
permissions Comment {
read, create = post.viewer
update = author and post.viewer
delete = author and post.viewer or post.editor
}main.rs
use anyhow::{Result, ensure};
use rent::policy::viewer::Viewer;
use rent::uuid::Uuid;
#[allow(dead_code, unused_imports)]
#[rustfmt::skip]
#[path = "generated/mod.rs"]
mod generated;
use generated::client::Client;
use generated::{
post::{PostId, PostPermission},
user::{User, UserId},
};
async fn example(database_url: &str) -> Result<()> {
let root = Client::connect(database_url).await?;
// Account provisioning is trusted application work, outside request handlers.
let system = root.system();
system
.upsert_user(generated::user::unique::tenant_id_id)
.tenant_id("acme")
.id("maya")
.name("Maya")
.save()
.await?;
system
.upsert_user(generated::user::unique::tenant_id_id)
.tenant_id("acme")
.id("ken")
.name("Ken")
.save()
.await?;
let maya = root.clone().with_viewer(
Viewer::of(User::subject(UserId {
tenant_id: "acme".into(),
id: "maya".into(),
}))
.tenant("acme"),
);
let ken = root.clone().with_viewer(
Viewer::of(User::subject(UserId {
tenant_id: "acme".into(),
id: "ken".into(),
}))
.tenant("acme"),
);
let post = maya
.create_post()
.id(Uuid::now_v7().to_string())
.title("Launch notes")
.body("An early draft")
.save()
.await?;
let post_key = PostId {
tenant_id: "acme".into(),
id: post.id.clone(),
};
ensure!(!ken.post_permissions(&post_key).can(PostPermission::Viewer).await?);
maya.post_permissions(&post_key)
.grant_editor(User::subject(UserId {
tenant_id: "acme".into(),
id: "ken".into(),
}))
.save()
.await?;
let edited = ken
.update_post()
.one(post_key.clone())
.title("Reviewed launch notes")
.save_one()
.await?;
ensure!(edited.title == "Reviewed launch notes");
let comment = ken
.create_comment()
.id(Uuid::now_v7().to_string())
.post_id(&post.id)
.body("Ready for review")
.save()
.await?;
ensure!(comment.author_id == "ken");
let rows = ken.post().id_eq(&post.id).with_permissions().all().await?;
ensure!(rows.len() == 1);
ensure!(rows.first().is_some_and(|row| row.permissions.has(PostPermission::Editor)));
let people = maya
.user()
.who_can(PostPermission::Viewer, &post_key)
.order_by(User::name)
.all()
.await?;
ensure!(people.subjects.iter().any(|person| person.id == "ken"));
let explanation = ken.post_permissions(&post_key).explain(PostPermission::Viewer).await?;
ensure!(explanation.is_some_and(|value| value.allowed));
maya.post_permissions(&post_key)
.revoke_editor(User::subject(UserId {
tenant_id: "acme".into(),
id: "ken".into(),
}))
.await?;
ensure!(!ken.post_permissions(&post_key).can(PostPermission::Viewer).await?);
ensure!(ken.comment().id_eq(&comment.id).all().await?.is_empty());
println!("Maya shared a post with Ken, then removed his access to the discussion.");
Ok(())
}
#[tokio::main]
async fn main() -> Result<()> {
example(&std::env::var("DATABASE_URL")?).await
}
#[cfg(test)]
mod test_support;
#[cfg(test)]
mod tests {
#[tokio::test]
async fn sharing_and_revocation() -> anyhow::Result<()> {
let (_directory, url) = super::test_support::database()?;
super::example(&url).await
}
}test_support.rs
use anyhow::{Context, Result, ensure};
use std::process::Command;
pub fn database() -> Result<(tempfile::TempDir, String)> {
let directory = tempfile::tempdir()?;
std::fs::write(directory.path().join("schema.rsl"), include_str!("schema.rsl"))?;
std::fs::write(directory.path().join("rent.toml"), r#"schema = "schema.rsl""#)?;
let url = format!("sqlite://{}?mode=rwc", directory.path().join("app.db").display());
let executable = std::env::var("RENT_CLI").unwrap_or_else(|_| "rent".into());
let output = Command::new(executable)
.arg("migrate")
.arg("dev")
.arg("--root")
.arg(directory.path())
.arg("--to")
.arg("schema.rsl")
.arg("--database-url")
.arg(&url)
.output()
.context("run the Rent CLI")?;
ensure!(
output.status.success(),
"migration failed: {}",
String::from_utf8_lossy(&output.stderr)
);
Ok((directory, url))
}