The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Normalize IP address when adding restriction (#20514)
Joshen Limda2d94d41a43
diff --git a/apps/studio/components/interfaces/Settings/Database/NetworkRestrictions/AddRestrictionModal.tsx b/apps/studio/components/interfaces/Settings/Database/NetworkRestrictions/AddRestrictionModal.tsxindex 79993d75263..82b4bd88db0 100644--- a/apps/studio/components/interfaces/Settings/Database/NetworkRestrictions/AddRestrictionModal.tsx+++ b/apps/studio/components/interfaces/Settings/Database/NetworkRestrictions/AddRestrictionModal.tsx@@ -1,13 +1,17 @@import * as Tooltip from '@radix-ui/react-tooltip'-import { Address4 } from 'ip-address'+import { useParams } from 'common'import { useState } from 'react'+import toast from 'react-hot-toast'import { Button, Form, IconHelpCircle, Input, Modal } from 'ui'-import { useParams } from 'common/hooks'import InformationBox from 'components/ui/InformationBox'import { useNetworkRestrictionsApplyMutation } from 'data/network-restrictions/network-retrictions-apply-mutation'-import { useStore } from 'hooks'-import { checkIfPrivate, getAddressEndRange } from './NetworkRestrictions.utils'+import {+ checkIfPrivate,+ getAddressEndRange,+ isValidAddress,+ normalize,+} from './NetworkRestrictions.utils'interface AddRestrictionModalProps {restrictedIps: string[]@@ -23,10 +27,14 @@ const AddRestrictionModal = ({onClose,}: AddRestrictionModalProps) => {const formId = 'add-restriction-form'- const { ui } = useStore()const { ref } = useParams()const { mutate: applyNetworkRestrictions, isLoading: isApplying } =- useNetworkRestrictionsApplyMutation({ onSuccess: () => onClose() })+ useNetworkRestrictionsApplyMutation({+ onSuccess: () => {+ toast.success('Successfully added restriction')+ onClose()+ },+ })const validate = (values: any) => {const errors: any = {}@@ -39,7 +47,7 @@ const AddRestrictionModal = ({}// Validate IP address- const isValid = Address4.isValid(ipAddress)+ const isValid = isValidAddress(ipAddress)if (!isValid) {errors.ipAddress = 'Please enter a valid IP address'return errors@@ -54,22 +62,23 @@ const AddRestrictionModal = ({const onSubmit = async (values: any) => {if (!ref) return console.error('Project ref is required')- const cidr = `${values.ipAddress}/${values.cidrBlockSize}`- const alreadyExists = restrictedIps.includes(cidr)+ const address = `${values.ipAddress}/${values.cidrBlockSize}`+ const normalizedAddress = normalize(address)++ const alreadyExists =+ restrictedIps.includes(address) || restrictedIps.includes(normalizedAddress)if (alreadyExists) {- return ui.setNotification({- category: 'info',- message: `The address ${cidr} is already restricted`,- })+ return toast(`The address ${address} is already restricted`)}- const dbAllowedCidrs = hasOverachingRestriction ? [cidr] : [...restrictedIps, cidr]+ const dbAllowedCidrs = hasOverachingRestriction+ ? [normalizedAddress]+ : [...restrictedIps, normalizedAddress]applyNetworkRestrictions({ projectRef: ref, dbAllowedCidrs })}return (<Modal- closablehideFootersize="medium"visible={visible}@@ -85,7 +94,7 @@ const AddRestrictionModal = ({onSubmit={onSubmit}>{({ values, resetForm }: any) => {- const isPrivate = Address4.isValid(values.ipAddress)+ const isPrivate = isValidAddress(values.ipAddress)? checkIfPrivate(values.ipAddress): falseconst isValidBlockSize =@@ -94,29 +103,9 @@ const AddRestrictionModal = ({const addressRange = getAddressEndRange(`${values.ipAddress}/${values.cidrBlockSize}`)const isValidCIDR = isValidBlockSize && !isPrivate && addressRange !== undefined-- // [Alaister] although this "technically" is breaking the rules of React hooks- // it won't error because the hooks are always rendered in the same order- // eslint-disable-next-line react-hooks/rules-of-hooks- const [isFetchingAddress, setIsFetchingAddress] = useState(false)-- const getClientIpAddress = async () => {- setIsFetchingAddress(true)- const res = await fetch('http://www.geoplugin.net/json.gp', { method: 'GET' })- const { geoplugin_request } = await res.json()-- if (geoplugin_request) {- const updatedValues = { ...values, ipAddress: geoplugin_request, cidrBlockSize: 32 }- resetForm({ initialValues: updatedValues, values: updatedValues })- } else {- ui.setNotification({- category: 'error',- duration: 4000,- message: 'Failed to retrieve client IP address, please enter address manually',- })- }- setIsFetchingAddress(false)- }+ const normalizedAddress = isValidCIDR+ ? normalize(`${values.ipAddress}/${values.cidrBlockSize}`)+ : `{values.ipAddress}/{values.cidrBlockSize}`return (<>@@ -178,14 +167,6 @@ const AddRestrictionModal = ({/></div></div>- <Button- type="default"- loading={isFetchingAddress}- disabled={isFetchingAddress}- onClick={() => getClientIpAddress()}- >- Use my IP address- </Button></div></Modal.Content><Modal.Separator />@@ -193,11 +174,8 @@ const AddRestrictionModal = ({<Modal.Content><div className="space-y-1 pt-2 pb-4"><p className="text-sm">- The address range{' '}- <code className="text-xs">- {values.ipAddress}/{values.cidrBlockSize}- </code>{' '}- will be restricted+ The address range <code className="text-xs">{normalizedAddress}</code> will be+ restricted</p><p className="text-sm text-foreground-light">Selected address space: <code className="text-xs">{addressRange.start}</code>{' '}@@ -214,7 +192,7 @@ const AddRestrictionModal = ({<div className="h-[68px] flex items-center"><p className="text-sm text-foreground-light">A summary of your restriction will be shown here after entering a valid IP- address and CIDR block size+ address and CIDR block size. IP addresses will also be normalized.</p></div></div>diff --git a/apps/studio/components/interfaces/Settings/Database/NetworkRestrictions/DisallowAllModal.tsx b/apps/studio/components/interfaces/Settings/Database/NetworkRestrictions/DisallowAllModal.tsxindex fae43938ad2..53e9ffbb6f2 100644--- a/apps/studio/components/interfaces/Settings/Database/NetworkRestrictions/DisallowAllModal.tsx+++ b/apps/studio/components/interfaces/Settings/Database/NetworkRestrictions/DisallowAllModal.tsx@@ -1,6 +1,6 @@+import { useParams } from 'common'import { Button, Modal } from 'ui'-import { useParams } from 'common/hooks'import InformationBox from 'components/ui/InformationBox'import { useNetworkRestrictionsApplyMutation } from 'data/network-restrictions/network-retrictions-apply-mutation'diff --git a/apps/studio/components/interfaces/Settings/Database/NetworkRestrictions/NetworkRestrictions.utils.ts b/apps/studio/components/interfaces/Settings/Database/NetworkRestrictions/NetworkRestrictions.utils.tsindex 36999d6bb0b..806111e9b17 100644--- a/apps/studio/components/interfaces/Settings/Database/NetworkRestrictions/NetworkRestrictions.utils.ts+++ b/apps/studio/components/interfaces/Settings/Database/NetworkRestrictions/NetworkRestrictions.utils.ts@@ -1,22 +1,48 @@-import { Address4 } from 'ip-address'+import { IPv4CidrRange, IPv6CidrRange, Validator, collapseIPv6Number } from 'ip-num'const privateIPRanges = [- new Address4('10.0.0.0/8'),- new Address4('172.16.0.0/12'),- new Address4('192.168.0.0/16'),+ IPv4CidrRange.fromCidr('10.0.0.0/8'),+ IPv4CidrRange.fromCidr('172.16.0.0/12'),+ IPv4CidrRange.fromCidr('192.168.0.0/16'),]+export const isValidAddress = (address: string) => {+ // Only validating address, should not include cidr block size+ if (address.includes('/')) return false+ const [isIpv4] = Validator.isValidIPv4String(address)+ return isIpv4+}+export const checkIfPrivate = (cidr: string) => {- const address = new Address4(cidr)- const res = privateIPRanges.map((range) => address.isInSubnet(range))+ const address = IPv4CidrRange.fromCidr(`${cidr}/32`)+ const res = privateIPRanges.map((range) => address.inside(range))return res.includes(true)}-export const getAddressEndRange = (cidr: string) => {+export const getAddressEndRange = (address: string) => {try {- const address = new Address4(cidr)- return { start: address.startAddress().address, end: address.endAddress().address }+ const cidr = IPv4CidrRange.fromCidr(address)+ const start = cidr.getFirst().octets.join('.')+ const end = cidr.getLast().octets.join('.')+ return { start, end }} catch (error: any) {return undefined}}++// [Joshen] Using same logic as worker+// https://github.com/supabase/infrastructure/blob/840c9596e8bf9e9090ec94de1756bd511e67393a/worker/src/tasks/db/add_as_pooler_tenant.ts#L176C15-L176C15+export const normalize = (address: string) => {+ const [isIpV4] = Validator.isValidIPv4String(address.split('/')[0])+ if (isIpV4) {+ const cidr = IPv4CidrRange.fromCidr(address)+ const base = cidr.getFirst().toString()+ const mask = cidr.getPrefix().toString()+ return `${base}/${mask}`+ } else {+ const cidr = IPv6CidrRange.fromCidr(address)+ const base = collapseIPv6Number(cidr.getFirst().toString())+ const mask = cidr.getPrefix().toString()+ return `${base}/${mask}`+ }+}diff --git a/apps/studio/package.json b/apps/studio/package.jsonindex df9d85fad93..c3835cee2e9 100644--- a/apps/studio/package.json+++ b/apps/studio/package.json@@ -53,7 +53,7 @@"generate-password-browser": "^1.1.0","html-to-image": "^1.10.8","immutability-helper": "^3.1.1",- "ip-address": "^8.1.0",+ "ip-num": "^1.5.1","json-logic-js": "^2.0.2","jsonrepair": "^3.2.3","jwt-simple": "^0.5.6",diff --git a/package-lock.json b/package-lock.jsonindex bb4d0e19cb6..766d68aa99e 100644--- a/package-lock.json+++ b/package-lock.json@@ -757,7 +757,7 @@"generate-password-browser": "^1.1.0","html-to-image": "^1.10.8","immutability-helper": "^3.1.1",- "ip-address": "^8.1.0",+ "ip-num": "^1.5.1","json-logic-js": "^2.0.2","jsonrepair": "^3.2.3","jwt-simple": "^0.5.6",@@ -20964,20 +20964,10 @@"version": "2.0.0","license": "MIT"},- "node_modules/ip-address": {- "version": "8.1.0",- "license": "MIT",- "dependencies": {- "jsbn": "1.1.0",- "sprintf-js": "1.1.2"- },- "engines": {- "node": ">= 12"- }- },- "node_modules/ip-address/node_modules/sprintf-js": {- "version": "1.1.2",- "license": "BSD-3-Clause"+ "node_modules/ip-num": {+ "version": "1.5.1",+ "resolved": "https://registry.npmjs.org/ip-num/-/ip-num-1.5.1.tgz",+ "integrity": "sha512-QziFxgxq3mjIf5CuwlzXFYscHxgLqdEdJKRo2UJ5GurL5zrSRMzT/O+nK0ABimoFH8MWF8YwIiwECYsHc1LpUQ=="},"node_modules/ipaddr.js": {"version": "1.9.1",@@ -23434,10 +23424,6 @@"un-eval": "^1.2.0"}},- "node_modules/jsbn": {- "version": "1.1.0",- "license": "MIT"- },"node_modules/jscodeshift": {"version": "0.14.0","dev": true,