AddRestrictionModal.tsx265 lines · main
| 1 | import { zodResolver } from '@hookform/resolvers/zod' |
| 2 | import { useParams } from 'common' |
| 3 | import { HelpCircle } from 'lucide-react' |
| 4 | import { useEffect } from 'react' |
| 5 | import { useForm, useWatch } from 'react-hook-form' |
| 6 | import { toast } from 'sonner' |
| 7 | import { |
| 8 | Button, |
| 9 | Form, |
| 10 | FormControl, |
| 11 | FormField, |
| 12 | Input, |
| 13 | Modal, |
| 14 | Tooltip, |
| 15 | TooltipContent, |
| 16 | TooltipTrigger, |
| 17 | } from 'ui' |
| 18 | import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout' |
| 19 | import * as z from 'zod' |
| 20 | |
| 21 | import { checkIfPrivate, getAddressEndRange, normalize } from './NetworkRestrictions.utils' |
| 22 | import InformationBox from '@/components/ui/InformationBox' |
| 23 | import { useNetworkRestrictionsQuery } from '@/data/network-restrictions/network-restrictions-query' |
| 24 | import { useNetworkRestrictionsApplyMutation } from '@/data/network-restrictions/network-retrictions-apply-mutation' |
| 25 | import { DOCS_URL } from '@/lib/constants' |
| 26 | |
| 27 | const IPV4_MAX_CIDR_BLOCK_SIZE = 32 |
| 28 | const IPV6_MAX_CIDR_BLOCK_SIZE = 128 |
| 29 | |
| 30 | interface AddRestrictionModalProps { |
| 31 | type?: 'IPv4' | 'IPv6' |
| 32 | hasOverachingRestriction: boolean |
| 33 | onClose: () => void |
| 34 | } |
| 35 | |
| 36 | const AddRestrictionModal = ({ |
| 37 | type, |
| 38 | hasOverachingRestriction, |
| 39 | onClose, |
| 40 | }: AddRestrictionModalProps) => { |
| 41 | const formId = 'add-restriction-form' |
| 42 | const { ref } = useParams() |
| 43 | |
| 44 | const { data } = useNetworkRestrictionsQuery({ projectRef: ref }, { enabled: type !== undefined }) |
| 45 | const ipv4Restrictions = data?.config?.dbAllowedCidrs ?? [] |
| 46 | // @ts-ignore [Joshen] API typing issue |
| 47 | const ipv6Restrictions = data?.config?.dbAllowedCidrsV6 ?? [] |
| 48 | const restrictedIps = ipv4Restrictions.concat(ipv6Restrictions) |
| 49 | |
| 50 | const { mutate: applyNetworkRestrictions, isPending: isApplying } = |
| 51 | useNetworkRestrictionsApplyMutation({ |
| 52 | onSuccess: () => { |
| 53 | toast.success('Successfully added restriction') |
| 54 | onClose() |
| 55 | }, |
| 56 | }) |
| 57 | |
| 58 | const cidrBlockSizeValidationMessage = `Size has to be between 0 to ${ |
| 59 | type === 'IPv4' ? IPV4_MAX_CIDR_BLOCK_SIZE : IPV6_MAX_CIDR_BLOCK_SIZE |
| 60 | }` |
| 61 | const formSchema = z.object({ |
| 62 | cidrBlockSize: z.coerce |
| 63 | .number() |
| 64 | .min(0, cidrBlockSizeValidationMessage) |
| 65 | .max( |
| 66 | type === 'IPv4' ? IPV4_MAX_CIDR_BLOCK_SIZE : IPV6_MAX_CIDR_BLOCK_SIZE, |
| 67 | cidrBlockSizeValidationMessage |
| 68 | ), |
| 69 | ipAddress: z |
| 70 | .string() |
| 71 | .min(1, `Please enter a valid IP address`) |
| 72 | .ip({ |
| 73 | version: type === 'IPv4' ? 'v4' : 'v6', |
| 74 | message: `Please enter a valid ${type} address`, |
| 75 | }) |
| 76 | .refine((val) => !checkIfPrivate(type, val), 'Private IP addresses are not supported'), |
| 77 | }) |
| 78 | |
| 79 | const form = useForm<z.infer<typeof formSchema>>({ |
| 80 | resolver: zodResolver(formSchema as any), |
| 81 | defaultValues: { |
| 82 | ipAddress: '', |
| 83 | cidrBlockSize: type === 'IPv4' ? IPV4_MAX_CIDR_BLOCK_SIZE : IPV6_MAX_CIDR_BLOCK_SIZE, |
| 84 | }, |
| 85 | }) |
| 86 | const { reset, formState } = form |
| 87 | const { errors } = formState |
| 88 | |
| 89 | useEffect(() => { |
| 90 | reset({ |
| 91 | ipAddress: '', |
| 92 | cidrBlockSize: type === 'IPv4' ? IPV4_MAX_CIDR_BLOCK_SIZE : IPV6_MAX_CIDR_BLOCK_SIZE, |
| 93 | }) |
| 94 | }, [type, reset]) |
| 95 | |
| 96 | const onSubmit = async (values: any) => { |
| 97 | if (!ref) return console.error('Project ref is required') |
| 98 | |
| 99 | const address = `${values.ipAddress}/${values.cidrBlockSize}` |
| 100 | const normalizedAddress = normalize(address) |
| 101 | |
| 102 | const alreadyExists = |
| 103 | restrictedIps.includes(address) || restrictedIps.includes(normalizedAddress) |
| 104 | if (alreadyExists) { |
| 105 | return toast(`The address ${address} is already restricted`) |
| 106 | } |
| 107 | |
| 108 | // Need to replace over arching restriction (allow all / disallow all) |
| 109 | if (hasOverachingRestriction) { |
| 110 | const dbAllowedCidrs = type === 'IPv4' ? [normalizedAddress] : [] |
| 111 | const dbAllowedCidrsV6 = type === 'IPv6' ? [normalizedAddress] : [] |
| 112 | applyNetworkRestrictions({ projectRef: ref, dbAllowedCidrs, dbAllowedCidrsV6 }) |
| 113 | } else { |
| 114 | const dbAllowedCidrs = |
| 115 | type === 'IPv4' ? [...ipv4Restrictions, normalizedAddress] : ipv4Restrictions |
| 116 | const dbAllowedCidrsV6 = |
| 117 | type === 'IPv6' ? [...ipv6Restrictions, normalizedAddress] : ipv6Restrictions |
| 118 | applyNetworkRestrictions({ projectRef: ref, dbAllowedCidrs, dbAllowedCidrsV6 }) |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | const [cidrBlockSize, ipAddress] = useWatch({ |
| 123 | name: ['cidrBlockSize', 'ipAddress'], |
| 124 | control: form.control, |
| 125 | }) |
| 126 | |
| 127 | const availableAddresses = |
| 128 | type === 'IPv4' |
| 129 | ? Math.pow(2, IPV4_MAX_CIDR_BLOCK_SIZE - (cidrBlockSize ?? 0)) |
| 130 | : Math.pow(2, IPV6_MAX_CIDR_BLOCK_SIZE - (cidrBlockSize ?? 0)) |
| 131 | |
| 132 | const addressRange = |
| 133 | type !== undefined ? getAddressEndRange(type, `${ipAddress}/${cidrBlockSize}`) : undefined |
| 134 | |
| 135 | const isValidCIDR = |
| 136 | errors.cidrBlockSize == null && errors.ipAddress == null && addressRange != null |
| 137 | |
| 138 | const normalizedAddress = isValidCIDR |
| 139 | ? normalize(`${ipAddress}/${cidrBlockSize}`) |
| 140 | : `${ipAddress}/${cidrBlockSize}` |
| 141 | |
| 142 | return ( |
| 143 | <Modal |
| 144 | hideFooter |
| 145 | size="medium" |
| 146 | visible={type !== undefined} |
| 147 | onCancel={onClose} |
| 148 | header={`Add a new ${type} restriction`} |
| 149 | > |
| 150 | <Form {...form}> |
| 151 | <Modal.Content className="space-y-4"> |
| 152 | <p className="text-sm text-foreground-light"> |
| 153 | This will add an IP address range to a list of allowed ranges that can access your |
| 154 | database. |
| 155 | </p> |
| 156 | <InformationBox |
| 157 | title="Note: Restrictions only apply to direct connections to your database and connection pooler" |
| 158 | description="They do not currently apply to APIs offered over HTTPS, such as PostgREST, Storage, or Authentication." |
| 159 | urlLabel="Learn more" |
| 160 | url={`${DOCS_URL}/guides/platform/network-restrictions#limitations`} |
| 161 | /> |
| 162 | <form |
| 163 | id={formId} |
| 164 | onSubmit={form.handleSubmit(onSubmit)} |
| 165 | noValidate |
| 166 | className="flex space-x-4" |
| 167 | > |
| 168 | <div className="w-[55%]"> |
| 169 | <FormField |
| 170 | control={form.control} |
| 171 | name="ipAddress" |
| 172 | render={({ field }) => ( |
| 173 | <FormItemLayout layout="vertical" label={`${type} address`}> |
| 174 | <FormControl> |
| 175 | <Input {...field} placeholder={type === 'IPv4' ? '0.0.0.0' : '::0'} /> |
| 176 | </FormControl> |
| 177 | </FormItemLayout> |
| 178 | )} |
| 179 | /> |
| 180 | </div> |
| 181 | <div className="grow"> |
| 182 | <FormField |
| 183 | control={form.control} |
| 184 | name="cidrBlockSize" |
| 185 | render={({ field }) => ( |
| 186 | <FormItemLayout |
| 187 | layout="vertical" |
| 188 | label={ |
| 189 | <div className="flex items-center space-x-2"> |
| 190 | <p>CIDR Block Size</p> |
| 191 | <Tooltip> |
| 192 | <TooltipTrigger> |
| 193 | <HelpCircle size="14" strokeWidth={2} /> |
| 194 | </TooltipTrigger> |
| 195 | <TooltipContent side="bottom" className="w-80"> |
| 196 | Classless inter-domain routing (CIDR) notation is the notation used to |
| 197 | identify networks and hosts in the networks. The block size tells us how |
| 198 | many bits we need to take for the network prefix, and is a value between |
| 199 | 0 to{' '} |
| 200 | {type === 'IPv4' ? IPV4_MAX_CIDR_BLOCK_SIZE : IPV6_MAX_CIDR_BLOCK_SIZE}. |
| 201 | </TooltipContent> |
| 202 | </Tooltip> |
| 203 | </div> |
| 204 | } |
| 205 | > |
| 206 | <FormControl> |
| 207 | <Input |
| 208 | {...field} |
| 209 | type="number" |
| 210 | min={0} |
| 211 | max={type === 'IPv4' ? IPV4_MAX_CIDR_BLOCK_SIZE : IPV6_MAX_CIDR_BLOCK_SIZE} |
| 212 | onChange={(e) => field.onChange(Number(e.target.value))} |
| 213 | placeholder={ |
| 214 | type === 'IPv4' |
| 215 | ? IPV4_MAX_CIDR_BLOCK_SIZE.toString() |
| 216 | : IPV6_MAX_CIDR_BLOCK_SIZE.toString() |
| 217 | } |
| 218 | /> |
| 219 | </FormControl> |
| 220 | </FormItemLayout> |
| 221 | )} |
| 222 | /> |
| 223 | </div> |
| 224 | </form> |
| 225 | </Modal.Content> |
| 226 | <Modal.Separator /> |
| 227 | {isValidCIDR ? ( |
| 228 | <Modal.Content className="space-y-1"> |
| 229 | <p className="text-sm"> |
| 230 | The address range <code className="text-code-inline">{normalizedAddress}</code> will |
| 231 | be restricted |
| 232 | </p> |
| 233 | <p className="text-sm text-foreground-light"> |
| 234 | Selected address space: <code className="text-code-inline">{addressRange.start}</code>{' '} |
| 235 | to <code className="text-code-inline">{addressRange.end}</code>{' '} |
| 236 | </p> |
| 237 | <p className="text-sm text-foreground-light"> |
| 238 | Number of addresses: {availableAddresses} |
| 239 | </p> |
| 240 | </Modal.Content> |
| 241 | ) : ( |
| 242 | <Modal.Content> |
| 243 | <div className="h-[68px] flex items-center"> |
| 244 | <p className="text-sm text-foreground-light"> |
| 245 | A summary of your restriction will be shown here after entering a valid IP address |
| 246 | and CIDR block size. IP addresses will also be normalized. |
| 247 | </p> |
| 248 | </div> |
| 249 | </Modal.Content> |
| 250 | )} |
| 251 | <Modal.Separator /> |
| 252 | <Modal.Content className="flex items-center justify-end space-x-2"> |
| 253 | <Button type="default" disabled={isApplying} onClick={() => onClose()}> |
| 254 | Cancel |
| 255 | </Button> |
| 256 | <Button form={formId} htmlType="submit" loading={isApplying} disabled={isApplying}> |
| 257 | Save restriction |
| 258 | </Button> |
| 259 | </Modal.Content> |
| 260 | </Form> |
| 261 | </Modal> |
| 262 | ) |
| 263 | } |
| 264 | |
| 265 | export default AddRestrictionModal |