fosrl.pangolin/server/routers/target/createTarget.ts

136 lines
4.4 KiB
TypeScript
Raw Normal View History

2024-10-01 21:34:07 -04:00
import { Request, Response, NextFunction } from 'express';
2024-10-01 21:53:49 -04:00
import { z } from 'zod';
import { db } from '@server/db';
import { resources, sites, targets } from '@server/db/schema';
2024-10-01 21:34:07 -04:00
import response from "@server/utils/response";
import HttpCode from '@server/types/HttpCode';
2024-10-01 21:53:49 -04:00
import createHttpError from 'http-errors';
2024-10-06 16:43:59 -04:00
import { ActionsEnum, checkUserActionPermission } from '@server/auth/actions';
2024-10-06 18:05:20 -04:00
import logger from '@server/logger';
import { addPeer } from '../gerbil/peers';
import { eq, and } from 'drizzle-orm';
import { isIpInCidr } from '@server/utils/ip';
2024-10-01 21:53:49 -04:00
2024-10-02 22:05:21 -04:00
const createTargetParamsSchema = z.object({
2024-10-26 12:15:03 -04:00
resourceId: z.string().transform(Number).pipe(z.number().int().positive()),
2024-10-02 22:05:21 -04:00
});
const createTargetSchema = z.object({
2024-10-06 18:05:20 -04:00
ip: z.string().ip(),
method: z.string().min(1).max(10),
port: z.number().int().min(1).max(65535),
protocol: z.string().optional(),
enabled: z.boolean().default(true),
2024-10-01 21:53:49 -04:00
});
2024-10-01 21:34:07 -04:00
export async function createTarget(req: Request, res: Response, next: NextFunction): Promise<any> {
2024-10-06 18:05:20 -04:00
try {
const parsedBody = createTargetSchema.safeParse(req.body);
if (!parsedBody.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
parsedBody.error.errors.map(e => e.message).join(', ')
)
);
}
2024-10-01 21:53:49 -04:00
2024-10-06 18:05:20 -04:00
const targetData = parsedBody.data;
2024-10-01 21:53:49 -04:00
2024-10-06 18:05:20 -04:00
const parsedParams = createTargetParamsSchema.safeParse(req.params);
if (!parsedParams.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
parsedParams.error.errors.map(e => e.message).join(', ')
)
);
}
2024-10-02 22:05:21 -04:00
2024-10-06 18:05:20 -04:00
const { resourceId } = parsedParams.data;
2024-10-02 22:05:21 -04:00
2024-10-06 18:05:20 -04:00
// Check if the user has permission to list sites
const hasPermission = await checkUserActionPermission(ActionsEnum.createTarget, req);
if (!hasPermission) {
2024-10-12 21:36:14 -04:00
return next(createHttpError(HttpCode.FORBIDDEN, 'User does not have permission to perform this action'));
2024-10-06 18:05:20 -04:00
}
2024-10-06 16:43:59 -04:00
// get the resource
const [resource] = await db.select({
siteId: resources.siteId,
})
.from(resources)
.where(eq(resources.resourceId, resourceId));
if (!resource) {
return next(
createHttpError(
HttpCode.NOT_FOUND,
`Resource with ID ${resourceId} not found`
)
);
}
// TODO: is this all inefficient?
// get the site
const [site] = await db.select()
.from(sites)
.where(eq(sites.siteId, resource.siteId!))
.limit(1);
if (!site) {
return next(
createHttpError(
HttpCode.NOT_FOUND,
`Site with ID ${resource.siteId} not found`
)
);
}
// make sure the target is within the site subnet
if (!isIpInCidr(targetData.ip, site.subnet!)) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
`Target IP is not within the site subnet`
)
);
}
2024-10-06 18:05:20 -04:00
const newTarget = await db.insert(targets).values({
resourceId,
...targetData
}).returning();
2024-10-01 21:53:49 -04:00
// Fetch resources for this site
const resourcesRes = await db.query.resources.findMany({
where: eq(resources.siteId, site.siteId),
});
// Fetch targets for all resources of this site
const targetIps = await Promise.all(resourcesRes.map(async (resource) => {
const targetsRes = await db.query.targets.findMany({
where: eq(targets.resourceId, resource.resourceId),
});
return targetsRes.map(target => `${target.ip}/32`);
}));
await addPeer(site.exitNodeId!, {
publicKey: site.pubKey,
allowedIps: targetIps.flat()
});
2024-10-06 18:05:20 -04:00
return response(res, {
data: newTarget[0],
success: true,
error: false,
message: "Target created successfully",
status: HttpCode.CREATED,
});
} catch (error) {
logger.error(error);
return next(createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred..."));
}
}