Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Add vault_sharing Rust module to centralize vault share access split logic (#2159)
Leendert de Borstef853e9a48f7
diff --git a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.tsindex fb354d0d7..d6b9c2100 100644--- a/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts+++ b/apps/browser-extension/src/entrypoints/background/VaultMessageHandler.ts@@ -1883,7 +1883,7 @@ async function pullAndMaterializeServerVault(syncState: VaultSyncState, encryptiasync function pruneRowsOfLostManifests(encryptionKey: string): Promise<void> {try {const sqliteClient = await createVaultSqliteClient();- const dropped = vaultSyncService.dropRowsOfLostManifests(sqliteClient, vaultSyncService.manifestIdsServedByLastSnapshot());+ const dropped = await vaultSyncService.dropRowsOfLostManifests(sqliteClient, vaultSyncService.manifestIdsServedByLastSnapshot());if (dropped.length === 0) {return;}diff --git a/apps/browser-extension/src/utils/RustCore.ts b/apps/browser-extension/src/utils/RustCore.tsindex 8594d084c..db2d09f18 100644--- a/apps/browser-extension/src/utils/RustCore.ts+++ b/apps/browser-extension/src/utils/RustCore.ts@@ -520,6 +520,61 @@ export async function vaultCodecComputeContentFingerprint(payloadJson: string):return core.vaultCodecComputeContentFingerprint(payloadJson);}+/** A shared manifest's key record. */+export type SharingManifestRecord = {+ manifestId: string;+ salt: string;+ name?: string | null;+ canAdminister?: boolean;+};++/** One manifest the next push writes. */+export type SharingWriteRecord = {+ manifestId: string;+ isPersonal: boolean;+ salt: string;+ name: string | null;+ canAdminister: boolean;+};++/** The manifests a push writes, personal first, plus what was left out and why. */+export type SharingWriteSet = {+ records: SharingWriteRecord[];+ skipped: Array<{ manifestId: string; reason: 'NO_ROWS_IN_VAULT' | 'KEY_DID_NOT_OPEN' }>;+};++/** What the vault holds but cannot write, and what it holds but has lost access to. */+export type SharingAccessPartition = { unwritable: string[]; lost: string[] };++/**+ * Work out which manifests the next push writes, personal manifest first.+ * @param input - the personal manifest, what the vault holds rows for, what opened, and the held records.+ */+export async function vaultSharingResolveManifestWriteSet(input: {+ personalManifestId: string;+ personalManifestSalt: string;+ stampedManifestIds: string[];+ openedManifestIds: string[];+ heldRecords: SharingManifestRecord[];+ displayNames: Record<string, string>;+}): Promise<SharingWriteSet> {+ await initRustCore();+ return core.vaultSharingResolveManifestWriteSet(input) as SharingWriteSet;+}++/**+ * Split what the local vault holds by what this account can still open.+ * @param input - what the vault holds, what this session can write, and what the last snapshot served.+ */+export async function vaultSharingPartitionManifestAccess(input: {+ manifestIdsInVault: string[];+ writableManifestIds: string[];+ grantedManifestIds: string[];+}): Promise<SharingAccessPartition> {+ await initRustCore();+ return core.vaultSharingPartitionManifestAccess(input) as SharingAccessPartition;+}+/*** Read all non-empty values for a field key from an item, returning them as* a string array (single-value fields are wrapped to a 1-element array).diff --git a/apps/browser-extension/src/utils/VaultSyncService.ts b/apps/browser-extension/src/utils/VaultSyncService.tsindex c58084fc4..316874209 100644--- a/apps/browser-extension/src/utils/VaultSyncService.ts+++ b/apps/browser-extension/src/utils/VaultSyncService.ts@@ -9,14 +9,14 @@ import { storage } from 'wxt/utils/storage';import { base64ToBytes } from '@/utils/Base64';import { bucketRevisionKey, StorageKeys } from '@/utils/constants/storageKeys';import { devError, devLog, devWarn } from '@/utils/devLogger/DevLogger';-import { ManifestKeyType, VaultKeyAlgorithm, type VaultResponse } from '@/utils/dist/core/models/webapi';+import { ManifestKeyType, VaultKeyAlgorithm, type BucketRevision, type VaultResponse } from '@/utils/dist/core/models/webapi';import { VaultSqlGenerator } from '@/utils/dist/core/vault';import { buildEmailRouting } from '@/utils/EmailRouting';import { EncryptionUtility } from '@/utils/EncryptionUtility';import { completeLegacyAccountKeyMigration, isLegacySqliteBlobSnapshot, legacyUnstampedRowAdoption, openLegacySqliteBlobSnapshot, prepareLegacyAccountKeyMigration, withOutdatedServerGuard, type LegacyAccountKeyMigration, type LegacySqliteBlobSnapshot } from '@/utils/legacy/LegacyStorageModelMigration';import { getManifestRevisions, getPersonalManifestId, recordManifestRevisions, replaceManifestRevisions, toManifestRevisionMap } from '@/utils/ManifestRevisions';import { multiManifestRendering } from '@/utils/MultiManifestRendering';-import {vaultCodecComputeCiphertextHash, vaultCodecComputeContentFingerprint, vaultCodecCanonicalizeFromSqlite, vaultCodecExtractEncryptionKeyForPublicKey, vaultCodecGenerateManifestSalt, vaultCodecUnpackPayload, vaultCodecMaterializeAsSqlite, vaultCodecPackPayload, vaultCodecValidateManifest, vaultCodecValidateDataBucket, type CodecBlobEntry, type CodecCanonicalized, type CodecManifest, type CodecManifestSpec} from '@/utils/RustCore';+import {vaultCodecComputeCiphertextHash, vaultCodecComputeContentFingerprint, vaultCodecCanonicalizeFromSqlite, vaultCodecExtractEncryptionKeyForPublicKey, vaultCodecGenerateManifestSalt, vaultCodecUnpackPayload, vaultCodecMaterializeAsSqlite, vaultCodecPackPayload, vaultCodecValidateManifest, vaultCodecValidateDataBucket, type CodecBlobEntry, type CodecCanonicalized, type CodecManifest, type CodecManifestSpec, vaultSharingPartitionManifestAccess, vaultSharingResolveManifestWriteSet, type SharingAccessPartition} from '@/utils/RustCore';import { SharingService, type ManifestVekGrant, type SharedManifestRecord } from '@/utils/SharingService';import { SqliteClient } from '@/utils/SqliteClient';import { getStorageItem } from '@/utils/StorageUtility';@@ -182,8 +182,8 @@ type ManifestDto = {/** A data bucket as carried in the GET snapshot / bundled upload. `category` matches the server enum name (e.g. "Settings"). */type BucketDto = { manifestId: string; category: string; blob?: string | null; ciphertextHash?: string | null; revision?: number };-/** Per-kind revision as carried in upload responses. */-type BucketRevisionDto = { manifestId: string; category: string; revision: number };+/** Per-kind revision as carried in upload responses; the same shape the status response reports. */+type BucketRevisionDto = BucketRevision;/*** Pick the user's personal manifest out of a snapshot. The server names it by id rather than flagging each entry, so@@ -1335,14 +1335,27 @@ export class VaultSyncService {* @returns The manifest ids the vault holds but this session cannot write, empty when the two agree*/public async findUnwritableManifests(sqliteClient: SqliteClient): Promise<string[]> {- const writable = new Set<string>([...(await SharingService.openSharedManifestVeks(sqliteClient)).keys()].map(manifestIdKey));+ return (await this.partitionManifestAccess(sqliteClient, [])).unwritable;+ }++ /**+ * Split what the vault holds against what this account may still open.+ * @param sqliteClient - the open local vault+ * @param grantedManifestIds - the manifests the last snapshot served, empty when that is not being asked+ */+ private async partitionManifestAccess(sqliteClient: SqliteClient, grantedManifestIds: Iterable<string>): Promise<SharingAccessPartition> {+ const writable = [...(await SharingService.openSharedManifestVeks(sqliteClient)).keys()];const personalManifestId = await getPersonalManifestId();if (personalManifestId) {- writable.add(manifestIdKey(personalManifestId));+ writable.push(personalManifestId);}- return [...VaultCodec.manifestIdsInVault(sqliteClient)].filter(manifestId => !writable.has(manifestIdKey(manifestId)));+ return vaultSharingPartitionManifestAccess({+ manifestIdsInVault: [...VaultCodec.manifestIdsInVault(sqliteClient)],+ writableManifestIds: writable,+ grantedManifestIds: [...grantedManifestIds],+ });}/**@@ -1366,14 +1379,8 @@ export class VaultSyncService {* @param grantedManifestIds - the manifests the snapshot just served, the personal one included* @returns The manifest ids whose rows were dropped, empty when there was nothing to drop*/- public dropRowsOfLostManifests(sqliteClient: SqliteClient, grantedManifestIds: Iterable<string>): string[] {- const granted = new Set([...grantedManifestIds].map(manifestIdKey));- if (granted.size === 0) {- // Nothing is known about what this account may open, and guessing with the user's data is worse than keeping it.- return [];- }-- const lost = [...VaultCodec.manifestIdsInVault(sqliteClient)].filter(manifestId => !granted.has(manifestIdKey(manifestId)));+ public async dropRowsOfLostManifests(sqliteClient: SqliteClient, grantedManifestIds: Iterable<string>): Promise<string[]> {+ const { lost } = await this.partitionManifestAccess(sqliteClient, grantedManifestIds);if (lost.length === 0) {return [];}@@ -1390,6 +1397,9 @@ export class VaultSyncService {/*** Resolve every manifest this vault can write, personal manifest first, as one uniform list.+ *+ * The core decides which, so a second client cannot arrive at a different write set. It is told which+ * manifests opened, never what they opened with.* @param sqliteClient - the open local vault*/private async resolveManifestRecords(sqliteClient: SqliteClient): Promise<ManifestRecord[]> {@@ -1399,43 +1409,32 @@ export class VaultSyncService {await storage.setItem(StorageKeys.VAULT_MANIFEST_SALT, manifestSalt);}- const records: ManifestRecord[] = [{- manifestId: await this.resolvePersonalManifestId(),- isPersonal: true,- salt: manifestSalt,- vek: null,- name: null,- canAdminister: false,- }];-- const stampedManifestIds = new Set([...VaultCodec.manifestIdsInVault(sqliteClient)].map(manifestIdKey));const sharedVeks = await SharingService.openSharedManifestVeks(sqliteClient);- const manifestNames = multiManifestRendering.displayNames(sqliteClient);- for (const record of Object.values(await SharingService.getSharedManifestRecords())) {- if (!stampedManifestIds.has(manifestIdKey(record.manifestId))) {- devLog(`[V2Push] Shared manifest ${record.manifestId} has no rows in this vault; leaving it out of the write rather than emptying it server-side.`);- continue;- }-- // No key, no write.- const vek = sharedVeks.get(record.manifestId);- if (!vek) {- devWarn(`[V2Push] Shared manifest ${record.manifestId} did not open; leaving it out of the write.`);- continue;- }+ const writeSet = await vaultSharingResolveManifestWriteSet({+ personalManifestId: await this.resolvePersonalManifestId(),+ personalManifestSalt: manifestSalt,+ stampedManifestIds: [...VaultCodec.manifestIdsInVault(sqliteClient)],+ openedManifestIds: [...sharedVeks.keys()],+ heldRecords: Object.values(await SharingService.getSharedManifestRecords()),+ displayNames: multiManifestRendering.displayNames(sqliteClient),+ });- records.push({- manifestId: record.manifestId,- isPersonal: false,- salt: record.salt,- vek,- // Re-read how this client renders the manifest on every push, so the name inside it follows a rename instead of staying at whatever the vault was called when it was created.- name: manifestNames[record.manifestId.toLowerCase()] ?? record.name ?? null,- canAdminister: record.canAdminister === true,- });+ for (const skipped of writeSet.skipped) {+ const why = skipped.reason === 'NO_ROWS_IN_VAULT'+ ? 'has no rows in this vault; leaving it out of the write rather than emptying it server-side'+ : 'did not open; leaving it out of the write';+ devLog(`[V2Push] Shared manifest ${skipped.manifestId} ${why}.`);}- return records;+ // Re-attach the keys. Without one a shared manifest falls back to the personal key downstream, so assert it.+ const vekByManifestId = new Map([...sharedVeks].map(([manifestId, vek]) => [manifestIdKey(manifestId), vek]));+ return writeSet.records.map(record => {+ const vek = record.isPersonal ? null : vekByManifestId.get(manifestIdKey(record.manifestId)) ?? null;+ if (!record.isPersonal && !vek) {+ throw new Error(`VaultSyncService: manifest ${record.manifestId} is in the write set without a key, refusing to write it.`);+ }+ return { ...record, vek };+ });}/**diff --git a/core/rust/src/lib.rs b/core/rust/src/lib.rsindex ac2c5b8db..54ee30d50 100644--- a/core/rust/src/lib.rs+++ b/core/rust/src/lib.rs@@ -2,6 +2,7 @@//!//! Cross-platform core functionality for AliasVault, including://! - **vault_merge**: Vault merge using Last-Write-Wins (LWW) strategy+//! - **vault_sharing**: Sharing write logic for multi-manifest vaults//! - **vault_pruner**: Prunes expired items from trash (30-day retention)//! - **credential_matcher**: Cross-platform credential filtering for autofill//! - **password_generator**: Password and passphrase (Diceware) generation@@ -18,6 +19,7 @@ mod hex;mod rng;pub mod vault_merge;pub mod vault_codec;+pub mod vault_sharing;pub mod vault_pruner;pub mod credential_matcher;pub mod email_parser;@@ -38,6 +40,11 @@ pub use vault_codec::{CanonicalizeInput, CanonicalizedManifest, CanonicalizedVault, CodecRecord, CodecTableData, DataBucket, Manifest,MaterializeInput, MaterializedTables, ManifestSpec, ValidationResult,};+pub use vault_sharing::{+ partition_manifest_access, resolve_manifest_write_set, ManifestAccessPartition, ManifestAccessRequest,+ ManifestWriteRecord, ManifestWriteSet, ManifestWriteSetRequest, SharedManifestRecord, SkippedManifest,+ WriteSkipReason,+};pub use vault_pruner::{prune_vault, PruneInput, PruneOutput, PruneStats,};diff --git a/core/rust/src/uniffi_api.rs b/core/rust/src/uniffi_api.rsindex 4181f4540..472842d2b 100644--- a/core/rust/src/uniffi_api.rs+++ b/core/rust/src/uniffi_api.rs@@ -216,6 +216,22 @@ pub fn get_identity_age_ranges() -> Vec<String> {crate::identity_generator::available_age_ranges()}+// ═══════════════════════════════════════════════════════════════════════════════+// Vault Sharing Functions+// ═══════════════════════════════════════════════════════════════════════════════++/// Resolve which manifests the next push writes, personal manifest first.+#[uniffi::export]+pub fn vault_sharing_resolve_manifest_write_set(input_json: String) -> Result<String, VaultError> {+ crate::vault_sharing::resolve_manifest_write_set_json(&input_json)+}++/// Split what the vault holds into what cannot be written and what access was lost.+#[uniffi::export]+pub fn vault_sharing_partition_manifest_access(input_json: String) -> Result<String, VaultError> {+ crate::vault_sharing::partition_manifest_access_json(&input_json)+}+// ═══════════════════════════════════════════════════════════════════════════════// Vault Codec Functions (manifest-v1 storage format) — JSON-string in/out.// ═══════════════════════════════════════════════════════════════════════════════diff --git a/core/rust/src/vault_sharing/mod.rs b/core/rust/src/vault_sharing/mod.rsnew file mode 100644index 000000000..4617b884f--- /dev/null+++ b/core/rust/src/vault_sharing/mod.rs@@ -0,0 +1,99 @@+//! Sharing write logic for multi-manifest vaults.+pub mod types;++#[cfg(test)]+mod tests;++use std::collections::HashMap;++use crate::error::VaultResult;++pub use types::{+ ManifestAccessPartition, ManifestAccessRequest, ManifestWriteRecord, ManifestWriteSet,+ ManifestWriteSetRequest, SharedManifestRecord, SkippedManifest, WriteSkipReason,+};++use types::id_key;++/// Resolve which manifests the next push writes, personal manifest first.+///+/// A manifest is written when the vault holds rows for it and this session opened its key.+pub fn resolve_manifest_write_set(request: ManifestWriteSetRequest) -> ManifestWriteSet {+ let stamped: Vec<String> = request.stamped_manifest_ids.iter().map(|id| id_key(id)).collect();+ let opened: Vec<String> = request.opened_manifest_ids.iter().map(|id| id_key(id)).collect();++ let mut records = vec![ManifestWriteRecord {+ manifest_id: request.personal_manifest_id,+ is_personal: true,+ salt: request.personal_manifest_salt,+ name: None,+ can_administer: false,+ }];+ let mut skipped = Vec::new();++ for record in &request.held_records {+ let key = id_key(&record.manifest_id);++ if !stamped.contains(&key) {+ skipped.push(SkippedManifest { manifest_id: record.manifest_id.clone(), reason: WriteSkipReason::NoRowsInVault });+ continue;+ }++ if !opened.contains(&key) {+ skipped.push(SkippedManifest { manifest_id: record.manifest_id.clone(), reason: WriteSkipReason::KeyDidNotOpen });+ continue;+ }++ records.push(ManifestWriteRecord {+ manifest_id: record.manifest_id.clone(),+ is_personal: false,+ salt: record.salt.clone(),+ // Re-read on every push, so the name inside the manifest follows a rename.+ name: resolve_name(&request.display_names, &record.manifest_id, record.name.as_deref()),+ can_administer: record.can_administer,+ });+ }++ ManifestWriteSet { records, skipped }+}++/// Split what the vault holds into what this session cannot write and what the account has lost.+///+/// Lost rows can never be written again and a merge keeps local-only rows, so leaving them would make+/// every following push refuse itself.+pub fn partition_manifest_access(request: ManifestAccessRequest) -> ManifestAccessPartition {+ let held: Vec<String> = request.manifest_ids_in_vault;+ let writable: Vec<String> = request.writable_manifest_ids.iter().map(|id| id_key(id)).collect();+ let granted: Vec<String> = request.granted_manifest_ids.iter().map(|id| id_key(id)).collect();++ let unwritable = held.iter().filter(|id| !writable.contains(&id_key(id))).cloned().collect();++ // An empty grant set means nothing is known yet, not that all access was revoked.+ let lost = match granted.is_empty() {+ true => Vec::new(),+ false => held.iter().filter(|id| !granted.contains(&id_key(id))).cloned().collect(),+ };++ ManifestAccessPartition { unwritable, lost }+}++/// The name to write into a manifest: the rendered one, else the stored one, else none.+fn resolve_name(display_names: &HashMap<String, String>, manifest_id: &str, record_name: Option<&str>) -> Option<String> {+ let wanted = id_key(manifest_id);+ display_names+ .iter()+ .find(|(key, _)| id_key(key) == wanted)+ .map(|(_, name)| name.clone())+ .or_else(|| record_name.map(|name| name.to_string()))+ .filter(|name| !name.is_empty())+}++/// Resolve a push's write set. Input: `ManifestWriteSetRequest` JSON. Output: `ManifestWriteSet` JSON.+pub fn resolve_manifest_write_set_json(input_json: &str) -> VaultResult<String> {+ Ok(serde_json::to_string(&resolve_manifest_write_set(serde_json::from_str(input_json)?))?)+}++/// Partition manifest access. Input: `ManifestAccessRequest` JSON. Output: `ManifestAccessPartition` JSON.+pub fn partition_manifest_access_json(input_json: &str) -> VaultResult<String> {+ Ok(serde_json::to_string(&partition_manifest_access(serde_json::from_str(input_json)?))?)+}diff --git a/core/rust/src/vault_sharing/tests.rs b/core/rust/src/vault_sharing/tests.rsnew file mode 100644index 000000000..a401cec9f--- /dev/null+++ b/core/rust/src/vault_sharing/tests.rs@@ -0,0 +1,192 @@+//! Tests for the sharing policy.++use std::collections::HashMap;++use super::*;++/// A held key record for a manifest.+fn record(manifest_id: &str, name: Option<&str>) -> SharedManifestRecord {+ SharedManifestRecord {+ manifest_id: manifest_id.to_string(),+ salt: "salt-1".to_string(),+ name: name.map(|n| n.to_string()),+ can_administer: true,+ }+}++/// A write-set request with one personal manifest and the given shared records.+fn write_set_request(stamped: &[&str], opened: &[&str], held: Vec<SharedManifestRecord>) -> ManifestWriteSetRequest {+ ManifestWriteSetRequest {+ personal_manifest_id: "PERSONAL".to_string(),+ personal_manifest_salt: "personal-salt".to_string(),+ stamped_manifest_ids: stamped.iter().map(|id| id.to_string()).collect(),+ opened_manifest_ids: opened.iter().map(|id| id.to_string()).collect(),+ held_records: held,+ display_names: HashMap::new(),+ }+}++// ─────────────────────────────────────────────────────────────────────────────+// The write set+// ─────────────────────────────────────────────────────────────────────────────++#[test]+fn the_write_set_leads_with_the_personal_manifest() {+ let set = resolve_manifest_write_set(write_set_request(&["PERSONAL", "MAN-1"], &["MAN-1"], vec![record("MAN-1", Some("Family"))]));++ assert_eq!(set.records.len(), 2);+ assert!(set.records[0].is_personal);+ assert_eq!(set.records[0].manifest_id, "PERSONAL");+ assert_eq!(set.records[0].salt, "personal-salt");+ // A personal manifest is never named and is not administered through a group.+ assert_eq!(set.records[0].name, None);+ assert!(!set.records[0].can_administer);++ assert!(!set.records[1].is_personal);+ assert_eq!(set.records[1].manifest_id, "MAN-1");+ assert_eq!(set.records[1].salt, "salt-1");+ assert_eq!(set.records[1].name.as_deref(), Some("Family"));+ assert!(set.records[1].can_administer);+ assert!(set.skipped.is_empty());+}++#[test]+fn a_manifest_with_no_local_rows_is_left_alone_rather_than_emptied() {+ let set = resolve_manifest_write_set(write_set_request(&["PERSONAL"], &["MAN-1"], vec![record("MAN-1", None)]));++ assert_eq!(set.records.len(), 1);+ assert_eq!(set.skipped.len(), 1);+ assert_eq!(set.skipped[0].manifest_id, "MAN-1");+ assert_eq!(set.skipped[0].reason, WriteSkipReason::NoRowsInVault);+}++#[test]+fn a_manifest_whose_key_did_not_open_is_not_written() {+ let set = resolve_manifest_write_set(write_set_request(&["PERSONAL", "MAN-1"], &[], vec![record("MAN-1", None)]));++ assert_eq!(set.records.len(), 1);+ assert_eq!(set.skipped[0].reason, WriteSkipReason::KeyDidNotOpen);+}++#[test]+fn the_write_set_matches_ids_regardless_of_casing() {+ let set = resolve_manifest_write_set(write_set_request(&["man-1"], &["MAN-1"], vec![record("Man-1", None)]));++ assert_eq!(set.records.len(), 2);+ // The record's own spelling comes back, since that is what addresses the write.+ assert_eq!(set.records[1].manifest_id, "Man-1");+ assert!(set.skipped.is_empty());+}++#[test]+fn the_rendered_name_overrides_the_stored_one_on_every_push() {+ let mut request = write_set_request(&["PERSONAL", "MAN-1"], &["MAN-1"], vec![record("MAN-1", Some("Name at creation"))]);+ request.display_names.insert("MAN-1".to_string(), "Renamed since".to_string());++ let set = resolve_manifest_write_set(request);+ assert_eq!(set.records[1].name.as_deref(), Some("Renamed since"));+}++#[test]+fn a_manifest_with_no_name_anywhere_is_written_without_one() {+ let mut request = write_set_request(&["PERSONAL", "MAN-1"], &["MAN-1"], vec![record("MAN-1", None)]);+ // An empty rendered name must not shadow the absent one.+ request.display_names.insert("MAN-1".to_string(), String::new());++ let set = resolve_manifest_write_set(request);+ assert_eq!(set.records[1].name, None);+}++#[test]+fn several_manifests_keep_the_order_they_were_held_in() {+ let held = vec![record("MAN-1", None), record("MAN-2", None), record("MAN-3", None)];+ let set = resolve_manifest_write_set(write_set_request(&["PERSONAL", "MAN-1", "MAN-3"], &["MAN-1", "MAN-2", "MAN-3"], held));++ let written: Vec<&str> = set.records.iter().map(|r| r.manifest_id.as_str()).collect();+ assert_eq!(written, vec!["PERSONAL", "MAN-1", "MAN-3"]);+ assert_eq!(set.skipped.len(), 1);+ assert_eq!(set.skipped[0].manifest_id, "MAN-2");+}++// ─────────────────────────────────────────────────────────────────────────────+// Access partitioning+// ─────────────────────────────────────────────────────────────────────────────++#[test]+fn access_splits_unwritable_from_lost() {+ let partition = partition_manifest_access(ManifestAccessRequest {+ manifest_ids_in_vault: vec!["PERSONAL".to_string(), "MAN-1".to_string(), "MAN-GONE".to_string()],+ writable_manifest_ids: vec!["personal".to_string(), "man-1".to_string()],+ granted_manifest_ids: vec!["PERSONAL".to_string(), "MAN-1".to_string()],+ });++ assert_eq!(partition.unwritable, vec!["MAN-GONE".to_string()]);+ assert_eq!(partition.lost, vec!["MAN-GONE".to_string()]);+}++#[test]+fn nothing_is_lost_while_nothing_is_known() {+ // No snapshot this session, so nothing is known about what the account may open.+ let partition = partition_manifest_access(ManifestAccessRequest {+ manifest_ids_in_vault: vec!["PERSONAL".to_string(), "MAN-1".to_string()],+ writable_manifest_ids: vec!["PERSONAL".to_string()],+ granted_manifest_ids: vec![],+ });++ assert_eq!(partition.unwritable, vec!["MAN-1".to_string()]);+ assert!(partition.lost.is_empty());+}++#[test]+fn a_manifest_that_is_served_but_did_not_open_is_unwritable_without_being_lost() {+ // A blob that fails to decrypt once is still this account's, so its rows must not be dropped.+ let partition = partition_manifest_access(ManifestAccessRequest {+ manifest_ids_in_vault: vec!["PERSONAL".to_string(), "MAN-1".to_string()],+ writable_manifest_ids: vec!["PERSONAL".to_string()],+ granted_manifest_ids: vec!["PERSONAL".to_string(), "MAN-1".to_string()],+ });++ assert_eq!(partition.unwritable, vec!["MAN-1".to_string()]);+ assert!(partition.lost.is_empty());+}++#[test]+fn a_vault_that_agrees_with_its_access_reports_nothing() {+ let partition = partition_manifest_access(ManifestAccessRequest {+ manifest_ids_in_vault: vec!["PERSONAL".to_string(), "MAN-1".to_string()],+ writable_manifest_ids: vec!["PERSONAL".to_string(), "MAN-1".to_string()],+ granted_manifest_ids: vec!["PERSONAL".to_string(), "MAN-1".to_string()],+ });++ assert!(partition.unwritable.is_empty());+ assert!(partition.lost.is_empty());+}++// ─────────────────────────────────────────────────────────────────────────────+// The wire shape the hosts read+// ─────────────────────────────────────────────────────────────────────────────++#[test]+fn the_json_boundary_round_trips() {+ let input = r#"{+ "personalManifestId": "PERSONAL",+ "personalManifestSalt": "personal-salt",+ "stampedManifestIds": ["PERSONAL", "MAN-1"],+ "openedManifestIds": ["MAN-1"],+ "heldRecords": [{ "manifestId": "MAN-1", "salt": "salt-1", "encryptedVek": "ignored", "canAdminister": true }],+ "displayNames": { "man-1": "Family" }+ }"#;++ let output: serde_json::Value = serde_json::from_str(&resolve_manifest_write_set_json(input).unwrap()).unwrap();+ assert_eq!(output["records"][1]["manifestId"], "MAN-1");+ assert_eq!(output["records"][1]["name"], "Family");+ assert_eq!(output["records"][1]["isPersonal"], false);+ assert_eq!(output["skipped"].as_array().unwrap().len(), 0);+}++#[test]+fn a_skip_reason_is_a_stable_token() {+ let set = resolve_manifest_write_set(write_set_request(&["PERSONAL"], &[], vec![record("MAN-1", None)]));+ let json = serde_json::to_value(&set).unwrap();+ assert_eq!(json["skipped"][0]["reason"], "NO_ROWS_IN_VAULT");+}diff --git a/core/rust/src/vault_sharing/types.rs b/core/rust/src/vault_sharing/types.rsnew file mode 100644index 000000000..9de8a6e3e--- /dev/null+++ b/core/rust/src/vault_sharing/types.rs@@ -0,0 +1,118 @@+//! Input and output types for the sharing write logic.+use std::collections::HashMap;++use serde::{Deserialize, Serialize};++/// Lower-cased comparison key for a manifest id.+pub(crate) fn id_key(id: &str) -> String {+ id.trim().to_lowercase()+}++/// A shared manifest's key record.+#[derive(Debug, Clone, Deserialize, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct SharedManifestRecord {+ /// Id of the manifest this record holds the key to.+ pub manifest_id: String,+ /// Salt this manifest's blob hashes are derived with.+ pub salt: String,+ /// Name as recorded on the last pull.+ #[serde(default)]+ pub name: Option<String>,+ /// Whether this account may publish the manifest's email delivery key.+ #[serde(default)]+ pub can_administer: bool,+}++/// Input for resolving a push's write set.+#[derive(Debug, Clone, Deserialize, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct ManifestWriteSetRequest {+ /// The vault's own manifest.+ pub personal_manifest_id: String,+ /// Salt the personal manifest's blob hashes are derived with.+ pub personal_manifest_salt: String,+ /// Every manifest the local vault holds rows for.+ #[serde(default)]+ pub stamped_manifest_ids: Vec<String>,+ /// The shared manifests whose grant this session unwrapped.+ #[serde(default)]+ pub opened_manifest_ids: Vec<String>,+ /// The shared-manifest key records this client holds.+ #[serde(default)]+ pub held_records: Vec<SharedManifestRecord>,+ /// What this client renders each manifest as, keyed by manifest id.+ #[serde(default)]+ pub display_names: HashMap<String, String>,+}++/// Why a manifest is left out of the write.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]+pub enum WriteSkipReason {+ /// The vault holds no rows for it, so writing would delete all its rows.+ NoRowsInVault,+ /// Its grant did not unwrap in this session.+ KeyDidNotOpen,+}++/// One manifest left out of the write, for the caller to log.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct SkippedManifest {+ /// Id of the manifest that was left out.+ pub manifest_id: String,+ /// Why it was left out.+ pub reason: WriteSkipReason,+}++/// One manifest the push writes. Carries no key; the caller looks the VEK up by id.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct ManifestWriteRecord {+ /// Id of the manifest to write.+ pub manifest_id: String,+ /// Whether this is the vault's own manifest.+ pub is_personal: bool,+ /// Salt this manifest's blob hashes are derived with.+ pub salt: String,+ /// Name to write into the manifest, or none.+ pub name: Option<String>,+ /// Whether this account may publish the manifest's email delivery key.+ pub can_administer: bool,+}++/// The manifests a push writes, personal first, plus what was left out.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct ManifestWriteSet {+ /// The manifests to write, personal manifest first.+ pub records: Vec<ManifestWriteRecord>,+ /// The manifests left out, with the reason for each.+ pub skipped: Vec<SkippedManifest>,+}++/// Input for splitting a vault by what the account can still open.+#[derive(Debug, Clone, Deserialize, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct ManifestAccessRequest {+ /// Every manifest the local vault holds rows for.+ #[serde(default)]+ pub manifest_ids_in_vault: Vec<String>,+ /// The manifests this session can write: the personal one plus every grant that opened.+ #[serde(default)]+ pub writable_manifest_ids: Vec<String>,+ /// The manifests the last snapshot served. Empty means nothing is known yet.+ #[serde(default)]+ pub granted_manifest_ids: Vec<String>,+}++/// What the vault holds but cannot write, and what it holds but has lost access to.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct ManifestAccessPartition {+ /// Held but not writable, which the caller repairs before pushing.+ pub unwritable: Vec<String>,+ /// Held but no longer served to this account, so its rows are deleted.+ pub lost: Vec<String>,+}diff --git a/core/rust/src/wasm.rs b/core/rust/src/wasm.rsindex 79995533e..9c06d9516 100644--- a/core/rust/src/wasm.rs+++ b/core/rust/src/wasm.rs@@ -11,6 +11,7 @@ use crate::vault_codec::{self, CanonicalizeInput, DataBucket, ExtractBucketsInput, Manifest, MaterializeInput,};use crate::vault_merge::{merge_vaults, MergeInput, MergeOutput};+use crate::vault_sharing::{self, ManifestAccessRequest, ManifestWriteSetRequest};use crate::vault_pruner::{prune_vault, PruneInput, PruneOutput};#[wasm_bindgen]@@ -251,6 +252,35 @@ pub fn vault_codec_extract_encryption_key_for_public_key_js(manifest: JsValue, pcodec_to_js(&vault_codec::extract_encryption_key_for_public_key(&m, public_key))}+// ═══════════════════════════════════════════════════════════════════════════════+// Vault Sharing WASM Bindings+// ═══════════════════════════════════════════════════════════════════════════════++/// Serialize a sharing output to a JsValue.+fn sharing_to_js<T: serde::Serialize>(value: &T) -> Result<JsValue, JsValue> {+ value+ .serialize(&serde_wasm_bindgen::Serializer::new().serialize_maps_as_objects(true).serialize_missing_as_null(true))+ .map_err(|e| JsValue::from_str(&format!("Failed to serialize sharing output: {}", e)))+}++/// Resolve which manifests the next push writes, personal manifest first.+/// Input: `ManifestWriteSetRequest`. Output: `ManifestWriteSet`.+#[wasm_bindgen(js_name = vaultSharingResolveManifestWriteSet)]+pub fn vault_sharing_resolve_manifest_write_set_js(input: JsValue) -> Result<JsValue, JsValue> {+ let input: ManifestWriteSetRequest = serde_wasm_bindgen::from_value(input)+ .map_err(|e| JsValue::from_str(&format!("Failed to parse manifest-write-set request: {}", e)))?;+ sharing_to_js(&vault_sharing::resolve_manifest_write_set(input))+}++/// Split what the vault holds into what cannot be written and what access was lost.+/// Input: `ManifestAccessRequest`. Output: `ManifestAccessPartition`.+#[wasm_bindgen(js_name = vaultSharingPartitionManifestAccess)]+pub fn vault_sharing_partition_manifest_access_js(input: JsValue) -> Result<JsValue, JsValue> {+ let input: ManifestAccessRequest = serde_wasm_bindgen::from_value(input)+ .map_err(|e| JsValue::from_str(&format!("Failed to parse manifest-access request: {}", e)))?;+ sharing_to_js(&vault_sharing::partition_manifest_access(input))+}+// ═══════════════════════════════════════════════════════════════════════════════// Credential Matcher WASM Bindings// ═══════════════════════════════════════════════════════════════════════════════