-
Notifications
You must be signed in to change notification settings - Fork 10
fix(catalogs): catalog songs require authentication and ownership (chat#1912 row 6) #802
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+271
−28
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
bf422a4
fix(catalogs): catalog songs require authentication and ownership (ch…
sweetmantech ae380c0
fix(catalogs): authenticate before parsing, and check ownership in on…
sweetmantech a8098fa
refactor(catalogs): one validate call per handler (chat#1912 row 6 re…
sweetmantech File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,67 @@ | ||
| import { describe, it, expect, vi, beforeEach } from "vitest"; | ||
| import { NextResponse } from "next/server"; | ||
| import { authorizeCatalogAccess } from "@/lib/songs/authorizeCatalogAccess"; | ||
| import { selectAccountCatalogs } from "@/lib/supabase/account_catalogs/selectAccountCatalogs"; | ||
|
|
||
| vi.mock("@/lib/supabase/account_catalogs/selectAccountCatalogs", () => ({ | ||
| selectAccountCatalogs: vi.fn(), | ||
| })); | ||
| vi.mock("@/lib/networking/getCorsHeaders", () => ({ | ||
| getCorsHeaders: () => ({ "Access-Control-Allow-Origin": "*" }), | ||
| })); | ||
|
|
||
| describe("authorizeCatalogAccess", () => { | ||
| beforeEach(() => { | ||
| vi.clearAllMocks(); | ||
| }); | ||
|
|
||
| it("allows a catalog the account owns", async () => { | ||
| vi.mocked(selectAccountCatalogs).mockResolvedValue([{ id: "cat_1" }] as never); | ||
|
|
||
| expect(await authorizeCatalogAccess("acc_1", ["cat_1"])).toBeNull(); | ||
| }); | ||
|
|
||
| it("rejects a catalog the account does not own", async () => { | ||
| vi.mocked(selectAccountCatalogs).mockResolvedValue([{ id: "mine" }] as never); | ||
|
|
||
| const result = await authorizeCatalogAccess("acc_1", ["someone_elses"]); | ||
|
|
||
| expect(result).toBeInstanceOf(NextResponse); | ||
| expect((result as NextResponse).status).toBe(403); | ||
| }); | ||
|
|
||
| // A write can name several catalogs in one body; authorizing only the first | ||
| // would let one owned catalog carry edits into catalogs the caller does not own. | ||
| it("rejects when only one of several catalogs is unowned", async () => { | ||
| vi.mocked(selectAccountCatalogs).mockResolvedValue([{ id: "mine" }] as never); | ||
|
|
||
| const result = await authorizeCatalogAccess("acc_1", ["mine", "theirs"]); | ||
|
|
||
| expect((result as NextResponse).status).toBe(403); | ||
| }); | ||
|
|
||
| // Review finding (cubic, 2026-07-30). A bulk body naming many catalogs used | ||
| // to fan out into one query per catalog, which can exhaust the connection | ||
| // pool before the write even runs. | ||
| it("reads the caller's catalogs once regardless of how many are named", async () => { | ||
| vi.mocked(selectAccountCatalogs).mockResolvedValue([ | ||
| { id: "a" }, | ||
| { id: "b" }, | ||
| { id: "c" }, | ||
| ] as never); | ||
|
|
||
| await authorizeCatalogAccess("acc_1", ["a", "b", "c", "a", "b"]); | ||
|
|
||
| expect(selectAccountCatalogs).toHaveBeenCalledTimes(1); | ||
| expect(selectAccountCatalogs).toHaveBeenCalledWith("acc_1"); | ||
| }); | ||
|
|
||
| // Review finding (cubic, 2026-07-30). selectAccountCatalogs throws on a query | ||
| // failure, and that must surface as a 500 from the handler rather than being | ||
| // swallowed into a false "does not belong" 403 that clients will not retry. | ||
| it("propagates a database failure rather than reporting it as forbidden", async () => { | ||
| vi.mocked(selectAccountCatalogs).mockRejectedValue(new Error("connection reset")); | ||
|
|
||
| await expect(authorizeCatalogAccess("acc_1", ["cat_1"])).rejects.toThrow("connection reset"); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,93 @@ | ||
| import { describe, it, expect, vi, beforeEach } from "vitest"; | ||
| import { NextRequest, NextResponse } from "next/server"; | ||
| import { validateCatalogSongsRequest } from "@/lib/songs/validateCatalogSongsRequest"; | ||
| import { validateAuthContext } from "@/lib/auth/validateAuthContext"; | ||
| import { authorizeCatalogAccess } from "@/lib/songs/authorizeCatalogAccess"; | ||
|
|
||
| vi.mock("@/lib/auth/validateAuthContext", () => ({ validateAuthContext: vi.fn() })); | ||
| vi.mock("@/lib/songs/authorizeCatalogAccess", () => ({ authorizeCatalogAccess: vi.fn() })); | ||
| vi.mock("@/lib/networking/getCorsHeaders", () => ({ | ||
| getCorsHeaders: () => ({ "Access-Control-Allow-Origin": "*" }), | ||
| })); | ||
|
|
||
| const post = (body: unknown) => | ||
| new NextRequest("https://api.test/api/catalogs/songs", { | ||
| method: "POST", | ||
| body: JSON.stringify(body), | ||
| headers: { "Content-Type": "application/json" }, | ||
| }); | ||
|
|
||
| describe("validateCatalogSongsRequest", () => { | ||
| beforeEach(() => { | ||
| vi.clearAllMocks(); | ||
| vi.mocked(authorizeCatalogAccess).mockResolvedValue(null); | ||
| }); | ||
|
|
||
| /** | ||
| * chat#1912 row 6. The order is the contract: 401 before 400 before 403. | ||
| * A malformed body from an unauthenticated caller previously returned 400, | ||
| * and that 400-without-credentials is exactly what proved the endpoint had | ||
| * no auth layer. Body validation must never run first. | ||
| */ | ||
| it("returns 401 for a malformed body when the caller has no credentials", async () => { | ||
| vi.mocked(validateAuthContext).mockResolvedValue( | ||
| NextResponse.json({ status: "error" }, { status: 401 }) as never, | ||
| ); | ||
|
|
||
| const result = await validateCatalogSongsRequest(post({})); | ||
|
|
||
| expect((result as NextResponse).status).toBe(401); | ||
| expect(authorizeCatalogAccess).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it("returns 400 for a malformed body once the caller is authenticated", async () => { | ||
| vi.mocked(validateAuthContext).mockResolvedValue({ accountId: "acc_1" } as never); | ||
|
|
||
| const result = await validateCatalogSongsRequest(post({})); | ||
|
|
||
| expect((result as NextResponse).status).toBe(400); | ||
| // Ownership is meaningless without a valid body, so it must not be consulted. | ||
| expect(authorizeCatalogAccess).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it("returns the authorization failure for someone else's catalog", async () => { | ||
| vi.mocked(validateAuthContext).mockResolvedValue({ accountId: "acc_1" } as never); | ||
| vi.mocked(authorizeCatalogAccess).mockResolvedValue( | ||
| NextResponse.json({ status: "error" }, { status: 403 }) as never, | ||
| ); | ||
|
|
||
| const result = await validateCatalogSongsRequest( | ||
| post({ songs: [{ catalog_id: "theirs", isrc: "X" }] }), | ||
| ); | ||
|
|
||
| expect((result as NextResponse).status).toBe(403); | ||
| }); | ||
|
|
||
| it("returns the validated body plus the authenticated account on success", async () => { | ||
| vi.mocked(validateAuthContext).mockResolvedValue({ accountId: "acc_1" } as never); | ||
|
|
||
| const result = await validateCatalogSongsRequest( | ||
| post({ songs: [{ catalog_id: "mine", isrc: "X" }] }), | ||
| ); | ||
|
|
||
| expect(result).toMatchObject({ | ||
| accountId: "acc_1", | ||
| songs: [{ catalog_id: "mine", isrc: "X" }], | ||
| }); | ||
| }); | ||
|
|
||
| it("checks every catalog named in the body, not just the first", async () => { | ||
| vi.mocked(validateAuthContext).mockResolvedValue({ accountId: "acc_1" } as never); | ||
|
|
||
| await validateCatalogSongsRequest( | ||
| post({ | ||
| songs: [ | ||
| { catalog_id: "mine", isrc: "X" }, | ||
| { catalog_id: "theirs", isrc: "Y" }, | ||
| ], | ||
| }), | ||
| ); | ||
|
|
||
| expect(authorizeCatalogAccess).toHaveBeenCalledWith("acc_1", ["mine", "theirs"]); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,39 @@ | ||
| import { NextResponse } from "next/server"; | ||
| import { getCorsHeaders } from "@/lib/networking/getCorsHeaders"; | ||
| import { selectAccountCatalogs } from "@/lib/supabase/account_catalogs/selectAccountCatalogs"; | ||
|
|
||
| /** | ||
| * Ownership half of the `/api/catalogs/songs` gate: every catalog the operation | ||
| * touches must belong to `accountId`. | ||
| * | ||
| * Authentication is deliberately **not** done here. Callers run | ||
| * `validateAuthContext` before parsing or validating the request, so a caller | ||
| * with no credentials gets 401 rather than a body-validation 400 — the exact | ||
| * confusion that hid this hole in the first place (chat#1912 row 6). | ||
| * | ||
| * Reads the caller's catalogs in **one** query and checks membership in memory, | ||
| * so a bulk body naming many catalogs cannot fan out into many simultaneous | ||
| * queries. `selectAccountCatalogs` throws on a query failure, so a database | ||
| * outage surfaces as a 500 rather than a false "does not belong" 403. | ||
| * | ||
| * @param accountId - The authenticated account | ||
| * @param catalogIds - Every catalog the operation touches | ||
| * @returns A 403 NextResponse when any catalog is not the caller's, else null | ||
| */ | ||
| export async function authorizeCatalogAccess( | ||
| accountId: string, | ||
| catalogIds: string[], | ||
| ): Promise<NextResponse | null> { | ||
| const owned = await selectAccountCatalogs(accountId); | ||
| const ownedIds = new Set(owned.map(catalog => catalog.id)); | ||
|
|
||
| if (catalogIds.every(id => ownedIds.has(id))) return null; | ||
|
|
||
| return NextResponse.json( | ||
| { | ||
| status: "error", | ||
| error: "This catalog does not belong to the authenticated account", | ||
| }, | ||
| { status: 403, headers: getCorsHeaders() }, | ||
| ); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win
File/function naming violates
validate*.tsconvention.This file validates the request body but is named
validateCatalogSongsRequest.ts/ exportsvalidateCatalogSongsRequest, notvalidateCatalogSongsBody.ts/validateCatalogSongsBodyas the path instruction forlib/**/validate*.tsrequires.As per path instructions,
lib/**/validate*.tsfiles must "Follow naming: validateBody.ts or validateQuery.ts".♻️ Suggested rename
Also rename the file to
validateCatalogSongsBody.tsand update its two call sites.🤖 Prompt for AI Agents
Source: Path instructions