Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
fix(pki-discovery): target validation
bernie-ged40390e6146
diff --git a/backend/src/ee/routes/v1/pki-discovery-router.ts b/backend/src/ee/routes/v1/pki-discovery-router.tsindex 9b63982821..86160f520d 100644--- a/backend/src/ee/routes/v1/pki-discovery-router.ts+++ b/backend/src/ee/routes/v1/pki-discovery-router.ts@@ -7,12 +7,10 @@ import {MAX_DOMAINS,MAX_IPS,MAX_PORTS,- MIN_CIDR_PREFIX,- validateTargetConfig+ MIN_CIDR_PREFIX} from "@app/ee/services/pki-discovery/pki-discovery-fns";import { PkiDiscoveryType, TPkiDiscoveryTargetConfig } from "@app/ee/services/pki-discovery/pki-discovery-types";import { ApiDocsTags } from "@app/lib/api-docs";-import { BadRequestError } from "@app/lib/errors";import { readLimit, writeLimit } from "@app/server/config/rateLimiter";import { openApiHidden, slugSchema } from "@app/server/lib/schemas";import { getTelemetryDistinctId } from "@app/server/lib/telemetry";@@ -107,16 +105,6 @@ export const registerPkiDiscoveryRouter = async (server: FastifyZodProvider) =>}},handler: async (req) => {- const validation = validateTargetConfig(- req.body.targetConfig.ipRanges,- req.body.targetConfig.ports,- req.body.targetConfig.domains,- !!req.body.gatewayId || !!req.body.gatewayPoolId- );- if (!validation.valid) {- throw new BadRequestError({ message: validation.error || "Invalid target configuration" });- }-const projectId = req.internalCertManagerProjectId;const discovery = await server.services.pkiDiscovery.createDiscovery({projectId,@@ -321,31 +309,6 @@ export const registerPkiDiscoveryRouter = async (server: FastifyZodProvider) =>}},handler: async (req) => {- if (req.body.targetConfig) {- let hasGateway =- (req.body.gatewayId !== null && req.body.gatewayId !== undefined) ||- (req.body.gatewayPoolId !== null && req.body.gatewayPoolId !== undefined);- if (!hasGateway && req.body.gatewayId === undefined && req.body.gatewayPoolId === undefined) {- const existing = await server.services.pkiDiscovery.getDiscovery({- discoveryId: req.params.discoveryId,- actor: req.permission.type,- actorId: req.permission.id,- actorAuthMethod: req.permission.authMethod,- actorOrgId: req.permission.orgId- });- hasGateway = !!existing.gatewayId || !!existing.gatewayPoolId;- }- const validation = validateTargetConfig(- req.body.targetConfig.ipRanges,- req.body.targetConfig.ports,- req.body.targetConfig.domains,- hasGateway- );- if (!validation.valid) {- throw new BadRequestError({ message: validation.error || "Invalid target configuration" });- }- }-const discovery = await server.services.pkiDiscovery.updateDiscovery({discoveryId: req.params.discoveryId,name: req.body.name,diff --git a/backend/src/ee/services/pki-discovery/pki-discovery-fns.ts b/backend/src/ee/services/pki-discovery/pki-discovery-fns.tsindex 5b39eae0ab..567e5e26b9 100644--- a/backend/src/ee/services/pki-discovery/pki-discovery-fns.ts+++ b/backend/src/ee/services/pki-discovery/pki-discovery-fns.ts@@ -50,6 +50,23 @@ const shouldBlockPrivateIps = (hasGateway: boolean): boolean => {return true;};+export const getPrivateIpRangeError = (ipRanges: string[] | undefined, hasGateway: boolean): string | undefined => {+ if (!ipRanges?.length || !shouldBlockPrivateIps(hasGateway)) return undefined;++ const appCfg = getConfig();+ const selfHostedHint = appCfg.isCloud+ ? ""+ : " If you are self-hosting, you can alternatively set the 'ALLOW_INTERNAL_IP_CONNECTIONS' environment variable to 'true' on your instance to scan private networks without a gateway.";++ if (ipRanges.some((ip) => !ip.includes("/") && isPrivateIp(ip))) {+ return `Private/internal IP addresses require a gateway. Use a gateway to scan private networks.${selfHostedHint}`;+ }+ if (ipRanges.some((cidr) => cidr.includes("/") && isPrivateIp(cidr.split("/")[0]))) {+ return `Private/internal CIDR ranges require a gateway. Use a gateway to scan private networks.${selfHostedHint}`;+ }+ return undefined;+};+export type TTargetValidationResult = {valid: boolean;error?: string;@@ -102,26 +119,9 @@ export const validateTargetConfig = (const cidrRanges = ipRanges.filter((r) => r.includes("/"));const singleIps = ipRanges.filter((r) => !r.includes("/"));- if (shouldBlockPrivateIps(!!hasGateway)) {- const appCfg = getConfig();- const selfHostedHint = appCfg.isCloud- ? ""- : " If you are self-hosting, you can alternatively set the 'ALLOW_INTERNAL_IP_CONNECTIONS' environment variable to 'true' on your instance to scan private networks without a gateway.";-- const privateIp = singleIps.find((ip) => isPrivateIp(ip));- if (privateIp) {- return {- valid: false,- error: `Private/internal IP addresses require a gateway. Use a gateway to scan private networks.${selfHostedHint}`- };- }- const privateCidr = cidrRanges.find((cidr) => isPrivateIp(cidr.split("/")[0]));- if (privateCidr) {- return {- valid: false,- error: `Private/internal CIDR ranges require a gateway. Use a gateway to scan private networks.${selfHostedHint}`- };- }+ const privateIpRangeError = getPrivateIpRangeError(ipRanges, !!hasGateway);+ if (privateIpRangeError) {+ return { valid: false, error: privateIpRangeError };}let totalIpCount = singleIps.length;@@ -632,7 +632,8 @@ export const resolveTargets = async (if (targetConfig.ipRanges) {for (const range of targetConfig.ipRanges) {- const ips = expandCIDR(range);+ const expandedIps = expandCIDR(range);+ const ips = blockPrivate ? expandedIps.filter((ip) => !isPrivateIp(ip)) : expandedIps;for (const ip of ips) {for (const port of ports) {diff --git a/backend/src/ee/services/pki-discovery/pki-discovery-scan-fns.ts b/backend/src/ee/services/pki-discovery/pki-discovery-scan-fns.tsindex eb876de1dd..f9e1b84898 100644--- a/backend/src/ee/services/pki-discovery/pki-discovery-scan-fns.ts+++ b/backend/src/ee/services/pki-discovery/pki-discovery-scan-fns.ts@@ -21,7 +21,13 @@ import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";import { TPkiCertificateInstallationCertDALFactory } from "./pki-certificate-installation-cert-dal";import { TPkiCertificateInstallationDALFactory } from "./pki-certificate-installation-dal";import { TPkiDiscoveryConfigDALFactory } from "./pki-discovery-config-dal";-import { computeLocationFingerprint, resolveDomain, resolveTargets, scanEndpoint } from "./pki-discovery-fns";+import {+ computeLocationFingerprint,+ getPrivateIpRangeError,+ resolveDomain,+ resolveTargets,+ scanEndpoint+} from "./pki-discovery-fns";import { TPkiDiscoveryInstallationDALFactory } from "./pki-discovery-installation-dal";import { TPkiDiscoveryScanHistoryDALFactory } from "./pki-discovery-scan-history-dal";import {@@ -146,6 +152,14 @@ export const executeScan = async (discoveryId: string, deps: TExecuteScanDeps):const targetConfig = discoveryConfig.targetConfig as TPkiDiscoveryTargetConfig;const hasGateway = !!effectiveGatewayId;++ // The gateway FK is ON DELETE SET NULL, so a config saved with private ranges can lose its gateway later.+ if (getPrivateIpRangeError(targetConfig.ipRanges, hasGateway)) {+ throw new Error(+ "This job targets private IP addresses but has no gateway attached. Attach a gateway or gateway pool to scan private networks."+ );+ }+const targets = await resolveTargets(targetConfig, hasGateway);const uniqueHosts = new Set(targets.map((t) => t.host)).size;diff --git a/backend/src/ee/services/pki-discovery/pki-discovery-service.ts b/backend/src/ee/services/pki-discovery/pki-discovery-service.tsindex 6c58027e8c..f2434904ed 100644--- a/backend/src/ee/services/pki-discovery/pki-discovery-service.ts+++ b/backend/src/ee/services/pki-discovery/pki-discovery-service.ts@@ -17,6 +17,7 @@ import { TOrgDALFactory } from "@app/services/org/org-dal";import { TGatewayV2DALFactory } from "../gateway-v2/gateway-v2-dal";import { TPkiDiscoveryConfigDALFactory } from "./pki-discovery-config-dal";+import { validateTargetConfig } from "./pki-discovery-fns";import { TPkiDiscoveryScanHistoryDALFactory } from "./pki-discovery-scan-history-dal";import {PkiDiscoveryScanStatus,@@ -62,15 +63,24 @@ type TPkiDiscoveryServiceFactoryDep = {export type TPkiDiscoveryServiceFactory = ReturnType<typeof pkiDiscoveryServiceFactory>;-const validateTargetConfigForType = (discoveryType: PkiDiscoveryType, config: TPkiDiscoveryTargetConfig) => {+const validateTargetConfigForType = (+ discoveryType: PkiDiscoveryType,+ config: TPkiDiscoveryTargetConfig,+ hasGateway: boolean+) => {switch (discoveryType) {- case PkiDiscoveryType.Network:+ case PkiDiscoveryType.Network: {if (!config.ipRanges?.length && !config.domains?.length) {throw new BadRequestError({message: "Target configuration must include at least one IP range or domain"});}+ const validation = validateTargetConfig(config.ipRanges, config.ports, config.domains, hasGateway);+ if (!validation.valid) {+ throw new BadRequestError({ message: validation.error || "Invalid target configuration" });+ }break;+ }default:throw new BadRequestError({ message: `Unsupported discovery type: ${discoveryType as string}` });}@@ -139,7 +149,7 @@ export const pkiDiscoveryServiceFactory = ({}}- validateTargetConfigForType(discoveryType, targetConfig);+ validateTargetConfigForType(discoveryType, targetConfig, Boolean(gatewayId || gatewayPoolId));if (gatewayId) {const gateway = await gatewayV2DAL.findOne({ id: gatewayId, orgId: actorOrgId });@@ -234,10 +244,16 @@ export const pkiDiscoveryServiceFactory = ({ProjectPermissionSub.PkiDiscovery);- if (targetConfig) {+ const gatewayIdValue = gatewayPoolId ? null : gatewayId;+ const gatewayPoolIdValue = gatewayId ? null : gatewayPoolId;++ if (targetConfig || gatewayIdValue !== undefined || gatewayPoolIdValue !== undefined) {+ const effectiveGatewayId = gatewayIdValue === undefined ? discovery.gatewayId : gatewayIdValue;+ const effectiveGatewayPoolId = gatewayPoolIdValue === undefined ? discovery.gatewayPoolId : gatewayPoolIdValue;validateTargetConfigForType((discovery.discoveryType as PkiDiscoveryType) || PkiDiscoveryType.Network,- targetConfig+ targetConfig ?? (discovery.targetConfig as TPkiDiscoveryTargetConfig),+ Boolean(effectiveGatewayId || effectiveGatewayPoolId));}@@ -275,9 +291,6 @@ export const pkiDiscoveryServiceFactory = ({});}- const gatewayIdValue = gatewayPoolId ? null : gatewayId;- const gatewayPoolIdValue = gatewayId ? null : gatewayPoolId;-try {const updatedDiscovery = await pkiDiscoveryConfigDAL.updateById(discoveryId, {name,