Skip to content

Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.

Create email delivery keypair on account creation in new apps/web (#2439)

Leendert de Borst905ad4adb585
diff --git a/.github/actions/start-smtp-service/action.yml b/.github/actions/start-smtp-service/action.yml
new file mode 100644
index 000000000..9946eb99f
--- /dev/null
+++ b/.github/actions/start-smtp-service/action.yml
@@ -0,0 +1,60 @@
+name: "Start SMTP Service"
+description: "Sets up .NET, builds AliasVault.SmtpService and starts it in the background on ports 25 and 587 against an existing PostgreSQL database (start the API first, it applies the migrations)"
+inputs:
+ database:
+ description: "Name of the PostgreSQL database the SMTP service stores mail in (the same one the API uses)"
+ required: true
+ db-port:
+ description: "Port PostgreSQL listens on (5109 for ./scripts/dev.sh db-start, 5432 for a runner-installed PostgreSQL)"
+ required: false
+ default: "5109"
+ private-email-domains:
+ description: "Comma-separated domains the SMTP service accepts mail for (match the API's PRIVATE_EMAIL_DOMAINS)"
+ required: true
+
+outputs:
+ log-file:
+ description: "Path of the SMTP service log"
+ value: /tmp/smtp-service.log
+
+runs:
+ using: "composite"
+ steps:
+ - name: Setup .NET
+ uses: actions/setup-dotnet@v5
+ with:
+ dotnet-version: 10.0.x
+
+ - name: Build SMTP service
+ shell: bash
+ working-directory: apps/server
+ run: dotnet build Services/AliasVault.SmtpService
+
+ # The service listens on the fixed ports 25 and 587; let the non-root runner user bind them.
+ - name: Allow binding the SMTP ports
+ shell: bash
+ run: sudo sysctl -w net.ipv4.ip_unprivileged_port_start=25
+
+ - name: Start SMTP service
+ shell: bash
+ working-directory: apps/server/Services/AliasVault.SmtpService
+ run: |
+ dotnet run --no-build --no-launch-profile > /tmp/smtp-service.log 2>&1 &
+ echo "Waiting for the SMTP service to start..."
+ for i in {1..30}; do
+ # Ready once port 25 answers with the 220 greeting.
+ if timeout 2 bash -c 'exec 3<>/dev/tcp/127.0.0.1/25 && head -c 3 <&3' 2>/dev/null | grep -q 220; then
+ echo "SMTP service is ready!"
+ exit 0
+ fi
+ echo "Attempt $i: SMTP service not ready yet..."
+ sleep 2
+ done
+ echo "::error::SMTP service did not start within 60 seconds"
+ tail -n 100 /tmp/smtp-service.log
+ exit 1
+ env:
+ DOTNET_ENVIRONMENT: "Development"
+ ConnectionStrings__AliasServerDbContext: "Host=localhost;Port=${{ inputs.db-port }};Database=${{ inputs.database }};Username=aliasvault;Password=password"
+ PRIVATE_EMAIL_DOMAINS: ${{ inputs.private-email-domains }}
+ SMTP_TLS_ENABLED: "false"
diff --git a/.github/workflows/e2e-tests-web.yml b/.github/workflows/e2e-tests-web.yml
index cae2482f2..a7ef2a01f 100644
--- a/.github/workflows/e2e-tests-web.yml
+++ b/.github/workflows/e2e-tests-web.yml
@@ -11,6 +11,8 @@ on:
- '.github/workflows/e2e-tests-web.yml'
- '.github/actions/build-core-libraries/**'
- '.github/actions/start-api-server/**'
+ - '.github/actions/start-smtp-service/**'
+ - 'apps/server/Services/AliasVault.SmtpService/**'
pull_request:
branches: [ "main" ]
paths:
@@ -20,6 +22,8 @@ on:
- '.github/workflows/e2e-tests-web.yml'
- '.github/actions/build-core-libraries/**'
- '.github/actions/start-api-server/**'
+ - '.github/actions/start-smtp-service/**'
+ - 'apps/server/Services/AliasVault.SmtpService/**'
workflow_dispatch:
concurrency:
@@ -53,6 +57,12 @@ jobs:
with:
database: aliasdb_e2e_web
+ - name: Start SMTP service
+ uses: ./.github/actions/start-smtp-service
+ with:
+ database: aliasdb_e2e_web
+ private-email-domains: "example.tld,example2.tld,aliasvault.net,disabled.tld"
+
- name: Install web app dependencies
run: npm ci
working-directory: apps/web
@@ -100,3 +110,12 @@ jobs:
path: /tmp/api-server.log
retention-days: 30
if-no-files-found: ignore
+
+ - name: Upload SMTP service log on failure
+ if: failure()
+ uses: actions/upload-artifact@v7
+ with:
+ name: web-smtp-service-log
+ path: /tmp/smtp-service.log
+ retention-days: 30
+ if-no-files-found: ignore
diff --git a/apps/web/tests/e2e/05-email.spec.ts b/apps/web/tests/e2e/05-email.spec.ts
new file mode 100644
index 000000000..db5c81380
--- /dev/null
+++ b/apps/web/tests/e2e/05-email.spec.ts
@@ -0,0 +1,65 @@
+/**
+ * Category 5: Email (requires API and SMTP service, e.g. `./scripts/dev.sh smtp`)
+ */
+import { test, expect } from '../fixtures';
+import { isSmtpAvailable, resolveSmtpTarget, sendMail } from '../helpers/smtp';
+
+test.describe('5. Email', () => {
+ test.beforeAll(async () => {
+ const { host, port } = resolveSmtpTarget();
+ const available = await isSmtpAvailable();
+ const hint = `No SMTP service at ${host}:${port}. Start it with ./scripts/dev.sh smtp, or set ALIASVAULT_SMTP_HOST / ALIASVAULT_SMTP_PORT.`;
+ // CI starts the SMTP service, so a missing one there is a failure, not a reason to skip.
+ if (!available && process.env.CI) {
+ throw new Error(hint);
+ }
+ test.skip(!available, hint);
+ });
+
+ test('5.1 should receive and decrypt mail on an alias of a new account', async ({ app, testUser }) => {
+ const { page } = app;
+ const id = Math.random().toString(36).substring(2, 10);
+ const address = `e2e_${id}@example.tld`;
+ // Short, as the item page truncates long subjects.
+ const subject = `Mail ${id}`;
+
+ await app.login(testUser.username, testUser.password);
+
+ await test.step('create a login item with an address on a private domain', async () => {
+ await page.locator('#quickIdentityButton').click();
+ await page.locator('#serviceName').fill('Mail test');
+ await page.locator('#quickIdentitySubmit').click();
+ await page.getByRole('button', { name: 'Email', exact: true }).click();
+ await page.locator('#email').fill(address);
+ await app.saveItemButton().click();
+ await expect(page.getByText('Item created successfully')).toBeVisible();
+ await app.expectItemView('Mail test');
+ });
+
+ await test.step('the SMTP service accepts mail for the address', async () => {
+ /*
+ * The service answers 550 after DATA when none of the vaults carrying the address published an email delivery
+ * key, so a failure here (and not a missing email later) means the vault never created its keypair.
+ */
+ await sendMail({
+ to: address,
+ subject,
+ text: 'This is a test email plain.',
+ html: '<html><body><h1>Test Email</h1><p>Link: <a href="https://example.com">Example</a></p></body></html>',
+ });
+ });
+
+ await test.step('the email shows decrypted on the item page', async () => {
+ await page.locator('#recent-email-refresh').click();
+ await expect(page.getByText(subject)).toBeVisible();
+ });
+
+ await test.step('and on the emails page', async () => {
+ await page.getByRole('link', { name: 'Emails', exact: true }).first().click();
+ await expect(page).toHaveURL(/\/emails$/);
+ // The page renders a mobile and a desktop list; only one of them is shown.
+ await expect(page.getByText(subject).filter({ visible: true }).first()).toBeVisible();
+ });
+ });
+});
diff --git a/apps/web/tests/fixtures/WebApp.ts b/apps/web/tests/fixtures/WebApp.ts
index 4a1fcc6c8..d867ce50a 100644
--- a/apps/web/tests/fixtures/WebApp.ts
+++ b/apps/web/tests/fixtures/WebApp.ts
@@ -35,7 +35,15 @@ export class WebApp {
await expect(this.page).toHaveURL(/\/user\/login$/);
await this.submitLogin(username, password);
- await expect(this.page).toHaveURL(/\/(items|welcome)$/);
+
+ /*
+ * An empty vault without the tutorial done opens on /items and moves on to /welcome once the items page loaded,
+ * so wait until the items page is done loading (or the tutorial shows) before looking at the URL.
+ */
+ await expect(async () => {
+ expect(this.page.url()).toMatch(/\/(items|welcome)$/);
+ await expect(this.page.locator('.aliasvault-spinner-inline')).toHaveCount(0, { timeout: 0 });
+ }).toPass();
if (this.page.url().endsWith('/welcome')) {
await this.finishTutorial();
}
diff --git a/apps/web/tests/helpers/smtp.ts b/apps/web/tests/helpers/smtp.ts
new file mode 100644
index 000000000..253579343
--- /dev/null
+++ b/apps/web/tests/helpers/smtp.ts
@@ -0,0 +1,170 @@
+/**
+ * Minimal SMTP client, used to deliver test mail to a running AliasVault SMTP service.
+ */
+import { connect, type Socket } from 'node:net';
+
+/**
+ * Where the SMTP service listens: ALIASVAULT_SMTP_HOST / ALIASVAULT_SMTP_PORT, else port 25 of this machine
+ * (the fixed port of `./scripts/dev.sh smtp`). IPv4 on purpose, so a Docker stack bound to [::]:25 is not hit instead.
+ */
+export function resolveSmtpTarget(): { host: string; port: number } {
+ return {
+ host: process.env.ALIASVAULT_SMTP_HOST || '127.0.0.1',
+ port: Number(process.env.ALIASVAULT_SMTP_PORT || 25),
+ };
+}
+
+/**
+ * A message to send.
+ */
+export type TestMail = {
+ from: string;
+ to: string;
+ subject: string;
+ text: string;
+ html: string;
+};
+
+/**
+ * Whether an SMTP service answers with its greeting.
+ */
+export async function isSmtpAvailable(): Promise<boolean> {
+ try {
+ const session = await SmtpSession.open();
+ await session.close();
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Send a message; throws with the server reply when any step is refused, e.g. when AliasVault rejects the recipient.
+ */
+export async function sendMail(mail: TestMail): Promise<void> {
+ const session = await SmtpSession.open();
+ try {
+ await session.command('EHLO e2e.test', 250, 'EHLO');
+ await session.command(`MAIL FROM:<${mail.from}>`, 250, 'MAIL FROM');
+ await session.command(`RCPT TO:<${mail.to}>`, 250, 'RCPT TO');
+ await session.command('DATA', 354, 'DATA');
+ await session.command(`${buildMessage(mail)}\r\n.`, 250, 'message');
+ } finally {
+ await session.close();
+ }
+}
+
+/**
+ * A multipart/alternative message with a text and an HTML part.
+ */
+function buildMessage(mail: TestMail): string {
+ const boundary = `e2e-${Date.now()}`;
+ const lines = [
+ `From: E2E Sender <${mail.from}>`,
+ `To: <${mail.to}>`,
+ `Subject: ${mail.subject}`,
+ `Date: ${new Date().toUTCString()}`,
+ 'MIME-Version: 1.0',
+ `Content-Type: multipart/alternative; boundary="${boundary}"`,
+ '',
+ `--${boundary}`,
+ 'Content-Type: text/plain; charset=utf-8',
+ '',
+ mail.text,
+ `--${boundary}`,
+ 'Content-Type: text/html; charset=utf-8',
+ '',
+ mail.html,
+ `--${boundary}--`,
+ ];
+ // Dot-stuffing: a line starting with "." would otherwise end the DATA section early.
+ return lines.map(line => (line.startsWith('.') ? `.${line}` : line)).join('\r\n');
+}
+
+/**
+ * One SMTP connection that sends a command at a time and waits for its (possibly multi-line) reply.
+ */
+class SmtpSession {
+ private buffer = '';
+ private waiter: ((reply: string) => void) | null = null;
+
+ /**
+ * Wrap a connected socket.
+ */
+ private constructor(private readonly socket: Socket) {
+ socket.setEncoding('utf8');
+ socket.on('data', (chunk: string) => {
+ this.buffer += chunk;
+ this.flush();
+ });
+ }
+
+ /**
+ * Connect and wait for the 220 greeting.
+ */
+ public static open(): Promise<SmtpSession> {
+ const { host, port } = resolveSmtpTarget();
+ return new Promise((resolve, reject) => {
+ const socket = connect({ host, port, timeout: 5000 });
+ socket.once('timeout', () => {
+ socket.destroy();
+ reject(new Error(`SMTP connection to ${host}:${port} timed out`));
+ });
+ socket.once('error', reject);
+ socket.once('connect', () => {
+ const session = new SmtpSession(socket);
+ session.expect(220).then(() => resolve(session), reject);
+ });
+ });
+ }
+
+ /**
+ * Send one command and check the reply code.
+ */
+ public async command(line: string, expectedCode: number, step: string): Promise<string> {
+ this.socket.write(`${line}\r\n`);
+ return this.expect(expectedCode, step);
+ }
+
+ /**
+ * Say goodbye and close the connection.
+ */
+ public async close(): Promise<void> {
+ if (!this.socket.destroyed) {
+ this.socket.end('QUIT\r\n');
+ }
+ }
+
+ /**
+ * Wait for the next reply and check its code.
+ */
+ private async expect(expectedCode: number, step = 'greeting'): Promise<string> {
+ const reply = await new Promise<string>((resolve) => {
+ this.waiter = resolve;
+ this.flush();
+ });
+ if (!reply.startsWith(String(expectedCode))) {
+ throw new Error(`SMTP ${step} refused, expected ${expectedCode} but got: ${reply.trim()}`);
+ }
+ return reply;
+ }
+
+ /**
+ * Hand a complete reply to the waiter; a reply ends at a line with a space after the code ("250 OK").
+ */
+ private flush(): void {
+ if (!this.waiter) {
+ return;
+ }
+ const lines = this.buffer.split('\r\n');
+ const lastIndex = lines.findIndex(l => /^\d{3} /.test(l) || /^\d{3}$/.test(l));
+ if (lastIndex === -1) {
+ return;
+ }
+ const reply = lines.slice(0, lastIndex + 1).join('\n');
+ this.buffer = lines.slice(lastIndex + 1).join('\r\n');
+ const waiter = this.waiter;
+ this.waiter = null;
+ waiter(reply);
+ }
+}
diff --git a/core/rust/src/vault_sync/push.rs b/core/rust/src/vault_sync/push.rs
index 1bd5f6bb4..fb1c891ad 100644
--- a/core/rust/src/vault_sync/push.rs
+++ b/core/rust/src/vault_sync/push.rs
@@ -186,7 +186,8 @@ pub(crate) async fn upload_vault(ctx: &mut Ctx, cache: Option<(u64, Canonicalize
let create_vault_key = create_vault_key || !keys::has_local_vault_key(&ctx.host).await?;
let scopes = ctx.request.dirty_scopes.clone();
- let bucket_only = !force_full_write && !create_vault_key && !scopes.is_empty() && !scopes.iter().any(|s| s == MANIFEST_SCOPE);
+ // A missing delivery keypair is created on the full path only, as publishing it takes a manifest write.
+ let bucket_only = !force_full_write && !create_vault_key && !scopes.is_empty() && !scopes.iter().any(|s| s == MANIFEST_SCOPE) && !personal_delivery_key_missing(ctx).await?;
let (status, vault_changed) = if bucket_only {
(upload_dirty_buckets_only(ctx, &scopes).await?, false)
@@ -230,21 +231,26 @@ async fn upload_dirty_buckets_only(ctx: &mut Ctx, scopes: &[String]) -> SyncResu
Ok(PushStatus::Ok)
}
-/// Upload a new version of the vault, pruning expired trash items first. Returns the status and whether the
-/// stored vault changed (pruned or re-keyed).
+/// Upload a new version of the vault, pruning expired trash items and creating a missing personal delivery keypair
+/// first. Returns the status and whether the stored vault changed (pruned, keypair added or re-keyed).
async fn upload_new_vault_to_server(ctx: &mut Ctx, cached: Option<CanonicalizedSet>, force_full_write: bool, create_vault_key: bool) -> SyncResult<(PushStatus, bool)> {
let key_before = ctx.encryption_key()?;
let mut cached = cached;
- let mut vault_pruned = false;
+ let mut vault_rewritten = false;
match db::prune_in_place(&ctx.host, TRASH_RETENTION_DEFAULT_DAYS).await {
Ok(0) => {}
Ok(count) => {
ctx.log(format!("[VaultMerge] Pruned expired items from trash ({} SQL statements executed)", count)).await;
- vault_pruned = true;
+ vault_rewritten = true;
cached = None;
}
Err(error) => ctx.warn(format!("[VaultSync] Failed to prune vault, continuing with upload: {}", error)).await,
}
+ if personal_delivery_key_missing(ctx).await? {
+ create_personal_delivery_key(ctx).await?;
+ vault_rewritten = true;
+ cached = None;
+ }
let (status, new_key) = push(ctx, cached, create_vault_key, force_full_write).await?;
if let Some(new_key) = new_key {
@@ -255,12 +261,30 @@ async fn upload_new_vault_to_server(ctx: &mut Ctx, cached: Option<CanonicalizedS
// Re-encrypt and persist locally only when the stored blob went stale or the encryption key changed.
let key_after = ctx.encryption_key()?;
- if vault_pruned || key_after != key_before {
+ if vault_rewritten || key_after != key_before {
let bytes = db::export(&ctx.host, Db::Local).await?;
ctx.store_vault(&state::encrypt_vault_blob(&bytes, &key_after)?, false, None, None).await?;
ctx.vault_changed = true;
}
- Ok((status, vault_pruned))
+ Ok((status, vault_rewritten))
+}
+
+/// Whether the personal manifest has no active mail delivery keypair. Without one the server has no public key to
+/// encrypt incoming mail with, and rejects every email sent to the vault's aliases.
+async fn personal_delivery_key_missing(ctx: &Ctx) -> SyncResult<bool> {
+ let Some(personal_manifest_id) = state::get::<String>(&ctx.host, state::VAULT_PERSONAL_MANIFEST_ID).await? else {
+ return Ok(false);
+ };
+ Ok(db::active_public_key_for_manifest(&ctx.host, &personal_manifest_id).await?.is_none())
+}
+
+/// Create the personal manifest's mail delivery keypair in the local vault; the manifest write publishes its public half.
+async fn create_personal_delivery_key(ctx: &Ctx) -> SyncResult<()> {
+ let personal_manifest_id = resolve_personal_manifest_id(ctx).await?;
+ let pair = crypto::generate_rsa_key_pair()?;
+ db::set_active_key_for_manifest(&ctx.host, &personal_manifest_id, &pair.public_key, &pair.private_key).await?;
+ ctx.log(format!("[V2Push] Personal manifest {} had no mail delivery keypair; created one.", personal_manifest_id)).await;
+ Ok(())
}
/// The tables of one bucket category read from the local vault, as extract_buckets takes them.
diff --git a/core/rust/src/vault_sync/tests/mod.rs b/core/rust/src/vault_sync/tests/mod.rs
index a30b75619..440ce9517 100644
--- a/core/rust/src/vault_sync/tests/mod.rs
+++ b/core/rust/src/vault_sync/tests/mod.rs
@@ -41,6 +41,21 @@ fn insert_item(conn: &rusqlite::Connection, id: &str, name: &str, manifest_id: &
.unwrap();
}
+/// Give a manifest the mail delivery keypair every written vault carries.
+fn insert_delivery_key(conn: &rusqlite::Connection, manifest_id: &str) {
+ let now = crate::common::timestamp::now_vault_datetime();
+ conn.execute(
+ "INSERT INTO EncryptionKeys (Id, ManifestId, PublicKey, PrivateKey, IsPrimary, CreatedAt, UpdatedAt, IsDeleted) VALUES ('dddddddd-0000-4000-8000-000000000001', ?, 'public', 'private', 1, ?, ?, 0)",
+ rusqlite::params![manifest_id, now, now],
+ )
+ .unwrap();
+}
+
+/// The active delivery keys of a manifest in a connection.
+fn active_delivery_keys(conn: &rusqlite::Connection, manifest_id: &str) -> Vec<String> {
+ query(conn, "SELECT PublicKey FROM EncryptionKeys WHERE ManifestId = ? AND IsPrimary = 1 AND IsDeleted = 0", &[json!(manifest_id)]).unwrap().iter().map(|r| r["PublicKey"].as_str().unwrap().to_string()).collect()
+}
+
/// Read every user table of a connection into the codec's input shape.
fn read_tables(conn: &rusqlite::Connection) -> Vec<CodecTableData> {
let names: Vec<String> = query(conn, "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name", &[]).unwrap().iter().map(|r| r["name"].as_str().unwrap().to_string()).collect();
@@ -374,6 +389,78 @@ fn no_op_mutation_clears_the_dirty_flag_without_a_write() {
assert!(!host.is_dirty);
}
+/// A host that pulled a server vault at revision 7 holding one item and no mail delivery keypair.
+fn host_with_keyless_vault(vek: &str) -> TestHost {
+ let mut host = TestHost::new(vek);
+ let server_db = test_host::open_schema_db(&host.schema_sql);
+ insert_item(&server_db, "aaaaaaaa-0000-4000-8000-000000000001", "Server item", PERSONAL_MANIFEST_ID);
+ let (status, vault) = snapshot_of(&server_db, vek, 7, &vault_codec::generate_manifest_salt());
+ host.state.insert(state::ENCRYPTED_ACCOUNT_KEY.to_string(), json!("wrapped"));
+ host.respond("GET", "Status", status);
+ host.respond("GET", "Vault", vault);
+ host.drive(&SyncSession::new(&request("fullSync", vek, false, 0)).unwrap());
+ assert!(active_delivery_keys(&host.local, PERSONAL_MANIFEST_ID).is_empty());
+ host
+}
+
+/// Mark the local vault changed and sync it with the given dirty scopes; returns the result and the last vault write.
+fn push_local_edit(host: &mut TestHost, vek: &str, name: &str, scopes: &[&str]) -> (Value, Value) {
+ host.local.execute("UPDATE Items SET Name = ?, UpdatedAt = '2099-01-01 00:00:00.000'", [name]).unwrap();
+ host.store_local_as_blob();
+ host.mutation_sequence += 1;
+ host.is_dirty = true;
+ host.respond("POST", "Vault/blobs/missing", json!({ "missing": [] }));
+ host.respond("POST", "Vault", json!({ "status": 0, "manifestRevisions": [{ "manifestId": PERSONAL_MANIFEST_ID, "revision": 8 }], "bucketRevisions": [], "missingBlobHashes": [] }));
+ let mut sync = serde_json::from_str::<Value>(&request("fullSync", vek, true, host.mutation_sequence)).unwrap();
+ sync["dirtyScopes"] = json!(scopes);
+ let result = host.drive(&SyncSession::new(&sync.to_string()).unwrap());
+ let write = host.requests_to("Vault").into_iter().rfind(|r| r.method == "POST").map(|r| r.body.clone().unwrap()).unwrap_or(Value::Null);
+ (result, write)
+}
+
+#[test]
+fn push_creates_and_publishes_a_missing_personal_delivery_key() {
+ let vek = crypto::generate_key_base64();
+ let mut host = host_with_keyless_vault(&vek);
+
+ let (result, write) = push_local_edit(&mut host, &vek, "Renamed", &["Main"]);
+
+ assert_eq!(result["success"], true, "{}", result);
+ let keys = active_delivery_keys(&host.local, PERSONAL_MANIFEST_ID);
+ assert_eq!(keys.len(), 1, "the push created exactly one keypair");
+ assert_eq!(write["manifests"][0]["encryptionPublicKey"], json!(keys[0]), "the write publishes the new public key");
+
+ // The keypair travels inside the manifest, so the other devices get the private half.
+ let blob = write["manifests"][0]["manifestBlob"].as_str().unwrap();
+ let plain = crypto::symmetric_decrypt_bytes(&crate::common::encoding::base64_decode(blob).unwrap(), &vek).unwrap();
+ let manifest: Value = serde_json::from_str(&vault_codec::unpack_payload(&plain).unwrap()).unwrap();
+ assert_eq!(manifest["tables"]["EncryptionKeys"].as_array().unwrap().len(), 1);
+
+ // The stored vault holds it too, so a reload does not read the keypair as deleted.
+ let stored = state::decrypt_vault_blob(host.vault_blob.as_ref().unwrap(), &host.vault_key).unwrap();
+ assert_eq!(active_delivery_keys(&test_host::open_from_bytes(&stored), PERSONAL_MANIFEST_ID), keys);
+
+ // The next push keeps the same keypair.
+ let (again, second_write) = push_local_edit(&mut host, &vek, "Renamed again", &["Main"]);
+ assert_eq!(again["success"], true, "{}", again);
+ assert_eq!(active_delivery_keys(&host.local, PERSONAL_MANIFEST_ID), keys);
+ assert_eq!(second_write["manifests"][0]["encryptionPublicKey"], json!(keys[0]));
+}
+
+#[test]
+fn bucket_only_push_writes_the_manifest_while_the_personal_delivery_key_is_missing() {
+ let vek = crypto::generate_key_base64();
+ let mut host = host_with_keyless_vault(&vek);
+ let category = vault_codec::bucket_layout()[0].category.clone();
+
+ let (result, write) = push_local_edit(&mut host, &vek, "Renamed", &[category.as_str()]);
+
+ assert_eq!(result["success"], true, "{}", result);
+ let keys = active_delivery_keys(&host.local, PERSONAL_MANIFEST_ID);
+ assert_eq!(keys.len(), 1);
+ assert_eq!(write["manifests"][0]["encryptionPublicKey"], json!(keys[0]), "the full write publishes the key a bucket-only write could not");
+}
+
#[test]
fn outdated_push_merges_the_server_change_and_retries() {
let vek = crypto::generate_key_base64();
diff --git a/core/rust/src/vault_sync/tests/unloaded_blobs.rs b/core/rust/src/vault_sync/tests/unloaded_blobs.rs
index 556318dc1..1f4911a7f 100644
--- a/core/rust/src/vault_sync/tests/unloaded_blobs.rs
+++ b/core/rust/src/vault_sync/tests/unloaded_blobs.rs
@@ -4,7 +4,7 @@
use serde_json::{json, Value};
use super::test_host::{self, query, TestHost};
-use super::{insert_item, item_names, read_tables, request, PERSONAL_MANIFEST_ID};
+use super::{insert_delivery_key, insert_item, item_names, read_tables, request, PERSONAL_MANIFEST_ID};
use crate::crypto;
use crate::vault_codec::{self, CanonicalizeInput, ManifestSpec};
use crate::vault_sync::blob_keys;
@@ -32,6 +32,7 @@ impl ServerBlob {
fn server_db(host: &TestHost) -> rusqlite::Connection {
let db = test_host::open_schema_db(&host.schema_sql);
insert_item(&db, ITEM_ID, "Server item", PERSONAL_MANIFEST_ID);
+ insert_delivery_key(&db, PERSONAL_MANIFEST_ID);
let now = crate::common::timestamp::now_vault_datetime();
db.execute("INSERT INTO Logos (ManifestId, Id, Source, FileData, Kind, CreatedAt, UpdatedAt, IsDeleted) VALUES (?, 'bbbbbbbb-0000-4000-8000-000000000001', 'example.com', ?, 'favicon', ?, ?, 0)", rusqlite::params![PERSONAL_MANIFEST_ID, vec![1u8, 2, 3, 4], now, now]).unwrap();
db.execute("UPDATE Items SET LogoId = 'bbbbbbbb-0000-4000-8000-000000000001'", []).unwrap();