Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
fix(share): apply per-note access checks in the search endpoint
Elian Doran49fc7b67d9d4
diff --git a/apps/server/src/share/routes.spec.ts b/apps/server/src/share/routes.spec.tsindex 4c0bc2657a..6a37fb4d53 100644--- a/apps/server/src/share/routes.spec.ts+++ b/apps/server/src/share/routes.spec.ts@@ -90,6 +90,41 @@ describe("Share API test", () => {expect(cannotSetHeadersCount).toBe(0);});+ // The public search endpoint must apply the same per-note authorization as the+ // direct content routes: it must not leak notes protected by `shareCredentials`+ // or hidden with `shareHiddenFromTree`. The fixture's "Shared notes" root+ // (y0AFOwgOgkWO) contains "Password protected share" (shareCredentials+ // root:password) and "Shared Note Template" (shareHiddenFromTree).+ const SHARE_ROOT_ID = "y0AFOwgOgkWO";++ async function searchTitles(query: string, auth?: string) {+ let request = supertest(app).get(`/share/api/notes?ancestorNoteId=${SHARE_ROOT_ID}&search=${encodeURIComponent(query)}`);+ if (auth) {+ request = request.set("Authorization", `Basic ${Buffer.from(auth).toString("base64")}`);+ }+ const response = await request.expect(200);+ return (response.body.results as Array<{ title: string }>).map((r) => r.title);+ }++ it("does not leak shareHiddenFromTree notes via public search", async () => {+ const titles = await searchTitles("Shared Note Template");+ expect(titles).not.toContain("Shared Note Template");+ expect(cannotSetHeadersCount).toBe(0);+ });++ it("does not leak shareCredentials-protected notes via anonymous search, but returns them with credentials", async () => {+ const anonymousTitles = await searchTitles("Password protected share");+ expect(anonymousTitles).not.toContain("Password protected share");++ const authenticatedTitles = await searchTitles("Password protected share", "root:password");+ expect(authenticatedTitles).toContain("Password protected share");++ const wrongPasswordTitles = await searchTitles("Password protected share", "root:wrong");+ expect(wrongPasswordTitles).not.toContain("Password protected share");++ expect(cannotSetHeadersCount).toBe(0);+ });+it("renders custom share template", async () => {// Custom EJS templates require scripting to be enabledconst originalEnabled = config.Security.backendScriptingEnabled;diff --git a/apps/server/src/share/routes.ts b/apps/server/src/share/routes.tsindex d9c71f8a5e..b4d38f5440 100644--- a/apps/server/src/share/routes.ts+++ b/apps/server/src/share/routes.ts@@ -68,10 +68,22 @@ function checkNoteAccess(noteId: string, req: Request, res: Response) {return false;}+ if (!hasCredentialAccess(note, req)) {+ return false;+ }++ return note;+}++// Returns true when the request is allowed to read the given note: either the+// note (including inherited attributes) carries no shareCredentials, or the+// request presents matching HTTP Basic credentials. Pure predicate — does not+// touch the response, so it can also be reused to filter search results.+function hasCredentialAccess(note: SNote, req: Request) {const credentials = note.getCredentials();if (credentials.length === 0) {- return note;+ return true;}const header = req.header("Authorization");@@ -84,13 +96,31 @@ function checkNoteAccess(noteId: string, req: Request, res: Response) {const buffer = Buffer.from(base64Str, "base64");const authString = buffer.toString("utf-8");- for (const credentialLabel of credentials) {- if (safeCompare(authString, credentialLabel.value)) {- return note; // success;+ return credentials.some((credentialLabel) => safeCompare(authString, credentialLabel.value));+}++// Returns true when the note reached via `notePathArray` is actually visible in+// the public share tree below `ancestorNoteId`: every hop from the ancestor down+// to the note must be a non-hidden branch whose child note is not+// `shareHiddenFromTree`. Mirrors SNote.getVisibleChildBranches() so that search+// cannot enumerate notes the navigation tree deliberately hides.+function isVisibleInShareTree(ancestorNoteId: string, notePathArray: string[]) {+ const startIndex = notePathArray.indexOf(ancestorNoteId);++ if (startIndex < 0) {+ return false;+ }++ for (let i = startIndex + 1; i < notePathArray.length; i++) {+ const childNote = shaca.notes[notePathArray[i]];+ const branch = shaca.getBranchFromChildAndParent(notePathArray[i], notePathArray[i - 1]);++ if (!childNote || !branch || branch.isHidden || childNote.isLabelTruthy("shareHiddenFromTree")) {+ return false;}}- return false;+ return true;}// Like checkNoteAccess, but additionally refuses protected notes. Used by the@@ -403,13 +433,23 @@ function register(router: Router) {const searchContext = new SearchContext({ ancestorNoteId });const searchResults = searchService.findResultsWithQuery(search, searchContext);- const filteredResults = searchResults.map((sr) => {- const fullNote = shaca.notes[sr.noteId];- const startIndex = sr.notePathArray.indexOf(ancestorNoteId);- const localPathArray = sr.notePathArray.slice(startIndex + 1).filter((id) => shaca.notes[id]);- const pathTitle = localPathArray.map((id) => shaca.notes[id].title).join(" / ");- return { id: fullNote.shareId, title: fullNote.title, score: sr.score, path: pathTitle };- });+ const filteredResults = searchResults+ // Apply the same per-note authorization as the direct content routes:+ // keep only results the caller may access and that are visible in the tree.+ .filter((sr) => {+ const fullNote = shaca.notes[sr.noteId];++ return fullNote+ && hasCredentialAccess(fullNote, req)+ && isVisibleInShareTree(ancestorNoteId, sr.notePathArray);+ })+ .map((sr) => {+ const fullNote = shaca.notes[sr.noteId];+ const startIndex = sr.notePathArray.indexOf(ancestorNoteId);+ const localPathArray = sr.notePathArray.slice(startIndex + 1).filter((id) => shaca.notes[id]);+ const pathTitle = localPathArray.map((id) => shaca.notes[id].title).join(" / ");+ return { id: fullNote.shareId, title: fullNote.title, score: sr.score, path: pathTitle };+ });res.json({ results: filteredResults });});