Sharing and Keys
Add and remove the members of an encrypted space, and change its key.A space is a row of the table your schema names as a space, such as a project. Its members
share its key. An account that can read and update the space row can add and remove members, so
the space row's update rule decides who manages them. Any member can remove themselves.
Add members
When a signed-in client inserts a space row, Jazz adds the creator as a member in the same
transaction. Use members.add for everyone else.
export async function shareProject(db: Db, otherAccountId: string) {const project = await db.insert(app.projects, { name: "Plans" }).wait({ tier: "global" });await db.encryption.members.add(app.projects, project.id, otherAccountId).wait({ tier: "global" });return db.encryption.members.list(app.projects, project.id);}
use crate::jazz_app::{DurabilityTier, NewProject};pub async fn share_project(jazz: &Jazz, other_account: AccountId) -> Result<Vec<SpaceMember>> {let durable = jazz.durable(DurabilityTier::GlobalServer);let project = durable.insert(NewProject::new("Plans")).await?;durable.add_member::<Project>(project.id, other_account).await?;jazz.list_members::<Project>(project.id).await}
Pass the generated space row type.
try await client.encryption.addMember(table: "projects", id: project.id, accountId: otherAccountId, tier: .global)let members = try await client.encryption.listMembers(table: "projects", id: project.id)
jazz.encryption.addMember("projects", project.id, otherAccountId, WriteTier.Global)val members = jazz.encryption.listMembers("projects", project.id)
_, err := db.Encryption().AddMember(ctx, "projects", project.ID, otherAccountID,jazz.WaitFor(jazz.WriteGlobal))members, err := db.Encryption().ListMembers(ctx, "projects", project.ID)
To remove a member, see Remove a member. A removal needs a key change too.
Jazz adds the creator automatically only when all three of these are true:
- the space row is created with
insert - the client is a signed-in device
- automatic membership is on (it is by default)
In every other case, add the creator yourself.
To turn automatic membership off, pass { addCreatorAsMember: false } as the third argument of
db.insert, or set it in the client's encryption options.
After an upsert, add the creator in the same transaction as the upsert. Only that transaction
may add the creator without permission to update the space row:
export async function upsertProject(db: Db, projectId: string, accountId: string) {return db.transaction((tx) => {tx.upsert(app.projects, projectId, { name: "Plans" });return tx.encryption.members.add(app.projects, projectId, accountId);});}
A backend has no device, so when it creates a space for a user, it must add that user with
members.add. The user's first encrypted write then creates the key, which needs permission to
update the space row, so an update rule based on $createdBy won't let them.
members.add returns the member row. Await it, or call .wait({ tier }) on it as on an insert.
Adding an account that's already a member does no harm.
To add a member together with other writes, use tx.encryption.members.add. It returns a promise
of the member row. Await it inside the transaction:
export async function addMemberWithOtherWrites(db: Db, projectId: string, otherAccountId: string) {const written = await db.transaction(async (tx) => {await tx.encryption.members.add(app.projects, projectId, otherAccountId);});await written.wait({ tier: "global" });}
Members are rows of the __e2ee_members table. To query or write it yourself,
db.encryption.members.where(space) returns a filter for a space's member rows and
db.encryption.members.row(space, accountId) returns the values to insert. Here space is
{ table: "projects", id: project.id }. Rows you insert yourself aren't checked against existing
members.
On a device that has never synced, these calls can fail with not-observed. Try again after the
first sync.
When members get the key
The first encrypted write to a space creates its key. A new member's devices get the key from a
device that already holds it, so one of those has to be online. Until the key arrives, the new
member's reads leave the encrypted rows out,
and a write to the space waits up to ten seconds for the key, then fails with key-pending.
Jazz delivers keys when the app starts, when it reconnects, and while it has a subscription on the space. To deliver straight away:
export async function deliverKeysNow(db: Db) {const { delivered } = await db.encryption.keys.deliver();return delivered;}
Remove a member
Removing a member deletes their member row. The removed member still holds the space's key, so change the key straight after:
export async function removeMember(db: Db, projectId: string, otherAccountId: string) {const removed = await db.encryption.members.remove(app.projects, projectId, otherAccountId);if (removed > 0) {try {await db.encryption.keys.rotate({ table: "projects", id: projectId });} catch (error) {// `rotation-needs-key`: try again once this device holds the key.// Until the key changes, new writes still use the old one.console.warn("key not rotated", (error as { code?: string }).code);}}return removed;}
use serde_json::json;pub async fn remove_member(jazz: &Jazz,project_id: ObjectId,other_account: AccountId,) -> Result<usize> {let removed = jazz.remove_member::<Project>(project_id, other_account).await?;if removed > 0 {jazz.encryption().call("keysRotate",json!({ "table": "projects", "id": project_id.to_string() }),).await?;}Ok(removed)}
let removed = try await client.encryption.removeMember(table: "projects", id: project.id, accountId: otherAccountId)if removed > 0 {try await client.encryption.keysRotate(table: "projects", id: project.id)}
val removed = jazz.encryption.removeMember("projects", project.id, otherAccountId)if (removed > 0u) jazz.encryption.keysRotate("projects", project.id)
removed, err := db.Encryption().RemoveMember(ctx, "projects", project.ID, otherAccountID)if err == nil && removed > 0 {err = db.Encryption().KeysRotate(ctx, "projects", project.ID)}
members.remove resolves once the server accepts the removal, and returns the number of member
rows it deleted. 0 means the caller could see no member row for that account.
If you don't call rotate, members who can't update the space row keep writing with the old key.
The rotation then happens automatically before the next write by someone who can update the
space row. If you remove several members, rotate once at the end.
rotate returns the number of members who got the new key in the same transaction, up to 100.
It can fail with these codes:
rotation-needs-key: this device doesn't hold the current key yet. Try again once it does.not-a-member: this account isn't a member of the space.no-account: this device is waiting for approval.
Jazz prepares the new key for the rest of the members in the background, and shares it with them. If sharing fails, it tries again after 2 seconds, then 4, 8, 16 and 32, and gives up after 6 failed attempts in a row. Failures while offline aren't counted, and wait 2 seconds like a first failure. After it gives up, any device that holds the new key shares it with the members left out, the next time it shares keys. If the app stops before sharing finishes, the device that rotated tries again the next time it starts.
A removed member keeps everything they could already read, and the old key. The server stops sending them rows, and they don't get the new key. Until every device has the new key, some writes still use the old one: writes made offline, and writes from a device that hasn't heard of the rotation yet. The removed member can read those if they get hold of them.
To delete your own rows in the same transaction as the membership, use
db.serializableTransaction. Read the member rows with the filter from
members.where(space, accountId), delete them with your rows, and wait for the result before you
rotate.
If no online device holds the current key, a device that holds an earlier key can call
db.encryption.keys.recoverRotation(space). Ask the user to confirm first. Rows written under a
key that no member's device still holds stay unreadable. See
rotation and removal
in the spec.
Watch for failures
If Jazz can't change the key before a write, the write still goes ahead under the old key, which
the removed member may hold. Listen for this with onReport:
export function watchEncryptionFailures(db: Db) {return db.encryption.onReport((report) => {if (report.type === "rotation-check-failed")console.warn("rotation check failed", report.space, report.reason);if (report.type === "rotation-failed")console.warn("key not rotated", report.space, report.reason);if (report.type === "delivery-failed")console.warn("key delivery failed", report.space, report.reason);});}
rotation-check-failed: Jazz couldn't check whether the space needs a new key.rotation-failed: the key wasn't changed before a write. The next write tries again. After a permission refusal, this client stops trying for the session.delivery-failed: Jazz couldn't deliver keys to the space's members. It tries again later.
On the backend
The database from createJazz can add, list and remove members through db.encryption.members.
It holds no keys, so it can't deliver or rotate them. Use a device client for that.