A self-hostable bookmark-everything app (links, notes and images) with AI-based automatic tagging and full text search
fix: only delete owned avatar assets when clearing an avatar (#3260)
Mohamed Bassem91cb815e3ecd
diff --git a/packages/e2e_tests/tests/assetdb/local-filesystem-store.test.ts b/packages/e2e_tests/tests/assetdb/local-filesystem-store.test.tsindex 2421926a..314a2dd1 100644--- a/packages/e2e_tests/tests/assetdb/local-filesystem-store.test.ts+++ b/packages/e2e_tests/tests/assetdb/local-filesystem-store.test.ts@@ -197,6 +197,35 @@ describe("LocalFileSystemAssetStore - Filesystem-Specific Behaviors", () => {.catch(() => false),).toBe(false);});++ it("should reject asset ids that escape the user directory", async () => {+ const victim = createTestAssetData({ userId: "victim" });+ await store.saveAsset({+ userId: victim.userId,+ assetId: victim.assetId,+ asset: victim.content,+ metadata: victim.metadata,+ });++ for (const assetId of [+ "..",+ "../..",+ `../${victim.userId}`,+ `../${victim.userId}/${victim.assetId}`,+ ]) {+ await expect(+ store.deleteAsset({ userId: "attacker", assetId }),+ ).rejects.toThrow("Invalid asset path");+ }++ const victimAssetDir = path.join(tempDir, victim.userId, victim.assetId);+ expect(+ await fs.promises+ .access(victimAssetDir)+ .then(() => true)+ .catch(() => false),+ ).toBe(true);+ });});describe("File System Permissions", () => {diff --git a/packages/plugins/assetstore-filesystem/src/index.ts b/packages/plugins/assetstore-filesystem/src/index.tsindex a6d80342..425bd5e3 100644--- a/packages/plugins/assetstore-filesystem/src/index.ts+++ b/packages/plugins/assetstore-filesystem/src/index.ts@@ -12,7 +12,15 @@ export class LocalFileSystemAssetStore implements AssetStore {constructor(private readonly rootPath: string) {}private getAssetDir(userId: string, assetId: string) {- return path.join(this.rootPath, userId, assetId);+ // Ids are used as path segments, so make sure they can't escape the+ // user's directory (e.g. "../" traversal).+ const root = path.resolve(this.rootPath);+ const userDir = path.resolve(root, userId);+ const assetDir = path.resolve(userDir, assetId);+ if (path.dirname(userDir) !== root || path.dirname(assetDir) !== userDir) {+ throw new Error("Invalid asset path");+ }+ return assetDir;}private async isPathExists(filePath: string) {diff --git a/packages/trpc/models/users.ts b/packages/trpc/models/users.tsindex 71017afc..0db399f6 100644--- a/packages/trpc/models/users.ts+++ b/packages/trpc/models/users.ts@@ -375,13 +375,16 @@ export class User {this.user.image = assetId;- if (!previousImage || previousImage === assetId) {+ // Only delete files backed by an asset row this user owns. `users.image`+ // can hold arbitrary strings (e.g. OAuth picture URLs), so it must never be+ // used as a storage key on its own.+ if (!previousAsset || previousAsset.bookmarkId) {return;}await deleteAsset({userId: this.user.id,- assetId: previousImage,+ assetId: previousAsset.id,}).catch(() => ({}));}diff --git a/packages/trpc/routers/users.test.ts b/packages/trpc/routers/users.test.tsindex 3fffa4c1..f5ac5458 100644--- a/packages/trpc/routers/users.test.ts+++ b/packages/trpc/routers/users.test.ts@@ -1,5 +1,15 @@+import * as fs from "node:fs";+import * as path from "node:path";import { eq } from "drizzle-orm";-import { assert, beforeEach, describe, expect, test, vi } from "vitest";+import {+ afterAll,+ assert,+ beforeEach,+ describe,+ expect,+ test,+ vi,+} from "vitest";import {accounts,@@ -9,6 +19,7 @@ import {subscriptions,users,} from "@karakeep/db/schema";+import serverConfig from "@karakeep/shared/config";import { BookmarkTypes } from "@karakeep/shared/types/bookmarks";import type { CustomTestContext } from "../testUtils";@@ -22,10 +33,16 @@ import { createTestUser, defaultBeforeEach, getApiCaller } from "../testUtils";// Mock server config with email settingsvi.mock("@karakeep/shared/config", async (original) => {const mod = (await original()) as typeof import("@karakeep/shared/config");+ const fs = await import("node:fs");+ const os = await import("node:os");+ const path = await import("node:path");return {...mod,default: {...mod.default,+ assetsDir: fs.mkdtempSync(+ path.join(os.tmpdir(), "karakeep-users-test-assets-"),+ ),auth: {...mod.default.auth,emailVerificationRequired: true,@@ -45,6 +62,25 @@ vi.mock("@karakeep/shared/config", async (original) => {});beforeEach<CustomTestContext>(defaultBeforeEach(false));+afterAll(async () => {+ await fs.promises.rm(serverConfig.assetsDir, {+ recursive: true,+ force: true,+ });+});++async function writeAssetFile(userId: string, assetId: string) {+ const assetDir = path.join(serverConfig.assetsDir, userId, assetId);+ await fs.promises.mkdir(assetDir, { recursive: true });+ await fs.promises.writeFile(path.join(assetDir, "asset.bin"), "asset");+}++async function assetExists(userId: string, assetId: string) {+ return fs.promises+ .access(path.join(serverConfig.assetsDir, userId, assetId, "asset.bin"))+ .then(() => true)+ .catch(() => false);+}describe("User Routes", () => {test<CustomTestContext>("create user", async ({ db }) => {@@ -845,6 +881,7 @@ describe("User Routes", () => {fileName: "avatar.png",bookmarkId: null,});+ await writeAssetFile(user.id, "avatar-asset-3");await caller.users.updateAvatar({ assetId: "avatar-asset-3" });await caller.users.updateAvatar({ assetId: null });@@ -862,6 +899,45 @@ describe("User Routes", () => {expect(updatedUser?.image).toBeNull();expect(remainingAsset).toBeUndefined();+ expect(await assetExists(user.id, "avatar-asset-3")).toBe(false);+ });++ test<CustomTestContext>("updateAvatar - does not delete files referenced by an untrusted image", async ({+ db,+ }) => {+ const victim = await createTestUser(db, {+ name: "Avatar Victim",+ email: "[email protected]",+ password: "pass1234",+ });+ const attacker = await createTestUser(db, {+ name: "Avatar Attacker",+ email: "[email protected]",+ password: "pass1234",+ });+ await writeAssetFile(victim.id, "victim-asset");+ // e.g. set through a client-supplied `image` at sign up+ await db+ .update(users)+ .set({ image: `../${victim.id}/victim-asset` })+ .where(eq(users.id, attacker.id));+ const caller = getApiCaller(+ db,+ attacker.id,+ attacker.email,+ attacker.role || "user",+ );++ await caller.users.updateAvatar({ assetId: null });++ const updatedUser = await db+ .select()+ .from(users)+ .where(eq(users.id, attacker.id))+ .then((rows) => rows[0]);++ expect(updatedUser?.image).toBeNull();+ expect(await assetExists(victim.id, "victim-asset")).toBe(true);});});