Skip to content

Build your personal knowledge base with Trilium Notes

packages/backup container: increase test coverage

Adorian Dorane58fae11d180
diff --git a/packages/trilium-backup-container/src/backend-node.ts b/packages/trilium-backup-container/src/backend-node.ts
index 3ddf81e8e3..f3502440fe 100644
--- a/packages/trilium-backup-container/src/backend-node.ts
+++ b/packages/trilium-backup-container/src/backend-node.ts
@@ -1,6 +1,15 @@
-import { createCipheriv, createDecipheriv, createHash, randomBytes, scrypt } from "node:crypto";
+import {
+ type BinaryLike,
+ createCipheriv,
+ createDecipheriv,
+ createHash,
+ randomBytes,
+ scrypt,
+ type ScryptOptions
+} from "node:crypto";
import { once } from "node:events";
import type { Duplex } from "node:stream";
+import { promisify } from "node:util";
import { createGunzip, createGzip } from "node:zlib";
import type { ByteSource, ContainerBackend } from "./backend.js";
@@ -30,28 +39,15 @@ export const nodeBackend: ContainerBackend = {
};
},
- deriveKey(passphrase, salt, params, maxMemoryBytes) {
- const options = {
+ // Async, which is what makes both of scrypt's failure modes one thing to the caller: it refuses
+ // impossible parameters by throwing where it is called and reports everything else through the
+ // callback, and an async function turns the first of those into a rejection like the second.
+ async deriveKey(passphrase, salt, params, maxMemoryBytes) {
+ return scryptAsync(passphrase, salt, KEY_BYTES, {
N: 2 ** params.log2N,
r: params.r,
p: params.p,
maxmem: maxMemoryBytes
- };
-
- return new Promise((resolve, reject) => {
- // scrypt rejects impossible parameters synchronously and everything else through the
- // callback.
- try {
- scrypt(
- passphrase,
- salt,
- KEY_BYTES,
- options,
- (error, key) => (error ? reject(error) : resolve(key))
- );
- } catch (error) {
- reject(error);
- }
});
},
@@ -86,6 +82,9 @@ export const nodeBackend: ContainerBackend = {
};
+/** Spelled out because `scrypt` is overloaded, and `promisify` picks the wrong one on its own. */
+const scryptAsync = promisify<BinaryLike, BinaryLike, number, ScryptOptions, Buffer>(scrypt);
+
/**
* Runs a byte source through a zlib stream, yielding what comes out the other side.
*
diff --git a/packages/trilium-backup-container/src/container.spec.ts b/packages/trilium-backup-container/src/container.spec.ts
index 89ec545e2a..fbc64b7ef1 100644
--- a/packages/trilium-backup-container/src/container.spec.ts
+++ b/packages/trilium-backup-container/src/container.spec.ts
@@ -9,6 +9,7 @@ import {
HEADER_BYTES_ENCRYPTED,
HEADER_BYTES_PLAIN,
containerSize,
+ SCRYPT_DEFAULTS,
TRAILER_BYTES,
TAG_BYTES
} from "./format.js";
@@ -564,3 +565,40 @@ describe("forward-only writing", () => {
expect((await readFromBuffer(written.bytes)).result.bytesWritten).toBe(database.length);
});
});
+
+describe("what the trailer is holding the file to", () => {
+ it("refuses a payload that is not the length the trailer counted", async () => {
+ const database = fakeDatabase(9_000);
+ const written = await writeToBuffer(database, { plaintextSize: database.length });
+
+ // The size field alone, leaving the digest beside it intact: this is the check that stands
+ // on its own, rather than the one the digest would have caught anyway.
+ const lying = Buffer.from(written.bytes);
+ lying.writeBigUInt64LE(8_000n, lying.length - 8);
+
+ expect(await failureOf(lying)).toBe("size-mismatch");
+ });
+
+ it("reads a container whose payload is shorter than its own trailer", async () => {
+ // The edge the rolling window exists for: with nothing but a trailer left to look at, the
+ // reader has to hold all of it back rather than emit any of it as payload.
+ const written = await writeToBuffer(Buffer.alloc(0));
+
+ expect(written.bytes).toHaveLength(containerSize(0, false));
+
+ const read = await readFromBuffer(written.bytes, { requireSqliteHeader: false });
+ expect(read.bytes).toHaveLength(0);
+ });
+
+});
+
+describe("the cost of a key nobody chose", () => {
+ it("derives at the recommended cost when the caller does not say", async () => {
+ // Every other test here asks for a cheap derivation, which leaves the default untried; it
+ // is the one real users get, and the one whose bounds a reader checks against.
+ const written = await writeToBuffer(fakeDatabase(4096), { passphrase: PASSPHRASE });
+
+ expect([ ...written.bytes.subarray(41, 44) ])
+ .toEqual([ SCRYPT_DEFAULTS.log2N, SCRYPT_DEFAULTS.r, SCRYPT_DEFAULTS.p ]);
+ });
+});
diff --git a/packages/trilium-backup-container/src/internals.spec.ts b/packages/trilium-backup-container/src/internals.spec.ts
index 622b56367a..ac465d510d 100644
--- a/packages/trilium-backup-container/src/internals.spec.ts
+++ b/packages/trilium-backup-container/src/internals.spec.ts
@@ -121,3 +121,60 @@ describe("compressed payload damage", () => {
expect(reason).toMatch(/no reason: Error: EIO/);
});
});
+
+describe("the node zlib plumbing", () => {
+ it("tears the stream down when the source it is fed fails partway", async () => {
+ let sourceClosed = false;
+ const poisoned = (async function* (): AsyncGenerator<Uint8Array> {
+ try {
+ yield fakeDatabase(1024);
+ // Not a byte chunk at all, which zlib refuses mid-write.
+ yield {} as unknown as Uint8Array;
+ } finally {
+ sourceClosed = true;
+ }
+ })();
+
+ const failure = await collect(nodeBackend.gzip(poisoned, 6)).catch((thrown) => thrown);
+
+ // Untranslated: a compressor that was handed nonsense is not a damaged payload.
+ expect(failure).toBeInstanceOf(Error);
+ expect(isBackupContainerError(failure)).toBe(false);
+ // The half that reads has to end too, or a failed backup leaves the database being read.
+ expect(sourceClosed).toBe(true);
+ });
+
+ it("stops feeding a stream the reader has walked away from", async () => {
+ let sourceClosed = false;
+ const source = (async function* (): AsyncGenerator<Uint8Array> {
+ try {
+ // More than the stream will buffer, so the writing half is still mid-flight when
+ // the reader leaves rather than already done.
+ for (let sent = 0; sent < 32; sent++) {
+ yield fakeDatabase(256 * 1024);
+ }
+ } finally {
+ sourceClosed = true;
+ }
+ })();
+
+ for await (const chunk of nodeBackend.gzip(source, 6)) {
+ expect(chunk.length).toBeGreaterThan(0);
+ break;
+ }
+
+ // A reader is entitled to take one chunk and go. What must not happen is the database
+ // going on being read into a stream that was torn down behind it.
+ await new Promise((resolve) => setImmediate(resolve));
+ expect(sourceClosed).toBe(true);
+ });
+});
+
+async function collect(source: AsyncIterable<Uint8Array>): Promise<Buffer> {
+ const chunks: Uint8Array[] = [];
+ for await (const chunk of source) {
+ chunks.push(chunk);
+ }
+
+ return Buffer.concat(chunks);
+}
diff --git a/packages/trilium-backup-container/src/read.ts b/packages/trilium-backup-container/src/read.ts
index 5c3236dc0b..2aeb1a6553 100644
--- a/packages/trilium-backup-container/src/read.ts
+++ b/packages/trilium-backup-container/src/read.ts
@@ -247,6 +247,9 @@ export async function readContainer(
// The payload readers always leave one behind or throw, so this is a guard on their contract
// rather than on the file.
const trailer = found.trailer;
+ /* v8 ignore next 3 -- no input reaches it: both readers end by decoding a trailer, which either
+ assigns this or throws `truncated` itself. It stands so a reader added later cannot return
+ having quietly skipped the digest. */
if (!trailer) {
throw new BackupContainerError("truncated", "The container ended without a trailer.");
}
diff --git a/packages/trilium-backup-container/vite.config.ts b/packages/trilium-backup-container/vite.config.ts
index 183c74e6f0..49a05f7b58 100644
--- a/packages/trilium-backup-container/vite.config.ts
+++ b/packages/trilium-backup-container/vite.config.ts
@@ -16,11 +16,14 @@ export default defineConfig(() => ({
[ "junit", { outputFile: "./test-output/vitest/junit.xml", addFileAttribute: true } ]
],
coverage: {
+ // Every line, and every branch that any input can reach. What no input reaches carries
+ // a `v8 ignore` naming the caller that makes it unreachable, so the exceptions are
+ // read and argued rather than absorbed into a percentage.
thresholds: {
- lines: 99,
+ lines: 100,
functions: 100,
- branches: 98,
- statements: 99
+ branches: 100,
+ statements: 100
},
reportsDirectory: "./test-output/vitest/coverage",
provider: "v8" as const,