Update gerbil with new sites and targets

This commit is contained in:
Owen Schwartz 2024-10-26 22:44:34 -04:00
parent 25224e0343
commit 4ed5ef1765
No known key found for this signature in database
GPG key ID: 8271FDFFD9E0CCBD
11 changed files with 270 additions and 104 deletions

View file

@ -1,12 +1,15 @@
import { Request, Response, NextFunction } from 'express';
import { z } from 'zod';
import { db } from '@server/db';
import { targets } from '@server/db/schema';
import { resources, sites, targets } from '@server/db/schema';
import response from "@server/utils/response";
import HttpCode from '@server/types/HttpCode';
import createHttpError from 'http-errors';
import { ActionsEnum, checkUserActionPermission } from '@server/auth/actions';
import logger from '@server/logger';
import { addPeer } from '../gerbil/peers';
import { eq, and } from 'drizzle-orm';
import { isIpInCidr } from '@server/utils/ip';
const createTargetParamsSchema = z.object({
resourceId: z.string().transform(Number).pipe(z.number().int().positive()),
@ -52,11 +55,72 @@ export async function createTarget(req: Request, res: Response, next: NextFuncti
return next(createHttpError(HttpCode.FORBIDDEN, 'User does not have permission to perform this action'));
}
// 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`
)
);
}
const newTarget = await db.insert(targets).values({
resourceId,
...targetData
}).returning();
// 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()
});
return response(res, {
data: newTarget[0],
success: true,