harden admin api authorization and add authz regression tests
This commit is contained in:
1 parent
272c9b36dd
commit
10b58245f5
28 files changed
+1336
-240
No files matched your search
@@ -0,0 +1,83 @@
|
||||
/**
|
||||
* @jest-environment node
|
||||
*/
|
||||
|
||||
import { POST } from "../route";
|
||||
|
||||
jest.mock("@clerk/nextjs/server", () => ({
|
||||
auth: jest.fn(),
|
||||
}));
|
||||
|
||||
jest.mock("@/lib/database", () => ({
|
||||
getDatabase: jest.fn(),
|
||||
}));
|
||||
|
||||
jest.mock("@/lib/sync-user", () => ({
|
||||
ensureUserSynced: jest.fn(),
|
||||
}));
|
||||
|
||||
jest.mock("@/lib/logger", () => ({
|
||||
info: jest.fn(),
|
||||
warn: jest.fn(),
|
||||
error: jest.fn(),
|
||||
debug: jest.fn(),
|
||||
}));
|
||||
|
||||
describe("POST /api/recommendations/approve authz", () => {
|
||||
const mockAuth = require("@clerk/nextjs/server").auth as jest.Mock;
|
||||
const mockGetDatabase = require("@/lib/database").getDatabase as jest.Mock;
|
||||
const mockEnsureUserSynced = require("@/lib/sync-user")
|
||||
.ensureUserSynced as jest.Mock;
|
||||
|
||||
const mockDb = {
|
||||
getAllRecommendations: jest.fn(),
|
||||
getUserById: jest.fn(),
|
||||
updateRecommendation: jest.fn(),
|
||||
createNotification: jest.fn(),
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
mockGetDatabase.mockResolvedValue(mockDb);
|
||||
});
|
||||
|
||||
it("returns 403 for non-staff role", async () => {
|
||||
mockAuth.mockResolvedValue({ userId: "client_1" });
|
||||
mockEnsureUserSynced.mockResolvedValue({
|
||||
id: "client_1",
|
||||
role: "client",
|
||||
gymId: "gym_a",
|
||||
});
|
||||
|
||||
const req = new Request("http://localhost/api/recommendations/approve", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ recommendationId: "rec_1", status: "approved" }),
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
|
||||
const res = await POST(req);
|
||||
expect(res.status).toBe(403);
|
||||
});
|
||||
|
||||
it("returns 403 for cross-gym approval by admin", async () => {
|
||||
mockAuth.mockResolvedValue({ userId: "admin_1" });
|
||||
mockEnsureUserSynced.mockResolvedValue({
|
||||
id: "admin_1",
|
||||
role: "admin",
|
||||
gymId: "gym_a",
|
||||
});
|
||||
mockDb.getAllRecommendations.mockResolvedValue([
|
||||
{ id: "rec_1", userId: "client_1" },
|
||||
]);
|
||||
mockDb.getUserById.mockResolvedValue({ id: "client_1", gymId: "gym_b" });
|
||||
|
||||
const req = new Request("http://localhost/api/recommendations/approve", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ recommendationId: "rec_1", status: "approved" }),
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
|
||||
const res = await POST(req);
|
||||
expect(res.status).toBe(403);
|
||||
});
|
||||
});
|
||||
@@ -1,13 +1,20 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { auth } from "@clerk/nextjs/server";
|
||||
import { getDatabase } from "@/lib/database";
|
||||
import log from "@/lib/logger";
|
||||
import { ensureUserSynced } from "@/lib/sync-user";
|
||||
|
||||
export async function POST(req: Request) {
|
||||
try {
|
||||
const { userId: clerkUserId } = await auth();
|
||||
if (!clerkUserId) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
const body = await req.json();
|
||||
log.debug("Approve recommendation request body", { body });
|
||||
|
||||
const { recommendationId, status, approvedBy } = body;
|
||||
const { recommendationId, status } = body;
|
||||
|
||||
if (!recommendationId || !status) {
|
||||
log.error("Missing required fields", {
|
||||
@@ -22,12 +29,52 @@ export async function POST(req: Request) {
|
||||
}
|
||||
|
||||
const db = await getDatabase();
|
||||
const currentUser = await ensureUserSynced(clerkUserId, db);
|
||||
|
||||
if (!currentUser) {
|
||||
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
|
||||
}
|
||||
|
||||
const canApproveRecommendations =
|
||||
currentUser.role === "superAdmin" ||
|
||||
currentUser.role === "admin" ||
|
||||
currentUser.role === "trainer";
|
||||
|
||||
if (!canApproveRecommendations) {
|
||||
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
|
||||
}
|
||||
|
||||
const existingRecommendation = (await db.getAllRecommendations()).find(
|
||||
(recommendation) => recommendation.id === recommendationId,
|
||||
);
|
||||
|
||||
if (!existingRecommendation) {
|
||||
return NextResponse.json(
|
||||
{ error: "Recommendation not found" },
|
||||
{ status: 404 },
|
||||
);
|
||||
}
|
||||
|
||||
if (currentUser.role !== "superAdmin") {
|
||||
const targetUser = await db.getUserById(existingRecommendation.userId);
|
||||
|
||||
if (
|
||||
!currentUser.gymId ||
|
||||
!targetUser ||
|
||||
targetUser.gymId !== currentUser.gymId
|
||||
) {
|
||||
return NextResponse.json(
|
||||
{ error: "Forbidden - Cannot access users from other gyms" },
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Update recommendation status
|
||||
const updates: any = {
|
||||
status,
|
||||
approvedAt: status === "approved" ? new Date() : undefined,
|
||||
approvedBy: status === "approved" ? approvedBy : undefined,
|
||||
approvedBy: status === "approved" ? clerkUserId : undefined,
|
||||
};
|
||||
|
||||
// Remove undefined keys
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
/**
|
||||
* @jest-environment node
|
||||
*/
|
||||
|
||||
import { POST } from "../route";
|
||||
|
||||
jest.mock("@clerk/nextjs/server", () => ({
|
||||
auth: jest.fn(),
|
||||
}));
|
||||
|
||||
jest.mock("@/lib/database", () => ({
|
||||
getDatabase: jest.fn(),
|
||||
}));
|
||||
|
||||
jest.mock("@/lib/sync-user", () => ({
|
||||
ensureUserSynced: jest.fn(),
|
||||
}));
|
||||
|
||||
jest.mock("@/lib/ai/ai-context", () => ({
|
||||
buildAIContext: jest.fn(),
|
||||
}));
|
||||
|
||||
jest.mock("@/lib/ai/prompt-builder", () => ({
|
||||
buildEnhancedPrompt: jest.fn(),
|
||||
buildBasicPrompt: jest.fn(),
|
||||
}));
|
||||
|
||||
jest.mock("@/lib/logger", () => ({
|
||||
info: jest.fn(),
|
||||
warn: jest.fn(),
|
||||
error: jest.fn(),
|
||||
debug: jest.fn(),
|
||||
}));
|
||||
|
||||
describe("POST /api/recommendations/generate authz", () => {
|
||||
const mockAuth = require("@clerk/nextjs/server").auth as jest.Mock;
|
||||
const mockGetDatabase = require("@/lib/database").getDatabase as jest.Mock;
|
||||
const mockEnsureUserSynced = require("@/lib/sync-user")
|
||||
.ensureUserSynced as jest.Mock;
|
||||
|
||||
const mockDb = {
|
||||
getUserById: jest.fn(),
|
||||
getFitnessProfileByUserId: jest.fn(),
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
mockGetDatabase.mockResolvedValue(mockDb);
|
||||
});
|
||||
|
||||
it("returns 401 when unauthenticated", async () => {
|
||||
mockAuth.mockResolvedValue({ userId: null });
|
||||
|
||||
const req = new Request("http://localhost/api/recommendations/generate", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ userId: "client_1" }),
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
|
||||
const res = await POST(req);
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it("returns 403 when staff accesses user from another gym", async () => {
|
||||
mockAuth.mockResolvedValue({ userId: "admin_1" });
|
||||
mockEnsureUserSynced.mockResolvedValue({
|
||||
id: "admin_1",
|
||||
role: "admin",
|
||||
gymId: "gym_a",
|
||||
});
|
||||
mockDb.getUserById.mockResolvedValue({
|
||||
id: "client_1",
|
||||
gymId: "gym_b",
|
||||
});
|
||||
|
||||
const req = new Request("http://localhost/api/recommendations/generate", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ userId: "client_1" }),
|
||||
headers: { "Content-Type": "application/json" },
|
||||
});
|
||||
|
||||
const res = await POST(req);
|
||||
expect(res.status).toBe(403);
|
||||
});
|
||||
});
|
||||
@@ -1,11 +1,18 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { auth } from "@clerk/nextjs/server";
|
||||
import { getDatabase } from "@/lib/database";
|
||||
import { buildAIContext } from "@/lib/ai/ai-context";
|
||||
import { buildEnhancedPrompt, buildBasicPrompt } from "@/lib/ai/prompt-builder";
|
||||
import log from "@/lib/logger";
|
||||
import { ensureUserSynced } from "@/lib/sync-user";
|
||||
|
||||
export async function POST(req: Request) {
|
||||
try {
|
||||
const { userId: clerkUserId } = await auth();
|
||||
if (!clerkUserId) {
|
||||
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||
}
|
||||
|
||||
const { userId, useExternalModel, modelProvider } = await req.json();
|
||||
|
||||
if (!userId) {
|
||||
@@ -22,6 +29,34 @@ export async function POST(req: Request) {
|
||||
});
|
||||
|
||||
const db = await getDatabase();
|
||||
const currentUser = await ensureUserSynced(clerkUserId, db);
|
||||
|
||||
if (!currentUser) {
|
||||
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
|
||||
}
|
||||
|
||||
const canGenerateRecommendations =
|
||||
currentUser.role === "superAdmin" ||
|
||||
currentUser.role === "admin" ||
|
||||
currentUser.role === "trainer";
|
||||
|
||||
if (!canGenerateRecommendations) {
|
||||
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
|
||||
}
|
||||
|
||||
const targetUser = await db.getUserById(userId);
|
||||
if (!targetUser) {
|
||||
return NextResponse.json({ error: "User not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
if (currentUser.role !== "superAdmin") {
|
||||
if (!currentUser.gymId || targetUser.gymId !== currentUser.gymId) {
|
||||
return NextResponse.json(
|
||||
{ error: "Forbidden - Cannot access users from other gyms" },
|
||||
{ status: 403 },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Fetch fitness profile
|
||||
const profile = await db.getFitnessProfileByUserId(userId);
|
||||
|
||||
@@ -106,7 +106,7 @@ export async function POST(request: NextRequest) {
|
||||
}
|
||||
|
||||
const db = await getDatabase();
|
||||
const currentUser = await db.getUserById(currentUserId);
|
||||
const currentUser = await ensureUserSynced(currentUserId, db);
|
||||
const isStaff =
|
||||
currentUser?.role === "admin" ||
|
||||
currentUser?.role === "superAdmin" ||
|
||||
@@ -140,6 +140,18 @@ export async function POST(request: NextRequest) {
|
||||
content,
|
||||
} = validation.data;
|
||||
|
||||
const targetUser = await db.getUserById(userId);
|
||||
if (!targetUser) {
|
||||
return badRequestResponse("Target user not found");
|
||||
}
|
||||
|
||||
if (
|
||||
currentUser?.role !== "superAdmin" &&
|
||||
(!currentUser?.gymId || targetUser.gymId !== currentUser.gymId)
|
||||
) {
|
||||
return forbiddenResponse("Cannot create recommendations for other gyms");
|
||||
}
|
||||
|
||||
// Handle AI Plan (Legacy/Specific)
|
||||
if (recommendationText && activityPlan && dietPlan && fitnessProfileId) {
|
||||
const recommendation = await db.createRecommendation({
|
||||
@@ -198,6 +210,41 @@ export async function PUT(request: NextRequest) {
|
||||
validation.data;
|
||||
|
||||
const db = await getDatabase();
|
||||
const currentUser = await ensureUserSynced(currentUserId, db);
|
||||
|
||||
if (!currentUser) {
|
||||
return forbiddenResponse("User not found");
|
||||
}
|
||||
|
||||
const isStaff =
|
||||
currentUser.role === "admin" ||
|
||||
currentUser.role === "superAdmin" ||
|
||||
currentUser.role === "trainer";
|
||||
|
||||
if (!isStaff) {
|
||||
return forbiddenResponse();
|
||||
}
|
||||
|
||||
const existingRecommendation = (await db.getAllRecommendations()).find(
|
||||
(recommendation) => recommendation.id === id,
|
||||
);
|
||||
|
||||
if (!existingRecommendation) {
|
||||
return badRequestResponse("Recommendation not found");
|
||||
}
|
||||
|
||||
if (currentUser.role !== "superAdmin") {
|
||||
const targetUser = await db.getUserById(existingRecommendation.userId);
|
||||
if (
|
||||
!currentUser.gymId ||
|
||||
!targetUser ||
|
||||
targetUser.gymId !== currentUser.gymId
|
||||
) {
|
||||
return forbiddenResponse(
|
||||
"Cannot modify recommendations for other gyms",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const updated = await db.updateRecommendation(id, {
|
||||
...(status && { status }),
|
||||
|
||||
Reference in new issue
Block a user