Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.
Refactor personal manifest id selection (#2159)
Leendert de Borstb9c9aad8f002
diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/BaseRepository.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/BaseRepository.ktindex 1463f1deb..18e63cf2e 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/BaseRepository.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/BaseRepository.kt@@ -18,7 +18,7 @@ open class BaseRepository(* folder or item take that parent's manifest through the SQL instead. Throws when no manifest has been* recorded yet, since an unstamped row would make every later push of the vault fail.*/- protected fun activeManifestId(): String {+ protected fun writeManifestId(): String {return database.getPersonalManifestId() ?: throw AppError.ManifestNotRecorded()}diff --git a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/PasskeyRepository.kt b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/PasskeyRepository.ktindex 4ea0ad13d..558284b63 100644--- a/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/PasskeyRepository.kt+++ b/apps/mobile-app/android/app/src/main/java/net/aliasvault/app/vaultstore/repositories/PasskeyRepository.kt@@ -144,7 +144,7 @@ class PasskeyRepository(database: VaultDatabase) : BaseRepository(database) {logo: ByteArray? = null,): Item {return withTransaction {- val manifestId = activeManifestId()+ val manifestId = writeManifestId()val itemId = passkey.parentItemId.toString().lowercase()val now = Date()val timestamp = DateHelpers.toStandardFormat(now)diff --git a/apps/mobile-app/platform/NativeDatabaseClient.ts b/apps/mobile-app/platform/NativeDatabaseClient.tsindex 9fb545055..4f3346ec5 100644--- a/apps/mobile-app/platform/NativeDatabaseClient.ts+++ b/apps/mobile-app/platform/NativeDatabaseClient.ts@@ -80,13 +80,6 @@ export class NativeDatabaseClient implements IDatabaseClient {return this.transactionOpen;}- /**- * TODO: implement multi-manifest group support.- */- public getActiveManifestId(): string | null {- return null;- }-/*** The personal manifest id, as the last sync recorded it in the native sync engine state.*/diff --git a/core/client/src/database/BaseRepository.ts b/core/client/src/database/BaseRepository.tsindex 0414fec2b..cf4432a4e 100644--- a/core/client/src/database/BaseRepository.ts+++ b/core/client/src/database/BaseRepository.ts@@ -5,7 +5,7 @@ import * as dateFormatter from '../utilities/DateFormatter';import { runAsync } from './DbOp';import { FolderQueries } from './queries/FolderQueries';-import type { DbOp, ManifestScope } from './DbOp';+import type { DbOp } from './DbOp';import type { Folder } from './repositories/FolderRepository';import type { ISqliteDatabase } from '../platform/SqliteEngine';import type { SharedManifest } from '../sharing/MultiManifestRendering';@@ -26,7 +26,6 @@ export interface IDatabaseClient {commitTransaction(scope?: VaultMutationScope): Promise<void>;rollbackTransaction(): void | Promise<void>;isInTransaction(): boolean;- getActiveManifestId(): string | null;getPersonalManifestId(): string | null | Promise<string | null>;recordMutationScope?(scope: VaultMutationScope): void;}@@ -87,31 +86,22 @@ export abstract class BaseRepository {return (yield { kind: 'execute', sql, params }) as number;}- /**- * The active and personal manifest ids of the client this op runs on.- * @returns Both ids, each null when unknown- */- protected *manifestScope(): DbOp<ManifestScope> {- return (yield { kind: 'manifestScope' }) as ManifestScope;- }-/*** The id of the user's personal manifest, as recorded by the last pull.* @returns The personal manifest id, or null when absent*/protected *personalManifestId(): DbOp<string | null> {- return (yield* this.manifestScope()).personal;+ return (yield { kind: 'personalManifestId' }) as string | null;}/**- * The manifest new rows are written into: the active manifest, else the personal one.+ * The manifest new rows outside any folder or item are written into: the personal manifest.* @returns The manifest id*/protected *writeManifestId(): DbOp<string> {- const { active, personal } = yield* this.manifestScope();- const manifestId = active ?? personal;+ const manifestId = yield* this.personalManifestId();if (!manifestId) {- throw new Error('BaseRepository: this client has no manifest recorded yet (no active manifest and no personal manifest); sync once before writing.');+ throw new Error('BaseRepository: this client has no personal manifest recorded yet; sync once before writing.');}return manifestId;}diff --git a/core/client/src/database/DbOp.ts b/core/client/src/database/DbOp.tsindex c93fd3529..53d5a0827 100644--- a/core/client/src/database/DbOp.ts+++ b/core/client/src/database/DbOp.ts@@ -8,21 +8,13 @@ import type { VaultMutationScope } from '../sync/VaultMutationScope';* asynchronous (mobile native vault store).*/-/**- * The active and personal manifest ids of the client an op runs on.- */-export type ManifestScope = {- active: string | null;- personal: string | null;-};-/*** One database step a DbOp asks its host to perform.*/export type DbEffect =| { kind: 'query'; sql: string; params: SqliteBindValue[] }| { kind: 'execute'; sql: string; params: SqliteBindValue[] }- | { kind: 'manifestScope' };+ | { kind: 'personalManifestId' };/*** A database operation that can run both synchronously and asynchronously.@@ -190,8 +182,8 @@ function performSync(effect: DbEffect, client: ISyncDatabaseClient): unknown {return client.executeQuery(effect.sql, effect.params);case 'execute':return client.executeUpdate(effect.sql, effect.params);- case 'manifestScope':- return { active: client.getActiveManifestId(), personal: client.getPersonalManifestId() } satisfies ManifestScope;+ case 'personalManifestId':+ return client.getPersonalManifestId();}}@@ -207,8 +199,8 @@ async function performAsync(effect: DbEffect, client: IDatabaseClient): Promise<return client.executeQuery(effect.sql, effect.params);case 'execute':return client.executeUpdate(effect.sql, effect.params);- case 'manifestScope':- return { active: client.getActiveManifestId(), personal: await client.getPersonalManifestId() } satisfies ManifestScope;+ case 'personalManifestId':+ return client.getPersonalManifestId();}}diff --git a/core/client/src/database/SqliteClient.ts b/core/client/src/database/SqliteClient.tsindex 24cf1bdd8..1bf481ac3 100644--- a/core/client/src/database/SqliteClient.ts+++ b/core/client/src/database/SqliteClient.ts@@ -48,12 +48,6 @@ export class SqliteClient implements ISyncDatabaseClient {*/private readonly pendingMutationScopes = new Set<VaultMutationScope>();- /**- * The manifest this client writes new rows into, when the user has switched to one explicitly.- * Null means "not chosen" and the user's personal manifest applies.- */- private activeManifestId: string | null = null;-/*** The id of the user's personal manifest.*/@@ -70,27 +64,7 @@ export class SqliteClient implements ISyncDatabaseClient {private _logoRepository: LogoRepository | null = null;/**- * The manifest new rows are stamped with when they cannot inherit one from a parent row, or null when- * the client has not switched vaults and the personal manifest applies.- * @returns The active manifest id, or null when none is set- */- public getActiveManifestId(): string | null {- return this.activeManifestId;- }-- /**- * Switch the manifest this client writes into. Pass null to go back to the personal manifest.- *- * TODO: this method is not called yet, as a null manifestId will default to the personal manifest- * which is what we want for now.- */- public setActiveManifestId(manifestId: string | null): void {- this.activeManifestId = manifestId;- }-- /**- * The id of the user's personal manifest, as reported by the last pull. It is what the client writes into while- * no other manifest is switched to.+ * The id of the user's personal manifest, as reported by the last pull.* @returns The personal manifest id, or null when no pull has recorded one yet*/public getPersonalManifestId(): string | null {diff --git a/core/client/src/database/__tests__/FieldValueRows.test.ts b/core/client/src/database/__tests__/FieldValueRows.test.tsindex fd23a140e..166d3e357 100644--- a/core/client/src/database/__tests__/FieldValueRows.test.ts+++ b/core/client/src/database/__tests__/FieldValueRows.test.ts@@ -84,14 +84,6 @@ class TestDatabaseClient implements ISyncDatabaseClient {return this.inTransaction;}- /**- * Get the manifest new rows are written into.- * @returns The personal manifest id- */- public getActiveManifestId(): string {- return PERSONAL;- }-/*** Get the personal manifest.* @returns The personal manifest iddiff --git a/core/client/src/database/queries/EncryptionKeyQueries.ts b/core/client/src/database/queries/EncryptionKeyQueries.tsindex ac58ca832..1317eb9dc 100644--- a/core/client/src/database/queries/EncryptionKeyQueries.ts+++ b/core/client/src/database/queries/EncryptionKeyQueries.ts@@ -13,16 +13,4 @@ export class EncryptionKeyQueries {x.IsPrimaryFROM EncryptionKeys xWHERE x.IsDeleted = 0`;-- /**- * Get the account keypair matching the given public half.- */- public static readonly GET_ACCOUNT_KEY_BY_PUBLIC_KEY = `- SELECT- x.PublicKey,- x.PrivateKey,- x.IsPrimary- FROM EncryptionKeys x- WHERE x.ManifestId = ? AND x.PublicKey = ? AND x.IsDeleted = 0- LIMIT 1`;}diff --git a/core/client/src/database/repositories/EncryptionKeyRepository.ts b/core/client/src/database/repositories/EncryptionKeyRepository.tsindex 545cb8e28..655f50e4f 100644--- a/core/client/src/database/repositories/EncryptionKeyRepository.ts+++ b/core/client/src/database/repositories/EncryptionKeyRepository.ts@@ -19,18 +19,4 @@ export class EncryptionKeyRepository extends BaseRepository {public *getAll(): DbOp<EncryptionKey[]> {return yield* this.query<EncryptionKey>(EncryptionKeyQueries.GET_ALL);}-- /**- * Get the account keypair matching the given public half.- * @param publicKey - The public half the grant was encrypted for- * @returns The keypair, or null when this vault holds no account key with that public half- */- public *getAccountKeypair(publicKey: string): DbOp<EncryptionKey | null> {- const personalManifestId = yield* this.personalManifestId();- if (!personalManifestId) {- return null;- }- const results = yield* this.query<EncryptionKey>(EncryptionKeyQueries.GET_ACCOUNT_KEY_BY_PUBLIC_KEY, [personalManifestId, publicKey]);- return results.length > 0 ? results[0] : null;- }}diff --git a/core/client/src/database/repositories/SettingsRepository.ts b/core/client/src/database/repositories/SettingsRepository.tsindex 184f118ec..509d023ce 100644--- a/core/client/src/database/repositories/SettingsRepository.ts+++ b/core/client/src/database/repositories/SettingsRepository.ts@@ -19,14 +19,13 @@ export type CredentialSortOrder = 'OldestFirst' | 'NewestFirst' | 'Alphabetical'*/export class SettingsRepository extends BaseRepository {/**- * Get setting from database for a given key, from the manifest this client writes into.+ * Get setting from database for a given key.* @param key - The setting key* @param defaultValue - Default value if setting not found* @returns The setting value*/public *getSetting(key: string, defaultValue: string = ''): DbOp<string> {- const { active, personal } = yield* this.manifestScope();- const manifestId = active ?? personal;+ const manifestId = yield* this.personalManifestId();if (!manifestId) {return defaultValue;}diff --git a/core/rust/src/vault_sync/db.rs b/core/rust/src/vault_sync/db.rsindex 93275543c..6f5d7470a 100644--- a/core/rust/src/vault_sync/db.rs+++ b/core/rust/src/vault_sync/db.rs@@ -222,7 +222,6 @@ pub(crate) fn new_id() -> String {}const GET_ACTIVE_PUBLIC_KEY_FOR_MANIFEST: &str = "SELECT x.PublicKey FROM EncryptionKeys x WHERE x.ManifestId = ? AND x.IsPrimary = 1 AND x.IsDeleted = 0 LIMIT 1";-const GET_ACCOUNT_KEY_BY_PUBLIC_KEY: &str = "SELECT x.PrivateKey FROM EncryptionKeys x WHERE x.ManifestId = ? AND x.PublicKey = ? AND x.IsDeleted = 0 LIMIT 1";const DEMOTE_KEYS_FOR_MANIFEST: &str = "UPDATE EncryptionKeys SET IsPrimary = 0, UpdatedAt = ? WHERE ManifestId = ? AND IsPrimary = 1";const INSERT_KEY_FOR_MANIFEST: &str = "INSERT INTO EncryptionKeys (Id, ManifestId, PublicKey, PrivateKey, IsPrimary, CreatedAt, UpdatedAt, IsDeleted) VALUES (?, ?, ?, ?, 1, ?, ?, 0)";const MANIFEST_NAMES: &str = "SELECT Id, Name FROM Manifests WHERE Name IS NOT NULL";@@ -235,12 +234,6 @@ pub(crate) async fn active_public_key_for_manifest(host: &Host, manifest_id: &stOk(rows.first().and_then(|row| row.get("PublicKey")).and_then(Value::as_str).map(str::to_string))}-/// The private half of the account keypair with the given public half, held in the personal manifest.-pub(crate) async fn account_private_key_for(host: &Host, personal_manifest_id: &str, public_key: &str) -> SyncResult<Option<String>> {- let rows = query(host, Db::Local, GET_ACCOUNT_KEY_BY_PUBLIC_KEY, vec![json!(personal_manifest_id), json!(public_key)]).await?;- Ok(rows.first().and_then(|row| row.get("PrivateKey")).and_then(Value::as_str).map(str::to_string))-}-/// Make a keypair the manifest's active one, demoting (never deleting) whatever it supersedes.pub(crate) async fn set_active_key_for_manifest(host: &Host, manifest_id: &str, public_key: &str, private_key: &str) -> SyncResult<()> {let now = now_vault_datetime();diff --git a/core/rust/src/vault_sync/keys.rs b/core/rust/src/vault_sync/keys.rsindex b29aed079..c5e129ddd 100644--- a/core/rust/src/vault_sync/keys.rs+++ b/core/rust/src/vault_sync/keys.rs@@ -6,7 +6,7 @@ use super::errors::{SyncError, SyncResult};use super::session::Host;use super::state::{self, Ctx};use super::types::{SharedManifestDto, VaultKeyGetResponse, VaultKeyResponse, ALGORITHM_RSA_OAEP_SHA256};-use super::{db, http};+use super::http;use crate::crypto;use zeroize::Zeroizing;@@ -71,14 +71,11 @@ pub(crate) async fn re_encrypt_shared_manifest_records(ctx: &Ctx, new_key: &str)}/// The private key that opens a grant made out to `public_key`.-pub(crate) async fn resolve_grant_private_key(ctx: &Ctx, public_key: &str) -> SyncResult<Option<String>> {- if ctx.account_public_key.as_deref() == Some(public_key) {- if let Some(private) = &ctx.account_private_key {- return Ok(Some(private.clone()));- }+pub(crate) fn resolve_grant_private_key(ctx: &Ctx, public_key: &str) -> Option<String> {+ if ctx.account_public_key.as_deref() != Some(public_key) {+ return None;}- let Some(personal_manifest_id) = state::get::<String>(&ctx.host, state::VAULT_PERSONAL_MANIFEST_ID).await? else { return Ok(None) };- db::account_private_key_for(&ctx.host, &personal_manifest_id, public_key).await+ ctx.account_private_key.clone()}/// Decrypt an RSA-OAEP encrypted manifest VEK.@@ -93,8 +90,8 @@ pub(crate) async fn open_shared_manifest_vek(ctx: &Ctx, record: &SharedManifestDctx.warn(format!("[Sharing] Manifest {} grants its key under an unsupported algorithm \"{}\" (newer server?); leaving it closed.", record.manifest_id, record.algorithm)).await;return Ok(None);}- let Some(private_key) = resolve_grant_private_key(ctx, &record.encryption_public_key).await? else {- ctx.warn(format!("[Sharing] No account key in this vault opens the grant on manifest {}; leaving it closed.", record.manifest_id)).await;+ let Some(private_key) = resolve_grant_private_key(ctx, &record.encryption_public_key) else {+ ctx.warn(format!("[Sharing] This session holds no account private key that opens the grant on manifest {}; leaving it closed.", record.manifest_id)).await;return Ok(None);};match decrypt_manifest_vek(&record.encrypted_vek, &private_key) {@@ -248,12 +245,11 @@ async fn adopt_vek(ctx: &mut Ctx, old_key: &str, vek: &str) -> SyncResult<()> {Ok(())}-/// Open the account private key with the Account Key and stage it for the grant flows of this run. A chain without-/// a keypair, or one whose private key does not open, leaves grant decryption to the personal manifest's key rows.+/// Open the account private key with the Account Key and stage it for the grant flows of this run.async fn stage_account_private_key(ctx: &mut Ctx, account_key: &str, encrypted_private_key: Option<&str>) {let Some(encrypted) = encrypted_private_key.filter(|e| !e.is_empty()) else { return };match crypto::symmetric_decrypt(encrypted, account_key) {Ok(private_key) => ctx.set_account_private_key(private_key),- Err(error) => ctx.warn(format!("[VaultSync] The cached account private key did not open; shared grants fall back to the vault's key rows. {}", error)).await,+ Err(error) => ctx.warn(format!("[VaultSync] The cached account private key did not open; shared grants stay closed. {}", error)).await,}}diff --git a/core/rust/src/vault_sync/pull.rs b/core/rust/src/vault_sync/pull.rsindex 9aba45e53..35b763f7e 100644--- a/core/rust/src/vault_sync/pull.rs+++ b/core/rust/src/vault_sync/pull.rs@@ -130,7 +130,7 @@ pub(crate) async fn open_manifests_and_record_sync_state(ctx: &mut Ctx, snapshotlet ordered: Vec<&ManifestDto> = std::iter::once(personal_dto).chain(snapshot.manifests.iter().filter(|m| m.manifest_id != personal_dto.manifest_id)).collect();for dto in ordered {let is_personal = dto.manifest_id == personal_dto.manifest_id;- let manifest_key = resolve_manifest_vek(ctx, dto, &personal_dto.manifest_id, vek, is_personal, resolved.first().map(|m| &m.manifest)).await?;+ let manifest_key = resolve_manifest_vek(ctx, dto, &personal_dto.manifest_id, vek, is_personal).await?;if dto.blob.as_deref().unwrap_or("").is_empty() {// A shared manifest served without content yet (created but never written); its grant and revision are still tracked.let (encrypted_vek, encryption_public_key, algorithm) = grant_of(dto).ok_or_else(|| SyncError::Snapshot(format!("shared manifest {} was served without content and without a grant, refusing to assemble", dto.manifest_id)))?;@@ -337,7 +337,7 @@ fn open_manifest(dto: &ManifestDto, vek: &str, is_personal: bool) -> SyncResult<}/// The key that opens one snapshot manifest.-async fn resolve_manifest_vek(ctx: &Ctx, dto: &ManifestDto, personal_manifest_id: &str, personal_vek: &str, is_personal: bool, personal_manifest: Option<&Manifest>) -> SyncResult<String> {+async fn resolve_manifest_vek(ctx: &Ctx, dto: &ManifestDto, personal_manifest_id: &str, personal_vek: &str, is_personal: bool) -> SyncResult<String> {let key_type = dto.key_type.clone().unwrap_or_else(|| if is_personal { types::KEY_TYPE_ACCOUNT_KEY.to_string() } else { types::KEY_TYPE_GRANT_KEY.to_string() });if key_type == types::KEY_TYPE_ACCOUNT_KEY {if dto.manifest_id != personal_manifest_id {@@ -348,25 +348,14 @@ async fn resolve_manifest_vek(ctx: &Ctx, dto: &ManifestDto, personal_manifest_idif key_type != types::KEY_TYPE_GRANT_KEY {return Err(SyncError::Snapshot(format!("manifest {} states an unknown key type \"{}\" (newer server?), refusing to assemble", dto.manifest_id, key_type)));}- let personal_manifest = personal_manifest.ok_or_else(|| SyncError::Snapshot(format!("manifest {} is opened through a grant, but no personal manifest is open to resolve the private key from, refusing to assemble", dto.manifest_id)))?;- resolve_granted_vek(ctx, personal_manifest, dto).await+ resolve_granted_vek(ctx, dto).await}-async fn resolve_granted_vek(ctx: &Ctx, personal_manifest: &Manifest, dto: &ManifestDto) -> SyncResult<String> {+async fn resolve_granted_vek(ctx: &Ctx, dto: &ManifestDto) -> SyncResult<String> {let (encrypted_vek, public_key, algorithm) = grant_of(dto).ok_or_else(|| SyncError::Snapshot(format!("shared manifest {} carries no grant to open it with, refusing to assemble", dto.manifest_id)))?;if algorithm != types::ALGORITHM_RSA_OAEP_SHA256 {return Err(SyncError::Snapshot(format!("shared manifest {} grants its VEK under an unsupported algorithm \"{}\" (newer server?), refusing to assemble", dto.manifest_id, algorithm)));}- let private_key = resolve_private_key_jwk(ctx, personal_manifest, &public_key).await?.ok_or_else(|| SyncError::Snapshot(format!("no private key in this vault opens the grant on shared manifest {}, refusing to assemble", dto.manifest_id)))?;+ let private_key = keys::resolve_grant_private_key(ctx, &public_key).ok_or_else(|| SyncError::Snapshot(format!("this session holds no account private key that opens the grant on shared manifest {}, refusing to assemble", dto.manifest_id)))?;keys::decrypt_manifest_vek(&encrypted_vek, &private_key).map_err(|e| SyncError::ServerVaultUnreadable(format!("failed to decrypt the VEK of shared manifest {}, refusing to assemble: {}", dto.manifest_id, e)))}--/// The private key (JWK) matching a grant's public key: the session's, else one the personal manifest keeps.-async fn resolve_private_key_jwk(ctx: &Ctx, personal_manifest: &Manifest, encryption_public_key: &str) -> SyncResult<Option<String>> {- if ctx.account_public_key.as_deref() == Some(encryption_public_key) {- if let Some(private) = &ctx.account_private_key {- return Ok(Some(private.clone()));- }- }- Ok(vault_codec::extract_encryption_key_for_public_key(personal_manifest, encryption_public_key).and_then(|row| row.get("PrivateKey").and_then(serde_json::Value::as_str).map(str::to_string)))-}