Complete trusted IPs feature

This commit is contained in:
Tuan Dang
2023-07-26 13:34:56 +07:00
parent a764087c83
commit 5899d7aee9
46 changed files with 1161 additions and 79 deletions
+1
View File
@@ -17,3 +17,4 @@ export * from "./tags";
export * from "./users";
export * from "./webhooks";
export * from "./workspace";
export * from "./trustedIps";
@@ -1,5 +1,4 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request";
import {
@@ -6,6 +6,7 @@ export type SubscriptionPlan = {
customAlerts: boolean;
customRateLimits: boolean;
pitRecovery: boolean;
ipAllowlisting: boolean;
rbac: boolean;
secretVersioning: boolean;
slug: string;
@@ -0,0 +1,6 @@
export {
useGetTrustedIps,
useAddTrustedIp,
useUpdateTrustedIp,
useDeleteTrustedIp
} from "./queries";
@@ -0,0 +1,106 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request";
import {
TrustedIp
} from "./types";
const trustedIps = {
getTrustedIps: (workspaceId: string) => [{ workspaceId }, "trusted-ips"] as const
}
export const useGetTrustedIps = (workspaceId: string) => {
return useQuery({
queryKey: trustedIps.getTrustedIps(workspaceId),
queryFn: async () => {
const { data } = await apiRequest.get<{ trustedIps: TrustedIp[] }>(`/api/v1/workspace/${workspaceId}/trusted-ips`);
return data.trustedIps;
}
});
}
export const useAddTrustedIp = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async ({
workspaceId,
ipAddress,
comment,
isActive
}: {
workspaceId: string;
ipAddress: string;
comment?: string;
isActive: boolean;
}) => {
const { data } = await apiRequest.post(
`/api/v1/workspace/${workspaceId}/trusted-ips`,
{
ipAddress,
...(comment ? { comment } : {}),
isActive
}
);
return data;
},
onSuccess(_, dto) {
queryClient.invalidateQueries(trustedIps.getTrustedIps(dto.workspaceId));
}
});
};
export const useUpdateTrustedIp = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async ({
workspaceId,
trustedIpId,
ipAddress,
comment,
isActive
}: {
workspaceId: string;
trustedIpId: string;
ipAddress: string;
comment?: string;
isActive: boolean;
}) => {
const { data } = await apiRequest.patch(
`/api/v1/workspace/${workspaceId}/trusted-ips/${trustedIpId}`,
{
ipAddress,
...(comment ? { comment } : {}),
isActive
}
);
return data;
},
onSuccess(_, dto) {
queryClient.invalidateQueries(trustedIps.getTrustedIps(dto.workspaceId));
}
});
};
export const useDeleteTrustedIp = () => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async ({
workspaceId,
trustedIpId,
}: {
workspaceId: string;
trustedIpId: string;
}) => {
const { data } = await apiRequest.delete(
`/api/v1/workspace/${workspaceId}/trusted-ips/${trustedIpId}`
);
return data;
},
onSuccess(_, dto) {
queryClient.invalidateQueries(trustedIps.getTrustedIps(dto.workspaceId));
}
});
};
@@ -0,0 +1,9 @@
export type TrustedIp = {
_id: string;
workspace: string;
ipAddress: string;
type: "ipv4" | "ipv6";
isActive: boolean;
comment: string;
prefix?: number;
};
+1
View File
@@ -5,6 +5,7 @@ export {
useCreateAPIKey,
useDeleteAPIKey,
useDeleteOrgMembership,
useGetMyIp,
useGetMyAPIKeys,
useGetMySessions,
useGetOrgUsers,
+14
View File
@@ -25,6 +25,7 @@ const userKeys = {
getUser: ["user"] as const,
userAction: ["user-action"] as const,
getOrgUsers: (orgId: string) => [{ orgId }, "user"],
myIp: ["ip"] as const,
myAPIKeys: ["api-keys"] as const,
mySessions: ["sessions"] as const
};
@@ -206,6 +207,19 @@ export const useLogoutUser = () =>
}
});
export const useGetMyIp = () => {
return useQuery({
queryKey: userKeys.myIp,
queryFn: async () => {
const { data } = await apiRequest.get<{ ip: string; }>(
"/api/v1/users/me/ip"
);
return data.ip;
},
enabled: true
});
}
export const useGetMyAPIKeys = () => {
return useQuery({
queryKey: userKeys.myAPIKeys,
@@ -404,6 +404,18 @@ export const AppLayout = ({ children }: LayoutProps) => {
</MenuItem>
</a>
</Link>
<Link href={`/project/${currentWorkspace?._id}/allowlist`} passHref>
<a>
<MenuItem
isSelected={
router.asPath === `/project/${currentWorkspace?._id}/allowlist`
}
icon="system-outline-109-slider-toggle-settings"
>
IP Allowlist
</MenuItem>
</a>
</Link>
<Link href={`/project/${currentWorkspace?._id}/audit-logs`} passHref>
<a>
<MenuItem
@@ -0,0 +1,20 @@
import { useTranslation } from "react-i18next";
import Head from "next/head";
import { IPAllowlistPage } from "@app/views/Project/IPAllowListPage";
const ProjectAllowlist = () => {
const { t } = useTranslation();
return (
<>
<Head>
<title>{t("common.head-title", { title: t("settings.project.title") })}</title>
<link rel="icon" href="/infisical.ico" />
</Head>
<IPAllowlistPage />
</>
);
}
export default ProjectAllowlist;
ProjectAllowlist.requireAuth = true;
@@ -0,0 +1,15 @@
import { IPAllowlistSection } from "./components";
export const IPAllowlistPage = () => {
return (
<div className="flex justify-center bg-bunker-800 text-white w-full h-full">
<div className="max-w-7xl px-6 w-full">
<div className="my-6">
<p className="text-3xl font-semibold text-gray-200">IP Allowlist</p>
<div />
</div>
<IPAllowlistSection />
</div>
</div>
);
}
@@ -0,0 +1,186 @@
import { useEffect } from "react";
import { Controller, useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
import { useNotificationContext } from "@app/components/context/Notifications/NotificationProvider";
import {
Button,
FormControl,
Input,
Modal,
ModalContent
} from "@app/components/v2";
import { UsePopUpState } from "@app/hooks/usePopUp";
import { useWorkspace } from "@app/context";
import {
useGetMyIp,
useAddTrustedIp,
useUpdateTrustedIp
} from "@app/hooks/api";
const schema = yup.object({
ipAddress: yup.string().required("IP address is required"),
comment: yup.string()
}).required();
export type FormData = yup.InferType<typeof schema>;
type Props = {
popUp: UsePopUpState<["trustedIp"]>;
handlePopUpClose: (popUpName: keyof UsePopUpState<["trustedIp"]>) => void;
handlePopUpToggle: (popUpName: keyof UsePopUpState<["trustedIp"]>, state?: boolean) => void;
};
export const IPAllowlistModal = ({
popUp,
handlePopUpClose,
handlePopUpToggle
}: Props) => {
const { createNotification } = useNotificationContext();
const { data, isLoading } = useGetMyIp();
const { currentWorkspace } = useWorkspace();
const addTrustedIp = useAddTrustedIp();
const updateTrustedIp = useUpdateTrustedIp();
const {
control,
setValue,
handleSubmit,
reset,
formState: { isSubmitting }
} = useForm<FormData>({
resolver: yupResolver(schema)
});
useEffect(() => {
if (popUp?.trustedIp?.data) {
reset(popUp?.trustedIp?.data as {
ipAddress: string;
comment: string;
});
} else {
reset({
ipAddress: "",
comment: ""
});
}
}, [popUp?.trustedIp?.data]);
const onIPAllowlistModalSubmit = async ({
ipAddress,
comment
}: FormData) => {
try {
if (!currentWorkspace?._id) return;
if (popUp?.trustedIp?.data) {
await updateTrustedIp.mutateAsync({
workspaceId: currentWorkspace._id,
trustedIpId: (popUp?.trustedIp?.data as { trustedIpId: string })?.trustedIpId,
ipAddress,
comment,
isActive: true
});
} else {
await addTrustedIp.mutateAsync({
workspaceId: currentWorkspace._id,
ipAddress,
comment,
isActive: true
});
}
createNotification({
text: `Successfully ${popUp?.trustedIp?.data ? "updated" : "added"} trusted IP`,
type: "success"
});
reset();
handlePopUpClose("trustedIp");
} catch (err) {
createNotification({
text: `Failed to ${popUp?.trustedIp?.data ? "update" : "add"} trusted IP`,
type: "error"
});
}
}
return (
<Modal
isOpen={popUp?.trustedIp?.isOpen}
onOpenChange={(isOpen) => {
handlePopUpToggle("trustedIp", isOpen);
reset();
}}
>
<ModalContent title={popUp?.trustedIp?.data ? "Update IP" : "Add IP"}>
<form onSubmit={handleSubmit(onIPAllowlistModalSubmit)}>
<Controller
control={control}
defaultValue=""
name="ipAddress"
render={({ field, fieldState: { error } }) => (
<FormControl
label="IPv4/IPv6 Address / CIDR Notation"
isError={Boolean(error)}
errorText={error?.message}
>
<Input
{...field}
placeholder="123.456.789.0"
/>
</FormControl>
)}
/>
{!isLoading && data && (
<Button
colorSchema="secondary"
type="button"
onClick={() => setValue("ipAddress", data)}
className="mb-8"
>
Add current IP address
</Button>
)}
<Controller
control={control}
defaultValue=""
name="comment"
render={({ field, fieldState: { error } }) => (
<FormControl
label="Comment"
isError={Boolean(error)}
errorText={error?.message}
>
<Input
{...field}
placeholder="My IP address"
/>
</FormControl>
)}
/>
<div className="mt-8 flex items-center">
<Button
className="mr-4"
size="sm"
type="submit"
isLoading={isSubmitting}
isDisabled={isSubmitting}
>
{popUp?.trustedIp?.data ? "Update" : "Add"}
</Button>
<Button
colorSchema="secondary"
variant="plain"
onClick={() => handlePopUpClose("trustedIp")}
>
Cancel
</Button>
</div>
</form>
</ModalContent>
</Modal>
);
}
@@ -0,0 +1,103 @@
import { useNotificationContext } from "@app/components/context/Notifications/NotificationProvider";
import { faPlus } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import {
Button,
DeleteActionModal,
UpgradePlanModal
} from "@app/components/v2";
import {
useDeleteTrustedIp
} from "@app/hooks/api";
import { useSubscription,useWorkspace } from "@app/context";
import { usePopUp } from "@app/hooks/usePopUp";
import { IPAllowlistTable } from "./IPAllowlistTable";
import { IPAllowlistModal } from "./IPAllowlistModal";
export const IPAllowlistSection = () => {
const { createNotification } = useNotificationContext();
const { mutateAsync } = useDeleteTrustedIp();
const { subscription } = useSubscription();
const { currentWorkspace } = useWorkspace();
const { popUp, handlePopUpOpen, handlePopUpClose, handlePopUpToggle } = usePopUp([
"trustedIp",
"deleteTrustedIp",
"upgradePlan"
] as const);
const onDeleteTrustedIpSubmit = async (trustedIpId: string) => {
try {
if (!currentWorkspace?._id) return;
await mutateAsync({
workspaceId: currentWorkspace._id,
trustedIpId
});
createNotification({
text: "Successfully deleted IP access range",
type: "success"
});
handlePopUpClose("deleteTrustedIp");
} catch (err) {
console.log(err);
createNotification({
text: "Failed to delete IP access range",
type: "error"
});
}
}
return (
<div className="p-4 bg-mineshaft-900 mb-6 rounded-lg border border-mineshaft-600">
<div className="flex items-center mb-8">
<h2 className="text-xl font-semibold flex-1 text-white">
IP Allowlist
</h2>
<Button
onClick={() => {
if (subscription?.ipAllowlisting) {
handlePopUpOpen("trustedIp")
} else {
handlePopUpOpen("upgradePlan");
}
}}
colorSchema="secondary"
isLoading={false}
leftIcon={<FontAwesomeIcon icon={faPlus} />}
>
Add IP
</Button>
</div>
<IPAllowlistTable
popUp={popUp}
handlePopUpOpen={handlePopUpOpen}
handlePopUpToggle={handlePopUpToggle}
/>
<IPAllowlistModal
popUp={popUp}
handlePopUpClose={handlePopUpClose}
handlePopUpToggle={handlePopUpToggle}
/>
<DeleteActionModal
isOpen={popUp.deleteTrustedIp.isOpen}
title={`Are you sure want to delete ${
(popUp?.deleteTrustedIp?.data as { name: string })?.name || " "
}?`}
onChange={(isOpen) => handlePopUpToggle("deleteTrustedIp", isOpen)}
deleteKey="confirm"
onDeleteApproved={() =>
onDeleteTrustedIpSubmit((popUp?.deleteTrustedIp?.data as { trustedIpId: string })?.trustedIpId)
}
/>
<UpgradePlanModal
isOpen={popUp.upgradePlan.isOpen}
onOpenChange={(isOpen) => handlePopUpToggle("upgradePlan", isOpen)}
text="You can use IP allowlisting if you switch to Infisical's Pro plan."
/>
</div>
);
}
@@ -0,0 +1,159 @@
import {
TableContainer,
Table,
THead,
Tr,
Th,
TBody,
Td,
EmptyState,
TableSkeleton,
IconButton,
UpgradePlanModal
} from "@app/components/v2";
import { useSubscription, useWorkspace } from "@app/context";
import {
useGetTrustedIps
} from "@app/hooks/api";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faGlobe, faPencil, faXmark } from "@fortawesome/free-solid-svg-icons";
import { UsePopUpState } from "@app/hooks/usePopUp";
type Props = {
popUp: UsePopUpState<["upgradePlan"]>;
handlePopUpOpen: (
popUpName: keyof UsePopUpState<["trustedIp", "deleteTrustedIp", "upgradePlan"]>,
data?: {
trustedIpId: string;
ipAddress?: string;
comment?: string;
isActive?: boolean;
},
) => void;
handlePopUpToggle: (popUpName: keyof UsePopUpState<["upgradePlan"]>, state?: boolean) => void;
};
export const IPAllowlistTable = ({
popUp,
handlePopUpOpen,
handlePopUpToggle
}: Props) => {
const { subscription } = useSubscription();
const { currentWorkspace } = useWorkspace();
const { data, isLoading } = useGetTrustedIps(currentWorkspace?._id ?? "");
const formatType = (type: string, prefix?: number) => {
return `${type.slice(0, 2).toUpperCase() + type.slice(2)} ${(prefix !== undefined) ? "CIDR" : ""}`;
}
return (
<div>
<TableContainer className="mt-4">
<Table>
<THead>
<Tr>
<Th className="flex-1">IP Address / Range</Th>
<Th className="flex-1">Format</Th>
<Th className="flex-1">Comment</Th>
{/* <Th className="flex-1">Status</Th> */}
<Th className="w-5"></Th>
</Tr>
</THead>
<TBody>
{!isLoading && data && data?.length > 0 && data
.sort((a, b) => a.ipAddress.localeCompare(b.ipAddress))
.map(({
_id,
ipAddress,
comment,
type,
prefix,
isActive
}) => {
return (
<Tr
key={`ip-access-range-${_id}`}
className="h-10"
>
<Td>
{`${ipAddress}${(prefix !== undefined) ? `/${prefix}` : ""}`}
</Td>
<Td>
{formatType(type, prefix)}
</Td>
<Td>
{comment}
</Td>
{/* <Td>
<div className="flex items-center">
<FontAwesomeIcon
icon={faCircle}
color="#2ecc71"
/>
<p className="ml-4">Active</p>
</div>
</Td> */}
<Td className="flex items-center">
<IconButton
className="mr-3 py-2"
onClick={() => {
if (subscription?.ipAllowlisting) {
handlePopUpOpen("trustedIp", {
trustedIpId: _id,
ipAddress,
comment,
isActive
});
} else {
handlePopUpOpen("upgradePlan");
}
}}
colorSchema="primary"
variant="plain"
ariaLabel="update"
>
<FontAwesomeIcon icon={faPencil} />
</IconButton>
<IconButton
onClick={() => {
if (subscription?.ipAllowlisting) {
handlePopUpOpen("deleteTrustedIp", {
trustedIpId: _id
});
} else {
handlePopUpOpen("upgradePlan");
}
}}
size="lg"
colorSchema="danger"
variant="plain"
ariaLabel="update"
>
<FontAwesomeIcon icon={faXmark} />
</IconButton>
</Td>
</Tr>
);
})}
{isLoading && <TableSkeleton columns={4} key="ip-access-ranges" />}
{!isLoading && data && data?.length === 0 && (
<Tr>
<Td colSpan={5}>
<EmptyState
title="No IP addresses added"
icon={faGlobe}
/>
</Td>
</Tr>
)}
</TBody>
</Table>
</TableContainer>
<UpgradePlanModal
isOpen={popUp.upgradePlan.isOpen}
onOpenChange={(isOpen) => handlePopUpToggle("upgradePlan", isOpen)}
text="You can use IP allowlisting if you switch to Infisical's Pro plan."
/>
</div>
);
}
@@ -0,0 +1 @@
export { IPAllowlistSection } from "./IPAllowlistSection";
@@ -0,0 +1 @@
export { IPAllowlistPage } from "./IPAllowlistPage";
@@ -1,7 +1,6 @@
import { faPlus } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import {
Button
} from "@app/components/v2";
@@ -1,6 +1,5 @@
import { faCreditCard, faXmark } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import {
EmptyState,
IconButton,
@@ -11,7 +10,8 @@ import {
Td,
Th,
THead,
Tr} from "@app/components/v2";
Tr
} from "@app/components/v2";
import { useOrganization } from "@app/context";
import {
useDeleteOrgPmtMethod,
@@ -1,7 +1,6 @@
import { Controller, useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
import { useNotificationContext } from "@app/components/context/Notifications/NotificationProvider";
import {
Button,
@@ -1,6 +1,5 @@
import { faDownload, faFileInvoice } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import {
EmptyState,
IconButton,
@@ -11,7 +10,8 @@ import {
Td,
Th,
THead,
Tr} from "@app/components/v2";
Tr
} from "@app/components/v2";
import { useOrganization } from "@app/context";
import {
useGetOrgInvoices
@@ -1,6 +1,5 @@
import { faPlus } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useNotificationContext } from "@app/components/context/Notifications/NotificationProvider";
import {
Button,
@@ -12,7 +11,6 @@ import {
useDeleteWsEnvironment
} from "@app/hooks/api";
import { usePopUp } from "@app/hooks/usePopUp";
import { AddEnvironmentModal } from "./AddEnvironmentModal";
import { EnvironmentTable } from "./EnvironmentTable";
import { UpdateEnvironmentModal } from "./UpdateEnvironmentModal";
@@ -18,7 +18,7 @@ import { UsePopUpState } from "@app/hooks/usePopUp";
type Props = {
handlePopUpOpen: (
popUpName: keyof UsePopUpState<["updateEnv", "deleteEnv", "deleteEnv", "upgradePlan"]>,
popUpName: keyof UsePopUpState<["updateEnv", "deleteEnv", "upgradePlan"]>,
{
name,
slug