Ownership was checked ad hoc: some handlers loaded-and-compared ownerId, some lib mutators enforced it in WHERE clauses and silently no-op'd for non-owners, and nothing tied the two together. Two real authorization bugs hid in the gaps: linkActivityToRoute ignored its ownerId parameter entirely (any logged-in user could relink any activity), and createRouteFromActivity loaded any activity without an ownership check (a non-owner could copy a private activity's GPX into their own route). PUT /api/v1/routes/:id also returned ok:true for non-owners without updating anything. ownership.server.ts is now the single enforcement point: - loadOwnedRoute / loadOwnedActivity (non-throwing, for callers with their own error vocabulary) and requireOwnedRoute / requireOwnedActivity (throwing data() 404/403 for web handlers; 404 by default so guessed ids don't leak existence) - the returned entities carry an Owned<> brand; mutators (updateRoute, deleteRoute, deleteActivity, updateActivityVisibility, linkActivityToRoute, createRouteFromActivity) now require an OwnedRef, so skipping the check is a compile error - vouchOwnership is the explicit, greppable escape hatch for the one non-session authorization path (the Planner JWT callback) - WHERE ownerId clauses stay in the mutators as defense in depth Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
170 lines
5.9 KiB
TypeScript
170 lines
5.9 KiB
TypeScript
import { describe, it, expect, vi, beforeEach } from "vitest";
|
|
|
|
import { TERMS_VERSION } from "~/lib/legal";
|
|
|
|
const mockUser = { id: "user-1", email: "test@test.com", username: "test", domain: "localhost", displayName: null, bio: null, createdAt: new Date(), termsVersion: TERMS_VERSION };
|
|
const mockGetAuthenticatedUser = vi.fn();
|
|
const mockListRoutes = vi.fn();
|
|
const mockCreateRoute = vi.fn();
|
|
const mockGetRouteWithVersions = vi.fn();
|
|
const mockGetRoute = vi.fn();
|
|
const mockDeleteRoute = vi.fn();
|
|
|
|
vi.mock("~/lib/db", () => ({ getDb: vi.fn() }));
|
|
vi.mock("~/lib/auth.server", () => ({ getSessionUser: vi.fn() }));
|
|
vi.mock("~/lib/oauth.server", async (importOriginal) => {
|
|
const actual = await importOriginal<typeof import("~/lib/oauth.server")>();
|
|
return { ...actual, getAuthenticatedUser: mockGetAuthenticatedUser };
|
|
});
|
|
vi.mock("~/lib/routes.server", () => ({
|
|
listRoutes: mockListRoutes,
|
|
createRoute: mockCreateRoute,
|
|
getRouteWithVersions: mockGetRouteWithVersions,
|
|
getRoute: mockGetRoute,
|
|
updateRoute: vi.fn(),
|
|
deleteRoute: mockDeleteRoute,
|
|
}));
|
|
|
|
function authRequest(path: string, init?: RequestInit) {
|
|
return new Request(`http://localhost:3000${path}`, {
|
|
...init,
|
|
headers: {
|
|
Authorization: "Bearer valid-token",
|
|
"Content-Type": "application/json",
|
|
...(init?.headers as Record<string, string> ?? {}),
|
|
},
|
|
});
|
|
}
|
|
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
function routeArgs(request: Request, params: Record<string, string>, pattern: string): any {
|
|
return { request, params, context: {}, unstable_url: new URL(request.url), unstable_pattern: pattern };
|
|
}
|
|
|
|
beforeEach(() => {
|
|
vi.clearAllMocks();
|
|
mockGetAuthenticatedUser.mockResolvedValue(mockUser);
|
|
});
|
|
|
|
describe("GET /api/v1/routes", () => {
|
|
it("returns paginated routes", async () => {
|
|
const now = new Date();
|
|
mockListRoutes.mockResolvedValue([
|
|
{
|
|
id: "r1", name: "Tour", description: "", distance: 42000,
|
|
elevationGain: 340, elevationLoss: 320, routingProfile: "fastbike",
|
|
dayBreaks: [], geojson: null, ownerId: "user-1", gpx: null,
|
|
tags: null, plannerState: null, createdAt: now, updatedAt: now,
|
|
},
|
|
]);
|
|
|
|
const { loader } = await import("./api.v1.routes._index.ts");
|
|
const resp = await loader(routeArgs(authRequest("/api/v1/routes"), {}, "api/v1/routes")) as Response;
|
|
const data = await resp.json();
|
|
|
|
expect(data.routes).toHaveLength(1);
|
|
expect(data.routes[0].id).toBe("r1");
|
|
expect(data.nextCursor).toBeNull();
|
|
});
|
|
|
|
it("returns 401 without auth", async () => {
|
|
mockGetAuthenticatedUser.mockResolvedValue(null);
|
|
const { loader } = await import("./api.v1.routes._index.ts");
|
|
|
|
try {
|
|
await loader(routeArgs(new Request("http://localhost:3000/api/v1/routes"), {}, "api/v1/routes"));
|
|
expect.fail("should throw");
|
|
} catch (err) {
|
|
expect(err).toBeInstanceOf(Response);
|
|
expect((err as Response).status).toBe(401);
|
|
}
|
|
});
|
|
});
|
|
|
|
describe("POST /api/v1/routes", () => {
|
|
it("creates a route with valid body", async () => {
|
|
mockCreateRoute.mockResolvedValue("new-id");
|
|
const { action } = await import("./api.v1.routes._index.ts");
|
|
|
|
const resp = await action(routeArgs(
|
|
authRequest("/api/v1/routes", {
|
|
method: "POST",
|
|
body: JSON.stringify({ name: "New Route" }),
|
|
}), {}, "api/v1/routes",
|
|
)) as Response;
|
|
|
|
expect(resp.status).toBe(201);
|
|
const data = await resp.json();
|
|
expect(data.id).toBe("new-id");
|
|
});
|
|
|
|
it("returns 400 on validation error", async () => {
|
|
const { action } = await import("./api.v1.routes._index.ts");
|
|
const resp = await action(routeArgs(
|
|
authRequest("/api/v1/routes", {
|
|
method: "POST",
|
|
body: JSON.stringify({ name: "" }),
|
|
}), {}, "api/v1/routes",
|
|
)) as Response;
|
|
|
|
expect(resp.status).toBe(400);
|
|
const data = await resp.json();
|
|
expect(data.code).toBe("VALIDATION_ERROR");
|
|
});
|
|
});
|
|
|
|
describe("GET /api/v1/routes/:id", () => {
|
|
it("returns route detail", async () => {
|
|
const now = new Date();
|
|
mockGetRouteWithVersions.mockResolvedValue({
|
|
id: "r1", name: "Tour", description: "", distance: 42000,
|
|
elevationGain: 340, elevationLoss: 320, routingProfile: "fastbike",
|
|
dayBreaks: [], gpx: "<gpx/>", ownerId: "user-1",
|
|
tags: null, plannerState: null, createdAt: now, updatedAt: now,
|
|
versions: [{ id: "v1", routeId: "r1", version: 1, gpx: "<gpx/>", createdBy: "user-1", changeDescription: null, createdAt: now }],
|
|
});
|
|
|
|
const { loader } = await import("./api.v1.routes.$id.ts");
|
|
const resp = await loader(routeArgs(
|
|
authRequest("/api/v1/routes/r1"), { id: "r1" }, "api/v1/routes/:id",
|
|
)) as Response;
|
|
|
|
const data = await resp.json();
|
|
expect(data.id).toBe("r1");
|
|
expect(data.gpx).toBe("<gpx/>");
|
|
expect(data.versions).toHaveLength(1);
|
|
});
|
|
|
|
it("returns 404 for missing route", async () => {
|
|
mockGetRouteWithVersions.mockResolvedValue(null);
|
|
const { loader } = await import("./api.v1.routes.$id.ts");
|
|
const resp = await loader(routeArgs(
|
|
authRequest("/api/v1/routes/missing"), { id: "missing" }, "api/v1/routes/:id",
|
|
)) as Response;
|
|
|
|
expect(resp.status).toBe(404);
|
|
});
|
|
});
|
|
|
|
describe("DELETE /api/v1/routes/:id", () => {
|
|
it("returns 204 on success", async () => {
|
|
mockGetRoute.mockResolvedValue({ id: "r1", ownerId: "user-1" });
|
|
mockDeleteRoute.mockResolvedValue(true);
|
|
const { action } = await import("./api.v1.routes.$id.ts");
|
|
const resp = await action(routeArgs(
|
|
authRequest("/api/v1/routes/r1", { method: "DELETE" }), { id: "r1" }, "api/v1/routes/:id",
|
|
)) as Response;
|
|
|
|
expect(resp.status).toBe(204);
|
|
});
|
|
|
|
it("returns 404 if not found", async () => {
|
|
mockGetRoute.mockResolvedValue(null);
|
|
const { action } = await import("./api.v1.routes.$id.ts");
|
|
const resp = await action(routeArgs(
|
|
authRequest("/api/v1/routes/missing", { method: "DELETE" }), { id: "missing" }, "api/v1/routes/:id",
|
|
)) as Response;
|
|
|
|
expect(resp.status).toBe(404);
|
|
});
|
|
});
|