Allow configuration of client and org subnets

This commit is contained in:
Owen 2025-04-16 22:00:24 -04:00
parent 569635f3ed
commit db0328fa71
No known key found for this signature in database
GPG key ID: 8271FDFFD9E0CCBD
10 changed files with 218 additions and 48 deletions

View file

@ -274,4 +274,13 @@ export async function getNextAvailableOrgSubnet(): Promise<string> {
} }
return subnet; return subnet;
}
export function isValidCidr(cidr: string): boolean {
try {
cidrToRange(cidr);
return true;
} catch (e) {
return false;
}
} }

View file

@ -19,8 +19,7 @@ import { eq, and } from "drizzle-orm";
import { fromError } from "zod-validation-error"; import { fromError } from "zod-validation-error";
import moment from "moment"; import moment from "moment";
import { hashPassword } from "@server/auth/password"; import { hashPassword } from "@server/auth/password";
import { getNextAvailableClientSubnet } from "@server/lib/ip"; import { isValidCIDR } from "@server/lib/validators";
import config from "@server/lib/config";
const createClientParamsSchema = z const createClientParamsSchema = z
.object({ .object({
@ -34,6 +33,7 @@ const createClientSchema = z
siteIds: z.array(z.number().int().positive()), siteIds: z.array(z.number().int().positive()),
olmId: z.string(), olmId: z.string(),
secret: z.string(), secret: z.string(),
subnet: z.string(),
type: z.enum(["olm"]) type: z.enum(["olm"])
}) })
.strict(); .strict();
@ -58,7 +58,7 @@ export async function createClient(
); );
} }
const { name, type, siteIds, olmId, secret } = parsedBody.data; const { name, type, siteIds, olmId, secret, subnet } = parsedBody.data;
const parsedParams = createClientParamsSchema.safeParse(req.params); const parsedParams = createClientParamsSchema.safeParse(req.params);
if (!parsedParams.success) { if (!parsedParams.success) {
@ -78,9 +78,14 @@ export async function createClient(
); );
} }
const newSubnet = await getNextAvailableClientSubnet(orgId); if (subnet && !isValidCIDR(subnet)) {
return next(
const subnet = `${newSubnet.split("/")[0]}/${config.getRawConfig().orgs.block_size}`; // we want the block size of the whole org createHttpError(
HttpCode.BAD_REQUEST,
"Invalid subnet format. Please provide a valid CIDR notation."
)
);
}
await db.transaction(async (trx) => { await db.transaction(async (trx) => {
// TODO: more intelligent way to pick the exit node // TODO: more intelligent way to pick the exit node

View file

@ -4,25 +4,53 @@ import HttpCode from "@server/types/HttpCode";
import createHttpError from "http-errors"; import createHttpError from "http-errors";
import logger from "@server/logger"; import logger from "@server/logger";
import { generateId } from "@server/auth/sessions/app"; import { generateId } from "@server/auth/sessions/app";
import { getNextAvailableClientSubnet } from "@server/lib/ip";
import config from "@server/lib/config";
import { z } from "zod";
import { fromError } from "zod-validation-error";
export type PickClientDefaultsResponse = { export type PickClientDefaultsResponse = {
olmId: string; olmId: string;
olmSecret: string; olmSecret: string;
subnet: string;
}; };
const pickClientDefaultsSchema = z
.object({
orgId: z.string()
})
.strict();
export async function pickClientDefaults( export async function pickClientDefaults(
req: Request, req: Request,
res: Response, res: Response,
next: NextFunction next: NextFunction
): Promise<any> { ): Promise<any> {
try { try {
const parsedParams = pickClientDefaultsSchema.safeParse(req.params);
if (!parsedParams.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedParams.error).toString()
)
);
}
const { orgId } = parsedParams.data;
const olmId = generateId(15); const olmId = generateId(15);
const secret = generateId(48); const secret = generateId(48);
const newSubnet = await getNextAvailableClientSubnet(orgId);
const subnet = `${newSubnet.split("/")[0]}/${config.getRawConfig().orgs.block_size}`; // we want the block size of the whole org
return response<PickClientDefaultsResponse>(res, { return response<PickClientDefaultsResponse>(res, {
data: { data: {
olmId: olmId, olmId: olmId,
olmSecret: secret olmSecret: secret,
subnet: subnet
}, },
success: true, success: true,
error: false, error: false,

View file

@ -47,8 +47,13 @@ unauthenticated.get("/", (_, res) => {
export const authenticated = Router(); export const authenticated = Router();
authenticated.use(verifySessionUserMiddleware); authenticated.use(verifySessionUserMiddleware);
authenticated.get(
"/pick-org-defaults",
org.pickOrgDefaults
);
authenticated.get("/org/checkId", org.checkId); authenticated.get("/org/checkId", org.checkId);
authenticated.put("/org", getUserOrgs, org.createOrg); authenticated.put("/org", getUserOrgs, org.createOrg);
authenticated.get("/orgs", getUserOrgs, org.listOrgs); // TODO we need to check the orgs here authenticated.get("/orgs", getUserOrgs, org.listOrgs); // TODO we need to check the orgs here
authenticated.get( authenticated.get(
"/org/:orgId", "/org/:orgId",

View file

@ -19,12 +19,13 @@ import { createAdminRole } from "@server/setup/ensureActions";
import config from "@server/lib/config"; import config from "@server/lib/config";
import { fromError } from "zod-validation-error"; import { fromError } from "zod-validation-error";
import { defaultRoleAllowedActions } from "../role"; import { defaultRoleAllowedActions } from "../role";
import { getNextAvailableOrgSubnet } from "@server/lib/ip"; import { isValidCIDR } from "@server/lib/validators";
const createOrgSchema = z const createOrgSchema = z
.object({ .object({
orgId: z.string(), orgId: z.string(),
name: z.string().min(1).max(255) name: z.string().min(1).max(255),
subnet: z.string()
}) })
.strict(); .strict();
@ -68,7 +69,16 @@ export async function createOrg(
); );
} }
const { orgId, name } = parsedBody.data; const { orgId, name, subnet } = parsedBody.data;
if (subnet && !isValidCIDR(subnet)) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"Invalid subnet format. Please provide a valid CIDR notation."
)
);
}
// make sure the orgId is unique // make sure the orgId is unique
const orgExists = await db const orgExists = await db
@ -89,8 +99,6 @@ export async function createOrg(
let error = ""; let error = "";
let org: Org | null = null; let org: Org | null = null;
const subnet = await getNextAvailableOrgSubnet();
await db.transaction(async (trx) => { await db.transaction(async (trx) => {
const allDomains = await trx const allDomains = await trx
.select() .select()

View file

@ -5,3 +5,4 @@ export * from "./updateOrg";
export * from "./listOrgs"; export * from "./listOrgs";
export * from "./checkId"; export * from "./checkId";
export * from "./getOrgOverview"; export * from "./getOrgOverview";
export* from "./pickOrgDefaults";

View file

@ -0,0 +1,35 @@
import { Request, Response, NextFunction } from "express";
import response from "@server/lib/response";
import HttpCode from "@server/types/HttpCode";
import createHttpError from "http-errors";
import logger from "@server/logger";
import { getNextAvailableOrgSubnet } from "@server/lib/ip";
export type PickOrgDefaultsResponse = {
subnet: string;
};
export async function pickOrgDefaults(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
try {
const subnet = await getNextAvailableOrgSubnet();
return response<PickOrgDefaultsResponse>(res, {
data: {
subnet: subnet
},
success: true,
error: false,
message: "Organization defaults created successfully",
status: HttpCode.OK
});
} catch (error) {
logger.error(error);
return next(
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
);
}
}

View file

@ -59,6 +59,9 @@ const createClientFormSchema = z.object({
}), }),
siteIds: z.array(z.number()).min(1, { siteIds: z.array(z.number()).min(1, {
message: "Select at least one site." message: "Select at least one site."
}),
subnet: z.string().min(1, {
message: "Subnet is required."
}) })
}); });
@ -66,7 +69,8 @@ type CreateClientFormValues = z.infer<typeof createClientFormSchema>;
const defaultValues: Partial<CreateClientFormValues> = { const defaultValues: Partial<CreateClientFormValues> = {
name: "", name: "",
siteIds: [] siteIds: [],
subnet: ""
}; };
type CreateClientFormProps = { type CreateClientFormProps = {
@ -151,6 +155,11 @@ export default function CreateClientForm({
setClientDefaults(data); setClientDefaults(data);
const olmConfig = `olm --id ${data?.olmId} --secret ${data?.olmSecret} --endpoint ${env.app.dashboardUrl}`; const olmConfig = `olm --id ${data?.olmId} --secret ${data?.olmSecret} --endpoint ${env.app.dashboardUrl}`;
setOlmCommand(olmConfig); setOlmCommand(olmConfig);
// Set the subnet value from client defaults
if (data?.subnet) {
form.setValue("subnet", data.subnet);
}
} }
}); });
}; };
@ -191,6 +200,7 @@ export default function CreateClientForm({
siteIds: data.siteIds, siteIds: data.siteIds,
olmId: clientDefaults.olmId, olmId: clientDefaults.olmId,
secret: clientDefaults.olmSecret, secret: clientDefaults.olmSecret,
subnet: data.subnet,
type: "olm" type: "olm"
} as CreateClientBody; } as CreateClientBody;
@ -249,6 +259,27 @@ export default function CreateClientForm({
)} )}
/> />
<FormField
control={form.control}
name="subnet"
render={({ field }) => (
<FormItem>
<FormLabel>Subnet</FormLabel>
<FormControl>
<Input
autoComplete="off"
placeholder="Subnet"
{...field}
/>
</FormControl>
<FormDescription>
The subnet that this client will use for connectivity.
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
<FormField <FormField
control={form.control} control={form.control}
name="siteIds" name="siteIds"
@ -387,4 +418,4 @@ export default function CreateClientForm({
</Form> </Form>
</div> </div>
); );
} }

View file

@ -1,5 +1,4 @@
"use client"; "use client";
import ConfirmDeleteDialog from "@app/components/ConfirmDeleteDialog"; import ConfirmDeleteDialog from "@app/components/ConfirmDeleteDialog";
import { Button } from "@app/components/ui/button"; import { Button } from "@app/components/ui/button";
import { useOrgContext } from "@app/hooks/useOrgContext"; import { useOrgContext } from "@app/hooks/useOrgContext";
@ -22,17 +21,9 @@ import { zodResolver } from "@hookform/resolvers/zod";
import { createApiClient } from "@app/lib/api"; import { createApiClient } from "@app/lib/api";
import { useEnvContext } from "@app/hooks/useEnvContext"; import { useEnvContext } from "@app/hooks/useEnvContext";
import { formatAxiosError } from "@app/lib/api"; import { formatAxiosError } from "@app/lib/api";
import { AlertTriangle, Trash2 } from "lucide-react";
import {
Card,
CardContent,
CardFooter,
CardHeader,
CardTitle
} from "@/components/ui/card";
import { AxiosResponse } from "axios"; import { AxiosResponse } from "axios";
import { DeleteOrgResponse, ListOrgsResponse } from "@server/routers/org"; import { DeleteOrgResponse, ListOrgsResponse } from "@server/routers/org";
import { redirect, useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { import {
SettingsContainer, SettingsContainer,
SettingsSection, SettingsSection,
@ -44,27 +35,28 @@ import {
SettingsSectionFooter SettingsSectionFooter
} from "@app/components/Settings"; } from "@app/components/Settings";
// Updated schema to include subnet field
const GeneralFormSchema = z.object({ const GeneralFormSchema = z.object({
name: z.string() name: z.string(),
subnet: z.string().optional()
}); });
type GeneralFormValues = z.infer<typeof GeneralFormSchema>; type GeneralFormValues = z.infer<typeof GeneralFormSchema>;
export default function GeneralPage() { export default function GeneralPage() {
const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false); const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
const { orgUser } = userOrgUserContext(); const { orgUser } = userOrgUserContext();
const router = useRouter(); const router = useRouter();
const { org } = useOrgContext(); const { org } = useOrgContext();
const api = createApiClient(useEnvContext()); const api = createApiClient(useEnvContext());
const [loadingDelete, setLoadingDelete] = useState(false); const [loadingDelete, setLoadingDelete] = useState(false);
const [loadingSave, setLoadingSave] = useState(false); const [loadingSave, setLoadingSave] = useState(false);
const form = useForm<GeneralFormValues>({ const form = useForm<GeneralFormValues>({
resolver: zodResolver(GeneralFormSchema), resolver: zodResolver(GeneralFormSchema),
defaultValues: { defaultValues: {
name: org?.org.name name: org?.org.name,
subnet: org?.org.subnet || "" // Add default value for subnet
}, },
mode: "onChange" mode: "onChange"
}); });
@ -75,12 +67,10 @@ export default function GeneralPage() {
const res = await api.delete<AxiosResponse<DeleteOrgResponse>>( const res = await api.delete<AxiosResponse<DeleteOrgResponse>>(
`/org/${org?.org.orgId}` `/org/${org?.org.orgId}`
); );
toast({ toast({
title: "Organization deleted", title: "Organization deleted",
description: "The organization and its data has been deleted." description: "The organization and its data has been deleted."
}); });
if (res.status === 200) { if (res.status === 200) {
pickNewOrgAndNavigate(); pickNewOrgAndNavigate();
} }
@ -102,7 +92,6 @@ export default function GeneralPage() {
async function pickNewOrgAndNavigate() { async function pickNewOrgAndNavigate() {
try { try {
const res = await api.get<AxiosResponse<ListOrgsResponse>>(`/orgs`); const res = await api.get<AxiosResponse<ListOrgsResponse>>(`/orgs`);
if (res.status === 200) { if (res.status === 200) {
if (res.data.data.orgs.length > 0) { if (res.data.data.orgs.length > 0) {
const orgId = res.data.data.orgs[0].orgId; const orgId = res.data.data.orgs[0].orgId;
@ -130,14 +119,14 @@ export default function GeneralPage() {
setLoadingSave(true); setLoadingSave(true);
await api await api
.post(`/org/${org?.org.orgId}`, { .post(`/org/${org?.org.orgId}`, {
name: data.name name: data.name,
subnet: data.subnet // Include subnet in the API request
}) })
.then(() => { .then(() => {
toast({ toast({
title: "Organization updated", title: "Organization updated",
description: "The organization has been updated." description: "The organization has been updated."
}); });
router.refresh(); router.refresh();
}) })
.catch((e) => { .catch((e) => {
@ -182,7 +171,6 @@ export default function GeneralPage() {
string={org?.org.name || ""} string={org?.org.name || ""}
title="Delete Organization" title="Delete Organization"
/> />
<SettingsSection> <SettingsSection>
<SettingsSectionHeader> <SettingsSectionHeader>
<SettingsSectionTitle> <SettingsSectionTitle>
@ -192,7 +180,6 @@ export default function GeneralPage() {
Manage your organization details and configuration Manage your organization details and configuration
</SettingsSectionDescription> </SettingsSectionDescription>
</SettingsSectionHeader> </SettingsSectionHeader>
<SettingsSectionBody> <SettingsSectionBody>
<SettingsSectionForm> <SettingsSectionForm>
<Form {...form}> <Form {...form}>
@ -218,11 +205,31 @@ export default function GeneralPage() {
</FormItem> </FormItem>
)} )}
/> />
{/* New FormField for subnet input */}
<FormField
control={form.control}
name="subnet"
render={({ field }) => (
<FormItem>
<FormLabel>Subnet</FormLabel>
<FormControl>
<Input
{...field}
placeholder="e.g., 192.168.1.0/24"
/>
</FormControl>
<FormMessage />
<FormDescription>
The subnet for this organization's network configuration.
</FormDescription>
</FormItem>
)}
/>
</form> </form>
</Form> </Form>
</SettingsSectionForm> </SettingsSectionForm>
</SettingsSectionBody> </SettingsSectionBody>
<SettingsSectionFooter> <SettingsSectionFooter>
<Button <Button
type="submit" type="submit"
@ -234,7 +241,6 @@ export default function GeneralPage() {
</Button> </Button>
</SettingsSectionFooter> </SettingsSectionFooter>
</SettingsSection> </SettingsSection>
<SettingsSection> <SettingsSection>
<SettingsSectionHeader> <SettingsSectionHeader>
<SettingsSectionTitle> <SettingsSectionTitle>
@ -245,7 +251,6 @@ export default function GeneralPage() {
be certain. be certain.
</SettingsSectionDescription> </SettingsSectionDescription>
</SettingsSectionHeader> </SettingsSectionHeader>
<SettingsSectionFooter> <SettingsSectionFooter>
<Button <Button
variant="destructive" variant="destructive"
@ -260,4 +265,4 @@ export default function GeneralPage() {
</SettingsSection> </SettingsSection>
</SettingsContainer> </SettingsContainer>
); );
} }

View file

@ -2,8 +2,6 @@
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import Link from "next/link";
import { toast } from "@app/hooks/useToast"; import { toast } from "@app/hooks/useToast";
import { useCallback, useEffect, useState } from "react"; import { useCallback, useEffect, useState } from "react";
import { import {
@ -13,7 +11,6 @@ import {
CardHeader, CardHeader,
CardTitle CardTitle
} from "@app/components/ui/card"; } from "@app/components/ui/card";
import CopyTextBox from "@app/components/CopyTextBox";
import { formatAxiosError } from "@app/lib/api";; import { formatAxiosError } from "@app/lib/api";;
import { createApiClient } from "@app/lib/api"; import { createApiClient } from "@app/lib/api";
import { useEnvContext } from "@app/hooks/useEnvContext"; import { useEnvContext } from "@app/hooks/useEnvContext";
@ -32,13 +29,13 @@ import {
FormMessage FormMessage
} from "@app/components/ui/form"; } from "@app/components/ui/form";
import { Alert, AlertDescription } from "@app/components/ui/alert"; import { Alert, AlertDescription } from "@app/components/ui/alert";
import CreateSiteForm from "../[orgId]/settings/sites/CreateSiteForm";
type Step = "org" | "site" | "resources"; type Step = "org" | "site" | "resources";
const orgSchema = z.object({ const orgSchema = z.object({
orgName: z.string().min(1, { message: "Organization name is required" }), orgName: z.string().min(1, { message: "Organization name is required" }),
orgId: z.string().min(1, { message: "Organization ID is required" }) orgId: z.string().min(1, { message: "Organization ID is required" }),
subnet: z.string().min(1, { message: "Subnet is required" })
}); });
export default function StepperForm() { export default function StepperForm() {
@ -53,13 +50,35 @@ export default function StepperForm() {
resolver: zodResolver(orgSchema), resolver: zodResolver(orgSchema),
defaultValues: { defaultValues: {
orgName: "", orgName: "",
orgId: "" orgId: "",
subnet: ""
} }
}); });
const api = createApiClient(useEnvContext()); const api = createApiClient(useEnvContext());
const router = useRouter(); const router = useRouter();
// Fetch default subnet on component mount
useEffect(() => {
fetchDefaultSubnet();
}, []);
const fetchDefaultSubnet = async () => {
try {
const res = await api.get(`/pick-org-defaults`);
if (res && res.data && res.data.data) {
orgForm.setValue("subnet", res.data.data.subnet);
}
} catch (e) {
console.error("Failed to fetch default subnet:", e);
toast({
title: "Error",
description: "Failed to fetch default subnet",
variant: "destructive"
});
}
};
const checkOrgIdAvailability = useCallback(async (value: string) => { const checkOrgIdAvailability = useCallback(async (value: string) => {
try { try {
const res = await api.get(`/org/checkId`, { const res = await api.get(`/org/checkId`, {
@ -92,7 +111,8 @@ export default function StepperForm() {
try { try {
const res = await api.put(`/org`, { const res = await api.put(`/org`, {
orgId: values.orgId, orgId: values.orgId,
name: values.orgName name: values.orgName,
subnet: values.subnet
}); });
if (res && res.status === 201) { if (res && res.status === 201) {
@ -256,6 +276,29 @@ export default function StepperForm() {
</FormItem> </FormItem>
)} )}
/> />
<FormField
control={orgForm.control}
name="subnet"
render={({ field }) => (
<FormItem>
<FormLabel>
Subnet
</FormLabel>
<FormControl>
<Input
type="text"
{...field}
/>
</FormControl>
<FormMessage />
<FormDescription>
Network subnet for this organization.
A default value has been provided.
</FormDescription>
</FormItem>
)}
/>
{orgIdTaken && ( {orgIdTaken && (
<Alert variant="destructive"> <Alert variant="destructive">
@ -311,4 +354,4 @@ function debounce<T extends (...args: any[]) => any>(
func(...args); func(...args);
}, wait); }, wait);
}; };
} }