// This file is licensed under the Fossorial Commercial License. // Unauthorized use, copying, modification, or distribution is strictly prohibited. // // Copyright (c) 2025 Fossorial LLC. All rights reserved. import { Request, Response, NextFunction } from "express"; import { db } from "@server/db"; import { resources, targets, apiKeyOrg } from "@server/db/schemas"; import { and, eq } from "drizzle-orm"; import createHttpError from "http-errors"; import HttpCode from "@server/types/HttpCode"; export async function verifyApiKeyTargetAccess( req: Request, res: Response, next: NextFunction ) { try { const apiKey = req.apiKey; const targetId = parseInt(req.params.targetId); if (!apiKey) { return next( createHttpError(HttpCode.UNAUTHORIZED, "Key not authenticated") ); } if (isNaN(targetId)) { return next( createHttpError(HttpCode.BAD_REQUEST, "Invalid target ID") ); } const [target] = await db .select() .from(targets) .where(eq(targets.targetId, targetId)) .limit(1); if (!target) { return next( createHttpError( HttpCode.NOT_FOUND, `Target with ID ${targetId} not found` ) ); } const resourceId = target.resourceId; if (!resourceId) { return next( createHttpError( HttpCode.INTERNAL_SERVER_ERROR, `Target with ID ${targetId} does not have a resource ID` ) ); } const [resource] = await db .select() .from(resources) .where(eq(resources.resourceId, resourceId)) .limit(1); if (!resource) { return next( createHttpError( HttpCode.NOT_FOUND, `Resource with ID ${resourceId} not found` ) ); } if (!resource.orgId) { return next( createHttpError( HttpCode.INTERNAL_SERVER_ERROR, `Resource with ID ${resourceId} does not have an organization ID` ) ); } if (!req.apiKeyOrg) { const apiKeyOrgResult = await db .select() .from(apiKeyOrg) .where( and( eq(apiKeyOrg.apiKeyId, apiKey.apiKeyId), eq(apiKeyOrg.orgId, resource.orgId) ) ) .limit(1); if (apiKeyOrgResult.length > 0) { req.apiKeyOrg = apiKeyOrgResult[0]; } } if (!req.apiKeyOrg) { return next( createHttpError( HttpCode.FORBIDDEN, "Key does not have access to this organization" ) ); } return next(); } catch (error) { return next( createHttpError( HttpCode.INTERNAL_SERVER_ERROR, "Error verifying target access" ) ); } }