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
Address greptile comments
Carlos Monastyrski849231d2385a
diff --git a/backend/src/ee/services/pki-discovery/pki-discovery-fns.ts b/backend/src/ee/services/pki-discovery/pki-discovery-fns.tsindex e4f5ae0fda..b479d1ccdb 100644--- a/backend/src/ee/services/pki-discovery/pki-discovery-fns.ts+++ b/backend/src/ee/services/pki-discovery/pki-discovery-fns.ts@@ -290,21 +290,7 @@ export const scanEndpoint = async (});};-const parseDistinguishedName = (value: string): Record<string, string> => {- const fields: Record<string, string[]> = {};- value- .split("\n")- .map((line) => line.trim())- .filter(Boolean)- .forEach((line) => {- const separator = line.indexOf("=");- if (separator <= 0) return;- const key = line.substring(0, separator);- const fieldValue = line.substring(separator + 1);- fields[key] = [...(fields[key] ?? []), fieldValue];- });- return Object.fromEntries(Object.entries(fields).map(([key, values]) => [key, values.join(", ")]));-};+const getNameField = (name: x509.Name, field: string) => name.getField(field).join(", ") || undefined;export const parseCertificateDer = (derBuffer: Buffer): TScanCertificateResult | null => {try {@@ -338,8 +324,8 @@ export const parseCertificateDer = (derBuffer: Buffer): TScanCertificateResult |}const basicConstraints = x509Cert.getExtension(x509.BasicConstraintsExtension);- const subject = parseDistinguishedName(nodeCert.subject);- const issuer = parseDistinguishedName(nodeCert.issuer);+ const subject = x509Cert.subjectName;+ const issuer = x509Cert.issuerName;return {pemChain: [x509Cert.toString("pem")],@@ -347,16 +333,16 @@ export const parseCertificateDer = (derBuffer: Buffer): TScanCertificateResult |fingerprint: computeCertFingerprint(derBuffer),// eslint-disable-next-line @typescript-eslint/no-use-before-definefingerprintSha1: computeCertFingerprintSha1(derBuffer),- commonName: subject.CN || "",+ commonName: getNameField(subject, "CN") || "",altNames: altNames || undefined,notBefore: new Date(nodeCert.validFrom),notAfter: new Date(nodeCert.validTo),serialNumber: nodeCert.serialNumber,- subjectOrganization: subject.O,- subjectOrganizationalUnit: subject.OU,- subjectCountry: subject.C,- subjectState: subject.ST,- subjectLocality: subject.L,+ subjectOrganization: getNameField(subject, "O"),+ subjectOrganizationalUnit: getNameField(subject, "OU"),+ subjectCountry: getNameField(subject, "C"),+ subjectState: getNameField(subject, "ST"),+ subjectLocality: getNameField(subject, "L"),// eslint-disable-next-line @typescript-eslint/no-use-before-definekeyAlgorithm: extractKeyAlgorithm(x509Cert),// eslint-disable-next-line @typescript-eslint/no-use-before-define@@ -365,8 +351,8 @@ export const parseCertificateDer = (derBuffer: Buffer): TScanCertificateResult |extendedKeyUsages,isCA: basicConstraints ? basicConstraints.ca : nodeCert.ca,pathLength: basicConstraints?.pathLength,- issuerCommonName: issuer.CN,- issuerOrganization: issuer.O+ issuerCommonName: getNameField(issuer, "CN"),+ issuerOrganization: getNameField(issuer, "O")};} catch (error) {logger.error(error, "Failed to parse discovered certificate");diff --git a/backend/src/ee/services/pki-discovery/pki-discovery-host-scan-fns.test.ts b/backend/src/ee/services/pki-discovery/pki-discovery-host-scan-fns.test.tsindex 25f25fc605..0e3747896f 100644--- a/backend/src/ee/services/pki-discovery/pki-discovery-host-scan-fns.test.ts+++ b/backend/src/ee/services/pki-discovery/pki-discovery-host-scan-fns.test.ts@@ -3,7 +3,7 @@ import { webcrypto } from "crypto";import { NotFoundError } from "@app/lib/errors";-import { computeCertFingerprint } from "./pki-discovery-fns";+import { computeCertFingerprint, parseCertificateDer } from "./pki-discovery-fns";import { scanHost, THostScanDeps, toHostScanErrorMessage, writeHostFile } from "./pki-discovery-host-scan-fns";import { HostCertificateChainKind, HostCertificateFileStatus } from "./pki-discovery-types";@@ -65,7 +65,10 @@ test("unexpected errors are hidden behind a product message", () => {});test("writeHostFile names a new installation after the hostname and links its certificate", async () => {- const keys = await webcrypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, ["sign", "verify"]);+ const keys = (await webcrypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, [+ "sign",+ "verify"+ ])) as CryptoKeyPair;const der = Buffer.from((await x509.X509CertificateGenerator.createSelfSigned({@@ -110,3 +113,34 @@ test("writeHostFile names a new installation after the hostname and links its ceexpect(create).toHaveBeenCalledWith(expect.objectContaining({ name: "web-01:/etc/ssl/a.pem" }), tx);expect(upsertCertLink).toHaveBeenCalledWith("installation-1", "cert-1", { lastSeenAt: ctx.scanTime }, tx);});++test("parseCertificateDer reads subject and issuer fields without escaping", async () => {+ const keys = (await webcrypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, [+ "sign",+ "verify"+ ])) as CryptoKeyPair;+ const cert = await x509.X509CertificateGenerator.createSelfSigned({+ serialNumber: "0d0e0f",+ name: [{ CN: ["ca.example.com"] }, { O: ["Example, Inc."] }, { OU: ["one"] }, { OU: ["two"] }],+ notBefore: new Date("2026-01-01T00:00:00Z"),+ notAfter: new Date("2027-01-01T00:00:00Z"),+ keys,+ signingAlgorithm: { name: "ECDSA", hash: "SHA-256" },+ extensions: [+ new x509.BasicConstraintsExtension(true, 1, true),+ new x509.SubjectAlternativeNameExtension([{ type: "dns", value: "ca.example.com" }])+ ]+ });++ expect(parseCertificateDer(Buffer.from(cert.rawData))).toMatchObject({+ commonName: "ca.example.com",+ subjectOrganization: "Example, Inc.",+ subjectOrganizationalUnit: "one, two",+ issuerCommonName: "ca.example.com",+ issuerOrganization: "Example, Inc.",+ altNames: "ca.example.com",+ isCA: true,+ pathLength: 1+ });+ expect(parseCertificateDer(Buffer.from("not a certificate"))).toBeNull();+});diff --git a/backend/src/ee/services/pki-discovery/pki-discovery-rescan-fns.ts b/backend/src/ee/services/pki-discovery/pki-discovery-rescan-fns.tsindex 74b16f63f6..4396cb40a7 100644--- a/backend/src/ee/services/pki-discovery/pki-discovery-rescan-fns.ts+++ b/backend/src/ee/services/pki-discovery/pki-discovery-rescan-fns.ts@@ -1,5 +1,6 @@import { getProjectKmsCertificateKeyId } from "@app/services/project/project-fns";+import { computeLocationFingerprint } from "./pki-discovery-fns";import { describeHostFileError } from "./pki-discovery-host-fns";import {buildScanRequest,@@ -12,7 +13,12 @@ import {} from "./pki-discovery-host-scan-fns";import { DB_SHORT_VARCHAR_LIMIT, truncateString } from "./pki-discovery-scan-run-fns";import { LinuxServerTargetConfigSchema } from "./pki-discovery-schemas";-import { HostCertificateFileStatus, TLinuxServerTargetConfig, TPkiInstallationMetadata } from "./pki-discovery-types";+import {+ HostCertificateFileStatus,+ PkiInstallationLocationType,+ TLinuxServerTargetConfig,+ TPkiInstallationMetadata+} from "./pki-discovery-types";const recordInstallationError = async (installationId: string, message: string, deps: THostScanDeps) => {const installation = await deps.pkiCertificateInstallationDAL.findById(@@ -53,6 +59,19 @@ export const rescanInstallation = async (installationId: string, deps: THostScanconst connection = await deps.appConnectionDAL.findById(details.connectionId);const host = await resolveHost(connection, project.orgId, deps);+ const currentFingerprint = computeLocationFingerprint(+ installation.locationType as PkiInstallationLocationType,+ { hostIdentifier: host.hostIdentifier, filePath: details.filePath },+ host.fingerprintGatewayKey+ );+ if (currentFingerprint !== installation.locationFingerprint) {+ await recordInstallationError(+ installation.id,+ "The SSH connection now points to a different server or gateway. Run the discovery job again to scan this file.",+ deps+ );+ return;+ }const keystorePasswords = await loadKeystorePasswords(installation.projectId, host, deps);const response = await scanHost(host, buildScanRequest(targetConfig, keystorePasswords, [details.filePath]), deps);diff --git a/docs/documentation/platform/pki/discovery/linux-server.mdx b/docs/documentation/platform/pki/discovery/linux-server.mdxindex 3cef4c56f9..970209bafb 100644--- a/docs/documentation/platform/pki/discovery/linux-server.mdx+++ b/docs/documentation/platform/pki/discovery/linux-server.mdx@@ -33,7 +33,7 @@ Scans only open files with these extensions: `.pem`, `.crt`, `.cer`, `.cert`, `.## Give the SSH user read access-Certificate files are often readable only by root. Give the SSH user read access in one of two ways.+Certificate files are often readable only by root. Give the SSH user read access through a group or ACL where you can, and use `sudo` only with a dedicated scan account.<Tabs><Tab title="Group or ACL">@@ -54,6 +54,10 @@ Certificate files are often readable only by root. Give the SSH user read access```The gateway tries every folder and file as the SSH user first, and uses `sudo` only for the ones it can't read.++ <Warning>+ This rule lets the SSH user read any file on the server and run commands as root through `find`. Use it only for a dedicated scan account that nothing else can sign in with, and prefer a group or ACL.+ </Warning></Tab></Tabs>diff --git a/docs/documentation/platform/pki/discovery/network.mdx b/docs/documentation/platform/pki/discovery/network.mdxindex d3325091de..654533c0d2 100644--- a/docs/documentation/platform/pki/discovery/network.mdx+++ b/docs/documentation/platform/pki/discovery/network.mdx@@ -11,27 +11,36 @@ Network discovery scans network endpoints over TLS to discover certificates serv<Tabs><Tab title="Infisical UI">- 1. In **Certificate Manager**, go to **Discovery** and select **Add Job**, then select **Network**.-- 2. Under **Targets**, set what to scan:- - **Targets**: Domains, IP addresses, or CIDR ranges to scan (e.g., `example.com`, `192.168.1.1`, `10.0.0.0/24`).+ <Steps>+ <Step>+ In **Certificate Manager**, go to **Discovery** and select **Add Job**, then select **Network**.+ </Step>+ <Step>+ Under **Targets**, set what to scan:+ - **Targets**: Domains, IP addresses, or CIDR ranges to scan, such as `example.com`, `192.168.1.1`, or `10.0.0.0/24`.- **Ports**: Ports to scan for TLS certificates. Defaults to common TLS ports if not specified.- **Gateway** (optional): The Infisical Gateway for scanning private networks.<Note>At least one target (domain or IP) must be specified.</Note>-- 3. Enter a **Name** and an optional **Description**. To run the job on a schedule, turn on **Scan on a Schedule** and pick a **Scan Interval**.-- 4. Review the job and select **Create Job**.-- 5. Open the job and select **Trigger Scan**, or wait for the next scheduled scan.-- 6. After a scan completes, view the results:+ </Step>+ <Step>+ Enter a **Name** and an optional **Description**. To run the job on a schedule, turn on **Scan on a Schedule** and pick a **Scan Interval**.+ </Step>+ <Step>+ Review the job and select **Create Job**.+ </Step>+ <Step>+ Open the job and select **Trigger Scan**, or wait for the next scheduled scan.+ </Step>+ <Step>+ After a scan completes, view the results:- **Installations**: Unique locations where certificates were found.- **Certificates**: Details including common name, issuer, and expiration date.- **Scan History**: Log of all scans with status and timestamps.+ </Step>+ </Steps></Tab><Tab title="API">To create a **Network** discovery job, make an API request to the [Create Discovery](/api-reference/endpoints/pki-discovery/create) API endpoint.diff --git a/frontend/src/hooks/api/pkiDiscovery/types.ts b/frontend/src/hooks/api/pkiDiscovery/types.tsindex afb4131ca0..b34a3d9993 100644--- a/frontend/src/hooks/api/pkiDiscovery/types.ts+++ b/frontend/src/hooks/api/pkiDiscovery/types.ts@@ -246,7 +246,7 @@ export type TGetPkiInstallationDTO = {export type TUpdatePkiInstallationDTO = {installationId: string;name?: string;- keystorePassword?: string | null;+ keystorePassword?: string;};export type TDeletePkiInstallationDTO = {diff --git a/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/DiscoveryJobSheet.tsx b/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/DiscoveryJobSheet.tsxindex 6bcf4a5435..ff989fbd6e 100644--- a/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/DiscoveryJobSheet.tsx+++ b/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/DiscoveryJobSheet.tsx@@ -1,4 +1,4 @@-import { useEffect, useState } from "react";+import { useEffect, useRef, useState } from "react";import { ArrowLeftIcon } from "lucide-react";import {@@ -42,11 +42,22 @@ export const DiscoveryJobSheet = ({ isOpen, onClose, projectId, discovery }: ProonClose();};+ const returnToTypeSelect = () => {+ setIsDirty(false);+ setSelectedType(null);+ };++ const discardActionRef = useRef<VoidFunction>(closeSheet);const { confirmDiscard, isDiscardDialogOpen, requestDiscard, setIsDiscardDialogOpen } =- useDiscardChangesGuard({ isDirty, onDiscard: closeSheet });+ useDiscardChangesGuard({ isDirty, onDiscard: () => discardActionRef.current() });++ const requestDiscardAction = (action: VoidFunction) => {+ discardActionRef.current = action;+ requestDiscard();+ };const handleOpenChange = (nextOpen: boolean) => {- if (!nextOpen) requestDiscard();+ if (!nextOpen) requestDiscardAction(closeSheet);};const showBack = !discovery && Boolean(selectedType);@@ -60,7 +71,7 @@ export const DiscoveryJobSheet = ({ isOpen, onClose, projectId, discovery }: ProprojectId={projectId}discovery={discovery}onComplete={closeSheet}- onCancel={() => (discovery ? requestDiscard() : setSelectedType(null))}+ onCancel={() => requestDiscardAction(discovery ? closeSheet : returnToTypeSelect)}onDirtyChange={setIsDirty}/>);@@ -84,10 +95,7 @@ export const DiscoveryJobSheet = ({ isOpen, onClose, projectId, discovery }: Provariant="link"size="xs"className="mb-1 w-fit px-0"- onClick={() => {- setSelectedType(null);- setIsDirty(false);- }}+ onClick={() => requestDiscardAction(returnToTypeSelect)}><ArrowLeftIcon />Select Another Typediff --git a/frontend/src/pages/cert-manager/DiscoveryPage/components/InstallationsTab.tsx b/frontend/src/pages/cert-manager/DiscoveryPage/components/InstallationsTab.tsxindex 50b5c612e3..6ee8f52093 100644--- a/frontend/src/pages/cert-manager/DiscoveryPage/components/InstallationsTab.tsx+++ b/frontend/src/pages/cert-manager/DiscoveryPage/components/InstallationsTab.tsx@@ -56,7 +56,11 @@ import {import { DiscoveryTypeIcon } from "./DiscoveryJobSheet/DiscoveryTypeIcon";import { DeleteInstallationModal } from "./DeleteInstallationModal";import { EditInstallationModal } from "./EditInstallationModal";-import { SetKeystorePasswordDialog } from "./SetKeystorePasswordDialog";+import {+ RESCAN_POLL_INTERVAL_MS,+ RESCAN_POLL_TIMEOUT_MS,+ SetKeystorePasswordDialog+} from "./SetKeystorePasswordDialog";type Props = {projectId: string;@@ -79,12 +83,34 @@ export const InstallationsTab = ({ projectId }: Props) => {"setKeystorePassword"] as const);- const { data, isPending } = useListPkiInstallations({- projectId,- offset: (page - 1) * PAGE_SIZE,- limit: PAGE_SIZE,- search: debouncedSearch || undefined- });+ const [pendingRescan, setPendingRescan] = useState<{+ installationId: string;+ previousCheckedAt?: string;+ } | null>(null);++ useEffect(() => {+ if (!pendingRescan) return undefined;+ const timeout = setTimeout(() => setPendingRescan(null), RESCAN_POLL_TIMEOUT_MS);+ return () => clearTimeout(timeout);+ }, [pendingRescan]);++ const { data, isPending } = useListPkiInstallations(+ {+ projectId,+ offset: (page - 1) * PAGE_SIZE,+ limit: PAGE_SIZE,+ search: debouncedSearch || undefined+ },+ { refetchInterval: pendingRescan ? RESCAN_POLL_INTERVAL_MS : false }+ );++ useEffect(() => {+ if (!pendingRescan) return;+ const rescanned = data?.installations.find((item) => item.id === pendingRescan.installationId);+ if (rescanned && rescanned.metadata?.lastCheckedAt !== pendingRescan.previousCheckedAt) {+ setPendingRescan(null);+ }+ }, [data, pendingRescan]);useEffect(() => {setPage(1);@@ -275,6 +301,15 @@ export const InstallationsTab = ({ projectId }: Props) => {onOpenChange={(isOpen) => handlePopUpToggle("setKeystorePassword", isOpen)}projectId={projectId}installation={popUp.setKeystorePassword.data as TPkiInstallation | undefined}+ onSaved={() => {+ const saved = popUp.setKeystorePassword.data as TPkiInstallation | undefined;+ if (saved) {+ setPendingRescan({+ installationId: saved.id,+ previousCheckedAt: saved.metadata?.lastCheckedAt+ });+ }+ }}/><DeleteInstallationModaldiff --git a/frontend/src/pages/cert-manager/DiscoveryPage/components/SetKeystorePasswordDialog.tsx b/frontend/src/pages/cert-manager/DiscoveryPage/components/SetKeystorePasswordDialog.tsxindex ec31c6e536..74c18c249d 100644--- a/frontend/src/pages/cert-manager/DiscoveryPage/components/SetKeystorePasswordDialog.tsx+++ b/frontend/src/pages/cert-manager/DiscoveryPage/components/SetKeystorePasswordDialog.tsx@@ -19,6 +19,9 @@ import {} from "@app/components/v3";import { TPkiInstallation, useUpdatePkiInstallation } from "@app/hooks/api";+export const RESCAN_POLL_INTERVAL_MS = 3000;+export const RESCAN_POLL_TIMEOUT_MS = 2 * 60 * 1000;+const MAX_PASSWORD_LENGTH = 1024;type Props = {diff --git a/frontend/src/pages/cert-manager/InstallationDetailsByIDPage/InstallationDetailsByIDPage.tsx b/frontend/src/pages/cert-manager/InstallationDetailsByIDPage/InstallationDetailsByIDPage.tsxindex bc6eecb475..6e66e2a1b8 100644--- a/frontend/src/pages/cert-manager/InstallationDetailsByIDPage/InstallationDetailsByIDPage.tsx+++ b/frontend/src/pages/cert-manager/InstallationDetailsByIDPage/InstallationDetailsByIDPage.tsx@@ -42,12 +42,13 @@ import {useCanRescanPkiInstallations} from "@app/pages/cert-manager/pki-discovery-utils";-import { SetKeystorePasswordDialog } from "../DiscoveryPage/components/SetKeystorePasswordDialog";+import {+ RESCAN_POLL_INTERVAL_MS,+ RESCAN_POLL_TIMEOUT_MS,+ SetKeystorePasswordDialog+} from "../DiscoveryPage/components/SetKeystorePasswordDialog";import { InstallationCertificatesSection, InstallationDetailsSection } from "./components";-const RESCAN_POLL_INTERVAL_MS = 3000;-const RESCAN_POLL_TIMEOUT_MS = 2 * 60 * 1000;-const Page = () => {const { currentProject } = useProject();const canRescanInstallation = useCanRescanPkiInstallations();