Skip to content

Build your personal knowledge base with Trilium Notes

core/start again: improve security

Adorian Doran499435557bb9
diff --git a/apps/client/src/services/utils.ts b/apps/client/src/services/utils.ts
index 0a0e8b302a..c490f8bfa1 100644
--- a/apps/client/src/services/utils.ts
+++ b/apps/client/src/services/utils.ts
@@ -8,23 +8,25 @@ const SVG_MIME = "image/svg+xml";
export const isShare = !window.glob;
/**
- * True when the client is showing one of the DB-initialized *pre-auth* SPA screens — the login
- * screen (`loggedIn: false`) or the set-password screen (`passwordSet: false`).
+ * True when the client is showing a *pre-auth* SPA screen — the login screen (`loggedIn: false`),
+ * the set-password screen (`passwordSet: false`), or a setup wizard still waiting to be unlocked
+ * (`setupAuthRequired: true`).
*
- * These screens run with the database already initialized, so `glob.dbInitialized` (the historical
+ * The first two run with the database already initialized, so `glob.dbInitialized` (the historical
* proxy for "pre-auth", back when setup was the only pre-auth screen) does NOT catch them. The eager
* module-load side effects — froca's initial tree load, the WebSocket auto-connect, and the options /
* keyboard-actions / fonts fetches — must skip on these screens too, otherwise they fire
* unauthenticated requests that 401 with "Logged in session not found" (#10589).
*
- * The setup screen (`dbInitialized: false`) is deliberately NOT flagged here: froca and the WebSocket
- * already gate on `!glob.dbInitialized`, and the options / keyboard-actions / fonts requests are
- * accepted unauthenticated server-side while the DB is uninitialized. The strict `=== false`
- * comparison is intentional: an unset flag (the fully-authenticated app, or a unit-test `glob`) must
- * not be treated as pre-auth, so the eager loads keep working there.
+ * An ordinary setup screen (`dbInitialized: false`) is deliberately NOT flagged: froca and the
+ * WebSocket already gate on `!glob.dbInitialized`, and those requests are accepted unauthenticated
+ * server-side while there is no database to protect. A wizard standing over a knowledge base is the
+ * exception — there the server asks for the wizard's password first, which this screen has not been
+ * given yet. The strict comparisons are intentional: an unset flag (the fully-authenticated app, or
+ * a unit-test `glob`) must not be treated as pre-auth, so the eager loads keep working there.
*/
export function isPreAuthScreen(): boolean {
- return glob.loggedIn === false || glob.passwordSet === false;
+ return glob.loggedIn === false || glob.passwordSet === false || glob.setupAuthRequired === true;
}
export function reloadFrontendApp(reason?: string) {
diff --git a/apps/server/src/services/auth.spec.ts b/apps/server/src/services/auth.spec.ts
index a9070d2be2..f9cc96a55b 100644
--- a/apps/server/src/services/auth.spec.ts
+++ b/apps/server/src/services/auth.spec.ts
@@ -556,9 +556,21 @@ describe("Auth", () => {
* around a supertest call.
*/
describe("the setup wizard's gate", () => {
+ type GateOpts = {
+ token?: string;
+ internalElectron?: boolean;
+ /** Which guard to drive; `checkSetupAuth` by default. */
+ middleware?: "checkSetupAuth" | "checkApiAuth" | "checkApiAuthOrElectron";
+ };
+
/** A request carrying the token, or nothing, plus what the middleware did with it. */
- function callGate({ token, internalElectron = false }: { token?: string; internalElectron?: boolean } = {}) {
- const req = { headers: token ? { "trilium-setup-auth": token } : {}, method: "POST", path: "/api/setup/existing/delete" } as unknown as Request;
+ function callGate({ token, internalElectron = false, middleware = "checkSetupAuth" }: GateOpts = {}) {
+ const req = {
+ headers: token ? { "trilium-setup-auth": token } : {},
+ method: "POST",
+ path: "/api/database/backup-database",
+ session: {}
+ } as unknown as Request;
if (internalElectron) {
markAsInternalElectronRequest(req);
}
@@ -576,7 +588,7 @@ describe("the setup wizard's gate", () => {
outcome.passed = true;
};
- auth.checkSetupAuth(req, res as unknown as Response, next);
+ auth[middleware](req, res as unknown as Response, next);
return outcome;
}
@@ -633,4 +645,39 @@ describe("the setup wizard's gate", () => {
expect(callGate()).toMatchObject({ passed: true });
});
+
+ describe("and the rest of the API, which stands down for the same reason", () => {
+ // The wizard's own routes are not the only ones reachable while it is open. Every ordinary
+ // API guard gives way on an instance that reports itself uninitialized — which setup mode
+ // makes it report — and the database is attached the whole time, so anything reaching it
+ // through SQL rather than through becca works. Backing the knowledge base up and then
+ // downloading that backup is two such requests, and would have been the whole of it.
+ for (const middleware of [ "checkApiAuth", "checkApiAuthOrElectron" ] as const) {
+ it(`refuses an unauthenticated request through ${middleware} while the wizard is locked`, () => {
+ expect(callGate({ middleware })).toEqual({ passed: false, status: 401 });
+ });
+
+ it(`lets ${middleware} through once the wizard has been unlocked`, async () => {
+ vi.spyOn(passwordEncryptionService, "verifyPassword").mockResolvedValue(true as never);
+ const token = await authenticateSetup("whatever the fixture's is");
+
+ // The client sends the token on every request once it holds one, so the rest of the
+ // wizard's own needs — keyboard actions, options, network addresses — keep working.
+ expect(callGate({ middleware, token: token ?? "" })).toMatchObject({ passed: true });
+
+ vi.restoreAllMocks();
+ });
+
+ it(`lets ${middleware} through on a first run, which has nothing to protect`, () => {
+ // No marker, so nothing behind the wizard, and no database open either: the state
+ // the bypass was written for, and the one it has to go on allowing.
+ leaveSetupMode();
+ vi.spyOn(sqlInit, "isDbInitialized").mockReturnValue(false);
+
+ expect(callGate({ middleware })).toMatchObject({ passed: true });
+
+ vi.restoreAllMocks();
+ });
+ }
+ });
});
diff --git a/apps/server/src/services/auth.ts b/apps/server/src/services/auth.ts
index 353e8ca62f..3c16058d4b 100644
--- a/apps/server/src/services/auth.ts
+++ b/apps/server/src/services/auth.ts
@@ -108,10 +108,39 @@ export function refreshAuth() {
noAuthentication = (config.General && config.General.noAuthentication === true);
}
+/**
+ * Whether an uninitialized instance may let this request through unauthenticated.
+ *
+ * The bypass below exists because an instance with no database has nobody to authenticate and
+ * nothing worth protecting. An instance sitting in the setup wizard with a knowledge base behind it
+ * has both: the database is attached, and every route that reaches it through SQL rather than
+ * through becca works exactly as it would on a running instance. Taking a backup of it and
+ * downloading that backup are two such routes.
+ *
+ * So for the length of that window the bypass is conditional on the wizard's own token instead of
+ * being granted outright. The exemptions are the ones `checkSetupAuth` makes, for the same reasons.
+ */
+function mayPassAsUninitialized(req: Request): boolean {
+ if (sqlInit.isDbInitialized()) {
+ return false;
+ }
+ if (!isSetupAuthRequired() || isInternalElectronRequest(req) || noAuthentication) {
+ return true;
+ }
+
+ return isSetupAuthorized(readSetupAuthToken(req));
+}
+
+function readSetupAuthToken(req: Request): string | undefined {
+ const token = req.headers["trilium-setup-auth"];
+
+ return typeof token === "string" ? token : undefined;
+}
+
// for electron things which need network stuff
// currently, we're doing that for file upload because handling form data seems to be difficult
function checkApiAuthOrElectron(req: Request, res: Response, next: NextFunction) {
- if (!sqlInit.isDbInitialized()) {
+ if (mayPassAsUninitialized(req)) {
return next();
}
@@ -124,7 +153,7 @@ function checkApiAuthOrElectron(req: Request, res: Response, next: NextFunction)
}
function checkApiAuth(req: Request, res: Response, next: NextFunction) {
- if (!sqlInit.isDbInitialized()) {
+ if (mayPassAsUninitialized(req)) {
return next();
}
@@ -194,8 +223,7 @@ function checkSetupAuth(req: Request, res: Response, next: NextFunction) {
return next();
}
- const token = req.headers["trilium-setup-auth"];
- if (typeof token !== "string" || !isSetupAuthorized(token)) {
+ if (!isSetupAuthorized(readSetupAuthToken(req))) {
reject(req, res, "The existing knowledge base has not been unlocked.");
return;
}
diff --git a/apps/server/src/services/database_restore.spec.ts b/apps/server/src/services/database_restore.spec.ts
index 3a3f3771d4..b354e5dd58 100644
--- a/apps/server/src/services/database_restore.spec.ts
+++ b/apps/server/src/services/database_restore.spec.ts
@@ -1,5 +1,7 @@
import { writeBackupContainer } from "@triliumnext/backup-container";
-import { app_info as appInfo, getBackup, getLog, getSql } from "@triliumnext/core";
+// `sql_init` from core rather than the server's own re-export, which copies the function references
+// onto a fresh object: a spy on that one would not be seen by `database_restore`.
+import { app_info as appInfo, getBackup, getLog, getSql, sql_init as sqlInit } from "@triliumnext/core";
import Database from "better-sqlite3";
import fs from "fs";
import os from "os";
@@ -30,6 +32,9 @@ let counter = 0;
beforeEach(() => {
fs.rmSync(tempRoot, { recursive: true, force: true });
fs.mkdirSync(tempRoot, { recursive: true });
+ // The state a restore actually runs in: the setup screen, with no database of this instance's
+ // own open. `restoreDatabase` refuses anywhere else, and the shared fixture is initialized.
+ vi.spyOn(sqlInit, "isDbInitialized").mockReturnValue(false);
});
afterEach(() => vi.restoreAllMocks());
@@ -426,6 +431,22 @@ describe("recovering from an interrupted restore", () => {
});
describe("restoring a database", () => {
+ it("refuses outright on an instance that already has a database", async () => {
+ // The route this is reached through is guarded by `checkAppNotInitialized`, and until this
+ // check existed that middleware was the only thing between a running instance and a restore
+ // over the top of it. Every other way of replacing a database refuses on its own account.
+ vi.spyOn(sqlInit, "isDbInitialized").mockReturnValue(true);
+ const detach = vi.spyOn(getSql(), "detachConnection").mockImplementation(() => {});
+
+ await expect(restoreDatabase({
+ path: validDatabase(),
+ fileName: "holiday.db",
+ consumable: false
+ })).rejects.toMatchObject({ reason: "restore-refused" });
+
+ expect(detach).not.toHaveBeenCalled();
+ });
+
it("stops before touching the live database when the backup is not one", async () => {
const detach = vi.spyOn(getSql(), "detachConnection").mockImplementation(() => {});
diff --git a/apps/server/src/services/database_restore.ts b/apps/server/src/services/database_restore.ts
index 28054c9fe6..3694582a1f 100644
--- a/apps/server/src/services/database_restore.ts
+++ b/apps/server/src/services/database_restore.ts
@@ -254,6 +254,15 @@ export function getRestoreProgress(): RestoreProgress | null {
export async function restoreDatabase(request: RestoreRequest): Promise<void> {
const startedAt = Date.now();
+ // Refused against a live database, and said here rather than left to the route that calls it.
+ // Every other way of replacing a database refuses on its own account too — `createInitialDatabase`
+ // and `createDatabaseForSync` both do — and this was the one that did not, which made
+ // `checkAppNotInitialized` the single thing standing between a running instance and a restore
+ // over the top of it. The standalone build has had the same check on its own restore all along.
+ if (sqlInit.isDbInitialized()) {
+ throw new RestoreFailure("restore-refused", "This instance already has a database; a restore only runs from the setup screen.");
+ }
+
// The name is left out on purpose: it is the user's, and everything worth knowing about the file
// is stated below in terms that are not.
logRestore(`starting, from ${request.consumable ? "a backup this instance was given" : "a backup already on this device"}`);
diff --git a/packages/trilium-core/src/routes/setup_routes.spec.ts b/packages/trilium-core/src/routes/setup_routes.spec.ts
index d4e0102fd4..64da66be03 100644
--- a/packages/trilium-core/src/routes/setup_routes.spec.ts
+++ b/packages/trilium-core/src/routes/setup_routes.spec.ts
@@ -46,6 +46,24 @@ describe("how the setup routes are registered", () => {
"DELETE /api/setup/boot"
];
+ /**
+ * Every route that belongs to the wizard and must be refused on an instance that is running.
+ *
+ * The `boot` three are deliberately absent: asking for a start-over is something a running
+ * instance does, and it is guarded by the session instead.
+ */
+ const WIZARD_ONLY_ROUTES = [
+ "POST /api/setup/new-document",
+ "POST /api/setup/sync-from-server",
+ "POST /api/setup/sync-seed",
+ "POST /api/setup/auth",
+ "POST /api/setup/existing/backup",
+ "GET /api/setup/existing/backup-defaults",
+ "GET /api/setup/existing/status",
+ "POST /api/setup/existing/delete",
+ "POST /api/setup/existing/keep"
+ ];
+
it("keeps every route that closes the database out of a transaction", () => {
const { builders } = captureRegistrations();
@@ -64,6 +82,19 @@ describe("how the setup routes are registered", () => {
}
});
+ it("keeps the wizard's own routes off a running instance, which is a different guard entirely", () => {
+ // `checkSetupAuth` does nothing on a running instance: it asks for a password only while
+ // there is a knowledge base behind the wizard, and on a running instance there is no wizard.
+ // What refuses these there is `checkAppNotInitialized`, so it is the one carrying the weight
+ // for the case where no start-over was ever asked for.
+ const { middleware } = captureRegistrations();
+
+ for (const route of WIZARD_ONLY_ROUTES) {
+ expect(middleware.get(route), `${route} is not registered at all`)
+ .toContain("checkAppNotInitialized");
+ }
+ });
+
it("leaves open only the routes that have to be", () => {
// Read as a whole rather than one at a time: what matters is that the list of setup routes
// anybody can reach stays this short, and that each one on it is deliberate. A route added