Skip to content

A one-of-a-kind resume builder that keeps your privacy in mind. Completely secure, customizable, portable, open-source and free forever. Try it out today!

fix(api): exempt resume owner from public PDF password challenge (#3668)

Hoàng Anh Tuấn520fdf59df7c
diff --git a/packages/api/src/features/resume/access-policy.test.ts b/packages/api/src/features/resume/access-policy.test.ts
index 8cc8581be..9cc07fa77 100644
--- a/packages/api/src/features/resume/access-policy.test.ts
+++ b/packages/api/src/features/resume/access-policy.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, it } from "vite-plus/test";
import { defaultResumeData } from "@reactive-resume/schema/resume/default";
import { sampleResumeData } from "@reactive-resume/schema/resume/sample";
-import { assertCanView, redactResumeForViewer } from "./access-policy";
+import { assertCanView, redactResumeForViewer, requiresPassword } from "./access-policy";
describe("assertCanView", () => {
it("throws NOT_FOUND for private resume viewed by non-owner", () => {
@@ -67,3 +67,24 @@ describe("redactResumeForViewer", () => {
expect(shared.sections.education).toEqual(data.sections.education);
});
});
+
+describe("requiresPassword", () => {
+ it("returns false for the resume owner regardless of password state", () => {
+ expect(requiresPassword({ userId: "u1", passwordHash: "hash" }, { id: "u1" })).toBe(false);
+ expect(requiresPassword({ userId: "u1", hasPassword: true }, { id: "u1" })).toBe(false);
+ expect(requiresPassword({ userId: "u1", passwordHash: null }, { id: "u1" })).toBe(false);
+ });
+
+ it("returns true for non-owner when passwordHash or hasPassword is set", () => {
+ expect(requiresPassword({ userId: "u1", passwordHash: "hash" }, { id: "u2" })).toBe(true);
+ expect(requiresPassword({ userId: "u1", hasPassword: true }, { id: "u2" })).toBe(true);
+ expect(requiresPassword({ userId: "u1", passwordHash: "hash" }, null)).toBe(true);
+ expect(requiresPassword({ userId: "u1", hasPassword: true }, null)).toBe(true);
+ });
+
+ it("returns false when resume has no password", () => {
+ expect(requiresPassword({ userId: "u1", passwordHash: null }, { id: "u2" })).toBe(false);
+ expect(requiresPassword({ userId: "u1", hasPassword: false }, { id: "u2" })).toBe(false);
+ expect(requiresPassword({ userId: "u1", passwordHash: null }, null)).toBe(false);
+ });
+});
diff --git a/packages/api/src/features/resume/access-policy.ts b/packages/api/src/features/resume/access-policy.ts
index 83d50a564..fd64f18bc 100644
--- a/packages/api/src/features/resume/access-policy.ts
+++ b/packages/api/src/features/resume/access-policy.ts
@@ -29,7 +29,7 @@ export function ownerIsNotBanned() {
return sql`(${schema.user.banned} is not true or ${schema.user.banExpires} <= now())`;
}
-export function isOwner(resume: Resume, viewer: Viewer): boolean {
+export function isOwner(resume: { userId: string }, viewer: Viewer): boolean {
return viewer !== null && viewer.id === resume.userId;
}
@@ -44,6 +44,21 @@ export function assertCanView(resume: Resume, viewer: Viewer): void {
throw new ORPCError("NOT_FOUND");
}
+type PasswordProtectedResume = {
+ userId: string;
+ passwordHash?: string | null;
+ hasPassword?: boolean;
+};
+
+/**
+ * Returns true if the viewer must satisfy the password gate before viewing or downloading
+ * the resume. The owner is exempt from their own password challenge.
+ */
+export function requiresPassword(resume: PasswordProtectedResume, viewer: Viewer): boolean {
+ if (isOwner(resume, viewer)) return false;
+ return Boolean(resume.passwordHash || resume.hasPassword);
+}
+
/**
* Redact owner-only fields before serializing a resume to a non-owner viewer.
*
diff --git a/packages/api/src/features/resume/public-pdf.test.ts b/packages/api/src/features/resume/public-pdf.test.ts
index f87e6c5ab..81f24763a 100644
--- a/packages/api/src/features/resume/public-pdf.test.ts
+++ b/packages/api/src/features/resume/public-pdf.test.ts
@@ -17,12 +17,13 @@ vi.mock("@reactive-resume/db/client", async () => {
const mocks = vi.hoisted(() => ({
hasResumeAccess: vi.fn(),
+ resolveAuthentication: vi.fn(),
consume: vi.fn(),
renderPdf: vi.fn(),
files: new Map<string, Uint8Array>(),
}));
vi.mock("./access", () => ({ hasResumeAccess: mocks.hasResumeAccess }));
-vi.mock("../../context", () => ({ resolveAuthenticationFromRequestHeaders: async () => undefined }));
+vi.mock("../../context", () => ({ resolveAuthenticationFromRequestHeaders: mocks.resolveAuthentication }));
vi.mock("./public-render-rate-limit", () => ({ publicRenderRateLimiter: { consume: mocks.consume } }));
vi.mock("@reactive-resume/pdf/server", () => ({ createResumePdfFile: mocks.renderPdf }));
// Storage that keeps files in memory, so tests never write to the local data folder.
@@ -66,6 +67,7 @@ describe("createPublicResumePdf", () => {
pg.rows = [];
mocks.files.clear();
mocks.consume.mockReset();
+ mocks.resolveAuthentication.mockReset().mockResolvedValue(undefined);
mocks.hasResumeAccess.mockReset().mockReturnValue(false);
mocks.renderPdf.mockReset().mockResolvedValue(new File(["%PDF"], "resume.pdf", { type: "application/pdf" }));
});
@@ -80,6 +82,35 @@ describe("createPublicResumePdf", () => {
expect(mocks.renderPdf).not.toHaveBeenCalled();
});
+ it.each([true, false])("exempts the owner from the password gate (public: %s)", async (isPublic) => {
+ found(buildResume({ isPublic, passwordHash: "hash" }));
+ mocks.resolveAuthentication.mockResolvedValue({ user: { id: "owner-1" }, permissions: ["read"] });
+
+ await expect(createPublicResumePdf(input)).resolves.toMatchObject({ filename: "resume.pdf" });
+ expect(mocks.renderPdf).toHaveBeenCalledOnce();
+ expect(mocks.hasResumeAccess).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ { isPublic: true, code: "NEED_PASSWORD" },
+ { isPublic: false, code: "NOT_FOUND" },
+ ])("rejects authenticated non-owners with $code", async ({ isPublic, code }) => {
+ found(buildResume({ isPublic, passwordHash: "hash" }));
+ mocks.resolveAuthentication.mockResolvedValue({ user: { id: "other-user" }, permissions: ["read"] });
+
+ await expect(createPublicResumePdf(input)).rejects.toMatchObject({ code });
+ expect(mocks.consume).not.toHaveBeenCalled();
+ expect(mocks.renderPdf).not.toHaveBeenCalled();
+ });
+
+ it("requires read permission before exempting the owner", async () => {
+ found(buildResume({ passwordHash: "hash" }));
+ mocks.resolveAuthentication.mockResolvedValue({ user: { id: "owner-1" }, permissions: ["write"] });
+
+ await expect(createPublicResumePdf(input)).rejects.toMatchObject({ code: "NEED_PASSWORD" });
+ expect(mocks.renderPdf).not.toHaveBeenCalled();
+ });
+
it("does not look in Trash, so a trashed resume's link stops serving its PDF", async () => {
await expect(createPublicResumePdf(input)).rejects.toMatchObject({ code: "NOT_FOUND" });
expect(pg.queries.at(-1)?.text).toContain('"resume"."trashed_at" is null');
diff --git a/packages/api/src/features/resume/public-pdf.ts b/packages/api/src/features/resume/public-pdf.ts
index 562df5d76..625805d0c 100644
--- a/packages/api/src/features/resume/public-pdf.ts
+++ b/packages/api/src/features/resume/public-pdf.ts
@@ -5,7 +5,7 @@ import { ORPCError } from "@orpc/server";
import { env } from "@reactive-resume/env/server";
import { generateFilename } from "@reactive-resume/utils/file";
import { matchesIfNoneMatch } from "@reactive-resume/utils/http";
-import { assertCanView, redactResumeForViewer } from "./access-policy";
+import { assertCanView, redactResumeForViewer, requiresPassword } from "./access-policy";
import { publicRenderRateLimiter } from "./public-render-rate-limit";
import { parseStoredResumeData } from "./resume-data-validation";
@@ -52,9 +52,10 @@ export async function createPublicResumePdf(input: CreatePublicResumePdfInput):
if (!resume) throw new ORPCError("NOT_FOUND");
const currentUserId = await resolveCurrentUserId(input.requestHeaders);
- assertCanView(resume, currentUserId ? { id: currentUserId } : null);
+ const viewer = currentUserId ? { id: currentUserId } : null;
+ assertCanView(resume, viewer);
if (
- resume.passwordHash &&
+ requiresPassword(resume, viewer) &&
!(await import("./access")).hasResumeAccess(input.requestHeaders, resume.id, resume.passwordHash)
) {
throw new ORPCError("NEED_PASSWORD", {
diff --git a/packages/api/src/features/resume/service.ts b/packages/api/src/features/resume/service.ts
index 99c8d0e92..e72e3dde1 100644
--- a/packages/api/src/features/resume/service.ts
+++ b/packages/api/src/features/resume/service.ts
@@ -17,7 +17,13 @@ import { adoptEmbeddedLetters } from "../cover-letters/embedded";
import { lockUser } from "../documents/ownership";
import { getStorageService } from "../storage/service";
import { grantResumeAccess, hasResumeAccess } from "./access";
-import { assertCanView, isOwner, redactResumeForViewer, shouldCountForStatistics } from "./access-policy";
+import {
+ assertCanView,
+ isOwner,
+ redactResumeForViewer,
+ requiresPassword,
+ shouldCountForStatistics,
+} from "./access-policy";
import { publishResumeUpdated } from "./events";
import { parseStoredResumeData, parseWritableResumeData } from "./resume-data-validation";
import { checkSlug, findFreeSlug, findResumeBySlug, recordSlugChange, SLUG_PATTERN } from "./slugs";
@@ -213,11 +219,7 @@ const statistics = {
if (!resume) throw new ORPCError("NOT_FOUND");
const viewer = input.currentUserId ? { id: input.currentUserId } : null;
assertCanView(resume, viewer);
- if (
- resume.passwordHash &&
- !isOwner(resume, viewer) &&
- !hasResumeAccess(input.requestHeaders, resume.id, resume.passwordHash)
- ) {
+ if (requiresPassword(resume, viewer) && !hasResumeAccess(input.requestHeaders, resume.id, resume.passwordHash)) {
throw new ORPCError("NEED_PASSWORD", {
status: 401,
data: { username: input.username, slug: input.slug },
@@ -527,11 +529,7 @@ export const resumeService = {
const viewer = input.currentUserId ? { id: input.currentUserId } : null;
assertCanView(resume, viewer);
- if (
- resume.hasPassword &&
- !isOwner(resume, viewer) &&
- !hasResumeAccess(input.requestHeaders, resume.id, resume.passwordHash)
- ) {
+ if (requiresPassword(resume, viewer) && !hasResumeAccess(input.requestHeaders, resume.id, resume.passwordHash)) {
throw new ORPCError("NEED_PASSWORD", {
status: 401,
data: { username: input.username, slug: input.slug },