Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

feat(pki): add Linux Server certificate discovery over SSH connections and gateways

Carlos Monastyrski68730841c742
diff --git a/.infisicalignore b/.infisicalignore
index 1726719b5d..1e0c61dce1 100644
--- a/.infisicalignore
+++ b/.infisicalignore
@@ -72,3 +72,4 @@ backend/e2e-test/routes/v1/oauth-token-exchange.spec.ts:generic-api-key:216
backend/src/ee/services/audit-log-stream/splunk/splunk-provider-schemas.test.ts:generic-api-key:7
frontend/src/hooks/api/agentVault/sessionLogDecrypt.test.ts:generic-api-key:161
docs/documentation/platform/secret-scanning/scan-locally.mdx:generic-api-key:65
+backend/src/ee/services/pki-discovery/pki-discovery-host-scan-fns.test.ts:generic-api-key:23
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.md
index b70bd6cc4b..79a497be9f 100644
--- a/backend/CLAUDE.md
+++ b/backend/CLAUDE.md
@@ -977,6 +977,8 @@ EE routes register before community routes so they can override/extend endpoints
**PAM**: Before working on any `pam-*` service or router, read [`src/ee/services/pam/CLAUDE.md`](src/ee/services/pam/CLAUDE.md) for a high-level map of the PAM backend — module layout, permission model, and non-obvious invariants. It is intentionally a concept map, not a spec: read the referenced code for implementation detail. If you add a feature, keep any addition there brief (a concept or invariant, not code mechanics).
+**Certificate discovery**: before working on `pki-discovery-*` or `pki-installation-*`, read [`src/ee/services/pki-discovery/CLAUDE.md`](src/ee/services/pki-discovery/CLAUDE.md). Linux Server discovery splits work between the backend and the gateway's certificate scanner in the CLI repo, and keystore passwords live on installations, not jobs.
+
**Agent Vault**: the same applies to the `agent-vault-*` services and routers; the concept map is [`src/ee/services/agent-vault/CLAUDE.md`](src/ee/services/agent-vault/CLAUDE.md). PAM and Agent Vault are the two **org-scoped products**: one implicit project per org, resolved lazily, whose roles collapse to admin or member. Anything that branches on `ProjectType.PAM` (metering emits, predefined roles, the billable-project count, invite grants) almost always needs an Agent Vault arm too.
**Gateways: there is only one generation.** Gateway v1 (`ee/services/gateway`, `lib/gateway`, the QUIC
diff --git a/backend/src/db/migrations/20261006143417_pki-linux-server-discovery.ts b/backend/src/db/migrations/20261006143417_pki-linux-server-discovery.ts
new file mode 100644
index 0000000000..4b503ea76b
--- /dev/null
+++ b/backend/src/db/migrations/20261006143417_pki-linux-server-discovery.ts
@@ -0,0 +1,45 @@
+import { Knex } from "knex";
+
+import { TableName } from "../schemas";
+
+export async function up(knex: Knex): Promise<void> {
+ const hasEncryptedCredentials = await knex.schema.hasColumn(
+ TableName.PkiCertificateInstallation,
+ "encryptedCredentials"
+ );
+ if (!hasEncryptedCredentials) {
+ await knex.schema.table(TableName.PkiCertificateInstallation, (table) => {
+ table.binary("encryptedCredentials").nullable();
+ });
+ }
+
+ const hasLastScanMessage = await knex.schema.hasColumn(TableName.PkiDiscoveryConfig, "lastScanMessage");
+ if (hasLastScanMessage) {
+ await knex.schema.alterTable(TableName.PkiDiscoveryConfig, (table) => {
+ table.text("lastScanMessage").nullable().alter();
+ });
+ }
+}
+
+export async function down(knex: Knex): Promise<void> {
+ const hasLastScanMessage = await knex.schema.hasColumn(TableName.PkiDiscoveryConfig, "lastScanMessage");
+ if (hasLastScanMessage) {
+ await knex.raw(
+ `UPDATE ?? SET "lastScanMessage" = LEFT("lastScanMessage", 255) WHERE LENGTH("lastScanMessage") > 255`,
+ [TableName.PkiDiscoveryConfig]
+ );
+ await knex.schema.alterTable(TableName.PkiDiscoveryConfig, (table) => {
+ table.string("lastScanMessage", 255).nullable().alter();
+ });
+ }
+
+ const hasEncryptedCredentials = await knex.schema.hasColumn(
+ TableName.PkiCertificateInstallation,
+ "encryptedCredentials"
+ );
+ if (hasEncryptedCredentials) {
+ await knex.schema.table(TableName.PkiCertificateInstallation, (table) => {
+ table.dropColumn("encryptedCredentials");
+ });
+ }
+}
diff --git a/backend/src/db/schemas/pki-certificate-installations.ts b/backend/src/db/schemas/pki-certificate-installations.ts
index b9a4acc3f8..1ddd7184b7 100644
--- a/backend/src/db/schemas/pki-certificate-installations.ts
+++ b/backend/src/db/schemas/pki-certificate-installations.ts
@@ -5,6 +5,8 @@
import { z } from "zod";
+import { zodBuffer } from "@app/lib/zod";
+
import { TImmutableDBKeys } from "./models";
export const PkiCertificateInstallationsSchema = z.object({
@@ -18,7 +20,8 @@ export const PkiCertificateInstallationsSchema = z.object({
metadata: z.unknown().nullable().optional(),
lastSeenAt: z.date(),
createdAt: z.date(),
- updatedAt: z.date()
+ updatedAt: z.date(),
+ encryptedCredentials: zodBuffer.nullable().optional()
});
export type TPkiCertificateInstallations = z.infer<typeof PkiCertificateInstallationsSchema>;
diff --git a/backend/src/ee/routes/v1/pki-discovery-router.ts b/backend/src/ee/routes/v1/pki-discovery-router.ts
index 252eaa1b4f..d02af66ee6 100644
--- a/backend/src/ee/routes/v1/pki-discovery-router.ts
+++ b/backend/src/ee/routes/v1/pki-discovery-router.ts
@@ -7,29 +7,23 @@ import {
MAX_DOMAINS,
MAX_IPS,
MAX_PORTS,
- MIN_CIDR_PREFIX,
- validateTargetConfig
+ MIN_CIDR_PREFIX
} from "@app/ee/services/pki-discovery/pki-discovery-fns";
+import { DiscoveryTargetConfigInputSchema } from "@app/ee/services/pki-discovery/pki-discovery-schemas";
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";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
+import { AppConnection } from "@app/services/app-connection/app-connection-enums";
import { AuthMode } from "@app/services/auth/auth-type";
import { pkiDescriptionSchema } from "@app/services/certificate-common/certificate-constants";
import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
-const NetworkTargetConfigSchema = z
- .object({
- ipRanges: z.array(z.string().max(64)).optional(),
- domains: z.array(z.string().max(253)).optional(),
- ports: z.string().default(DEFAULT_TLS_PORTS)
- })
- .refine((data) => (data.ipRanges && data.ipRanges.length > 0) || (data.domains && data.domains.length > 0), {
- message: "At least one IP range or domain is required"
- });
+const DiscoveryConnectionsSchema = z
+ .array(z.object({ id: z.string().uuid(), name: z.string(), app: z.nativeEnum(AppConnection) }))
+ .optional();
export const registerPkiDiscoveryRouter = async (server: FastifyZodProvider) => {
server.route({
@@ -87,7 +81,7 @@ export const registerPkiDiscoveryRouter = async (server: FastifyZodProvider) =>
.optional()
.default(PkiDiscoveryType.Network)
.describe("Type of discovery scan"),
- targetConfig: NetworkTargetConfigSchema.describe("Target configuration for discovery scans"),
+ targetConfig: DiscoveryTargetConfigInputSchema,
isAutoScanEnabled: z.boolean().optional().default(false).describe("Enable automatic scheduled scans"),
scanIntervalDays: z.number().min(1).max(365).optional().describe("Interval in days between automatic scans"),
gatewayId: z.string().uuid().optional().describe("Gateway ID for scanning private networks"),
@@ -107,16 +101,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,
@@ -128,6 +112,7 @@ export const registerPkiDiscoveryRouter = async (server: FastifyZodProvider) =>
scanIntervalDays: req.body.scanIntervalDays,
gatewayId: req.body.gatewayId,
gatewayPoolId: req.body.gatewayPoolId,
+ orgActor: req.permission,
actor: req.permission.type,
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
@@ -184,7 +169,8 @@ export const registerPkiDiscoveryRouter = async (server: FastifyZodProvider) =>
discoveries: z.array(
PkiDiscoveryConfigsSchema.extend({
certificatesFound: z.number(),
- installationsFound: z.number()
+ installationsFound: z.number(),
+ connections: DiscoveryConnectionsSchema
})
),
totalCount: z.number()
@@ -238,7 +224,8 @@ export const registerPkiDiscoveryRouter = async (server: FastifyZodProvider) =>
200: PkiDiscoveryConfigsSchema.extend({
linkedInstallationsCount: z.number().optional(),
gatewayName: z.string().nullable().optional(),
- gatewayPoolName: z.string().nullable().optional()
+ gatewayPoolName: z.string().nullable().optional(),
+ connections: DiscoveryConnectionsSchema
})
}
},
@@ -289,7 +276,7 @@ export const registerPkiDiscoveryRouter = async (server: FastifyZodProvider) =>
.optional()
.nullable()
.describe("Description of the discovery configuration"),
- targetConfig: NetworkTargetConfigSchema.optional().describe("Target configuration for discovery scans"),
+ targetConfig: DiscoveryTargetConfigInputSchema.optional(),
isAutoScanEnabled: z.boolean().optional().describe("Enable automatic scheduled scans"),
scanIntervalDays: z
.number()
@@ -321,31 +308,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,
@@ -356,6 +318,7 @@ export const registerPkiDiscoveryRouter = async (server: FastifyZodProvider) =>
gatewayId: req.body.gatewayId,
gatewayPoolId: req.body.gatewayPoolId,
isActive: req.body.isActive,
+ orgActor: req.permission,
actor: req.permission.type,
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
diff --git a/backend/src/ee/routes/v1/pki-installation-router.ts b/backend/src/ee/routes/v1/pki-installation-router.ts
index 32b598e16b..c641b71fae 100644
--- a/backend/src/ee/routes/v1/pki-installation-router.ts
+++ b/backend/src/ee/routes/v1/pki-installation-router.ts
@@ -2,12 +2,17 @@ import { z } from "zod";
import { PkiCertificateInstallationsSchema } from "@app/db/schemas";
import { EventType } from "@app/ee/services/audit-log/audit-log-types";
+import { PkiKeystorePasswordChange } from "@app/ee/services/pki-discovery/pki-discovery-types";
import { ApiDocsTags } from "@app/lib/api-docs";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
import { openApiHidden } from "@app/server/lib/schemas";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { AuthMode } from "@app/services/auth/auth-type";
+const SanitizedPkiInstallationSchema = PkiCertificateInstallationsSchema.omit({ encryptedCredentials: true }).extend({
+ hasKeystorePassword: z.boolean().describe("Whether a keystore password is saved for this installation")
+});
+
export const registerPkiInstallationRouter = async (server: FastifyZodProvider) => {
server.route({
method: "GET",
@@ -32,7 +37,7 @@ export const registerPkiInstallationRouter = async (server: FastifyZodProvider)
response: {
200: z.object({
installations: z.array(
- PkiCertificateInstallationsSchema.extend({
+ SanitizedPkiInstallationSchema.extend({
certificatesCount: z.number().optional(),
primaryCertName: z.string().nullable().optional(),
discoveryName: z.string().nullable().optional()
@@ -88,8 +93,9 @@ export const registerPkiInstallationRouter = async (server: FastifyZodProvider)
installationId: z.string().uuid().describe("The ID of the installation")
}),
response: {
- 200: PkiCertificateInstallationsSchema.extend({
+ 200: SanitizedPkiInstallationSchema.extend({
discoveryName: z.string().nullable().optional(),
+ connection: z.object({ id: z.string().uuid(), name: z.string() }).nullable().optional(),
certificates: z
.array(
z.object({
@@ -155,16 +161,26 @@ export const registerPkiInstallationRouter = async (server: FastifyZodProvider)
installationId: z.string().uuid().describe("The ID of the installation")
}),
body: z.object({
- name: z.string().max(255).optional().describe("Name of the installation")
+ name: z.string().max(255).optional().describe("Name of the installation"),
+ keystorePassword: z
+ .string()
+ .min(1)
+ .max(1024)
+ .nullable()
+ .optional()
+ .describe(
+ "Password of the keystore at this installation. It is never returned. Setting it rescans the file. Send null to clear it."
+ )
}),
response: {
- 200: PkiCertificateInstallationsSchema
+ 200: SanitizedPkiInstallationSchema
}
},
handler: async (req) => {
const installation = await server.services.pkiInstallation.updateInstallation({
installationId: req.params.installationId,
name: req.body.name,
+ keystorePassword: req.body.keystorePassword,
actor: req.permission.type,
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
@@ -178,7 +194,11 @@ export const registerPkiInstallationRouter = async (server: FastifyZodProvider)
type: EventType.UPDATE_PKI_INSTALLATION,
metadata: {
installationId: installation.id,
- name: installation.name ?? undefined
+ name: installation.name ?? undefined,
+ ...(req.body.keystorePassword !== undefined && {
+ keystorePasswordChange:
+ req.body.keystorePassword === null ? PkiKeystorePasswordChange.Cleared : PkiKeystorePasswordChange.Set
+ })
}
}
});
@@ -203,7 +223,7 @@ export const registerPkiInstallationRouter = async (server: FastifyZodProvider)
installationId: z.string().uuid().describe("The ID of the installation")
}),
response: {
- 200: PkiCertificateInstallationsSchema
+ 200: SanitizedPkiInstallationSchema
}
},
handler: async (req) => {
diff --git a/backend/src/ee/routes/v2/gateway-router.ts b/backend/src/ee/routes/v2/gateway-router.ts
index 36ac6ef136..7fa3945120 100644
--- a/backend/src/ee/routes/v2/gateway-router.ts
+++ b/backend/src/ee/routes/v2/gateway-router.ts
@@ -139,6 +139,7 @@ export const registerGatewayV2Router = async (server: FastifyZodProvider) => {
pkcs11: z.boolean().optional(),
sessionLogMaskingBuiltInDetection: z.boolean().optional(),
clickhouseNativeProtocol: z.boolean().optional(),
+ certificateScan: z.boolean().optional(),
supported_account_types: z.array(z.string().trim().max(64)).max(64).optional()
})
.optional()
diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.ts
index 5bd3ccd0b9..de36604efc 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -1,7 +1,7 @@
import { ProjectType } from "@app/db/schemas";
import { GatewayTransport } from "@app/ee/services/gateway-v2/gateway-v2-constants";
import { HoneyTokenType } from "@app/ee/services/honey-token/honey-token-enums";
-import { CertificateSource } from "@app/ee/services/pki-discovery/pki-discovery-types";
+import { CertificateSource, PkiKeystorePasswordChange } from "@app/ee/services/pki-discovery/pki-discovery-types";
import { ScepChallengeType } from "@app/ee/services/pki-scep/challenge";
import { ScepEnrollmentStatus } from "@app/ee/services/pki-scep/pki-scep-types";
import {
@@ -4948,6 +4948,7 @@ interface UpdatePkiInstallationEvent {
installationId: string;
name?: string;
type?: string;
+ keystorePasswordChange?: PkiKeystorePasswordChange;
};
}
diff --git a/backend/src/ee/services/gateway-v2/gateway-v2-service.ts b/backend/src/ee/services/gateway-v2/gateway-v2-service.ts
index f818fb666f..0157562c71 100644
--- a/backend/src/ee/services/gateway-v2/gateway-v2-service.ts
+++ b/backend/src/ee/services/gateway-v2/gateway-v2-service.ts
@@ -1057,6 +1057,7 @@ export const gatewayV2ServiceFactory = ({
pkcs11?: boolean;
sessionLogMaskingBuiltInDetection?: boolean;
clickhouseNativeProtocol?: boolean;
+ certificateScan?: boolean;
supported_account_types?: string[];
};
}) => {
diff --git a/backend/src/ee/services/pki-discovery/CLAUDE.md b/backend/src/ee/services/pki-discovery/CLAUDE.md
new file mode 100644
index 0000000000..3aca39d41d
--- /dev/null
+++ b/backend/src/ee/services/pki-discovery/CLAUDE.md
@@ -0,0 +1,23 @@
+# Certificate discovery backend
+
+Invariants for `pki-discovery-*` and `pki-installation-*` that the code doesn't state on its own.
+
+- A discovery job (`pki_discovery_configs`) has a `discoveryType`: `network` (TLS handshakes, optional job
+ gateway) or `linux-server` (files over SSH). Every type records
+ its run through `pki-discovery-scan-run-fns.ts` and parses certificates with `parseCertificateDer`.
+- Linux Server jobs never have their own gateway. Each SSH connection must use a gateway or pool, and the
+ gateway (`packages/gateway-v2/certscan/` in the CLI repo, RPC `/v1/scan-certificates`) lists, reads and parses
+ the files. Private keys never reach the backend. Old gateways lack `capabilities.certificateScan` and get an
+ "update the gateway" message.
+- Host scans take a per-connection slot (`tryAdmitAppConnectionConcurrency`), shared with PKI syncs.
+- Nothing raw reaches users: gateway, transport and file errors map to product messages; raw text is logged.
+- Installation identity is `hostIdentifier` (connection host, plus `:port` unless 22) + real path + gateway or
+ pool id. The name is `<hostname>:<path>`, or `<hostIdentifier>:<path>` without a hostname, and never affects
+ identity.
+- Scans only add or refresh certificate links, never remove them. A certificate that left a file keeps its old
+ `lastSeenAt`.
+- Keystore passwords live on the installation (`encryptedCredentials`), never on the job, and are never returned
+ (`sanitizePkiInstallation`). They are looked up by installation identity, not by the connection that found the
+ file. Only PKCS#12 takes a password.
+- Setting a password queues a single-file rescan on the `PkiDiscoveryRescan` queue (`pki-discovery-rescan-fns.ts`),
+ which reads the installation from the primary.
diff --git a/backend/src/ee/services/pki-discovery/pki-certificate-installation-dal.ts b/backend/src/ee/services/pki-discovery/pki-certificate-installation-dal.ts
index 2b59a3fb5c..fb48154075 100644
--- a/backend/src/ee/services/pki-discovery/pki-certificate-installation-dal.ts
+++ b/backend/src/ee/services/pki-discovery/pki-certificate-installation-dal.ts
@@ -110,6 +110,12 @@ export const pkiCertificateInstallationDALFactory = (db: TDbClient) => {
])
.orWhereRaw(`"${TableName.PkiCertificateInstallation}"."locationDetails"->>'ipAddress' ILIKE ?`, [
`%${sanitizedSearch}%`
+ ])
+ .orWhereRaw(`"${TableName.PkiCertificateInstallation}"."locationDetails"->>'hostIdentifier' ILIKE ?`, [
+ `%${sanitizedSearch}%`
+ ])
+ .orWhereRaw(`"${TableName.PkiCertificateInstallation}"."locationDetails"->>'filePath' ILIKE ?`, [
+ `%${sanitizedSearch}%`
]);
});
}
@@ -177,6 +183,12 @@ export const pkiCertificateInstallationDALFactory = (db: TDbClient) => {
])
.orWhereRaw(`"${TableName.PkiCertificateInstallation}"."locationDetails"->>'ipAddress' ILIKE ?`, [
`%${sanitizedSearch}%`
+ ])
+ .orWhereRaw(`"${TableName.PkiCertificateInstallation}"."locationDetails"->>'hostIdentifier' ILIKE ?`, [
+ `%${sanitizedSearch}%`
+ ])
+ .orWhereRaw(`"${TableName.PkiCertificateInstallation}"."locationDetails"->>'filePath' ILIKE ?`, [
+ `%${sanitizedSearch}%`
]);
});
}
@@ -286,8 +298,30 @@ export const pkiCertificateInstallationDALFactory = (db: TDbClient) => {
}
};
+ const findKeystoreCredentialsByHost = async (projectId: string, hostIdentifier: string, tx?: Knex) => {
+ try {
+ const docs = await (tx || db.replicaNode())(TableName.PkiCertificateInstallation)
+ .select("id", "locationDetails", "locationFingerprint", "encryptedCredentials")
+ .where({ projectId })
+ .whereNotNull("encryptedCredentials")
+ .whereRaw(`"locationDetails"->>'hostIdentifier' = ?`, [hostIdentifier])
+ .orderBy("updatedAt", "desc");
+
+ return docs as Pick<
+ TPkiCertificateInstallations,
+ "id" | "locationDetails" | "locationFingerprint" | "encryptedCredentials"
+ >[];
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Find PKI keystore credentials by host" });
+ }
+ };
+
+ const primaryNode = () => db.primaryNode();
+
return {
...pkiCertificateInstallationOrm,
+ primaryNode,
+ findKeystoreCredentialsByHost,
findByProjectId,
countByProjectId,
findByIdWithCertificates,
diff --git a/backend/src/ee/services/pki-discovery/pki-discovery-fns.ts b/backend/src/ee/services/pki-discovery/pki-discovery-fns.ts
index 5caa62b989..e4f5ae0fda 100644
--- a/backend/src/ee/services/pki-discovery/pki-discovery-fns.ts
+++ b/backend/src/ee/services/pki-discovery/pki-discovery-fns.ts
@@ -19,7 +19,7 @@ import {
import {
PkiInstallationLocationType,
ScanEndpointFailureReason,
- TPkiDiscoveryTargetConfig,
+ TNetworkTargetConfig,
TPkiInstallationLocationDetails,
TScanCertificateResult,
TScanEndpointResult,
@@ -224,7 +224,7 @@ export const scanEndpoint = async (
seenFingerprints.add(currentCert.fingerprint256);
// eslint-disable-next-line @typescript-eslint/no-use-before-define
- const certResult = parsePeerCertificate(currentCert);
+ const certResult = parseCertificateDer(currentCert.raw);
if (certResult) {
if (certResult.pemChain.length > 0) {
chainPems.push(certResult.pemChain[0]);
@@ -290,34 +290,35 @@ export const scanEndpoint = async (
});
};
-const parsePeerCertificate = (cert: tls.DetailedPeerCertificate): TScanCertificateResult | null => {
- try {
- const derBuffer = cert.raw;
+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(", ")]));
+};
+export const parseCertificateDer = (derBuffer: Buffer): TScanCertificateResult | null => {
+ try {
+ const nodeCert = new crypto.X509Certificate(derBuffer);
const x509Cert = new x509.X509Certificate(derBuffer);
- const pem = x509Cert.toString("pem");
-
- let altNames: string | undefined;
- if (cert.subjectaltname) {
- altNames = cert.subjectaltname
- .split(", ")
- .map((entry) => {
- const colonIdx = entry.indexOf(":");
- return colonIdx >= 0 ? entry.substring(colonIdx + 1) : entry;
- })
- .filter(Boolean)
- .join(", ");
- }
-
- // eslint-disable-next-line @typescript-eslint/no-use-before-define
- const fingerprint = computeCertFingerprint(derBuffer);
- // eslint-disable-next-line @typescript-eslint/no-use-before-define
- const fingerprintSha1 = computeCertFingerprintSha1(derBuffer);
- const subject = cert.subject || {};
- // In Node 22, cert subject/issuer fields can be string | string[] for multi-valued attributes
- const certField = (val: string | string[] | undefined): string | undefined =>
- Array.isArray(val) ? val.join(", ") : val;
+ const altNames = nodeCert.subjectAltName
+ ?.split(", ")
+ .map((entry) => {
+ const colonIdx = entry.indexOf(":");
+ return colonIdx >= 0 ? entry.substring(colonIdx + 1) : entry;
+ })
+ .filter(Boolean)
+ .join(", ");
let keyUsages: CertKeyUsage[] = [];
const keyUsagesExt = x509Cert.getExtension("2.5.29.15") as x509.KeyUsagesExtension;
@@ -336,41 +337,39 @@ const parsePeerCertificate = (cert: tls.DetailedPeerCertificate): TScanCertifica
.filter(Boolean);
}
- const certBasicConstraints = cert as { ca?: boolean; pathlen?: number };
- const isCA = certBasicConstraints.ca;
- const pathLength = certBasicConstraints.pathlen;
-
- const issuer = cert.issuer || {};
-
- // eslint-disable-next-line @typescript-eslint/no-use-before-define
- const signatureAlgorithm = extractSignatureAlgorithm(x509Cert);
+ const basicConstraints = x509Cert.getExtension(x509.BasicConstraintsExtension);
+ const subject = parseDistinguishedName(nodeCert.subject);
+ const issuer = parseDistinguishedName(nodeCert.issuer);
return {
- pemChain: [pem],
- fingerprint,
- fingerprintSha1,
- commonName: certField(subject.CN) || "",
- altNames,
- notBefore: new Date(cert.valid_from),
- notAfter: new Date(cert.valid_to),
- serialNumber: cert.serialNumber,
- subjectOrganization: certField(subject.O),
- subjectOrganizationalUnit: certField(subject.OU),
- subjectCountry: certField(subject.C),
- subjectState: certField(subject.ST),
- subjectLocality: certField(subject.L),
+ pemChain: [x509Cert.toString("pem")],
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
+ fingerprint: computeCertFingerprint(derBuffer),
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
+ fingerprintSha1: computeCertFingerprintSha1(derBuffer),
+ commonName: 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,
// eslint-disable-next-line @typescript-eslint/no-use-before-define
keyAlgorithm: extractKeyAlgorithm(x509Cert),
- signatureAlgorithm,
+ // eslint-disable-next-line @typescript-eslint/no-use-before-define
+ signatureAlgorithm: extractSignatureAlgorithm(x509Cert),
keyUsages,
extendedKeyUsages,
- isCA,
- pathLength,
- issuerCommonName: certField(issuer.CN),
- issuerOrganization: certField(issuer.O)
+ isCA: basicConstraints ? basicConstraints.ca : nodeCert.ca,
+ pathLength: basicConstraints?.pathLength,
+ issuerCommonName: issuer.CN,
+ issuerOrganization: issuer.O
};
} catch (error) {
- logger.error(error, "Failed to parse peer certificate");
+ logger.error(error, "Failed to parse discovered certificate");
return null;
}
};
@@ -572,7 +571,7 @@ export const resolveDomain = async (domain: string): Promise<string[]> => {
};
export const resolveTargets = async (
- targetConfig: TPkiDiscoveryTargetConfig,
+ targetConfig: TNetworkTargetConfig,
hasGateway = false
): Promise<TScanTarget[]> => {
const targets: TScanTarget[] = [];
@@ -660,6 +659,7 @@ export const computeLocationFingerprint = (
if (locationDetails.ipAddress) parts.push(`ip:${locationDetails.ipAddress}`);
if (locationDetails.fqdn) parts.push(`fqdn:${locationDetails.fqdn}`);
if (locationDetails.port) parts.push(`port:${locationDetails.port}`);
+ if (locationDetails.hostIdentifier) parts.push(`host:${locationDetails.hostIdentifier}`);
if (locationDetails.filePath) parts.push(`path:${locationDetails.filePath}`);
if (gatewayId) parts.push(`gw:${gatewayId}`);
diff --git a/backend/src/ee/services/pki-discovery/pki-discovery-host-fns.test.ts b/backend/src/ee/services/pki-discovery/pki-discovery-host-fns.test.ts
new file mode 100644
index 0000000000..01dea9f04c
--- /dev/null
+++ b/backend/src/ee/services/pki-discovery/pki-discovery-host-fns.test.ts
@@ -0,0 +1,157 @@
+import { TCertificateScanRpcFailure } from "@app/lib/gateway-v2/certificate-scan-rpc";
+
+import { computeLocationFingerprint } from "./pki-discovery-fns";
+import {
+ buildHostInstallationName,
+ CertificateScanResponseSchema,
+ describeCertificateScanFailure,
+ describeHostFileError,
+ normalizeHostIdentifier,
+ planHostFileImport,
+ summarizeHostScanIssues,
+ TCertificateScanFile
+} from "./pki-discovery-host-fns";
+import { LinuxServerTargetConfigSchema } from "./pki-discovery-schemas";
+import {
+ HostCertificateChainKind,
+ HostCertificateFileStatus,
+ HostFileImportAction,
+ PkiInstallationLocationType,
+ PkiKeystoreStatus
+} from "./pki-discovery-types";
+import { sanitizePkiInstallation } from "./pki-installation-service";
+
+const baseFile = (overrides: Partial<TCertificateScanFile>): TCertificateScanFile => ({
+ path: "/etc/ssl/a.pem",
+ realPath: "/etc/ssl/a.pem",
+ status: HostCertificateFileStatus.Ok,
+ isKeystore: false,
+ chains: [],
+ ...overrides
+});
+
+const leafChain = { kind: HostCertificateChainKind.Leaf, certificates: ["AQID"] };
+const caChain = { kind: HostCertificateChainKind.Ca, certificates: ["BAUG"] };
+const plan = (file: TCertificateScanFile, importStandaloneCaCertificates = false) =>
+ planHostFileImport(file, { importStandaloneCaCertificates });
+
+describe("planHostFileImport", () => {
+ test("imports leaf chains and only imports standalone CAs when asked", () => {
+ expect(plan(baseFile({ chains: [leafChain, caChain] }))).toMatchObject({
+ action: HostFileImportAction.Upsert,
+ locationType: PkiInstallationLocationType.Filesystem,
+ chainsToImport: [expect.anything()]
+ });
+ expect(plan(baseFile({ chains: [caChain] })).action).toBe(HostFileImportAction.Skip);
+ expect(plan(baseFile({ chains: [caChain] }), true).action).toBe(HostFileImportAction.Upsert);
+ });
+
+ test("keystore states", () => {
+ expect(plan(baseFile({ isKeystore: true, status: HostCertificateFileStatus.Locked }))).toMatchObject({
+ action: HostFileImportAction.Upsert,
+ keystoreStatus: PkiKeystoreStatus.Locked,
+ chainsToImport: []
+ });
+ expect(plan(baseFile({ isKeystore: true, chains: [caChain] }))).toMatchObject({
+ action: HostFileImportAction.Refresh,
+ keystoreStatus: PkiKeystoreStatus.Readable
+ });
+ expect(plan(baseFile({ status: HostCertificateFileStatus.NoCertificates })).action).toBe(HostFileImportAction.Skip);
+ });
+
+ test.each([HostCertificateFileStatus.AccessDenied, HostCertificateFileStatus.TooLarge])(
+ "skips %s files",
+ (status) => {
+ expect(plan(baseFile({ status }), true).action).toBe(HostFileImportAction.Skip);
+ }
+ );
+});
+
+describe("host identity", () => {
+ test("the same path on two hosts gives two installations", () => {
+ const fingerprint = (hostIdentifier: string) =>
+ computeLocationFingerprint(
+ PkiInstallationLocationType.Filesystem,
+ { hostIdentifier, filePath: "/etc/ssl/a.pem" },
+ "gw-1"
+ );
+ expect(fingerprint("10.0.1.12")).not.toBe(fingerprint("10.0.1.13"));
+ });
+
+ test("host identifiers keep non-default ports and bracket IPv6", () => {
+ expect(normalizeHostIdentifier(" Web-01.Example.com ", 22)).toBe("web-01.example.com");
+ expect(normalizeHostIdentifier("bastion.example.com", 2201)).toBe("bastion.example.com:2201");
+ expect(normalizeHostIdentifier("FD00::5", 2222)).toBe("[fd00::5]:2222");
+ });
+
+ test("installations are named after the hostname, or the address without one", () => {
+ expect(buildHostInstallationName("127.0.0.1:2222", "web-01", "/a.pem")).toBe("web-01:/a.pem");
+ expect(buildHostInstallationName("127.0.0.1:2222", "", "/a.pem")).toBe("127.0.0.1:2222:/a.pem");
+ });
+});
+
+describe("messages", () => {
+ test("file errors and scan issues read as product messages", () => {
+ expect(describeHostFileError(HostCertificateFileStatus.ReadFailed)).toBe("The file could not be read");
+ const response = CertificateScanResponseSchema.parse({
+ host: { hostname: "web-01" },
+ files: [
+ { path: "/a", realPath: "/a", status: "accessDenied", chains: null },
+ { path: "/b", realPath: "/b", status: "accessDenied", chains: null },
+ { path: "/c", realPath: "/c", status: "somethingNew", chains: [{ kind: "somethingNew", certificates: [] }] }
+ ],
+ deniedFolders: ["/etc/private"],
+ truncatedReason: "somethingNew"
+ });
+ expect(summarizeHostScanIssues("web-01", response)).toEqual([
+ "web-01: The SSH user can't read the file (/a and 1 more)",
+ "web-01: The file could not be read (/c)",
+ "web-01: The SSH user can't open 1 folder(s) (/etc/private)",
+ "web-01: The scan stopped early, so some files were not checked"
+ ]);
+ expect(response.files[2].chains[0].kind).toBe(HostCertificateChainKind.Ca);
+ });
+
+ test("gateway failures never expose the raw gateway text", () => {
+ const failure = (overrides: Partial<TCertificateScanRpcFailure>): TCertificateScanRpcFailure => ({
+ ok: false,
+ status: 502,
+ kind: null,
+ detail: "ssh: handshake failed",
+ ...overrides
+ });
+ expect(describeCertificateScanFailure(failure({ kind: "auth" }), "gw")).toBe(
+ "Could not sign in with the SSH connection's credentials"
+ );
+ expect(describeCertificateScanFailure(failure({}), "gw")).toBe("Gateway 'gw' could not scan the host");
+ });
+});
+
+describe("target config validation", () => {
+ const connectionId = "4b7d3b5e-2f7c-4a8e-9a55-0b3f3d6f1a10";
+ const issues = (config: Record<string, unknown>) => {
+ const parsed = LinuxServerTargetConfigSchema.safeParse(config);
+ return parsed.success ? [] : parsed.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`);
+ };
+
+ test("Linux Server jobs check their own fields", () => {
+ expect(issues({ connectionIds: [connectionId], searchFolderPaths: ["/etc"] })).toEqual([]);
+ expect(issues({ connectionIds: [connectionId], searchFolderPaths: ["/etc"], domains: ["example.com"] })).toEqual([
+ ": Unrecognized key(s) in object: 'domains'"
+ ]);
+ expect(issues({ connectionIds: [connectionId, connectionId], searchFolderPaths: ["/etc"] })).toEqual([
+ "connectionIds: Each SSH connection can be listed once"
+ ]);
+ });
+
+ test.each(["etc/ssl", "/etc/../root", "/etc\nssl"])("rejects folder %s", (folder) => {
+ expect(issues({ connectionIds: [connectionId], searchFolderPaths: [folder] })).not.toEqual([]);
+ });
+});
+
+test("installation responses never include the encrypted keystore password", () => {
+ expect(sanitizePkiInstallation({ id: "x", encryptedCredentials: Buffer.from("secret") })).toEqual({
+ id: "x",
+ hasKeystorePassword: true
+ });
+});
diff --git a/backend/src/ee/services/pki-discovery/pki-discovery-host-fns.ts b/backend/src/ee/services/pki-discovery/pki-discovery-host-fns.ts
new file mode 100644
index 0000000000..745d0273a4
--- /dev/null
+++ b/backend/src/ee/services/pki-discovery/pki-discovery-host-fns.ts
@@ -0,0 +1,189 @@
+import net from "net";
+import { z } from "zod";
+
+import { CertificateScanRpcStatus, TCertificateScanRpcFailure } from "@app/lib/gateway-v2/certificate-scan-rpc";
+
+import { DB_SHORT_VARCHAR_LIMIT, truncateString } from "./pki-discovery-scan-run-fns";
+import {
+ HostCertificateChainKind,
+ HostCertificateFileStatus,
+ HostFileImportAction,
+ HostScanTruncationReason,
+ PkiCertificateFileFormat,
+ PkiInstallationLocationType,
+ PkiKeystoreStatus
+} from "./pki-discovery-types";
+
+const CertificateScanChainSchema = z.object({
+ kind: z.nativeEnum(HostCertificateChainKind).catch(HostCertificateChainKind.Ca),
+ certificates: z.array(z.string()).default([])
+});
+
+const CertificateScanFileSchema = z.object({
+ path: z.string(),
+ realPath: z.string(),
+ status: z.nativeEnum(HostCertificateFileStatus).catch(HostCertificateFileStatus.ReadFailed),
+ format: z.nativeEnum(PkiCertificateFileFormat).optional().catch(undefined),
+ isKeystore: z.boolean().default(false),
+ chains: z
+ .array(CertificateScanChainSchema)
+ .nullish()
+ .transform((value) => value ?? [])
+});
+
+export const CertificateScanResponseSchema = z.object({
+ host: z.object({
+ hostname: z.string().default("")
+ }),
+ files: z
+ .array(CertificateScanFileSchema)
+ .nullish()
+ .transform((value) => value ?? []),
+ deniedFolders: z
+ .array(z.string())
+ .nullish()
+ .transform((value) => value ?? []),
+ truncatedReason: z.string().optional()
+});
+
+export type TCertificateScanFile = z.infer<typeof CertificateScanFileSchema>;
+export type TCertificateScanResponse = z.infer<typeof CertificateScanResponseSchema>;
+
+type THostFileImportPlan =
+ | { action: HostFileImportAction.Skip }
+ | {
+ action: HostFileImportAction.Refresh;
+ locationType: PkiInstallationLocationType.Keystore;
+ keystoreStatus: PkiKeystoreStatus;
+ }
+ | {
+ action: HostFileImportAction.Upsert;
+ locationType: PkiInstallationLocationType;
+ keystoreStatus?: PkiKeystoreStatus;
+ chainsToImport: Buffer[][];
+ };
+
+const refreshKeystoreOrSkip = (file: TCertificateScanFile): THostFileImportPlan =>
+ file.isKeystore
+ ? {
+ action: HostFileImportAction.Refresh,
+ locationType: PkiInstallationLocationType.Keystore,
+ keystoreStatus: PkiKeystoreStatus.Readable
+ }
+ : { action: HostFileImportAction.Skip };
+
+export const planHostFileImport = (
+ file: TCertificateScanFile,
+ { importStandaloneCaCertificates }: { importStandaloneCaCertificates: boolean }
+): THostFileImportPlan => {
+ switch (file.status) {
+ case HostCertificateFileStatus.Locked:
+ case HostCertificateFileStatus.PasswordFailed:
+ return {
+ action: HostFileImportAction.Upsert,
+ locationType: PkiInstallationLocationType.Keystore,
+ keystoreStatus:
+ file.status === HostCertificateFileStatus.Locked
+ ? PkiKeystoreStatus.Locked
+ : PkiKeystoreStatus.PasswordFailed,
+ chainsToImport: []
+ };
+ case HostCertificateFileStatus.Ok: {
+ const chainsToImport = file.chains
+ .filter((chain) => chain.kind === HostCertificateChainKind.Leaf || importStandaloneCaCertificates)
+ .map((chain) => chain.certificates.map((certificate) => Buffer.from(certificate, "base64")))
+ .filter((chain) => chain.length > 0);
+ if (chainsToImport.length === 0) return refreshKeystoreOrSkip(file);
+ return {
+ action: HostFileImportAction.Upsert,
+ locationType: file.isKeystore ? PkiInstallationLocationType.Keystore : PkiInstallationLocationType.Filesystem,
+ keystoreStatus: file.isKeystore ? PkiKeystoreStatus.Readable : undefined,
+ chainsToImport
+ };
+ }
+ case HostCertificateFileStatus.NoCertificates:
+ return refreshKeystoreOrSkip(file);
+ default:
+ return { action: HostFileImportAction.Skip };
+ }
+};
+
+export const sshConnectionWithoutGatewayMessage = (connectionName: string) =>
+ `SSH connection '${connectionName}' does not use a gateway. Linux Server discovery runs on the gateway, so assign one to the connection.`;
+
+export const buildHostInstallationName = (hostIdentifier: string, hostname: string | undefined, filePath: string) =>
+ truncateString(`${hostname?.trim() || hostIdentifier}:${filePath}`, DB_SHORT_VARCHAR_LIMIT);
+
+const DEFAULT_SSH_PORT = 22;
+
+export const normalizeHostIdentifier = (host: string, port?: number) => {
+ const normalized = host.trim().toLowerCase();
+ if (!port || port === DEFAULT_SSH_PORT) return normalized;
+ return net.isIPv6(normalized) ? `[${normalized}]:${port}` : `${normalized}:${port}`;
+};
+
+const FILE_STATUS_ERRORS: Partial<Record<HostCertificateFileStatus, string>> = {
+ [HostCertificateFileStatus.AccessDenied]: "The SSH user can't read the file",
+ [HostCertificateFileStatus.NotFound]: "The file no longer exists",
+ [HostCertificateFileStatus.TooLarge]: "The file is bigger than the job's largest file setting",
+ [HostCertificateFileStatus.ParseError]: "The file could not be parsed",
+ [HostCertificateFileStatus.Unsupported]: "The file uses a format or encryption that isn't supported",
+ [HostCertificateFileStatus.NoCertificates]: "The file holds no certificates",
+ [HostCertificateFileStatus.ReadFailed]: "The file could not be read"
+};
+
+export const describeHostFileError = (status: HostCertificateFileStatus) =>
+ FILE_STATUS_ERRORS[status] ?? "The file could not be read";
+
+const TRUNCATION_MESSAGES: Record<string, string | undefined> = {
+ [HostScanTruncationReason.MaxFiles]: "stopped after 5,000 files, so some files were not checked",
+ [HostScanTruncationReason.FileList]: "found too many files to list, so some files were not checked",
+ [HostScanTruncationReason.ResponseSize]:
+ "found more certificate data than one scan can return, so some files were not checked",
+ [HostScanTruncationReason.TimeLimit]: "ran out of time, so some files were not checked"
+};
+
+export const summarizeHostScanIssues = (hostIdentifier: string, response: TCertificateScanResponse): string[] => {
+ const issues: string[] = [];
+ const counts = new Map<HostCertificateFileStatus, string[]>();
+ response.files.forEach((file) => {
+ if (
+ !FILE_STATUS_ERRORS[file.status] ||
+ file.status === HostCertificateFileStatus.NotFound ||
+ file.status === HostCertificateFileStatus.NoCertificates
+ )
+ return;
+ counts.set(file.status, [...(counts.get(file.status) ?? []), file.realPath]);
+ });
+ counts.forEach((paths, status) => {
+ const more = paths.length > 1 ? ` and ${paths.length - 1} more` : "";
+ issues.push(`${hostIdentifier}: ${FILE_STATUS_ERRORS[status]} (${paths[0]}${more})`);
+ });
+ if (response.deniedFolders.length > 0) {
+ issues.push(
+ `${hostIdentifier}: The SSH user can't open ${response.deniedFolders.length} folder(s) (${response.deniedFolders[0]})`
+ );
+ }
+ if (response.truncatedReason) {
+ const reason = TRUNCATION_MESSAGES[response.truncatedReason] ?? "stopped early, so some files were not checked";
+ issues.push(`${hostIdentifier}: The scan ${reason}`);
+ }
+ return issues;
+};
+
+export const describeCertificateScanFailure = (failure: TCertificateScanRpcFailure, gatewayName: string): string => {
+ if (failure.status === CertificateScanRpcStatus.Timeout) {
+ return "The scan did not finish in time";
+ }
+ if (failure.status === CertificateScanRpcStatus.Busy) {
+ return `Gateway '${gatewayName}' is busy with other certificate scans. Try again later.`;
+ }
+ switch (failure.kind) {
+ case "auth":
+ return "Could not sign in with the SSH connection's credentials";
+ case "transport":
+ return `Could not reach the host from gateway '${gatewayName}'`;
+ default:
+ return `Gateway '${gatewayName}' could not scan the host`;
+ }
+};
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.ts
new file mode 100644
index 0000000000..25f25fc605
--- /dev/null
+++ b/backend/src/ee/services/pki-discovery/pki-discovery-host-scan-fns.test.ts
@@ -0,0 +1,112 @@
+import * as x509 from "@peculiar/x509";
+import { webcrypto } from "crypto";
+
+import { NotFoundError } from "@app/lib/errors";
+
+import { computeCertFingerprint } from "./pki-discovery-fns";
+import { scanHost, THostScanDeps, toHostScanErrorMessage, writeHostFile } from "./pki-discovery-host-scan-fns";
+import { HostCertificateChainKind, HostCertificateFileStatus } from "./pki-discovery-types";
+
+vi.mock("@app/lib/logger", () => ({ logger: { error: vi.fn(), info: vi.fn(), warn: vi.fn() } }));
+vi.mock("@app/lib/delay", () => ({ delay: vi.fn().mockResolvedValue(undefined) }));
+
+x509.cryptoProvider.set(webcrypto as Crypto);
+
+const host = {
+ connectionId: "5f0c8a52-1b9e-4c2d-8f4a-7e6d5c4b3a21",
+ hostIdentifier: "127.0.0.1:2222",
+ hostAddress: "127.0.0.1",
+ targetHost: "127.0.0.1",
+ targetPort: 2222,
+ gatewayId: "0b1c2d3e-4f50-4a6b-8c7d-9e0f1a2b3c4d",
+ gatewayName: "gw-east",
+ fingerprintGatewayKey: "0b1c2d3e-4f50-4a6b-8c7d-9e0f1a2b3c4d",
+ credentials: {} as Parameters<typeof scanHost>[0]["credentials"]
+};
+
+const request = {
+ searchFolderPaths: ["/etc/ssl"],
+ skipFolderPaths: [],
+ maxFolderDepth: 8,
+ maxFileSizeBytes: 1024,
+ filePaths: [],
+ keystorePasswords: []
+};
+
+const scanDeps = (admitted: boolean) => {
+ const keyStore = {
+ incrementByAndRefreshExpiryIfUnderLimit: vi.fn().mockResolvedValue(admitted ? 1 : -1),
+ decrementByOrDelete: vi.fn().mockResolvedValue(0)
+ };
+ const gatewayV2Service = { getPlatformConnectionDetailsByGatewayId: vi.fn().mockResolvedValue(null) };
+ return { keyStore, gatewayV2Service, deps: { keyStore, gatewayV2Service } as unknown as THostScanDeps };
+};
+
+describe("scanHost", () => {
+ test("gives up on a busy connection without reaching the gateway", async () => {
+ const { keyStore, gatewayV2Service, deps } = scanDeps(false);
+ await expect(scanHost(host, request, deps)).rejects.toThrow("The SSH connection is busy");
+ expect(gatewayV2Service.getPlatformConnectionDetailsByGatewayId).not.toHaveBeenCalled();
+ expect(keyStore.decrementByOrDelete).not.toHaveBeenCalled();
+ });
+
+ test("releases the connection slot when the scan fails", async () => {
+ const { keyStore, deps } = scanDeps(true);
+ await expect(scanHost(host, request, deps)).rejects.toBeInstanceOf(NotFoundError);
+ expect(keyStore.decrementByOrDelete).toHaveBeenCalledTimes(1);
+ });
+});
+
+test("unexpected errors are hidden behind a product message", () => {
+ expect(toHostScanErrorMessage(new NotFoundError({ message: "Gateway not found" }), "ctx")).toBe("Gateway not found");
+ expect(toHostScanErrorMessage(new Error('relation "x" does not exist'), "ctx")).toBe(
+ "The scan failed unexpectedly. Try again later."
+ );
+});
+
+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 der = Buffer.from(
+ (
+ await x509.X509CertificateGenerator.createSelfSigned({
+ serialNumber: "0a1b2c",
+ name: "CN=a.example.com",
+ notBefore: new Date("2026-01-01T00:00:00Z"),
+ notAfter: new Date("2027-01-01T00:00:00Z"),
+ keys,
+ signingAlgorithm: { name: "ECDSA", hash: "SHA-256" }
+ })
+ ).rawData
+ );
+ const tx = {};
+ const create = vi.fn().mockResolvedValue({ id: "installation-1" });
+ const upsertCertLink = vi.fn().mockResolvedValue(undefined);
+ const deps = {
+ pkiDiscoveryConfigDAL: { transaction: (callback: (trx: unknown) => unknown) => callback(tx) },
+ pkiCertificateInstallationDAL: { findByFingerprint: vi.fn().mockResolvedValue(undefined), create },
+ pkiCertificateInstallationCertDAL: { upsertCertLink }
+ } as unknown as THostScanDeps;
+ const ctx = {
+ projectId: "c2a1f0e9-8d7c-4b6a-9f5e-4d3c2b1a0f9e",
+ scanTime: new Date("2026-10-07T00:00:00Z"),
+ importStandaloneCaCertificates: false,
+ kmsEncryptor: vi.fn(),
+ certificateIdsByFingerprint: new Map([[computeCertFingerprint(der), "cert-1"]])
+ } as unknown as Parameters<typeof writeHostFile>[2];
+
+ await writeHostFile(
+ { ...host, hostname: "web-01" },
+ {
+ path: "/etc/ssl/a.pem",
+ realPath: "/etc/ssl/a.pem",
+ status: HostCertificateFileStatus.Ok,
+ isKeystore: false,
+ chains: [{ kind: HostCertificateChainKind.Leaf, certificates: [der.toString("base64")] }]
+ },
+ ctx,
+ deps
+ );
+
+ expect(create).toHaveBeenCalledWith(expect.objectContaining({ name: "web-01:/etc/ssl/a.pem" }), tx);
+ expect(upsertCertLink).toHaveBeenCalledWith("installation-1", "cert-1", { lastSeenAt: ctx.scanTime }, tx);
+});
diff --git a/backend/src/ee/services/pki-discovery/pki-discovery-host-scan-fns.ts b/backend/src/ee/services/pki-discovery/pki-discovery-host-scan-fns.ts
new file mode 100644
index 0000000000..cf441fd7ea
--- /dev/null
+++ b/backend/src/ee/services/pki-discovery/pki-discovery-host-scan-fns.ts
@@ -0,0 +1,640 @@
+import * as x509 from "@peculiar/x509";
+import { Knex } from "knex";
+import net from "net";
+import pLimit from "p-limit";
+
+import { verifyHostInputValidity } from "@app/ee/services/dynamic-secret/dynamic-secret-fns";
+import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";
+import { TGatewayV2DALFactory } from "@app/ee/services/gateway-v2/gateway-v2-dal";
+import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
+import { TKeyStoreFactory } from "@app/keystore/keystore";
+import { delay } from "@app/lib/delay";
+import { BadRequestError, NotFoundError } from "@app/lib/errors";
+import { callCertificateScan, TCertificateScanRequest } from "@app/lib/gateway-v2/certificate-scan-rpc";
+import { getMissingGatewayMessage } from "@app/lib/gateway-v2/gateway-errors";
+import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
+import { GatewayProxyProtocol } from "@app/lib/gateway-v2/types";
+import { logger } from "@app/lib/logger";
+import {
+ releaseAppConnectionConcurrency,
+ tryAdmitAppConnectionConcurrency
+} from "@app/services/app-connection/app-connection-concurrency-fns";
+import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";
+import { decryptAppConnectionCredentials } from "@app/services/app-connection/app-connection-fns";
+import { toSshExecCredentials } from "@app/services/app-connection/ssh/ssh-connection-fns";
+import { TSshConnectionConfig } from "@app/services/app-connection/ssh/ssh-connection-types";
+import { TCertificateBodyDALFactory } from "@app/services/certificate/certificate-body-dal";
+import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";
+import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+import { PKI_SYNC_CONNECTION_LOCK_RETRY } from "@app/services/pki-sync/pki-sync-enums";
+import { TProjectDALFactory } from "@app/services/project/project-dal";
+import { getProjectKmsCertificateKeyId } from "@app/services/project/project-fns";
+import { TTelemetryServiceFactory } from "@app/services/telemetry/telemetry-service";
+
+import { TPkiCertificateInstallationCertDALFactory } from "./pki-certificate-installation-cert-dal";
+import { TPkiCertificateInstallationDALFactory } from "./pki-certificate-installation-dal";
+import { TPkiDiscoveryConfigDALFactory } from "./pki-discovery-config-dal";
+import { computeLocationFingerprint, parseCertificateDer } from "./pki-discovery-fns";
+import {
+ buildHostInstallationName,
+ CertificateScanResponseSchema,
+ describeCertificateScanFailure,
+ normalizeHostIdentifier,
+ planHostFileImport,
+ sshConnectionWithoutGatewayMessage,
+ summarizeHostScanIssues,
+ TCertificateScanFile,
+ TCertificateScanResponse
+} from "./pki-discovery-host-fns";
+import { TPkiDiscoveryInstallationDALFactory } from "./pki-discovery-installation-dal";
+import { processDiscoveredCertificate, TKmsEncryptor } from "./pki-discovery-scan-fns";
+import { TPkiDiscoveryScanHistoryDALFactory } from "./pki-discovery-scan-history-dal";
+import {
+ discardScanRunIfDeleted,
+ failScanRun,
+ finishScanRun,
+ sendScanCompletedTelemetry,
+ startScanRun
+} from "./pki-discovery-scan-run-fns";
+import {
+ HostFileImportAction,
+ PkiDiscoveryScanStatus,
+ PkiDiscoveryType,
+ PkiInstallationLocationType,
+ PkiInstallationType,
+ PkiKeystoreStatus,
+ TLinuxServerTargetConfig,
+ TPkiInstallationLocationDetails,
+ TPkiInstallationMetadata
+} from "./pki-discovery-types";
+import { createPkiInstallationCredentialsDecryptor } from "./pki-installation-credentials-fns";
+
+const HOST_CONCURRENCY = 8;
+const BYTES_PER_KB = 1024;
+const UNEXPECTED_HOST_SCAN_ERROR = "The scan failed unexpectedly. Try again later.";
+
+export type THostScanDeps = {
+ pkiDiscoveryConfigDAL: TPkiDiscoveryConfigDALFactory;
+ pkiDiscoveryScanHistoryDAL: TPkiDiscoveryScanHistoryDALFactory;
+ pkiCertificateInstallationDAL: TPkiCertificateInstallationDALFactory;
+ pkiDiscoveryInstallationDAL: TPkiDiscoveryInstallationDALFactory;
+ pkiCertificateInstallationCertDAL: TPkiCertificateInstallationCertDALFactory;
+ certificateDAL: TCertificateDALFactory;
+ certificateBodyDAL: TCertificateBodyDALFactory;
+ projectDAL: Pick<TProjectDALFactory, "findOne" | "findById" | "updateById" | "transaction">;
+ kmsService: Pick<TKmsServiceFactory, "encryptWithKmsKey" | "generateKmsKey" | "createCipherPairWithDataKey">;
+ appConnectionDAL: Pick<TAppConnectionDALFactory, "findById" | "find">;
+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
+ gatewayV2DAL: Pick<TGatewayV2DALFactory, "findById">;
+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "selectGatewayFromPool">;
+ keyStore: Pick<TKeyStoreFactory, "incrementByAndRefreshExpiryIfUnderLimit" | "decrementByOrDelete">;
+ telemetryService: Pick<TTelemetryServiceFactory, "sendPostHogEvents">;
+};
+
+type TResolvedHost = {
+ connectionId: string;
+ hostIdentifier: string;
+ hostAddress: string;
+ targetHost: string;
+ targetPort: number;
+ gatewayId: string;
+ gatewayName: string;
+ fingerprintGatewayKey: string;
+ credentials: ReturnType<typeof toSshExecCredentials>;
+};
+
+type TScannedHost = TResolvedHost & { hostname: string };
+
+type TKeystorePassword = TCertificateScanRequest["keystorePasswords"][number];
+
+const derToPem = (der: Buffer) => new x509.X509Certificate(der).toString("pem");
+
+const canScanCertificates = (capabilities: unknown) =>
+ (capabilities as Record<string, unknown> | null)?.certificateScan === true;
+
+export const toHostScanErrorMessage = (error: unknown, logContext: string): string => {
+ if (error instanceof BadRequestError || error instanceof NotFoundError) {
+ logger.warn(`${logContext} [error=${error.message}]`);
+ return error.message;
+ }
+ logger.error(error, logContext);
+ return UNEXPECTED_HOST_SCAN_ERROR;
+};
+
+type TAppConnectionRow = Awaited<ReturnType<THostScanDeps["appConnectionDAL"]["findById"]>>;
+
+export const resolveHost = async (connection: TAppConnectionRow | undefined, orgId: string, deps: THostScanDeps) => {
+ if (!connection || connection.orgId !== orgId) {
+ throw new BadRequestError({ message: "The SSH connection no longer exists" });
+ }
+ if (!connection.gatewayId && !connection.gatewayPoolId) {
+ throw new BadRequestError({ message: sshConnectionWithoutGatewayMessage(connection.name) });
+ }
+
+ const credentials = (await decryptAppConnectionCredentials({
+ orgId: connection.orgId,
+ encryptedCredentials: connection.encryptedCredentials,
+ kmsService: deps.kmsService,
+ projectId: connection.projectId
+ })) as TSshConnectionConfig["credentials"];
+
+ const config = {
+ method: connection.method,
+ app: connection.app,
+ credentials,
+ gatewayId: connection.gatewayId,
+ gatewayPoolId: connection.gatewayPoolId,
+ orgId: connection.orgId
+ } as TSshConnectionConfig;
+
+ let gatewayId: string;
+ let gatewayName: string;
+ if (connection.gatewayPoolId) {
+ const selected = await deps.gatewayPoolService.selectGatewayFromPool({
+ poolId: connection.gatewayPoolId,
+ filter: (gateway) => canScanCertificates(gateway.capabilities),
+ unavailableMessage:
+ "No healthy gateway in the connection's pool supports certificate scanning. Update the pool's gateways to the latest version."
+ });
+ gatewayId = selected.id;
+ gatewayName = selected.name;
+ } else {
+ const gateway = await deps.gatewayV2DAL.findById(connection.gatewayId as string);
+ if (!gateway) {
+ throw new BadRequestError({ message: `The gateway of SSH connection '${connection.name}' no longer exists` });
+ }
+ if (!canScanCertificates(gateway.capabilities)) {
+ throw new BadRequestError({
+ message: `Gateway '${gateway.name}' is too old for certificate scanning. Update it to the latest version.`
+ });
+ }
+ gatewayId = gateway.id;
+ gatewayName = gateway.name;
+ }
+
+ const [targetHost] = await verifyHostInputValidity({
+ host: credentials.host,
+ isGateway: true,
+ isDynamicSecret: false
+ });
+
+ return {
+ connectionId: connection.id,
+ hostIdentifier: normalizeHostIdentifier(credentials.host, credentials.port),
+ hostAddress: credentials.host.trim().toLowerCase(),
+ targetHost,
+ targetPort: credentials.port,
+ gatewayId,
+ gatewayName,
+ fingerprintGatewayKey: connection.gatewayPoolId ?? gatewayId,
+ credentials: toSshExecCredentials(config)
+ } satisfies TResolvedHost;
+};
+
+export const loadKeystorePasswords = async (projectId: string, host: TResolvedHost, deps: THostScanDeps) => {
+ const rows = await deps.pkiCertificateInstallationDAL.findKeystoreCredentialsByHost(
+ projectId,
+ host.hostIdentifier,
+ deps.pkiCertificateInstallationDAL.primaryNode()
+ );
+ const passwords: TKeystorePassword[] = [];
+ const installationsOnThisHost = rows.filter(
+ (row) =>
+ row.locationFingerprint ===
+ computeLocationFingerprint(
+ PkiInstallationLocationType.Keystore,
+ {
+ hostIdentifier: host.hostIdentifier,
+ filePath: (row.locationDetails as TPkiInstallationLocationDetails).filePath
+ },
+ host.fingerprintGatewayKey
+ )
+ );
+ if (installationsOnThisHost.length === 0) return passwords;
+ const decrypt = await createPkiInstallationCredentialsDecryptor({ projectId, kmsService: deps.kmsService });
+ installationsOnThisHost.forEach((row) => {
+ const { filePath } = row.locationDetails as TPkiInstallationLocationDetails;
+ if (!row.encryptedCredentials || !filePath) return;
+ const { keystorePassword } = decrypt(row.encryptedCredentials);
+ if (keystorePassword !== undefined) passwords.push({ path: filePath, password: keystorePassword });
+ });
+ return passwords;
+};
+
+const admitConnectionScanSlot = async (connectionId: string, deps: THostScanDeps): Promise<boolean> => {
+ const { retryCount, retryDelay, retryJitter } = PKI_SYNC_CONNECTION_LOCK_RETRY;
+ for (let attempt = 0; attempt <= retryCount; attempt += 1) {
+ // eslint-disable-next-line no-await-in-loop
+ if (attempt > 0) await delay(retryDelay + Math.random() * retryJitter);
+ // eslint-disable-next-line no-await-in-loop
+ if (await tryAdmitAppConnectionConcurrency(deps.keyStore, connectionId)) return true;
+ }
+ return false;
+};
+
+const runCertificateScan = async (
+ host: TResolvedHost,
+ request: TCertificateScanRequest,
+ deps: THostScanDeps
+): Promise<TCertificateScanResponse> => {
+ const connectionDetails = await deps.gatewayV2Service.getPlatformConnectionDetailsByGatewayId({
+ gatewayId: host.gatewayId,
+ targetHost: host.targetHost,
+ targetPort: host.targetPort
+ });
+ if (!connectionDetails) {
+ throw new NotFoundError({ message: getMissingGatewayMessage(host.gatewayId) });
+ }
+
+ const response = await withGatewayV2Proxy(
+ (proxyPort) => callCertificateScan({ port: proxyPort, credentials: host.credentials, request }),
+ { protocol: GatewayProxyProtocol.Discovery, longLived: true, ...connectionDetails }
+ );
+
+ if (!response.ok) {
+ logger.warn(
+ `Certificate scan RPC failed [connectionId=${host.connectionId}] [gatewayId=${host.gatewayId}] [status=${response.status}] [kind=${response.kind ?? "none"}] [detail=${response.detail}]`
+ );
+ throw new BadRequestError({
+ message: describeCertificateScanFailure(response, host.gatewayName)
+ });
+ }
+ const parsed = CertificateScanResponseSchema.safeParse(response.result);
+ if (!parsed.success) {
+ logger.warn(
+ { issues: parsed.error.issues },
+ `Certificate scan result did not match the expected shape [connectionId=${host.connectionId}] [gatewayId=${host.gatewayId}]`
+ );
+ throw new BadRequestError({ message: "The gateway returned a scan result that could not be read" });
+ }
+ return parsed.data;
+};
+
+export const scanHost = async (
+ host: TResolvedHost,
+ request: TCertificateScanRequest,
+ deps: THostScanDeps
+): Promise<TCertificateScanResponse> => {
+ if (!(await admitConnectionScanSlot(host.connectionId, deps))) {
+ throw new BadRequestError({ message: "The SSH connection is busy with other jobs. Try again later." });
+ }
+ try {
+ return await runCertificateScan(host, request, deps);
+ } finally {
+ await releaseAppConnectionConcurrency(deps.keyStore, host.connectionId).catch((error: unknown) =>
+ logger.error(error, `Failed to release the connection scan slot [connectionId=${host.connectionId}]`)
+ );
+ }
+};
+
+type TWriteContext = {
+ projectId: string;
+ discoveryId?: string;
+ scanTime: Date;
+ importStandaloneCaCertificates: boolean;
+ kmsEncryptor: TKmsEncryptor;
+ certificateIdsByFingerprint: Map<string, string>;
+ targetInstallationId?: string;
+};
+
+const findTargetInstallation = (ctx: TWriteContext, fingerprint: string, deps: THostScanDeps, tx: Knex) =>
+ ctx.targetInstallationId
+ ? deps.pkiCertificateInstallationDAL.findById(ctx.targetInstallationId, tx)
+ : deps.pkiCertificateInstallationDAL.findByFingerprint(ctx.projectId, fingerprint, tx);
+
+const buildHostLocationDetails = (host: TScannedHost, file: TCertificateScanFile): TPkiInstallationLocationDetails => ({
+ hostIdentifier: host.hostIdentifier,
+ filePath: file.realPath,
+ connectionId: host.connectionId,
+ ...(net.isIP(host.hostAddress) !== 0 && { ipAddress: host.hostAddress }),
+ ...(host.hostname && { hostname: host.hostname }),
+ ...(file.format && { format: file.format }),
+ gatewayName: host.gatewayName
+});
+
+const importCertificateChains = async (
+ host: TScannedHost,
+ file: TCertificateScanFile,
+ chains: Buffer[][],
+ ctx: TWriteContext,
+ deps: THostScanDeps
+) => {
+ const certificateIds: string[] = [];
+ for (const chain of chains) {
+ const parsed = parseCertificateDer(chain[0]);
+ if (!parsed) continue; // eslint-disable-line no-continue
+ const knownCertificateId = ctx.certificateIdsByFingerprint.get(parsed.fingerprint);
+ if (knownCertificateId) {
+ certificateIds.push(knownCertificateId);
+ continue; // eslint-disable-line no-continue
+ }
+ parsed.pemChain = [...parsed.pemChain, ...chain.slice(1).map(derToPem)];
+ // eslint-disable-next-line no-await-in-loop
+ const certificateId = await processDiscoveredCertificate(
+ parsed,
+ ctx.projectId,
+ {
+ certificateDAL: deps.certificateDAL,
+ certificateBodyDAL: deps.certificateBodyDAL,
+ kmsEncryptor: ctx.kmsEncryptor
+ },
+ {
+ discoveredBy: ctx.discoveryId,
+ hostIdentifier: host.hostIdentifier,
+ hostname: host.hostname,
+ filePath: file.realPath,
+ format: file.format,
+ discoveredAt: ctx.scanTime.toISOString(),
+ issuerCommonName: parsed.issuerCommonName,
+ issuerOrganization: parsed.issuerOrganization
+ }
+ );
+ if (certificateId) {
+ ctx.certificateIdsByFingerprint.set(parsed.fingerprint, certificateId);
+ certificateIds.push(certificateId);
+ }
+ }
+ return certificateIds;
+};
+
+const upsertInstallationWithLinks = async (
+ host: TScannedHost,
+ file: TCertificateScanFile,
+ {
+ fingerprint,
+ locationType,
+ keystoreStatus,
+ certificateIds,
+ refreshOnly
+ }: {
+ fingerprint: string;
+ locationType: PkiInstallationLocationType;
+ keystoreStatus?: PkiKeystoreStatus;
+ certificateIds: string[];
+ refreshOnly: boolean;
+ },
+ ctx: TWriteContext,
+ deps: THostScanDeps
+) => {
+ const locationDetails = buildHostLocationDetails(host, file);
+
+ return deps.pkiDiscoveryConfigDAL.transaction(async (tx) => {
+ let installation = await findTargetInstallation(ctx, fingerprint, deps, tx);
+ if (!installation && refreshOnly) return undefined;
+ const previousMetadata = (installation?.metadata as TPkiInstallationMetadata | null) ?? {};
+ const metadata: TPkiInstallationMetadata = {
+ ...previousMetadata,
+ ...(keystoreStatus && { keystoreStatus }),
+ ...(keystoreStatus === PkiKeystoreStatus.Readable && { lastReadAt: ctx.scanTime.toISOString() }),
+ lastCheckedAt: new Date().toISOString(),
+ lastError: undefined
+ };
+
+ if (!installation) {
+ installation = await deps.pkiCertificateInstallationDAL.create(
+ {
+ projectId: ctx.projectId,
+ locationType,
+ locationDetails,
+ locationFingerprint: fingerprint,
+ name: buildHostInstallationName(host.hostIdentifier, host.hostname, file.realPath),
+ type: PkiInstallationType.Server,
+ metadata,
+ lastSeenAt: ctx.scanTime
+ },
+ tx
+ );
+ } else {
+ await deps.pkiCertificateInstallationDAL.updateById(
+ installation.id,
+ { lastSeenAt: ctx.scanTime, locationDetails, locationType, metadata },
+ tx
+ );
+ }
+
+ if (ctx.discoveryId) {
+ const link = await deps.pkiDiscoveryInstallationDAL.upsertLink(
+ ctx.discoveryId,
+ installation.id,
+ ctx.scanTime,
+ tx
+ );
+ if (!link) return undefined;
+ }
+
+ for (const certificateId of certificateIds) {
+ // eslint-disable-next-line no-await-in-loop
+ await deps.pkiCertificateInstallationCertDAL.upsertCertLink(
+ installation.id,
+ certificateId,
+ { lastSeenAt: ctx.scanTime },
+ tx
+ );
+ }
+ return installation.id;
+ });
+};
+
+export const writeHostFile = async (
+ host: TScannedHost,
+ file: TCertificateScanFile,
+ ctx: TWriteContext,
+ deps: THostScanDeps
+): Promise<{ installationId?: string; certificateIds: string[] }> => {
+ const plan = planHostFileImport(file, { importStandaloneCaCertificates: ctx.importStandaloneCaCertificates });
+ if (plan.action === HostFileImportAction.Skip) return { certificateIds: [] };
+
+ const fingerprint = computeLocationFingerprint(
+ plan.locationType,
+ { hostIdentifier: host.hostIdentifier, filePath: file.realPath },
+ host.fingerprintGatewayKey
+ );
+
+ const certificateIds =
+ plan.action === HostFileImportAction.Refresh
+ ? []
+ : await importCertificateChains(host, file, plan.chainsToImport, ctx, deps);
+ const installationId = await upsertInstallationWithLinks(
+ host,
+ file,
+ {
+ fingerprint,
+ locationType: plan.locationType,
+ keystoreStatus: plan.keystoreStatus,
+ certificateIds,
+ refreshOnly: plan.action === HostFileImportAction.Refresh
+ },
+ ctx,
+ deps
+ );
+
+ return { installationId, certificateIds };
+};
+
+export const buildScanRequest = (
+ targetConfig: TLinuxServerTargetConfig,
+ keystorePasswords: TKeystorePassword[],
+ filePaths: string[] = []
+): TCertificateScanRequest => ({
+ searchFolderPaths: targetConfig.searchFolderPaths,
+ skipFolderPaths: targetConfig.skipFolderPaths,
+ maxFolderDepth: targetConfig.maxFolderDepth,
+ maxFileSizeBytes: targetConfig.maxFileSizeKb * BYTES_PER_KB,
+ filePaths,
+ keystorePasswords
+});
+
+type TLinuxServerScanRun = {
+ discoveryId: string;
+ projectId: string;
+ orgId: string;
+ targetConfig: TLinuxServerTargetConfig;
+ ctx: TWriteContext;
+ writeLimit: ReturnType<typeof pLimit>;
+ certificateIds: Set<string>;
+ installationIds: Set<string>;
+};
+
+type THostScanOutcome = { issues: string[]; failure?: { label: string; message: string } };
+
+const scanConnection = async (
+ connection: TAppConnectionRow | undefined,
+ label: string,
+ run: TLinuxServerScanRun,
+ deps: THostScanDeps
+): Promise<THostScanOutcome> => {
+ let hostLabel = label;
+ const issues: string[] = [];
+ try {
+ const host = await resolveHost(connection, run.orgId, deps);
+ hostLabel = host.hostIdentifier;
+ const keystorePasswords = await loadKeystorePasswords(run.projectId, host, deps);
+ const response = await scanHost(host, buildScanRequest(run.targetConfig, keystorePasswords), deps);
+
+ issues.push(...summarizeHostScanIssues(host.hostIdentifier, response));
+
+ await run.writeLimit(async () => {
+ for (const file of response.files) {
+ // eslint-disable-next-line no-await-in-loop
+ const result = await writeHostFile({ ...host, hostname: response.host.hostname }, file, run.ctx, deps);
+ if (result.installationId) run.installationIds.add(result.installationId);
+ result.certificateIds.forEach((id) => run.certificateIds.add(id));
+ }
+ });
+ return { issues };
+ } catch (error) {
+ const message = toHostScanErrorMessage(
+ error,
+ `Linux Server discovery host failed [discoveryId=${run.discoveryId}] [connection=${label}]`
+ );
+ return { issues, failure: { label: hostLabel, message } };
+ }
+};
+
+export const executeLinuxServerScan = async (discoveryId: string, deps: THostScanDeps): Promise<void> => {
+ const { pkiDiscoveryConfigDAL } = deps;
+ const startedAt = new Date();
+ let scanHistoryId: string | undefined;
+
+ try {
+ const discoveryConfig = await pkiDiscoveryConfigDAL.findById(discoveryId);
+ if (!discoveryConfig) {
+ throw new Error(`Discovery config not found: ${discoveryId}`);
+ }
+ const project = await deps.projectDAL.findById(discoveryConfig.projectId);
+ const targetConfig = discoveryConfig.targetConfig as TLinuxServerTargetConfig;
+
+ logger.info(
+ `Linux Server discovery scan starting [discoveryId=${discoveryId}] [projectId=${discoveryConfig.projectId}]`
+ );
+
+ const certificateKmsKeyId = await getProjectKmsCertificateKeyId({
+ projectId: discoveryConfig.projectId,
+ projectDAL: deps.projectDAL,
+ kmsService: deps.kmsService
+ });
+ const kmsEncryptor = await deps.kmsService.encryptWithKmsKey({ kmsId: certificateKmsKeyId });
+
+ scanHistoryId = await startScanRun(discoveryId, startedAt, deps);
+
+ const hostLimit = pLimit(HOST_CONCURRENCY);
+ const run: TLinuxServerScanRun = {
+ discoveryId,
+ projectId: discoveryConfig.projectId,
+ orgId: project.orgId,
+ targetConfig,
+ ctx: {
+ projectId: discoveryConfig.projectId,
+ discoveryId,
+ scanTime: startedAt,
+ importStandaloneCaCertificates: targetConfig.importStandaloneCaCertificates,
+ kmsEncryptor,
+ certificateIdsByFingerprint: new Map()
+ },
+ writeLimit: pLimit(1),
+ certificateIds: new Set(),
+ installationIds: new Set()
+ };
+
+ const connectionsById = new Map(
+ (await deps.appConnectionDAL.find({ $in: { id: targetConfig.connectionIds } })).map((connection) => [
+ connection.id,
+ connection
+ ])
+ );
+
+ const outcomes = await Promise.all(
+ targetConfig.connectionIds.map((connectionId) => {
+ const connection = connectionsById.get(connectionId);
+ return hostLimit(() => scanConnection(connection, connection?.name ?? "Deleted connection", run, deps));
+ })
+ );
+
+ if (await discardScanRunIfDeleted(discoveryId, scanHistoryId, deps)) return;
+
+ const completedAt = new Date();
+ const hostFailures = new Map<string, string[]>();
+ outcomes.forEach(({ failure }) => {
+ if (failure) hostFailures.set(failure.message, [...(hostFailures.get(failure.message) ?? []), failure.label]);
+ });
+ const failedHosts = outcomes.filter(({ failure }) => failure).length;
+ const allHostsFailed = failedHosts > 0 && failedHosts === targetConfig.connectionIds.length;
+ const finalStatus = allHostsFailed ? PkiDiscoveryScanStatus.Failed : PkiDiscoveryScanStatus.Completed;
+ const failureIssues = [...hostFailures.entries()].map(([message, labels]) => `${labels.join(", ")}: ${message}`);
+ const allIssues = [...failureIssues, ...outcomes.flatMap(({ issues }) => issues)];
+ const errorMessage = allIssues.length > 0 ? allIssues.join("; ") : null;
+
+ await finishScanRun(
+ {
+ discoveryId,
+ scanHistoryId,
+ status: finalStatus,
+ completedAt,
+ targetsScannedCount: targetConfig.connectionIds.length,
+ certificatesFoundCount: run.certificateIds.size,
+ installationsFoundCount: run.installationIds.size,
+ errorMessage
+ },
+ deps
+ );
+
+ await sendScanCompletedTelemetry(deps.telemetryService, {
+ discoveryId,
+ discoveryType: PkiDiscoveryType.LinuxServer,
+ projectId: run.projectId,
+ orgId: run.orgId,
+ status: finalStatus,
+ certificatesFound: run.certificateIds.size,
+ installationsFound: run.installationIds.size,
+ durationMs: completedAt.getTime() - startedAt.getTime()
+ });
+
+ logger.info(
+ `Linux Server discovery scan finished [discoveryId=${discoveryId}] [status=${finalStatus}] [certificates=${run.certificateIds.size}] [installations=${run.installationIds.size}]`
+ );
+ } catch (error) {
+ const message = toHostScanErrorMessage(error, `Linux Server discovery scan failed [discoveryId=${discoveryId}]`);
+ await failScanRun(discoveryId, scanHistoryId, new Error(message), deps);
+ throw error;
+ }
+};
diff --git a/backend/src/ee/services/pki-discovery/pki-discovery-installation-dal.ts b/backend/src/ee/services/pki-discovery/pki-discovery-installation-dal.ts
index c45ad5fd11..ffee420852 100644
--- a/backend/src/ee/services/pki-discovery/pki-discovery-installation-dal.ts
+++ b/backend/src/ee/services/pki-discovery/pki-discovery-installation-dal.ts
@@ -45,9 +45,23 @@ export const pkiDiscoveryInstallationDALFactory = (db: TDbClient) => {
}
};
+ const findLatestLinkByInstallationId = async (installationId: string, tx?: Knex) => {
+ try {
+ const doc = await (tx || db.replicaNode())(TableName.PkiDiscoveryInstallation)
+ .where({ installationId })
+ .orderBy("lastScannedAt", "desc")
+ .first();
+
+ return doc;
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Find latest PKI discovery link by installation ID" });
+ }
+ };
+
return {
...pkiDiscoveryInstallationOrm,
findByDiscoveryId,
+ findLatestLinkByInstallationId,
upsertLink
};
};
diff --git a/backend/src/ee/services/pki-discovery/pki-discovery-queue.ts b/backend/src/ee/services/pki-discovery/pki-discovery-queue.ts
index ddc6a4894f..6be01d91de 100644
--- a/backend/src/ee/services/pki-discovery/pki-discovery-queue.ts
+++ b/backend/src/ee/services/pki-discovery/pki-discovery-queue.ts
@@ -1,9 +1,11 @@
import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";
import { TGatewayV2DALFactory } from "@app/ee/services/gateway-v2/gateway-v2-dal";
import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
+import { TKeyStoreFactory } from "@app/keystore/keystore";
import { CronJobName, TCronJobFactory } from "@app/lib/cron/cron-job";
import { logger } from "@app/lib/logger";
import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue/queue-service";
+import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";
import { TCertificateBodyDALFactory } from "@app/services/certificate/certificate-body-dal";
import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
@@ -13,7 +15,9 @@ import { TTelemetryServiceFactory } from "@app/services/telemetry/telemetry-serv
import { TPkiCertificateInstallationCertDALFactory } from "./pki-certificate-installation-cert-dal";
import { TPkiCertificateInstallationDALFactory } from "./pki-certificate-installation-dal";
import { TPkiDiscoveryConfigDALFactory } from "./pki-discovery-config-dal";
+import { executeLinuxServerScan } from "./pki-discovery-host-scan-fns";
import { TPkiDiscoveryInstallationDALFactory } from "./pki-discovery-installation-dal";
+import { rescanInstallation } from "./pki-discovery-rescan-fns";
import { executeScan } from "./pki-discovery-scan-fns";
import { TPkiDiscoveryScanHistoryDALFactory } from "./pki-discovery-scan-history-dal";
import { PkiDiscoveryType } from "./pki-discovery-types";
@@ -26,16 +30,20 @@ type TPkiDiscoveryQueueFactoryDep = {
pkiCertificateInstallationCertDAL: TPkiCertificateInstallationCertDALFactory;
certificateDAL: TCertificateDALFactory;
certificateBodyDAL: TCertificateBodyDALFactory;
- projectDAL: Pick<TProjectDALFactory, "findOne" | "updateById" | "transaction">;
- kmsService: Pick<TKmsServiceFactory, "encryptWithKmsKey" | "generateKmsKey">;
+ projectDAL: Pick<TProjectDALFactory, "findOne" | "findById" | "updateById" | "transaction">;
+ kmsService: Pick<TKmsServiceFactory, "encryptWithKmsKey" | "generateKmsKey" | "createCipherPairWithDataKey">;
+ appConnectionDAL: Pick<TAppConnectionDALFactory, "findById" | "find">;
queueService: TQueueServiceFactory;
cronJob: TCronJobFactory;
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
gatewayV2DAL: Pick<TGatewayV2DALFactory, "findById">;
- gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;
+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId" | "selectGatewayFromPool">;
telemetryService: Pick<TTelemetryServiceFactory, "sendPostHogEvents">;
+ keyStore: Pick<TKeyStoreFactory, "incrementByAndRefreshExpiryIfUnderLimit" | "decrementByOrDelete">;
};
+const RESCAN_WORKER_CONCURRENCY = 3;
+
export type TPkiDiscoveryQueueFactory = ReturnType<typeof pkiDiscoveryQueueFactory>;
export const pkiDiscoveryQueueFactory = ({
@@ -48,13 +56,33 @@ export const pkiDiscoveryQueueFactory = ({
certificateBodyDAL,
projectDAL,
kmsService,
+ appConnectionDAL,
queueService,
cronJob,
gatewayV2Service,
gatewayV2DAL,
gatewayPoolService,
- telemetryService
+ telemetryService,
+ keyStore
}: TPkiDiscoveryQueueFactoryDep) => {
+ const scanDeps = {
+ appConnectionDAL,
+ pkiDiscoveryConfigDAL,
+ pkiDiscoveryScanHistoryDAL,
+ pkiCertificateInstallationDAL,
+ pkiDiscoveryInstallationDAL,
+ pkiCertificateInstallationCertDAL,
+ certificateDAL,
+ certificateBodyDAL,
+ projectDAL,
+ kmsService,
+ gatewayV2Service,
+ gatewayV2DAL,
+ gatewayPoolService,
+ telemetryService,
+ keyStore
+ };
+
const startPkiDiscoveryScanQueue = () => {
queueService.start(QueueName.PkiDiscoveryScan, async (job) => {
try {
@@ -69,26 +97,13 @@ export const pkiDiscoveryQueueFactory = ({
const discoveryType = (discoveryConfig.discoveryType as PkiDiscoveryType) || PkiDiscoveryType.Network;
- const scanDeps = {
- pkiDiscoveryConfigDAL,
- pkiDiscoveryScanHistoryDAL,
- pkiCertificateInstallationDAL,
- pkiDiscoveryInstallationDAL,
- pkiCertificateInstallationCertDAL,
- certificateDAL,
- certificateBodyDAL,
- projectDAL,
- kmsService,
- gatewayV2Service,
- gatewayV2DAL,
- gatewayPoolService,
- telemetryService
- };
-
switch (discoveryType) {
case PkiDiscoveryType.Network:
await executeScan(discoveryId, scanDeps);
break;
+ case PkiDiscoveryType.LinuxServer:
+ await executeLinuxServerScan(discoveryId, scanDeps);
+ break;
default:
throw new Error(`Unsupported discovery type: ${discoveryType as string}`);
}
@@ -111,6 +126,19 @@ export const pkiDiscoveryQueueFactory = ({
}
});
+ queueService.start(
+ QueueName.PkiDiscoveryRescan,
+ async (job) => {
+ try {
+ await rescanInstallation(job.data.installationId, scanDeps);
+ } catch (error) {
+ logger.error({ error, jobName: job.name, jobId: job.id }, "PKI installation rescan job failed");
+ throw error;
+ }
+ },
+ { concurrency: RESCAN_WORKER_CONCURRENCY }
+ );
+
cronJob.register({
name: CronJobName.PkiDiscoveryScheduledScan,
pattern: "0 2 * * *",
@@ -123,6 +151,20 @@ export const pkiDiscoveryQueueFactory = ({
});
};
+ const queueInstallationRescan = async (installationId: string) => {
+ await queueService.queue(
+ QueueName.PkiDiscoveryRescan,
+ QueueJobs.PkiDiscoveryRescanInstallation,
+ { installationId },
+ {
+ jobId: `pki-installation-rescan-${installationId}-${Date.now()}`,
+ attempts: 1,
+ removeOnComplete: true,
+ removeOnFail: true
+ }
+ );
+ };
+
const queuePkiDiscoveryScan = async (discoveryId: string) => {
const jobId = `pki-discovery-scan-${discoveryId}-${Date.now()}`;
await queueService.queue(
@@ -140,6 +182,7 @@ export const pkiDiscoveryQueueFactory = ({
return {
startPkiDiscoveryScanQueue,
- queuePkiDiscoveryScan
+ queuePkiDiscoveryScan,
+ queueInstallationRescan
};
};
diff --git a/backend/src/ee/services/pki-discovery/pki-discovery-rescan-fns.test.ts b/backend/src/ee/services/pki-discovery/pki-discovery-rescan-fns.test.ts
new file mode 100644
index 0000000000..fc463b562c
--- /dev/null
+++ b/backend/src/ee/services/pki-discovery/pki-discovery-rescan-fns.test.ts
@@ -0,0 +1,44 @@
+import { THostScanDeps } from "./pki-discovery-host-scan-fns";
+import { rescanInstallation } from "./pki-discovery-rescan-fns";
+import { PkiInstallationLocationType } from "./pki-discovery-types";
+
+vi.mock("@app/lib/logger", () => ({ logger: { error: vi.fn(), info: vi.fn(), warn: vi.fn() } }));
+
+describe("rescanInstallation", () => {
+ test("reads the installation on the primary, since its password was just written", async () => {
+ const primary = { kind: "primary" };
+ const findById = vi.fn().mockResolvedValue(undefined);
+ const deps = {
+ pkiCertificateInstallationDAL: { findById, primaryNode: vi.fn(() => primary) }
+ } as unknown as THostScanDeps;
+
+ await rescanInstallation("8d3b0b0e-6a1f-4f4e-9c55-2f1f7a0b6c10", deps);
+
+ expect(findById).toHaveBeenCalledWith("8d3b0b0e-6a1f-4f4e-9c55-2f1f7a0b6c10", primary);
+ });
+
+ test("an unexpected failure is recorded as a product message, never the raw error", async () => {
+ const installation = {
+ id: "8d3b0b0e-6a1f-4f4e-9c55-2f1f7a0b6c10",
+ projectId: "c2a1f0e9-8d7c-4b6a-9f5e-4d3c2b1a0f9e",
+ locationType: PkiInstallationLocationType.Keystore,
+ locationDetails: { connectionId: "5f0c8a52-1b9e-4c2d-8f4a-7e6d5c4b3a21", filePath: "/etc/ssl/app.p12" },
+ metadata: {}
+ };
+ const updateById = vi.fn().mockResolvedValue(undefined);
+ const deps = {
+ pkiCertificateInstallationDAL: {
+ findById: vi.fn().mockResolvedValue(installation),
+ primaryNode: vi.fn(),
+ updateById
+ },
+ projectDAL: { findById: vi.fn().mockRejectedValue(new Error("connect ECONNREFUSED 10.0.0.4:5432")) }
+ } as unknown as THostScanDeps;
+
+ await rescanInstallation(installation.id, deps);
+
+ expect(updateById).toHaveBeenCalledWith(installation.id, {
+ metadata: expect.objectContaining({ lastError: "The scan failed unexpectedly. Try again later." }) as unknown
+ });
+ });
+});
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.ts
new file mode 100644
index 0000000000..74b16f63f6
--- /dev/null
+++ b/backend/src/ee/services/pki-discovery/pki-discovery-rescan-fns.ts
@@ -0,0 +1,92 @@
+import { getProjectKmsCertificateKeyId } from "@app/services/project/project-fns";
+
+import { describeHostFileError } from "./pki-discovery-host-fns";
+import {
+ buildScanRequest,
+ loadKeystorePasswords,
+ resolveHost,
+ scanHost,
+ THostScanDeps,
+ toHostScanErrorMessage,
+ writeHostFile
+} 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";
+
+const recordInstallationError = async (installationId: string, message: string, deps: THostScanDeps) => {
+ const installation = await deps.pkiCertificateInstallationDAL.findById(
+ installationId,
+ deps.pkiCertificateInstallationDAL.primaryNode()
+ );
+ if (!installation) return;
+ const metadata = {
+ ...((installation.metadata as TPkiInstallationMetadata | null) ?? {}),
+ lastCheckedAt: new Date().toISOString(),
+ lastError: truncateString(message, DB_SHORT_VARCHAR_LIMIT) ?? undefined
+ };
+ await deps.pkiCertificateInstallationDAL.updateById(installation.id, { metadata });
+};
+
+const buildFallbackTargetConfig = (connectionId: string): TLinuxServerTargetConfig => ({
+ connectionIds: [connectionId],
+ searchFolderPaths: [],
+ ...LinuxServerTargetConfigSchema.omit({ connectionIds: true, searchFolderPaths: true }).parse({})
+});
+
+export const rescanInstallation = async (installationId: string, deps: THostScanDeps): Promise<void> => {
+ const installation = await deps.pkiCertificateInstallationDAL.findById(
+ installationId,
+ deps.pkiCertificateInstallationDAL.primaryNode()
+ );
+ if (!installation) return;
+
+ const details = installation.locationDetails as { connectionId: string; filePath: string };
+
+ try {
+ const project = await deps.projectDAL.findById(installation.projectId);
+ const latestLink = await deps.pkiDiscoveryInstallationDAL.findLatestLinkByInstallationId(installationId);
+ const discoveryConfig = latestLink ? await deps.pkiDiscoveryConfigDAL.findById(latestLink.discoveryId) : undefined;
+ const targetConfig =
+ (discoveryConfig?.targetConfig as TLinuxServerTargetConfig | undefined) ??
+ buildFallbackTargetConfig(details.connectionId);
+
+ const connection = await deps.appConnectionDAL.findById(details.connectionId);
+ const host = await resolveHost(connection, project.orgId, deps);
+ const keystorePasswords = await loadKeystorePasswords(installation.projectId, host, deps);
+
+ const response = await scanHost(host, buildScanRequest(targetConfig, keystorePasswords, [details.filePath]), deps);
+ const file = response.files.find((f) => f.path === details.filePath || f.realPath === details.filePath);
+ if (!file) {
+ await recordInstallationError(installation.id, describeHostFileError(HostCertificateFileStatus.NotFound), deps);
+ return;
+ }
+
+ const certificateKmsKeyId = await getProjectKmsCertificateKeyId({
+ projectId: installation.projectId,
+ projectDAL: deps.projectDAL,
+ kmsService: deps.kmsService
+ });
+ const kmsEncryptor = await deps.kmsService.encryptWithKmsKey({ kmsId: certificateKmsKeyId });
+
+ const written = await writeHostFile(
+ { ...host, hostname: response.host.hostname },
+ file,
+ {
+ projectId: installation.projectId,
+ discoveryId: discoveryConfig?.id,
+ scanTime: new Date(),
+ importStandaloneCaCertificates: targetConfig.importStandaloneCaCertificates,
+ kmsEncryptor,
+ certificateIdsByFingerprint: new Map(),
+ targetInstallationId: installation.id
+ },
+ deps
+ );
+ if (!written.installationId)
+ await recordInstallationError(installation.id, describeHostFileError(file.status), deps);
+ } catch (error) {
+ const message = toHostScanErrorMessage(error, `Installation rescan failed [installationId=${installationId}]`);
+ await recordInstallationError(installation.id, message, deps);
+ }
+};
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.ts
index eb876de1dd..98e7b52129 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
@@ -16,7 +16,6 @@ import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { TProjectDALFactory } from "@app/services/project/project-dal";
import { getProjectKmsCertificateKeyId } from "@app/services/project/project-fns";
import { TTelemetryServiceFactory } from "@app/services/telemetry/telemetry-service";
-import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
import { TPkiCertificateInstallationCertDALFactory } from "./pki-certificate-installation-cert-dal";
import { TPkiCertificateInstallationDALFactory } from "./pki-certificate-installation-dal";
@@ -24,13 +23,24 @@ import { TPkiDiscoveryConfigDALFactory } from "./pki-discovery-config-dal";
import { computeLocationFingerprint, resolveDomain, resolveTargets, scanEndpoint } from "./pki-discovery-fns";
import { TPkiDiscoveryInstallationDALFactory } from "./pki-discovery-installation-dal";
import { TPkiDiscoveryScanHistoryDALFactory } from "./pki-discovery-scan-history-dal";
+import {
+ DB_SHORT_VARCHAR_LIMIT,
+ DB_VARCHAR_LIMIT,
+ discardScanRunIfDeleted,
+ failScanRun,
+ finishScanRun,
+ sendScanCompletedTelemetry,
+ startScanRun,
+ truncateString
+} from "./pki-discovery-scan-run-fns";
import {
CertificateSource,
PkiDiscoveryScanStatus,
+ PkiDiscoveryType,
PkiInstallationLocationType,
PkiInstallationType,
ScanEndpointFailureReason,
- TPkiDiscoveryTargetConfig,
+ TNetworkTargetConfig,
TScanCertificateResult,
TScanEndpointResult
} from "./pki-discovery-types";
@@ -39,20 +49,6 @@ const SCAN_CONCURRENCY = 20;
const DEFAULT_SCAN_TIMEOUT = 10000;
const GATEWAY_CONSECUTIVE_FAILURE_LIMIT = 10;
-const DB_VARCHAR_LIMIT = 4096;
-const DB_SHORT_VARCHAR_LIMIT = 255;
-
-const truncateString = (value: string | null | undefined, maxLength: number): string | null => {
- if (value === null || value === undefined) {
- return null;
- }
- if (value.length <= maxLength) {
- return value;
- }
- const truncationSuffix = "... (truncated)";
- return value.substring(0, maxLength - truncationSuffix.length) + truncationSuffix;
-};
-
type TExecuteScanDeps = {
pkiDiscoveryConfigDAL: TPkiDiscoveryConfigDALFactory;
pkiDiscoveryScanHistoryDAL: TPkiDiscoveryScanHistoryDALFactory;
@@ -70,15 +66,8 @@ type TExecuteScanDeps = {
};
export const executeScan = async (discoveryId: string, deps: TExecuteScanDeps): Promise<void> => {
- const {
- pkiDiscoveryConfigDAL,
- pkiDiscoveryScanHistoryDAL,
- projectDAL,
- kmsService,
- gatewayV2Service,
- gatewayPoolService,
- telemetryService
- } = deps;
+ const { pkiDiscoveryConfigDAL, projectDAL, kmsService, gatewayV2Service, gatewayPoolService, telemetryService } =
+ deps;
const startedAt = new Date();
let scanHistoryId: string | undefined;
@@ -105,31 +94,7 @@ export const executeScan = async (discoveryId: string, deps: TExecuteScanDeps):
kmsId: certificateKmsKeyId
});
- const scanHistory = await pkiDiscoveryConfigDAL.transaction(async (tx) => {
- const history = await pkiDiscoveryScanHistoryDAL.create(
- {
- discoveryConfigId: discoveryId,
- startedAt,
- status: PkiDiscoveryScanStatus.Running,
- targetsScannedCount: 0,
- certificatesFoundCount: 0,
- installationsFoundCount: 0
- },
- tx
- );
-
- await pkiDiscoveryConfigDAL.updateById(
- discoveryId,
- {
- lastScanStatus: PkiDiscoveryScanStatus.Running,
- lastScanJobId: history.id
- },
- tx
- );
-
- return history;
- });
- scanHistoryId = scanHistory.id;
+ scanHistoryId = await startScanRun(discoveryId, startedAt, deps);
const effectiveGatewayId = gatewayPoolService
? await gatewayPoolService.resolveEffectiveGatewayId({
@@ -144,7 +109,7 @@ export const executeScan = async (discoveryId: string, deps: TExecuteScanDeps):
gatewayName = gw?.name;
}
- const targetConfig = discoveryConfig.targetConfig as TPkiDiscoveryTargetConfig;
+ const targetConfig = discoveryConfig.targetConfig as TNetworkTargetConfig;
const hasGateway = !!effectiveGatewayId;
const targets = await resolveTargets(targetConfig, hasGateway);
@@ -254,32 +219,19 @@ export const executeScan = async (discoveryId: string, deps: TExecuteScanDeps):
const lastError = lastFailedResult?.error ? ` Last error: ${lastFailedResult.error}` : "";
const cbErrorMessage = `Gateway connection failed to reach target network. Check that the gateway is online and can reach the target network.${lastError}`;
- await pkiDiscoveryConfigDAL.transaction(async (tx) => {
- if (scanHistoryId) {
- await pkiDiscoveryScanHistoryDAL.updateById(
- scanHistoryId,
- {
- status: PkiDiscoveryScanStatus.Failed,
- completedAt,
- targetsScannedCount: results.length,
- certificatesFoundCount: 0,
- installationsFoundCount: 0,
- errorMessage: cbErrorMessage
- },
- tx
- );
- }
-
- await pkiDiscoveryConfigDAL.updateById(
+ await finishScanRun(
+ {
discoveryId,
- {
- lastScanStatus: PkiDiscoveryScanStatus.Failed,
- lastScannedAt: completedAt,
- lastScanMessage: truncateString(cbErrorMessage, DB_SHORT_VARCHAR_LIMIT)
- },
- tx
- );
- });
+ scanHistoryId,
+ status: PkiDiscoveryScanStatus.Failed,
+ completedAt,
+ targetsScannedCount: results.length,
+ certificatesFoundCount: 0,
+ installationsFoundCount: 0,
+ errorMessage: cbErrorMessage
+ },
+ deps
+ );
return;
}
@@ -299,14 +251,7 @@ export const executeScan = async (discoveryId: string, deps: TExecuteScanDeps):
logger.info({ discoveryId, scannedCount: results.length }, "TLS scans completed, processing results");
- const configStillExists = await pkiDiscoveryConfigDAL.findById(discoveryId);
- if (!configStillExists) {
- logger.warn({ discoveryId }, "Discovery config was deleted during scan, aborting result processing");
- if (scanHistoryId) {
- await pkiDiscoveryScanHistoryDAL.deleteById(scanHistoryId);
- }
- return;
- }
+ if (await discardScanRunIfDeleted(discoveryId, scanHistoryId, deps)) return;
const uniqueCertificateIds = new Set<string>();
const uniqueInstallationIds = new Set<string>();
@@ -448,58 +393,37 @@ export const executeScan = async (discoveryId: string, deps: TExecuteScanDeps):
errorMessage = `${certParseErrors} certificate(s) could not be parsed: ${scanErrors.join("; ")}`;
}
- await pkiDiscoveryConfigDAL.transaction(async (tx) => {
- if (scanHistoryId) {
- await pkiDiscoveryScanHistoryDAL.updateById(
- scanHistoryId,
- {
- status: finalStatus,
- completedAt,
- targetsScannedCount: targets.length,
- certificatesFoundCount: uniqueCertificateIds.size,
- installationsFoundCount: uniqueInstallationIds.size,
- errorMessage
- },
- tx
- );
- }
-
- await pkiDiscoveryConfigDAL.updateById(
+ await finishScanRun(
+ {
discoveryId,
- {
- lastScanStatus: finalStatus,
- lastScannedAt: completedAt,
- lastScanMessage: truncateString(errorMessage, DB_SHORT_VARCHAR_LIMIT)
- },
- tx
- );
- });
+ scanHistoryId,
+ status: finalStatus,
+ completedAt,
+ targetsScannedCount: targets.length,
+ certificatesFoundCount: uniqueCertificateIds.size,
+ installationsFoundCount: uniqueInstallationIds.size,
+ errorMessage
+ },
+ deps
+ );
const durationMs = completedAt.getTime() - startedAt.getTime();
const durationSec = (durationMs / 1000).toFixed(1);
- if (telemetryService) {
- // the scan already committed as completed, so reporting must not be able to mark it failed
- try {
- const project = await projectDAL.findOne({ id: discoveryConfig.projectId });
- if (project) {
- await telemetryService.sendPostHogEvents({
- event: PostHogEventTypes.PkiDiscoveryScanCompleted,
- distinctId: `platform/${discoveryConfig.projectId}`,
- organizationId: project.orgId,
- properties: {
- orgId: project.orgId,
- projectId: discoveryConfig.projectId,
- status: finalStatus,
- certificatesFound: uniqueCertificateIds.size,
- installationsFound: uniqueInstallationIds.size,
- durationMs
- }
- });
- }
- } catch (telemetryError) {
- logger.error(telemetryError, `Failed to send PKI discovery scan telemetry for discovery ${discoveryId}`);
- }
+ const project = telemetryService
+ ? await projectDAL.findOne({ id: discoveryConfig.projectId }).catch(() => undefined)
+ : undefined;
+ if (project) {
+ await sendScanCompletedTelemetry(telemetryService, {
+ discoveryId,
+ discoveryType: PkiDiscoveryType.Network,
+ projectId: discoveryConfig.projectId,
+ orgId: project.orgId,
+ status: finalStatus,
+ certificatesFound: uniqueCertificateIds.size,
+ installationsFound: uniqueInstallationIds.size,
+ durationMs
+ });
}
logger.info(
@@ -529,37 +453,12 @@ export const executeScan = async (discoveryId: string, deps: TExecuteScanDeps):
`PKI discovery scan failed after ${durationSec}s`
);
- const rawErrorMessage = error instanceof Error ? error.message : "Unknown error";
- const truncatedCatchErrorMessage = truncateString(rawErrorMessage, DB_SHORT_VARCHAR_LIMIT);
-
- await pkiDiscoveryConfigDAL.transaction(async (tx) => {
- if (scanHistoryId) {
- await pkiDiscoveryScanHistoryDAL.updateById(
- scanHistoryId,
- {
- status: PkiDiscoveryScanStatus.Failed,
- completedAt: new Date(),
- errorMessage: truncatedCatchErrorMessage
- },
- tx
- );
- }
-
- await pkiDiscoveryConfigDAL.updateById(
- discoveryId,
- {
- lastScanStatus: PkiDiscoveryScanStatus.Failed,
- lastScanMessage: truncatedCatchErrorMessage
- },
- tx
- );
- });
-
+ await failScanRun(discoveryId, scanHistoryId, error, deps);
throw error;
}
};
-type TKmsEncryptor = (data: { plainText: Buffer }) => Promise<{ cipherTextBlob: Buffer }>;
+export type TKmsEncryptor = (data: { plainText: Buffer }) => Promise<{ cipherTextBlob: Buffer }>;
const processEndpointResult = async (
result: TScanEndpointResult,
@@ -677,10 +576,10 @@ const processEndpointResult = async (
type TProcessDiscoveredCertDeps = {
certificateDAL: TCertificateDALFactory;
certificateBodyDAL: TCertificateBodyDALFactory;
- kmsEncryptor: (data: { plainText: Buffer }) => Promise<{ cipherTextBlob: Buffer }>;
+ kmsEncryptor: TKmsEncryptor;
};
-const processDiscoveredCertificate = async (
+export const processDiscoveredCertificate = async (
certResult: TScanCertificateResult,
projectId: string,
deps: TProcessDiscoveredCertDeps,
diff --git a/backend/src/ee/services/pki-discovery/pki-discovery-scan-run-fns.ts b/backend/src/ee/services/pki-discovery/pki-discovery-scan-run-fns.ts
new file mode 100644
index 0000000000..d39164599c
--- /dev/null
+++ b/backend/src/ee/services/pki-discovery/pki-discovery-scan-run-fns.ts
@@ -0,0 +1,159 @@
+import { logger } from "@app/lib/logger";
+import { TTelemetryServiceFactory } from "@app/services/telemetry/telemetry-service";
+import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
+
+import { TPkiDiscoveryConfigDALFactory } from "./pki-discovery-config-dal";
+import { TPkiDiscoveryScanHistoryDALFactory } from "./pki-discovery-scan-history-dal";
+import { PkiDiscoveryScanStatus, PkiDiscoveryType } from "./pki-discovery-types";
+
+export const DB_SHORT_VARCHAR_LIMIT = 255;
+export const DB_VARCHAR_LIMIT = 4096;
+
+export const truncateString = (value: string | null | undefined, maxLength: number): string | null => {
+ if (value === null || value === undefined) {
+ return null;
+ }
+ if (value.length <= maxLength) {
+ return value;
+ }
+ const truncationSuffix = "... (truncated)";
+ return value.substring(0, maxLength - truncationSuffix.length) + truncationSuffix;
+};
+
+type TScanRunDeps = {
+ pkiDiscoveryConfigDAL: Pick<TPkiDiscoveryConfigDALFactory, "transaction" | "updateById" | "findById">;
+ pkiDiscoveryScanHistoryDAL: Pick<TPkiDiscoveryScanHistoryDALFactory, "create" | "updateById" | "deleteById">;
+};
+
+export const startScanRun = async (discoveryId: string, startedAt: Date, deps: TScanRunDeps): Promise<string> => {
+ const history = await deps.pkiDiscoveryConfigDAL.transaction(async (tx) => {
+ const created = await deps.pkiDiscoveryScanHistoryDAL.create(
+ {
+ discoveryConfigId: discoveryId,
+ startedAt,
+ status: PkiDiscoveryScanStatus.Running,
+ targetsScannedCount: 0,
+ certificatesFoundCount: 0,
+ installationsFoundCount: 0
+ },
+ tx
+ );
+ await deps.pkiDiscoveryConfigDAL.updateById(
+ discoveryId,
+ { lastScanStatus: PkiDiscoveryScanStatus.Running, lastScanJobId: created.id },
+ tx
+ );
+ return created;
+ });
+ return history.id;
+};
+
+export const discardScanRunIfDeleted = async (
+ discoveryId: string,
+ scanHistoryId: string,
+ deps: TScanRunDeps
+): Promise<boolean> => {
+ const discoveryConfig = await deps.pkiDiscoveryConfigDAL.findById(discoveryId);
+ if (discoveryConfig) return false;
+ logger.warn({ discoveryId }, "Discovery config was deleted during scan, aborting result processing");
+ await deps.pkiDiscoveryScanHistoryDAL.deleteById(scanHistoryId);
+ return true;
+};
+
+export const finishScanRun = async (
+ {
+ discoveryId,
+ scanHistoryId,
+ status,
+ completedAt,
+ targetsScannedCount,
+ certificatesFoundCount,
+ installationsFoundCount,
+ errorMessage
+ }: {
+ discoveryId: string;
+ scanHistoryId: string;
+ status: PkiDiscoveryScanStatus;
+ completedAt: Date;
+ targetsScannedCount: number;
+ certificatesFoundCount: number;
+ installationsFoundCount: number;
+ errorMessage: string | null;
+ },
+ deps: TScanRunDeps
+) => {
+ await deps.pkiDiscoveryConfigDAL.transaction(async (tx) => {
+ await deps.pkiDiscoveryScanHistoryDAL.updateById(
+ scanHistoryId,
+ { status, completedAt, targetsScannedCount, certificatesFoundCount, installationsFoundCount, errorMessage },
+ tx
+ );
+ await deps.pkiDiscoveryConfigDAL.updateById(
+ discoveryId,
+ {
+ lastScanStatus: status,
+ lastScannedAt: completedAt,
+ lastScanMessage: truncateString(errorMessage, DB_VARCHAR_LIMIT)
+ },
+ tx
+ );
+ });
+};
+
+export const failScanRun = async (
+ discoveryId: string,
+ scanHistoryId: string | undefined,
+ error: unknown,
+ deps: TScanRunDeps
+) => {
+ const message = truncateString(error instanceof Error ? error.message : "Unknown error", DB_VARCHAR_LIMIT);
+ await deps.pkiDiscoveryConfigDAL.transaction(async (tx) => {
+ if (scanHistoryId) {
+ await deps.pkiDiscoveryScanHistoryDAL.updateById(
+ scanHistoryId,
+ { status: PkiDiscoveryScanStatus.Failed, completedAt: new Date(), errorMessage: message },
+ tx
+ );
+ }
+ await deps.pkiDiscoveryConfigDAL.updateById(
+ discoveryId,
+ { lastScanStatus: PkiDiscoveryScanStatus.Failed, lastScanMessage: message },
+ tx
+ );
+ });
+};
+
+export const sendScanCompletedTelemetry = async (
+ telemetryService: Pick<TTelemetryServiceFactory, "sendPostHogEvents"> | undefined,
+ {
+ discoveryId,
+ discoveryType,
+ projectId,
+ orgId,
+ status,
+ certificatesFound,
+ installationsFound,
+ durationMs
+ }: {
+ discoveryId: string;
+ discoveryType: PkiDiscoveryType;
+ projectId: string;
+ orgId: string;
+ status: PkiDiscoveryScanStatus;
+ certificatesFound: number;
+ installationsFound: number;
+ durationMs: number;
+ }
+) => {
+ if (!telemetryService) return;
+ try {
+ await telemetryService.sendPostHogEvents({
+ event: PostHogEventTypes.PkiDiscoveryScanCompleted,
+ distinctId: `platform/${projectId}`,
+ organizationId: orgId,
+ properties: { orgId, projectId, discoveryType, status, certificatesFound, installationsFound, durationMs }
+ });
+ } catch (telemetryError) {
+ logger.error(telemetryError, `Failed to send PKI discovery scan telemetry [discoveryId=${discoveryId}]`);
+ }
+};
diff --git a/backend/src/ee/services/pki-discovery/pki-discovery-schemas.ts b/backend/src/ee/services/pki-discovery/pki-discovery-schemas.ts
new file mode 100644
index 0000000000..5e5587b2f4
--- /dev/null
+++ b/backend/src/ee/services/pki-discovery/pki-discovery-schemas.ts
@@ -0,0 +1,80 @@
+import RE2 from "re2";
+import { z } from "zod";
+
+import { DEFAULT_TLS_PORTS } from "./pki-discovery-fns";
+
+const LINUX_SERVER_DEFAULT_MAX_FOLDER_DEPTH = 8;
+const LINUX_SERVER_MAX_FOLDER_DEPTH = 20;
+const LINUX_SERVER_DEFAULT_MAX_FILE_SIZE_KB = 512;
+const LINUX_SERVER_MAX_FILE_SIZE_KB = 10240;
+const LINUX_SERVER_MAX_CONNECTIONS = 100;
+const LINUX_SERVER_MAX_SEARCH_FOLDERS = 20;
+const LINUX_SERVER_MAX_SKIP_FOLDERS = 50;
+
+const FORBIDDEN_PATH_CHARACTERS = new RE2("[\\x00\\r\\n]");
+const PARENT_SEGMENT = new RE2("(^|/)\\.\\.(/|$)");
+
+const LinuxFolderPathSchema = z
+ .string()
+ .trim()
+ .min(1)
+ .max(1024)
+ .refine((value) => value.startsWith("/"), "Folder paths must be absolute, for example /etc/ssl")
+ .refine((value) => !FORBIDDEN_PATH_CHARACTERS.test(value), "Folder paths cannot contain line breaks")
+ .refine((value) => !PARENT_SEGMENT.test(value), "Folder paths cannot contain '..'");
+
+export const NetworkTargetConfigSchema = z
+ .object({
+ ipRanges: z.array(z.string().max(64)).optional().describe("IP addresses or CIDR ranges to scan (Network jobs)."),
+ domains: z.array(z.string().max(253)).optional().describe("Domains to scan (Network jobs)."),
+ ports: z.string().max(256).default(DEFAULT_TLS_PORTS).describe("Comma-separated ports or ranges (Network jobs).")
+ })
+ .strict();
+
+export const LinuxServerTargetConfigSchema = z
+ .object({
+ connectionIds: z
+ .array(z.string().uuid())
+ .min(1, "Select at least one SSH connection")
+ .max(LINUX_SERVER_MAX_CONNECTIONS)
+ .refine((ids) => new Set(ids).size === ids.length, "Each SSH connection can be listed once")
+ .describe("IDs of the SSH connections to scan. Each connection must use a gateway."),
+ searchFolderPaths: z
+ .array(LinuxFolderPathSchema)
+ .min(1, "Add at least one folder to search")
+ .max(LINUX_SERVER_MAX_SEARCH_FOLDERS)
+ .describe("Folders to search. Each folder is searched along with the folders below it."),
+ skipFolderPaths: z
+ .array(LinuxFolderPathSchema)
+ .max(LINUX_SERVER_MAX_SKIP_FOLDERS)
+ .default([])
+ .describe("Folders that are never entered."),
+ maxFolderDepth: z
+ .number()
+ .int()
+ .min(1)
+ .max(LINUX_SERVER_MAX_FOLDER_DEPTH)
+ .default(LINUX_SERVER_DEFAULT_MAX_FOLDER_DEPTH)
+ .describe("How many levels below each search folder to go."),
+ maxFileSizeKb: z
+ .number()
+ .int()
+ .min(1)
+ .max(LINUX_SERVER_MAX_FILE_SIZE_KB)
+ .default(LINUX_SERVER_DEFAULT_MAX_FILE_SIZE_KB)
+ .describe("Files bigger than this, in KB, are skipped."),
+ importStandaloneCaCertificates: z
+ .boolean()
+ .default(false)
+ .describe("Also import CA certificates found on their own. Leaf certificates always bring their chain.")
+ })
+ .strict();
+
+export const DiscoveryTargetConfigInputSchema = NetworkTargetConfigSchema.partial()
+ .merge(LinuxServerTargetConfigSchema.partial())
+ .describe(
+ "Target configuration. Network jobs use domains, ipRanges and ports. Linux Server jobs use connectionIds, searchFolderPaths, skipFolderPaths, maxFolderDepth, maxFileSizeKb and importStandaloneCaCertificates."
+ );
+
+export const formatTargetConfigIssue = ({ path, message }: z.ZodIssue) =>
+ path.length > 0 ? `targetConfig.${path.join(".")}: ${message}` : `targetConfig: ${message}`;
diff --git a/backend/src/ee/services/pki-discovery/pki-discovery-service.ts b/backend/src/ee/services/pki-discovery/pki-discovery-service.ts
index 6c58027e8c..3eafd9fd40 100644
--- a/backend/src/ee/services/pki-discovery/pki-discovery-service.ts
+++ b/backend/src/ee/services/pki-discovery/pki-discovery-service.ts
@@ -1,4 +1,6 @@
import { ForbiddenError } from "@casl/ability";
+import pLimit from "p-limit";
+import { z } from "zod";
import { ActionProjectType, OrganizationActionScope } from "@app/db/schemas";
import { TGatewayPoolDALFactory } from "@app/ee/services/gateway-pool/gateway-pool-dal";
@@ -13,11 +15,22 @@ import {
} from "@app/ee/services/permission/project-permission";
import { getConfig } from "@app/lib/config/env";
import { BadRequestError, DatabaseError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
+import { OrgServiceActor } from "@app/lib/types";
+import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";
+import { AppConnection } from "@app/services/app-connection/app-connection-enums";
+import { TAppConnectionServiceFactory } from "@app/services/app-connection/app-connection-service";
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 { sshConnectionWithoutGatewayMessage } from "./pki-discovery-host-fns";
import { TPkiDiscoveryScanHistoryDALFactory } from "./pki-discovery-scan-history-dal";
+import {
+ formatTargetConfigIssue,
+ LinuxServerTargetConfigSchema,
+ NetworkTargetConfigSchema
+} from "./pki-discovery-schemas";
import {
PkiDiscoveryScanStatus,
PkiDiscoveryType,
@@ -26,7 +39,9 @@ import {
TGetLatestScanDTO,
TGetPkiDiscoveryDTO,
TGetScanHistoryDTO,
+ TLinuxServerTargetConfig,
TListPkiDiscoveriesDTO,
+ TNetworkTargetConfig,
TPkiDiscoveryTargetConfig,
TTriggerPkiDiscoveryScanDTO,
TUpdatePkiDiscoveryDTO
@@ -34,6 +49,7 @@ import {
const MAX_CLOUD_DISCOVERIES = 10;
const SCAN_RATE_LIMIT_HOURS = 24;
+const CONNECTION_VALIDATION_CONCURRENCY = 5;
type TPkiDiscoveryServiceFactoryDep = {
pkiDiscoveryConfigDAL: Pick<
@@ -57,25 +73,13 @@ type TPkiDiscoveryServiceFactoryDep = {
gatewayPoolDAL: Pick<TGatewayPoolDALFactory, "findById">;
gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveAttachableGatewayFromPool">;
orgDAL: Pick<TOrgDALFactory, "findById">;
+ appConnectionService: Pick<TAppConnectionServiceFactory, "validateAppConnectionUsageById">;
+ appConnectionDAL: Pick<TAppConnectionDALFactory, "find">;
queuePkiDiscoveryScan: (discoveryId: string) => Promise<void>;
};
export type TPkiDiscoveryServiceFactory = ReturnType<typeof pkiDiscoveryServiceFactory>;
-const validateTargetConfigForType = (discoveryType: PkiDiscoveryType, config: TPkiDiscoveryTargetConfig) => {
- switch (discoveryType) {
- 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"
- });
- }
- break;
- default:
- throw new BadRequestError({ message: `Unsupported discovery type: ${discoveryType as string}` });
- }
-};
-
export const pkiDiscoveryServiceFactory = ({
pkiDiscoveryConfigDAL,
pkiDiscoveryScanHistoryDAL,
@@ -85,8 +89,82 @@ export const pkiDiscoveryServiceFactory = ({
gatewayPoolDAL,
gatewayPoolService,
orgDAL,
+ appConnectionService,
+ appConnectionDAL,
queuePkiDiscoveryScan
}: TPkiDiscoveryServiceFactoryDep) => {
+ const $parseTargetConfig = <T>(schema: z.ZodTypeAny, targetConfig: TPkiDiscoveryTargetConfig): T => {
+ const parsed = schema.safeParse(targetConfig);
+ if (!parsed.success) {
+ throw new BadRequestError({ message: parsed.error.issues.slice(0, 3).map(formatTargetConfigIssue).join("; ") });
+ }
+ return parsed.data as T;
+ };
+
+ const $validateNetworkTarget = (targetConfig: TPkiDiscoveryTargetConfig, hasGateway: boolean) => {
+ const config = $parseTargetConfig<TNetworkTargetConfig>(NetworkTargetConfigSchema, targetConfig);
+ const validation = validateTargetConfig(config.ipRanges, config.ports, config.domains, hasGateway);
+ if (!validation.valid) {
+ throw new BadRequestError({ message: validation.error || "Invalid target configuration" });
+ }
+ return config;
+ };
+
+ const $validateLinuxServerTarget = async (
+ targetConfig: TPkiDiscoveryTargetConfig,
+ projectId: string,
+ actor: OrgServiceActor
+ ): Promise<TLinuxServerTargetConfig> => {
+ const config = $parseTargetConfig<TLinuxServerTargetConfig>(LinuxServerTargetConfigSchema, targetConfig);
+ const limit = pLimit(CONNECTION_VALIDATION_CONCURRENCY);
+ const connections = await Promise.all(
+ config.connectionIds.map((connectionId) =>
+ limit(() =>
+ appConnectionService.validateAppConnectionUsageById(AppConnection.SSH, { connectionId, projectId }, actor)
+ )
+ )
+ );
+ const connectionWithoutGateway = connections.find(
+ (connection) => !connection.gatewayId && !connection.gatewayPoolId
+ );
+ if (connectionWithoutGateway) {
+ throw new BadRequestError({ message: sshConnectionWithoutGatewayMessage(connectionWithoutGateway.name) });
+ }
+ return config;
+ };
+
+ const $assertJobGatewayAllowed = (discoveryType: PkiDiscoveryType, hasJobGateway: boolean) => {
+ if (discoveryType !== PkiDiscoveryType.Network && hasJobGateway) {
+ throw new BadRequestError({
+ message:
+ "Linux Server discovery uses the gateway of each SSH connection, so a gateway or gateway pool cannot be set on the job"
+ });
+ }
+ };
+
+ const $validateTarget = async ({
+ discoveryType,
+ targetConfig,
+ hasGateway,
+ projectId,
+ actor
+ }: {
+ discoveryType: PkiDiscoveryType;
+ targetConfig: TPkiDiscoveryTargetConfig;
+ hasGateway: boolean;
+ projectId: string;
+ actor: OrgServiceActor;
+ }): Promise<TPkiDiscoveryTargetConfig> => {
+ switch (discoveryType) {
+ case PkiDiscoveryType.Network:
+ return $validateNetworkTarget(targetConfig, hasGateway);
+ case PkiDiscoveryType.LinuxServer:
+ return $validateLinuxServerTarget(targetConfig, projectId, actor);
+ default:
+ throw new BadRequestError({ message: `Unsupported discovery type: ${discoveryType as string}` });
+ }
+ };
+
const createDiscovery = async ({
projectId,
name,
@@ -97,6 +175,7 @@ export const pkiDiscoveryServiceFactory = ({
scanIntervalDays,
gatewayId,
gatewayPoolId,
+ orgActor,
actor,
actorId,
actorAuthMethod,
@@ -139,7 +218,14 @@ export const pkiDiscoveryServiceFactory = ({
}
}
- validateTargetConfigForType(discoveryType, targetConfig);
+ $assertJobGatewayAllowed(discoveryType, Boolean(gatewayId || gatewayPoolId));
+ const validatedTargetConfig = await $validateTarget({
+ discoveryType,
+ targetConfig,
+ hasGateway: Boolean(gatewayId || gatewayPoolId),
+ projectId,
+ actor: orgActor
+ });
if (gatewayId) {
const gateway = await gatewayV2DAL.findOne({ id: gatewayId, orgId: actorOrgId });
@@ -176,7 +262,7 @@ export const pkiDiscoveryServiceFactory = ({
name,
description,
discoveryType,
- targetConfig,
+ targetConfig: validatedTargetConfig,
isAutoScanEnabled: isAutoScanEnabled ?? false,
scanIntervalDays: isAutoScanEnabled ? scanIntervalDays : null,
gatewayId: gatewayPoolId ? null : gatewayId,
@@ -206,6 +292,7 @@ export const pkiDiscoveryServiceFactory = ({
gatewayId,
gatewayPoolId,
isActive,
+ orgActor,
actor,
actorId,
actorAuthMethod,
@@ -234,12 +321,23 @@ export const pkiDiscoveryServiceFactory = ({
ProjectPermissionSub.PkiDiscovery
);
- if (targetConfig) {
- validateTargetConfigForType(
- (discovery.discoveryType as PkiDiscoveryType) || PkiDiscoveryType.Network,
- targetConfig
- );
- }
+ const discoveryType = (discovery.discoveryType as PkiDiscoveryType) || PkiDiscoveryType.Network;
+ const effectiveHasGateway =
+ gatewayId !== undefined || gatewayPoolId !== undefined
+ ? Boolean(gatewayId || gatewayPoolId)
+ : Boolean(discovery.gatewayId || discovery.gatewayPoolId);
+
+ $assertJobGatewayAllowed(discoveryType, Boolean(gatewayId || gatewayPoolId));
+
+ const validatedTargetConfig = targetConfig
+ ? await $validateTarget({
+ discoveryType,
+ targetConfig,
+ hasGateway: effectiveHasGateway,
+ projectId: discovery.projectId,
+ actor: orgActor
+ })
+ : undefined;
if (gatewayId) {
const gateway = await gatewayV2DAL.findOne({ id: gatewayId, orgId: actorOrgId });
@@ -282,7 +380,7 @@ export const pkiDiscoveryServiceFactory = ({
const updatedDiscovery = await pkiDiscoveryConfigDAL.updateById(discoveryId, {
name,
description,
- targetConfig,
+ targetConfig: validatedTargetConfig,
isAutoScanEnabled,
scanIntervalDays: isAutoScanEnabled ? scanIntervalDays : null,
gatewayId: gatewayIdValue,
@@ -333,6 +431,28 @@ export const pkiDiscoveryServiceFactory = ({
return discovery;
};
+ const $attachConnections = async <T extends { discoveryType: string; targetConfig?: unknown }>(
+ discoveries: T[],
+ orgId: string
+ ) => {
+ const connectionIdsOf = (discovery: T) =>
+ discovery.discoveryType === PkiDiscoveryType.LinuxServer
+ ? (discovery.targetConfig as TLinuxServerTargetConfig).connectionIds
+ : [];
+ const connectionIds = [...new Set(discoveries.flatMap(connectionIdsOf))];
+ const rows = connectionIds.length ? await appConnectionDAL.find({ $in: { id: connectionIds }, orgId }) : [];
+ const connectionsById = new Map(
+ rows.map((row) => [row.id, { id: row.id, name: row.name, app: row.app as AppConnection }])
+ );
+ return discoveries.map((discovery) => ({
+ ...discovery,
+ connections: connectionIdsOf(discovery).flatMap((id) => {
+ const connection = connectionsById.get(id);
+ return connection ? [connection] : [];
+ })
+ }));
+ };
+
const getDiscovery = async ({ discoveryId, actor, actorId, actorAuthMethod, actorOrgId }: TGetPkiDiscoveryDTO) => {
const discovery = await pkiDiscoveryConfigDAL.findByIdWithInstallationCounts(discoveryId);
if (!discovery) {
@@ -367,7 +487,9 @@ export const pkiDiscoveryServiceFactory = ({
}
}
- return { ...discovery, gatewayName, gatewayPoolName };
+ const [discoveryWithConnections] = await $attachConnections([discovery], actorOrgId);
+
+ return { ...discoveryWithConnections, gatewayName, gatewayPoolName };
};
const listDiscoveries = async ({
@@ -397,7 +519,7 @@ export const pkiDiscoveryServiceFactory = ({
const discoveries = await pkiDiscoveryConfigDAL.findByProjectId(projectId, { offset, limit, search });
const totalCount = await pkiDiscoveryConfigDAL.countByProjectId(projectId, { search });
- return { discoveries, totalCount };
+ return { discoveries: await $attachConnections(discoveries, actorOrgId), totalCount };
};
const triggerScan = async ({
diff --git a/backend/src/ee/services/pki-discovery/pki-discovery-types.ts b/backend/src/ee/services/pki-discovery/pki-discovery-types.ts
index 029ef8f3f2..25da2d47be 100644
--- a/backend/src/ee/services/pki-discovery/pki-discovery-types.ts
+++ b/backend/src/ee/services/pki-discovery/pki-discovery-types.ts
@@ -1,7 +1,63 @@
-import { TProjectPermission } from "@app/lib/types";
+import { z } from "zod";
+
+import { OrgServiceActor, TProjectPermission } from "@app/lib/types";
+
+import type { LinuxServerTargetConfigSchema } from "./pki-discovery-schemas";
export enum PkiDiscoveryType {
- Network = "network"
+ Network = "network",
+ LinuxServer = "linux-server"
+}
+
+export enum PkiKeystoreStatus {
+ Locked = "locked",
+ Readable = "readable",
+ PasswordFailed = "password_failed"
+}
+
+export enum PkiCertificateFileFormat {
+ Pem = "pem",
+ Der = "der",
+ Pkcs7 = "pkcs7",
+ Pkcs12 = "pkcs12",
+ Jks = "jks",
+ Jceks = "jceks"
+}
+
+export enum HostCertificateFileStatus {
+ Ok = "ok",
+ Locked = "locked",
+ PasswordFailed = "passwordFailed",
+ AccessDenied = "accessDenied",
+ NotFound = "notFound",
+ TooLarge = "tooLarge",
+ ParseError = "parseError",
+ Unsupported = "unsupported",
+ NoCertificates = "noCertificates",
+ ReadFailed = "readFailed"
+}
+
+export enum HostScanTruncationReason {
+ FileList = "fileList",
+ MaxFiles = "maxFiles",
+ ResponseSize = "responseSize",
+ TimeLimit = "timeLimit"
+}
+
+export enum PkiKeystorePasswordChange {
+ Set = "set",
+ Cleared = "cleared"
+}
+
+export enum HostFileImportAction {
+ Skip = "skip",
+ Refresh = "refresh",
+ Upsert = "upsert"
+}
+
+export enum HostCertificateChainKind {
+ Leaf = "leaf",
+ Ca = "ca"
}
export enum PkiDiscoveryScanStatus {
@@ -41,7 +97,9 @@ export type TNetworkTargetConfig = {
ports?: string;
};
-export type TPkiDiscoveryTargetConfig = TNetworkTargetConfig;
+export type TLinuxServerTargetConfig = z.infer<typeof LinuxServerTargetConfigSchema>;
+
+export type TPkiDiscoveryTargetConfig = TNetworkTargetConfig | TLinuxServerTargetConfig;
export type TPkiInstallationLocationDetails = {
ipAddress?: string;
@@ -51,6 +109,16 @@ export type TPkiInstallationLocationDetails = {
filePath?: string;
protocol?: string;
gatewayName?: string;
+ hostname?: string;
+ connectionId?: string;
+ format?: PkiCertificateFileFormat;
+};
+
+export type TPkiInstallationMetadata = {
+ keystoreStatus?: PkiKeystoreStatus;
+ lastReadAt?: string;
+ lastCheckedAt?: string;
+ lastError?: string;
};
export type TCreatePkiDiscoveryDTO = {
@@ -63,6 +131,7 @@ export type TCreatePkiDiscoveryDTO = {
scanIntervalDays?: number;
gatewayId?: string | null;
gatewayPoolId?: string | null;
+ orgActor: OrgServiceActor;
} & Omit<TProjectPermission, "projectId">;
export type TUpdatePkiDiscoveryDTO = {
@@ -75,6 +144,7 @@ export type TUpdatePkiDiscoveryDTO = {
gatewayId?: string | null;
gatewayPoolId?: string | null;
isActive?: boolean;
+ orgActor: OrgServiceActor;
} & Omit<TProjectPermission, "projectId">;
export type TDeletePkiDiscoveryDTO = {
@@ -122,6 +192,7 @@ export type TGetPkiInstallationDTO = {
export type TUpdatePkiInstallationDTO = {
installationId: string;
name?: string;
+ keystorePassword?: string | null;
} & Omit<TProjectPermission, "projectId">;
export type TDeletePkiInstallationDTO = {
diff --git a/backend/src/ee/services/pki-discovery/pki-installation-credentials-fns.ts b/backend/src/ee/services/pki-discovery/pki-installation-credentials-fns.ts
new file mode 100644
index 0000000000..4263ccc5f3
--- /dev/null
+++ b/backend/src/ee/services/pki-discovery/pki-installation-credentials-fns.ts
@@ -0,0 +1,38 @@
+import { z } from "zod";
+
+import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+import { KmsDataKey } from "@app/services/kms/kms-types";
+
+const PkiInstallationCredentialsSchema = z.object({
+ keystorePassword: z.string().optional()
+});
+
+type TPkiInstallationCredentials = z.infer<typeof PkiInstallationCredentialsSchema>;
+
+type TKmsService = Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
+
+export const encryptPkiInstallationCredentials = async ({
+ projectId,
+ credentials,
+ kmsService
+}: {
+ projectId: string;
+ credentials: TPkiInstallationCredentials;
+ kmsService: TKmsService;
+}) => {
+ const { encryptor } = await kmsService.createCipherPairWithDataKey({ type: KmsDataKey.SecretManager, projectId });
+ const { cipherTextBlob } = encryptor({ plainText: Buffer.from(JSON.stringify(credentials)) });
+ return cipherTextBlob;
+};
+
+export const createPkiInstallationCredentialsDecryptor = async ({
+ projectId,
+ kmsService
+}: {
+ projectId: string;
+ kmsService: TKmsService;
+}) => {
+ const { decryptor } = await kmsService.createCipherPairWithDataKey({ type: KmsDataKey.SecretManager, projectId });
+ return (encryptedCredentials: Buffer): TPkiInstallationCredentials =>
+ PkiInstallationCredentialsSchema.parse(JSON.parse(decryptor({ cipherTextBlob: encryptedCredentials }).toString()));
+};
diff --git a/backend/src/ee/services/pki-discovery/pki-installation-service.ts b/backend/src/ee/services/pki-discovery/pki-installation-service.ts
index 31120b0056..40c57ae75b 100644
--- a/backend/src/ee/services/pki-discovery/pki-installation-service.ts
+++ b/backend/src/ee/services/pki-discovery/pki-installation-service.ts
@@ -4,17 +4,29 @@ import { ActionProjectType } from "@app/db/schemas";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
import {
ProjectPermissionPkiCertificateInstallationActions,
+ ProjectPermissionPkiDiscoveryActions,
ProjectPermissionSub
} from "@app/ee/services/permission/project-permission";
-import { NotFoundError } from "@app/lib/errors";
+import { BadRequestError, NotFoundError } from "@app/lib/errors";
+import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";
+import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { TPkiCertificateInstallationDALFactory } from "./pki-certificate-installation-dal";
import {
+ PkiCertificateFileFormat,
+ PkiInstallationLocationType,
TDeletePkiInstallationDTO,
TGetPkiInstallationDTO,
TListPkiInstallationsDTO,
+ TPkiInstallationLocationDetails,
TUpdatePkiInstallationDTO
} from "./pki-discovery-types";
+import { encryptPkiInstallationCredentials } from "./pki-installation-credentials-fns";
+
+export const sanitizePkiInstallation = <T extends { encryptedCredentials?: Buffer | null }>(installation: T) => {
+ const { encryptedCredentials, ...rest } = installation;
+ return { ...rest, hasKeystorePassword: Boolean(encryptedCredentials) };
+};
type TPkiInstallationServiceFactoryDep = {
pkiCertificateInstallationDAL: Pick<
@@ -22,13 +34,19 @@ type TPkiInstallationServiceFactoryDep = {
"findById" | "findByProjectId" | "countByProjectId" | "findByIdWithCertificates" | "updateById" | "deleteById"
>;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
+ appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">;
+ queueInstallationRescan: (installationId: string) => Promise<void>;
};
export type TPkiInstallationServiceFactory = ReturnType<typeof pkiInstallationServiceFactory>;
export const pkiInstallationServiceFactory = ({
pkiCertificateInstallationDAL,
- permissionService
+ permissionService,
+ kmsService,
+ appConnectionDAL,
+ queueInstallationRescan
}: TPkiInstallationServiceFactoryDep) => {
const listInstallations = async ({
projectId,
@@ -69,7 +87,7 @@ export const pkiInstallationServiceFactory = ({
search
});
- return { installations, totalCount };
+ return { installations: installations.map(sanitizePkiInstallation), totalCount };
};
const getInstallation = async ({
@@ -98,12 +116,19 @@ export const pkiInstallationServiceFactory = ({
ProjectPermissionSub.PkiCertificateInstallations
);
- return installation;
+ const { connectionId } = (installation.locationDetails as TPkiInstallationLocationDetails | null) ?? {};
+ const connection = connectionId ? await appConnectionDAL.findById(connectionId) : undefined;
+
+ return {
+ ...sanitizePkiInstallation(installation),
+ connection: connection && connection.orgId === actorOrgId ? { id: connection.id, name: connection.name } : null
+ };
};
const updateInstallation = async ({
installationId,
name,
+ keystorePassword,
actor,
actorId,
actorAuthMethod,
@@ -128,12 +153,47 @@ export const pkiInstallationServiceFactory = ({
ProjectPermissionSub.PkiCertificateInstallations
);
- const updateData: { name?: string } = {};
+ const isSettingPassword = typeof keystorePassword === "string";
+ if (isSettingPassword) {
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionPkiDiscoveryActions.RunScan,
+ ProjectPermissionSub.PkiDiscovery
+ );
+ }
+
+ if (keystorePassword !== undefined && installation.locationType !== PkiInstallationLocationType.Keystore) {
+ throw new BadRequestError({
+ message: `Installation '${installation.name ?? installationId}' is not a keystore, so it has no password to set`
+ });
+ }
+
+ const installationFormat = (installation.locationDetails as TPkiInstallationLocationDetails | null)?.format;
+ if (isSettingPassword && installationFormat && installationFormat !== PkiCertificateFileFormat.Pkcs12) {
+ throw new BadRequestError({
+ message: `Installation '${installation.name ?? installationId}' is a ${installationFormat.toUpperCase()} keystore, which is read without a password`
+ });
+ }
+
+ const updateData: { name?: string; encryptedCredentials?: Buffer | null } = {};
if (name !== undefined) updateData.name = name;
+ if (keystorePassword !== undefined) {
+ updateData.encryptedCredentials =
+ keystorePassword === null
+ ? null
+ : await encryptPkiInstallationCredentials({
+ projectId: installation.projectId,
+ credentials: { keystorePassword },
+ kmsService
+ });
+ }
const updatedInstallation = await pkiCertificateInstallationDAL.updateById(installationId, updateData);
- return updatedInstallation;
+ if (isSettingPassword) {
+ await queueInstallationRescan(installationId);
+ }
+
+ return sanitizePkiInstallation(updatedInstallation);
};
const deleteInstallation = async ({
@@ -164,7 +224,7 @@ export const pkiInstallationServiceFactory = ({
await pkiCertificateInstallationDAL.deleteById(installationId);
- return installation;
+ return sanitizePkiInstallation(installation);
};
return {
diff --git a/backend/src/lib/gateway-v2/certificate-scan-rpc.test.ts b/backend/src/lib/gateway-v2/certificate-scan-rpc.test.ts
new file mode 100644
index 0000000000..28a5b62c1e
--- /dev/null
+++ b/backend/src/lib/gateway-v2/certificate-scan-rpc.test.ts
@@ -0,0 +1,33 @@
+import { callCertificateScan } from "./certificate-scan-rpc";
+import { postGatewayRpc } from "./gateway-rpc";
+
+vi.mock("./gateway-rpc", () => ({ postGatewayRpc: vi.fn() }));
+
+const call = () =>
+ callCertificateScan({
+ port: 1,
+ credentials: {} as Parameters<typeof callCertificateScan>[0]["credentials"],
+ request: {
+ searchFolderPaths: ["/etc/ssl"],
+ skipFolderPaths: [],
+ maxFolderDepth: 8,
+ maxFileSizeBytes: 1024,
+ filePaths: [],
+ keystorePasswords: []
+ }
+ });
+
+describe("callCertificateScan", () => {
+ test("a gateway error keeps its kind and status and its text only as detail", async () => {
+ vi.mocked(postGatewayRpc).mockResolvedValue({
+ status: 502,
+ text: JSON.stringify({ error: { message: "ssh: unable to authenticate", kind: "auth" } })
+ });
+ expect(await call()).toEqual({ ok: false, status: 502, kind: "auth", detail: "ssh: unable to authenticate" });
+ });
+
+ test("a result is returned as is", async () => {
+ vi.mocked(postGatewayRpc).mockResolvedValue({ status: 200, text: JSON.stringify({ result: { files: [] } }) });
+ expect(await call()).toEqual({ ok: true, result: { files: [] } });
+ });
+});
diff --git a/backend/src/lib/gateway-v2/certificate-scan-rpc.ts b/backend/src/lib/gateway-v2/certificate-scan-rpc.ts
new file mode 100644
index 0000000000..802b835dee
--- /dev/null
+++ b/backend/src/lib/gateway-v2/certificate-scan-rpc.ts
@@ -0,0 +1,54 @@
+import { postGatewayRpc } from "./gateway-rpc";
+import { SshExecCredentials } from "./ssh-rpc";
+import { GatewayFailureKind } from "./test-connection-rpc";
+
+const CERTIFICATE_SCAN_RPC_TIMEOUT_MS = 12 * 60 * 1000;
+
+const MAX_CERTIFICATE_SCAN_RESPONSE_BYTES = 16 * 1024 * 1024;
+
+export enum CertificateScanRpcStatus {
+ Busy = 503,
+ Timeout = 504
+}
+
+export type TCertificateScanRequest = {
+ searchFolderPaths: string[];
+ skipFolderPaths: string[];
+ maxFolderDepth: number;
+ maxFileSizeBytes: number;
+ filePaths: string[];
+ keystorePasswords: { path: string; password: string }[];
+};
+
+export type TCertificateScanRpcFailure = {
+ ok: false;
+ status: number;
+ kind: GatewayFailureKind | null;
+ detail: string;
+};
+
+export const callCertificateScan = async (args: {
+ port: number;
+ credentials: SshExecCredentials;
+ request: TCertificateScanRequest;
+}): Promise<{ ok: true; result: unknown } | TCertificateScanRpcFailure> => {
+ const { status, text } = await postGatewayRpc({
+ port: args.port,
+ path: "/v1/scan-certificates",
+ payload: JSON.stringify({ ...args.credentials, ...args.request }),
+ timeoutMs: CERTIFICATE_SCAN_RPC_TIMEOUT_MS,
+ maxResponseBytes: MAX_CERTIFICATE_SCAN_RESPONSE_BYTES,
+ label: "Certificate scan"
+ });
+
+ if (status >= 200 && status < 300) return { ok: true, result: (JSON.parse(text) as { result?: unknown }).result };
+
+ const error = (() => {
+ try {
+ return (JSON.parse(text) as { error?: { message?: string; kind?: GatewayFailureKind } }).error;
+ } catch {
+ return undefined;
+ }
+ })();
+ return { ok: false, status, kind: error?.kind ?? null, detail: error?.message ?? `HTTP ${status}` };
+};
diff --git a/backend/src/queue/queue-service.ts b/backend/src/queue/queue-service.ts
index 3ae3833e79..bc99e27c6a 100644
--- a/backend/src/queue/queue-service.ts
+++ b/backend/src/queue/queue-service.ts
@@ -120,6 +120,7 @@ export enum QueueName {
PamDiscoveryScan = "pam-discovery-scan",
PkiAcmeChallengeValidation = "pki-acme-challenge-validation",
PkiDiscoveryScan = "pki-discovery-scan",
+ PkiDiscoveryRescan = "pki-discovery-rescan",
AppConnectionCredentialRotation = "app-connection-credential-rotation",
AppConnectionCredentialRotationRotate = "app-connection-credential-rotation-rotate",
AuditLogClickHouseBatch = "audit-log-clickhouse-batch",
@@ -203,6 +204,7 @@ export enum QueueJobs {
PkiAcmeChallengeValidation = "pki-acme-challenge-validation",
PkiDiscoveryRunScan = "pki-discovery-run-scan",
PkiDiscoveryScheduledScan = "pki-discovery-scheduled-scan",
+ PkiDiscoveryRescanInstallation = "pki-discovery-rescan-installation",
AppConnectionCredentialRotationQueueRotations = "app-connection-credential-rotation-queue-rotations",
AppConnectionCredentialRotationRotate = "app-connection-credential-rotation-rotate",
AppConnectionCredentialRotationSendNotification = "app-connection-credential-rotation-send-notification",
@@ -572,6 +574,10 @@ export type TQueueJobTypes = {
name: QueueJobs.PkiDiscoveryScheduledScan;
payload: undefined;
};
+ [QueueName.PkiDiscoveryRescan]: {
+ name: QueueJobs.PkiDiscoveryRescanInstallation;
+ payload: { installationId: string };
+ };
[QueueName.AppConnectionCredentialRotation]:
| {
name: QueueJobs.AppConnectionCredentialRotationQueueRotations;
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 4273694f34..56ef7b6739 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -4105,12 +4105,14 @@ export const registerRoutes = async (
certificateBodyDAL,
projectDAL,
kmsService,
+ appConnectionDAL,
queueService,
cronJob,
gatewayV2Service,
gatewayV2DAL,
gatewayPoolService,
- telemetryService
+ telemetryService,
+ keyStore
});
const pkiDiscoveryService = pkiDiscoveryServiceFactory({
@@ -4122,12 +4124,17 @@ export const registerRoutes = async (
gatewayV2DAL,
gatewayPoolDAL,
gatewayPoolService,
+ appConnectionService,
+ appConnectionDAL,
queuePkiDiscoveryScan: pkiDiscoveryQueue.queuePkiDiscoveryScan
});
const pkiInstallationService = pkiInstallationServiceFactory({
pkiCertificateInstallationDAL,
- permissionService
+ permissionService,
+ kmsService,
+ appConnectionDAL,
+ queueInstallationRescan: pkiDiscoveryQueue.queueInstallationRescan
});
const signerIssuanceService = signerIssuanceServiceFactory({
diff --git a/backend/src/server/routes/v1/app-connection-routers/app-connection-endpoints.ts b/backend/src/server/routes/v1/app-connection-routers/app-connection-endpoints.ts
index 53970520f8..69bda1e86d 100644
--- a/backend/src/server/routes/v1/app-connection-routers/app-connection-endpoints.ts
+++ b/backend/src/server/routes/v1/app-connection-routers/app-connection-endpoints.ts
@@ -161,7 +161,9 @@ export const buildListAvailableAppConnectionsRoute = (
name: z.string(),
id: z.string().uuid(),
projectId: z.string().nullish(),
- orgId: z.string()
+ orgId: z.string(),
+ gatewayId: z.string().uuid().nullish(),
+ gatewayPoolId: z.string().uuid().nullish()
})
.array()
})
diff --git a/backend/src/services/pki-sync/pki-sync-concurrency-fns.test.ts b/backend/src/services/app-connection/app-connection-concurrency-fns.test.ts
similarity index 53%
rename from backend/src/services/pki-sync/pki-sync-concurrency-fns.test.ts
rename to backend/src/services/app-connection/app-connection-concurrency-fns.test.ts
index 91cec23140..1f615d7cc4 100644
--- a/backend/src/services/pki-sync/pki-sync-concurrency-fns.test.ts
+++ b/backend/src/services/app-connection/app-connection-concurrency-fns.test.ts
@@ -4,11 +4,12 @@ import { describe, expect, it } from "vitest";
import { KeyStorePrefixes } from "@app/keystore/keystore";
-import { releasePkiSyncConcurrency, tryAdmitPkiSyncConcurrency } from "./pki-sync-concurrency-fns";
import {
- PKI_SYNC_CONNECTION_AGGREGATE_CONCURRENCY_LIMIT,
- PKI_SYNC_CONNECTION_CONCURRENCY_LIMIT
-} from "./pki-sync-enums";
+ APP_CONNECTION_AGGREGATE_CONCURRENCY_LIMIT,
+ APP_CONNECTION_CONCURRENCY_LIMIT,
+ releaseAppConnectionConcurrency,
+ tryAdmitAppConnectionConcurrency
+} from "./app-connection-concurrency-fns";
const buildKeyStore = () => {
const counts = new Map<string, number>();
@@ -33,14 +34,14 @@ const buildKeyStore = () => {
const CONNECTION = "connection-1";
const aggregateKey = KeyStorePrefixes.AppConnectionConcurrentJobs(CONNECTION);
-describe("pki sync connection concurrency", () => {
+describe("app connection concurrency", () => {
it("caps a single host at the per-host limit", async () => {
const keyStore = buildKeyStore();
- for (let i = 0; i < PKI_SYNC_CONNECTION_CONCURRENCY_LIMIT; i += 1) {
- expect(await tryAdmitPkiSyncConcurrency(keyStore, CONNECTION, "host-a")).toBe(true);
+ for (let i = 0; i < APP_CONNECTION_CONCURRENCY_LIMIT; i += 1) {
+ expect(await tryAdmitAppConnectionConcurrency(keyStore, CONNECTION, "host-a")).toBe(true);
}
- expect(await tryAdmitPkiSyncConcurrency(keyStore, CONNECTION, "host-a")).toBe(false);
+ expect(await tryAdmitAppConnectionConcurrency(keyStore, CONNECTION, "host-a")).toBe(false);
});
it("caps the connection across every host it backs", async () => {
@@ -48,31 +49,31 @@ describe("pki sync connection concurrency", () => {
let admitted = 0;
for (let host = 0; host < 50; host += 1) {
- for (let job = 0; job < PKI_SYNC_CONNECTION_CONCURRENCY_LIMIT; job += 1) {
- if (await tryAdmitPkiSyncConcurrency(keyStore, CONNECTION, `host-${host}`)) admitted += 1;
+ for (let job = 0; job < APP_CONNECTION_CONCURRENCY_LIMIT; job += 1) {
+ if (await tryAdmitAppConnectionConcurrency(keyStore, CONNECTION, `host-${host}`)) admitted += 1;
}
}
- expect(admitted).toBe(PKI_SYNC_CONNECTION_AGGREGATE_CONCURRENCY_LIMIT);
+ expect(admitted).toBe(APP_CONNECTION_AGGREGATE_CONCURRENCY_LIMIT);
});
it("does not consume an aggregate slot when the per-host limit refuses", async () => {
const keyStore = buildKeyStore();
- for (let i = 0; i < PKI_SYNC_CONNECTION_CONCURRENCY_LIMIT; i += 1) {
- await tryAdmitPkiSyncConcurrency(keyStore, CONNECTION, "host-a");
+ for (let i = 0; i < APP_CONNECTION_CONCURRENCY_LIMIT; i += 1) {
+ await tryAdmitAppConnectionConcurrency(keyStore, CONNECTION, "host-a");
}
const aggregateBefore = keyStore.counts.get(aggregateKey);
- expect(await tryAdmitPkiSyncConcurrency(keyStore, CONNECTION, "host-a")).toBe(false);
+ expect(await tryAdmitAppConnectionConcurrency(keyStore, CONNECTION, "host-a")).toBe(false);
expect(keyStore.counts.get(aggregateKey)).toBe(aggregateBefore);
});
it("releases both tiers so slots are reusable", async () => {
const keyStore = buildKeyStore();
- await tryAdmitPkiSyncConcurrency(keyStore, CONNECTION, "host-a");
- await releasePkiSyncConcurrency(keyStore, CONNECTION, "host-a");
+ await tryAdmitAppConnectionConcurrency(keyStore, CONNECTION, "host-a");
+ await releaseAppConnectionConcurrency(keyStore, CONNECTION, "host-a");
expect(keyStore.counts.size).toBe(0);
});
@@ -80,10 +81,10 @@ describe("pki sync connection concurrency", () => {
it("keeps one tier for a hosted sync, where the connection key is the host key", async () => {
const keyStore = buildKeyStore();
- for (let i = 0; i < PKI_SYNC_CONNECTION_CONCURRENCY_LIMIT; i += 1) {
- expect(await tryAdmitPkiSyncConcurrency(keyStore, CONNECTION)).toBe(true);
+ for (let i = 0; i < APP_CONNECTION_CONCURRENCY_LIMIT; i += 1) {
+ expect(await tryAdmitAppConnectionConcurrency(keyStore, CONNECTION)).toBe(true);
}
- expect(await tryAdmitPkiSyncConcurrency(keyStore, CONNECTION)).toBe(false);
- expect(keyStore.counts.get(aggregateKey)).toBe(PKI_SYNC_CONNECTION_CONCURRENCY_LIMIT);
+ expect(await tryAdmitAppConnectionConcurrency(keyStore, CONNECTION)).toBe(false);
+ expect(keyStore.counts.get(aggregateKey)).toBe(APP_CONNECTION_CONCURRENCY_LIMIT);
});
});
diff --git a/backend/src/services/pki-sync/pki-sync-concurrency-fns.ts b/backend/src/services/app-connection/app-connection-concurrency-fns.ts
similarity index 70%
rename from backend/src/services/pki-sync/pki-sync-concurrency-fns.ts
rename to backend/src/services/app-connection/app-connection-concurrency-fns.ts
index 962e19a5e9..915d68e92c 100644
--- a/backend/src/services/pki-sync/pki-sync-concurrency-fns.ts
+++ b/backend/src/services/app-connection/app-connection-concurrency-fns.ts
@@ -1,14 +1,14 @@
import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";
-import {
- PKI_SYNC_CONNECTION_AGGREGATE_CONCURRENCY_LIMIT,
- PKI_SYNC_CONNECTION_CONCURRENCY_LIMIT,
- PKI_SYNC_CONNECTION_CONCURRENCY_TTL_S
-} from "./pki-sync-enums";
+export const APP_CONNECTION_CONCURRENCY_LIMIT = 3;
+
+export const APP_CONNECTION_AGGREGATE_CONCURRENCY_LIMIT = 15;
+
+export const APP_CONNECTION_CONCURRENCY_TTL_S = 15 * 60;
type TConcurrencyKeyStore = Pick<TKeyStoreFactory, "incrementByAndRefreshExpiryIfUnderLimit" | "decrementByOrDelete">;
-export const tryAdmitPkiSyncConcurrency = async (
+export const tryAdmitAppConnectionConcurrency = async (
keyStore: TConcurrencyKeyStore,
connectionId: string,
targetHost?: string
@@ -18,23 +18,23 @@ export const tryAdmitPkiSyncConcurrency = async (
if (!targetHost) {
const count = await keyStore.incrementByAndRefreshExpiryIfUnderLimit(
aggregateKey,
- PKI_SYNC_CONNECTION_CONCURRENCY_LIMIT,
- PKI_SYNC_CONNECTION_CONCURRENCY_TTL_S
+ APP_CONNECTION_CONCURRENCY_LIMIT,
+ APP_CONNECTION_CONCURRENCY_TTL_S
);
return count !== -1;
}
const aggregateCount = await keyStore.incrementByAndRefreshExpiryIfUnderLimit(
aggregateKey,
- PKI_SYNC_CONNECTION_AGGREGATE_CONCURRENCY_LIMIT,
- PKI_SYNC_CONNECTION_CONCURRENCY_TTL_S
+ APP_CONNECTION_AGGREGATE_CONCURRENCY_LIMIT,
+ APP_CONNECTION_CONCURRENCY_TTL_S
);
if (aggregateCount === -1) return false;
const hostCount = await keyStore.incrementByAndRefreshExpiryIfUnderLimit(
KeyStorePrefixes.AppConnectionConcurrentJobs(connectionId, targetHost),
- PKI_SYNC_CONNECTION_CONCURRENCY_LIMIT,
- PKI_SYNC_CONNECTION_CONCURRENCY_TTL_S
+ APP_CONNECTION_CONCURRENCY_LIMIT,
+ APP_CONNECTION_CONCURRENCY_TTL_S
);
if (hostCount === -1) {
await keyStore.decrementByOrDelete(aggregateKey);
@@ -44,7 +44,7 @@ export const tryAdmitPkiSyncConcurrency = async (
return true;
};
-export const releasePkiSyncConcurrency = async (
+export const releaseAppConnectionConcurrency = async (
keyStore: TConcurrencyKeyStore,
connectionId: string,
targetHost?: string
diff --git a/backend/src/services/app-connection/ssh/ssh-connection-fns.ts b/backend/src/services/app-connection/ssh/ssh-connection-fns.ts
index f53c7222ae..2fe86df240 100644
--- a/backend/src/services/app-connection/ssh/ssh-connection-fns.ts
+++ b/backend/src/services/app-connection/ssh/ssh-connection-fns.ts
@@ -273,7 +273,7 @@ type TSshGatewayServices = {
gatewayPoolService?: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;
};
-const toSshExecCredentials = (config: TSshConnectionConfig): SshExecCredentials => {
+export const toSshExecCredentials = (config: TSshConnectionConfig): SshExecCredentials => {
switch (config.method) {
case SshConnectionMethod.Password:
return {
diff --git a/backend/src/services/pki-sync/pki-sync-enums.ts b/backend/src/services/pki-sync/pki-sync-enums.ts
index bd722ff5cb..bec41a4131 100644
--- a/backend/src/services/pki-sync/pki-sync-enums.ts
+++ b/backend/src/services/pki-sync/pki-sync-enums.ts
@@ -33,12 +33,6 @@ export enum PkiSyncFailureKind {
PostSyncCommand = "post-sync-command"
}
-export const PKI_SYNC_CONNECTION_CONCURRENCY_LIMIT = 3;
-
-export const PKI_SYNC_CONNECTION_AGGREGATE_CONCURRENCY_LIMIT = 15;
-
-export const PKI_SYNC_CONNECTION_CONCURRENCY_TTL_S = 15 * 60;
-
export const PKI_SYNC_CONNECTION_LOCK_RETRY = { retryCount: 10, retryDelay: 3_000, retryJitter: 500 };
export const HEALTH_CHECK_COMMAND_OPTION_KEY = "healthCheckCommand";
diff --git a/backend/src/services/pki-sync/pki-sync-health-check-queue.ts b/backend/src/services/pki-sync/pki-sync-health-check-queue.ts
index a2bb7d3c4d..a763604dfa 100644
--- a/backend/src/services/pki-sync/pki-sync-health-check-queue.ts
+++ b/backend/src/services/pki-sync/pki-sync-health-check-queue.ts
@@ -16,6 +16,10 @@ import { TNotificationServiceFactory } from "@app/services/notification/notifica
import { TPkiApplicationDALFactory } from "@app/services/pki-application/pki-application-dal";
import { TProjectDALFactory } from "@app/services/project/project-dal";
+import {
+ releaseAppConnectionConcurrency,
+ tryAdmitAppConnectionConcurrency
+} from "../app-connection/app-connection-concurrency-fns";
import { TAppConnectionDALFactory } from "../app-connection/app-connection-dal";
import { TCertificateBodyDALFactory } from "../certificate/certificate-body-dal";
import { TCertificateDALFactory } from "../certificate/certificate-dal";
@@ -23,7 +27,6 @@ import { TCertificateSecretDALFactory } from "../certificate/certificate-secret-
import { TCertificateAuthorityCertDALFactory } from "../certificate-authority/certificate-authority-cert-dal";
import { TCertificateAuthorityDALFactory } from "../certificate-authority/certificate-authority-dal";
import { buildCertificateMap } from "./pki-sync-certificate-map-fns";
-import { releasePkiSyncConcurrency, tryAdmitPkiSyncConcurrency } from "./pki-sync-concurrency-fns";
import { hydratePkiSyncCredentials } from "./pki-sync-credentials-fns";
import { TPkiSyncDALFactory } from "./pki-sync-dal";
import { PKI_SYNC_CONNECTION_LOCK_RETRY, PkiSync, PkiSyncFailureKind, PkiSyncStatus } from "./pki-sync-enums";
@@ -161,7 +164,7 @@ export const pkiSyncHealthCheckQueueFactory = ({
let admittedSlot = false;
try {
- admittedSlot = await tryAdmitPkiSyncConcurrency(keyStore, connectionId, targetHost);
+ admittedSlot = await tryAdmitAppConnectionConcurrency(keyStore, connectionId, targetHost);
if (!admittedSlot) {
throw new HealthCheckBusyError("This connection is at its concurrency limit.");
}
@@ -169,7 +172,7 @@ export const pkiSyncHealthCheckQueueFactory = ({
return await run();
} finally {
await Promise.allSettled([
- admittedSlot ? releasePkiSyncConcurrency(keyStore, connectionId, targetHost) : undefined,
+ admittedSlot ? releaseAppConnectionConcurrency(keyStore, connectionId, targetHost) : undefined,
connectionLock.release()
]);
}
diff --git a/backend/src/services/pki-sync/pki-sync-queue.ts b/backend/src/services/pki-sync/pki-sync-queue.ts
index 37faa443ef..8700ce68a9 100644
--- a/backend/src/services/pki-sync/pki-sync-queue.ts
+++ b/backend/src/services/pki-sync/pki-sync-queue.ts
@@ -20,6 +20,10 @@ import { TProjectDALFactory } from "@app/services/project/project-dal";
import { TTelemetryServiceFactory } from "@app/services/telemetry/telemetry-service";
import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
+import {
+ releaseAppConnectionConcurrency,
+ tryAdmitAppConnectionConcurrency
+} from "../app-connection/app-connection-concurrency-fns";
import { TAppConnectionDALFactory } from "../app-connection/app-connection-dal";
import { TCertificateBodyDALFactory } from "../certificate/certificate-body-dal";
import { TCertificateDALFactory } from "../certificate/certificate-dal";
@@ -29,7 +33,6 @@ import { TCertificateAuthorityDALFactory } from "../certificate-authority/certif
import { TCertificateSyncDALFactory } from "../certificate-sync/certificate-sync-dal";
import { CertificateSyncStatus } from "../certificate-sync/certificate-sync-enums";
import { buildCertificateMap } from "./pki-sync-certificate-map-fns";
-import { releasePkiSyncConcurrency, tryAdmitPkiSyncConcurrency } from "./pki-sync-concurrency-fns";
import { TPkiSyncDALFactory } from "./pki-sync-dal";
import { PKI_SYNC_CONNECTION_LOCK_RETRY, PkiSyncFailureKind, PkiSyncStatus } from "./pki-sync-enums";
import { PkiSyncError } from "./pki-sync-errors";
@@ -152,10 +155,10 @@ export const pkiSyncQueueFactory = ({
});
const $tryAdmitConnectionConcurrency = (connectionId: string, targetHost?: string) =>
- tryAdmitPkiSyncConcurrency(keyStore, connectionId, targetHost);
+ tryAdmitAppConnectionConcurrency(keyStore, connectionId, targetHost);
const $releaseConnectionConcurrency = (connectionId: string, targetHost?: string) =>
- releasePkiSyncConcurrency(keyStore, connectionId, targetHost);
+ releaseAppConnectionConcurrency(keyStore, connectionId, targetHost);
const $certificatesForSync = (pkiSync: TPkiSyncRaw) =>
buildCertificateMap(pkiSync, {
diff --git a/backend/src/services/telemetry/telemetry-types.ts b/backend/src/services/telemetry/telemetry-types.ts
index 50135f85b0..c996c26928 100644
--- a/backend/src/services/telemetry/telemetry-types.ts
+++ b/backend/src/services/telemetry/telemetry-types.ts
@@ -1730,6 +1730,7 @@ export type TPkiDiscoveryScanCompletedEvent = {
properties: {
orgId: string;
projectId: string;
+ discoveryType: string;
status: string;
certificatesFound: number;
installationsFound: number;
diff --git a/docs/docs.json b/docs/docs.json
index 391bdb92e8..909c72514a 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -590,7 +590,8 @@
"group": "Certificate discovery",
"pages": [
"documentation/platform/pki/discovery/overview",
- "documentation/platform/pki/discovery/network"
+ "documentation/platform/pki/discovery/network",
+ "documentation/platform/pki/discovery/linux-server"
]
},
{
diff --git a/docs/documentation/platform/pki/discovery/linux-server.mdx b/docs/documentation/platform/pki/discovery/linux-server.mdx
new file mode 100644
index 0000000000..3cef4c56f9
--- /dev/null
+++ b/docs/documentation/platform/pki/discovery/linux-server.mdx
@@ -0,0 +1,134 @@
+---
+title: "Linux Server"
+description: "Find the certificates stored in files and keystores on your Linux servers."
+---
+
+Linux Server discovery finds the certificates stored in files and keystores on your Linux servers, such as the certificates your web servers and Java applications load from disk. Scans reach each server through an [SSH connection](/integrations/app-connections/ssh) that uses an [Infisical Gateway](/documentation/platform/gateways/overview). Private keys in these files aren't imported.
+
+## Prerequisites
+
+- A [gateway](/documentation/platform/gateways/overview) running the latest version, deployed where it can reach your servers over SSH
+- An [SSH connection](/integrations/app-connections/ssh) for each server, configured to use a gateway or a [gateway pool](/documentation/platform/gateways/gateway-pools)
+- An SSH user that can read the folders you want to search (see [Give the SSH user read access](#give-the-ssh-user-read-access))
+
+<Warning>
+ The gateway doesn't verify the SSH host key of the servers it connects to. Only use SSH connections to servers on networks you trust.
+</Warning>
+
+## Supported files
+
+Each certificate file becomes an installation named after the server's hostname and the file path, for example `web-01:/etc/nginx/ssl/fullchain.pem`.
+
+A leaf certificate is imported with the CA certificates in the same file. Files that hold only CA certificates, such as trust bundles, are skipped unless you turn on **Import CA Certificates Found on Their Own**.
+
+Scans only open files with these extensions: `.pem`, `.crt`, `.cer`, `.cert`, `.der`, `.p7b`, `.p7c`, `.pfx`, `.p12`, `.jks`, `.keystore`, `.truststore`, `.jceks`, `.ks`, and files named `cacerts`.
+
+| Format | Notes |
+| --- | --- |
+| PEM | One or more certificates, including PEM-encoded PKCS#7 |
+| DER | A single certificate |
+| PKCS#7 | Certificate bundles |
+| PKCS#12 | Read without a password when possible, otherwise listed as locked |
+| JKS and JCEKS | Certificate entries are read without the keystore password |
+
+## 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.
+
+<Tabs>
+ <Tab title="Group or ACL">
+ Add the SSH user to a group that can read the folders, or grant read access with an ACL:
+
+ ```bash
+ setfacl -R -m u:<ssh-user>:rX /etc/ssl/private
+ setfacl -R -d -m u:<ssh-user>:rX /etc/ssl/private
+ ```
+
+ The second command makes files created later in the folder readable too.
+ </Tab>
+ <Tab title="sudo">
+ Allow the SSH user to run `find`, `readlink`, and `head` as root without a password. Add a file under `/etc/sudoers.d/`:
+
+ ```bash
+ <ssh-user> ALL=(root) NOPASSWD: /usr/bin/find, /usr/bin/readlink, /usr/bin/head
+ ```
+
+ The gateway tries every folder and file as the SSH user first, and uses `sudo` only for the ones it can't read.
+ </Tab>
+</Tabs>
+
+If a folder still can't be read, the scan completes and the job shows which folders were skipped.
+
+## Create a Linux Server discovery job
+
+<Tabs>
+ <Tab title="Infisical UI">
+ <Steps>
+ <Step>
+ In **Certificate Manager**, go to **Discovery** and select **Add Job**, then select **Linux Server**.
+ </Step>
+ <Step>
+ In **SSH Connections**, select the connection for each server to scan.
+ </Step>
+ <Step>
+ In **Search Folders**, add the folders to search. In **Skip Folders**, add any folders to leave out. `/proc`, `/sys`, and `/dev` are always skipped.
+ </Step>
+ <Step>
+ Set the options:
+ - **Folder Depth**: how many levels below each search folder to search (defaults to 8)
+ - **Largest File (KB)**: files bigger than this are skipped and listed in the scan results (defaults to 512)
+ - **Import CA Certificates Found on Their Own**: also import CA certificates from files that hold no leaf certificate
+ </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>
+ </Steps>
+ </Tab>
+ <Tab title="API">
+ To create the job, call [the endpoint that creates a discovery job](/api-reference/endpoints/pki-discovery/create) with `discoveryType` set to `linux-server`.
+
+ To start a scan, call [the endpoint that triggers a scan](/api-reference/endpoints/pki-discovery/trigger-scan).
+ </Tab>
+</Tabs>
+
+## Keystores that need a password
+
+If a PKCS#12 file can't be opened without a password, its installation is marked **Locked** and no certificates are read from it. To read it:
+
+<Steps>
+ <Step>
+ Go to **Discovery** > **Installations** and open the locked installation.
+ </Step>
+ <Step>
+ Select **Set Password**, enter the keystore password, and select **Save**.
+ </Step>
+</Steps>
+
+The file is scanned again right away, and later scans use the same password. If the password is wrong, the installation is marked **Password Failed**, and you can select **Change Password** to try again.
+
+To set the password through the API, call [the endpoint that updates an installation](/api-reference/endpoints/pki-installations/update) with `keystorePassword`. Send `null` to remove a saved password.
+
+## FAQ
+
+<AccordionGroup>
+ <Accordion title="Why does the job show a warning after a scan?">
+ The scan completed, but some files or folders couldn't be read, or the scan stopped early. The job lists what happened. For folders or files the SSH user can't open, [give the SSH user read access](#give-the-ssh-user-read-access). For files over the size limit, raise **Largest File (KB)**. If the scan stopped after 5,000 files, narrow the search folders or add skip folders.
+ </Accordion>
+</AccordionGroup>
+
+## What's next?
+
+<CardGroup cols={2}>
+ <Card title="Discovery overview" icon="radar" href="/documentation/platform/pki/discovery/overview">
+ Learn how installations and certificate matching work.
+ </Card>
+ <Card title="Network" icon="network" href="/documentation/platform/pki/discovery/network">
+ Scan TLS endpoints across IP ranges and domains.
+ </Card>
+</CardGroup>
diff --git a/docs/documentation/platform/pki/discovery/network.mdx b/docs/documentation/platform/pki/discovery/network.mdx
index 0b45921579..d3325091de 100644
--- a/docs/documentation/platform/pki/discovery/network.mdx
+++ b/docs/documentation/platform/pki/discovery/network.mdx
@@ -11,23 +11,24 @@ 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**.
+ 1. In **Certificate Manager**, go to **Discovery** and select **Add Job**, then select **Network**.
- 2. Fill in the discovery job details and click **Create**:
- - **Name**: A slug-friendly name for the discovery job (e.g., `prod-tls-scan`).
- - **Description**: An optional description.
+ 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`).
- **Ports**: Ports to scan for TLS certificates. Defaults to common TLS ports if not specified.
- **Gateway** (optional): The Infisical Gateway for scanning private networks.
- - **Auto Scan**: Enable automatic periodic scanning with a configurable interval.
<Note>
At least one target (domain or IP) must be specified.
</Note>
- 3. Trigger a scan manually by pressing **Scan Now**, or wait for the next automatic scan if enabled.
+ 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. After a scan completes, view the results:
+ 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:
- **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.
diff --git a/docs/documentation/platform/pki/discovery/overview.mdx b/docs/documentation/platform/pki/discovery/overview.mdx
index d64eca1025..64429f523c 100644
--- a/docs/documentation/platform/pki/discovery/overview.mdx
+++ b/docs/documentation/platform/pki/discovery/overview.mdx
@@ -11,15 +11,14 @@ Certificate Discovery automatically scans your infrastructure to find certificat
Discovery jobs scan your infrastructure and organize results as **installations** — unique locations where certificates were found. Each installation tracks certificates discovered at that location across multiple scans, allowing you to monitor changes over time.
<CardGroup cols={2}>
- <Card title="Network Discovery" icon="network" href="/documentation/platform/pki/discovery/network">
+ <Card title="Network" icon="network" href="/documentation/platform/pki/discovery/network">
Scan network endpoints over TLS to discover certificates served by hosts across IP ranges and domains.
</Card>
+ <Card title="Linux Server" icon="terminal" href="/documentation/platform/pki/discovery/linux-server">
+ Find the certificates stored in files and keystores on your Linux servers, through an SSH connection and a gateway.
+ </Card>
</CardGroup>
-<Note>
- Additional discovery types (cloud providers, file systems, etc.) will be added in future releases.
-</Note>
-
## Installations
An installation represents a unique location where a certificate was discovered — for example, a specific hostname and port combination.
@@ -50,9 +49,12 @@ Discovered certificates are matched to your existing inventory by fingerprint. I
## What's next?
<CardGroup cols={2}>
- <Card title="Network Discovery" icon="network" href="/documentation/platform/pki/discovery/network">
+ <Card title="Network" icon="network" href="/documentation/platform/pki/discovery/network">
Scan TLS endpoints across IP ranges and domains.
</Card>
+ <Card title="Linux Server" icon="terminal" href="/documentation/platform/pki/discovery/linux-server">
+ Find certificate files and keystores on Linux servers.
+ </Card>
<Card title="Applications" icon="layout-grid" href="/documentation/platform/pki/applications/overview">
Issue and manage certificates for your services.
</Card>
diff --git a/frontend/src/components/app-connections/AppConnectionOption.tsx b/frontend/src/components/app-connections/AppConnectionOption.tsx
index 19519aec9f..df166b366a 100644
--- a/frontend/src/components/app-connections/AppConnectionOption.tsx
+++ b/frontend/src/components/app-connections/AppConnectionOption.tsx
@@ -18,13 +18,15 @@ type TAppConnectionOptionContentProps = {
createLabel?: ReactNode;
isOnlyOption?: boolean;
isSelected?: boolean;
+ label?: ReactNode;
};
export const AppConnectionOptionContent = ({
data,
createLabel,
isOnlyOption = false,
- isSelected = false
+ isSelected = false,
+ label
}: TAppConnectionOptionContentProps) => {
const isCreateOption = data.id === "_create" || data.id.startsWith("_create:");
const { isSubOrganization } = useOrganization();
@@ -41,6 +43,7 @@ export const AppConnectionOptionContent = ({
) : (
<>
<p className="mr-auto truncate">{data.name}</p>
+ {label}
{!data.projectId && (
<Tooltip>
<TooltipTrigger asChild>
diff --git a/frontend/src/components/v3/generic/TagsInput/TagsInput.tsx b/frontend/src/components/v3/generic/TagsInput/TagsInput.tsx
index 6da0681423..fc09460237 100644
--- a/frontend/src/components/v3/generic/TagsInput/TagsInput.tsx
+++ b/frontend/src/components/v3/generic/TagsInput/TagsInput.tsx
@@ -135,7 +135,10 @@ const TagsInput = React.forwardRef<HTMLInputElement, TagsInputProps>(
multiple
items={NO_ITEMS}
value={tags}
- onValueChange={onValueChange}
+ onValueChange={(next, details) => {
+ if (details.reason === "escape-key") return;
+ onValueChange(next);
+ }}
// No popup is rendered, but the open state still drives aria-expanded and makes Base UI swallow Enter.
open={false}
onOpenChange={() => {}}
diff --git a/frontend/src/helpers/pkiDiscovery.ts b/frontend/src/helpers/pkiDiscovery.ts
new file mode 100644
index 0000000000..1bb54457e1
--- /dev/null
+++ b/frontend/src/helpers/pkiDiscovery.ts
@@ -0,0 +1,35 @@
+import { PkiDiscoveryType } from "@app/hooks/api/pkiDiscovery/types";
+
+export const PKI_DISCOVERY_TYPE_MAP: Record<
+ PkiDiscoveryType,
+ { name: string; category: string; description: string; image?: string }
+> = {
+ [PkiDiscoveryType.Network]: {
+ name: "Network",
+ category: "Network",
+ description: "Scan domains and IP ranges for certificates served on TLS ports."
+ },
+ [PkiDiscoveryType.LinuxServer]: {
+ name: "Linux Server",
+ category: "Infrastructure",
+ description: "Log in over SSH and read the certificate files on a Linux server.",
+ image: "SSH.png"
+ }
+};
+
+export const DEFAULT_LINUX_SEARCH_FOLDERS = [
+ "/etc/ssl",
+ "/etc/pki",
+ "/etc/nginx",
+ "/etc/httpd",
+ "/etc/letsencrypt",
+ "/opt"
+];
+
+export const DEFAULT_MAX_FOLDER_DEPTH = 8;
+export const MAX_FOLDER_DEPTH = 20;
+export const DEFAULT_MAX_FILE_SIZE_KB = 512;
+export const MAX_FILE_SIZE_KB = 10240;
+
+export const getDiscoveryDocsUrl = (type: PkiDiscoveryType) =>
+ `https://infisical.com/docs/documentation/platform/pki/discovery/${type}`;
diff --git a/frontend/src/hooks/api/appConnections/types/index.ts b/frontend/src/hooks/api/appConnections/types/index.ts
index 9df88a0039..3cd4282fb0 100644
--- a/frontend/src/hooks/api/appConnections/types/index.ts
+++ b/frontend/src/hooks/api/appConnections/types/index.ts
@@ -259,7 +259,10 @@ export type TAppConnection =
| TDaytonaConnection
| TStripeConnection;
-export type TAvailableAppConnection = Pick<TAppConnection, "name" | "id" | "projectId">;
+export type TAvailableAppConnection = Pick<TAppConnection, "name" | "id" | "projectId"> & {
+ gatewayId?: string | null;
+ gatewayPoolId?: string | null;
+};
export type TListAppConnections<T extends TAppConnection> = { appConnections: T[] };
// scott: we will need this once we have individual app connection page
diff --git a/frontend/src/hooks/api/pkiDiscovery/mutations.tsx b/frontend/src/hooks/api/pkiDiscovery/mutations.tsx
index 03952ddc41..2a76d832fc 100644
--- a/frontend/src/hooks/api/pkiDiscovery/mutations.tsx
+++ b/frontend/src/hooks/api/pkiDiscovery/mutations.tsx
@@ -120,13 +120,16 @@ export const useUpdatePkiInstallation = () => {
);
return data;
},
- onSuccess: (installation, { projectId }) => {
+ onSuccess: (installation, { projectId, keystorePassword }) => {
queryClient.invalidateQueries({ queryKey: pkiInstallationKeys.list(projectId) });
queryClient.invalidateQueries({
queryKey: pkiInstallationKeys.installation(installation.id)
});
createNotification({
- text: "Successfully updated installation",
+ text:
+ keystorePassword === undefined
+ ? "Successfully updated installation"
+ : "Password saved. Rescanning this file.",
type: "success"
});
}
diff --git a/frontend/src/hooks/api/pkiDiscovery/queries.tsx b/frontend/src/hooks/api/pkiDiscovery/queries.tsx
index 18ce4c94fb..ba20b44f6c 100644
--- a/frontend/src/hooks/api/pkiDiscovery/queries.tsx
+++ b/frontend/src/hooks/api/pkiDiscovery/queries.tsx
@@ -165,7 +165,10 @@ export const useListPkiInstallations = (
});
};
-export const useGetPkiInstallation = ({ installationId }: TGetPkiInstallationDTO) => {
+export const useGetPkiInstallation = (
+ { installationId }: TGetPkiInstallationDTO,
+ options?: { refetchInterval: (installation?: TPkiInstallation) => number | false }
+) => {
return useQuery({
queryKey: pkiInstallationKeys.installation(installationId),
queryFn: async () => {
@@ -174,6 +177,7 @@ export const useGetPkiInstallation = ({ installationId }: TGetPkiInstallationDTO
);
return data;
},
- enabled: Boolean(installationId)
+ enabled: Boolean(installationId),
+ refetchInterval: (query) => options?.refetchInterval(query.state.data) ?? false
});
};
diff --git a/frontend/src/hooks/api/pkiDiscovery/types.ts b/frontend/src/hooks/api/pkiDiscovery/types.ts
index d80701c96c..afb4131ca0 100644
--- a/frontend/src/hooks/api/pkiDiscovery/types.ts
+++ b/frontend/src/hooks/api/pkiDiscovery/types.ts
@@ -1,9 +1,30 @@
export enum PkiDiscoveryType {
- Network = "network"
+ Network = "network",
+ LinuxServer = "linux-server"
+}
+
+export enum PkiKeystoreStatus {
+ Locked = "locked",
+ Readable = "readable",
+ PasswordFailed = "password_failed"
+}
+
+export enum PkiCertificateFileFormat {
+ Pem = "pem",
+ Der = "der",
+ Pkcs7 = "pkcs7",
+ Pkcs12 = "pkcs12",
+ Jks = "jks",
+ Jceks = "jceks"
}
-export const PkiDiscoveryTypeLabels: Record<PkiDiscoveryType, string> = {
- [PkiDiscoveryType.Network]: "Network"
+export const PkiCertificateFileFormatLabels: Record<PkiCertificateFileFormat, string> = {
+ [PkiCertificateFileFormat.Pem]: "PEM",
+ [PkiCertificateFileFormat.Der]: "DER",
+ [PkiCertificateFileFormat.Pkcs7]: "PKCS#7",
+ [PkiCertificateFileFormat.Pkcs12]: "PKCS#12",
+ [PkiCertificateFileFormat.Jks]: "JKS",
+ [PkiCertificateFileFormat.Jceks]: "JCEKS"
};
export enum PkiDiscoveryScanStatus {
@@ -34,6 +55,12 @@ export type TPkiDiscoveryTargetConfig = {
ipRanges?: string[];
domains?: string[];
ports?: string; // Port specification: "443", "443, 8443", "8000-8100", or empty for auto-detect
+ connectionIds?: string[];
+ searchFolderPaths?: string[];
+ skipFolderPaths?: string[];
+ maxFolderDepth?: number;
+ maxFileSizeKb?: number;
+ importStandaloneCaCertificates?: boolean;
};
export type TPkiDiscovery = {
@@ -59,6 +86,7 @@ export type TPkiDiscovery = {
createdAt: string;
updatedAt: string;
linkedInstallationsCount?: number;
+ connections?: { id: string; name: string }[];
};
export type TPkiInstallation = {
@@ -75,11 +103,19 @@ export type TPkiInstallation = {
cloudProvider?: string;
cloudResource?: string;
gatewayName?: string;
+ hostname?: string;
+ format?: PkiCertificateFileFormat;
};
locationFingerprint: string;
name: string | null;
type: PkiInstallationType;
- metadata: Record<string, unknown> | null;
+ metadata: {
+ keystoreStatus?: PkiKeystoreStatus;
+ lastCheckedAt?: string;
+ lastError?: string;
+ } | null;
+ hasKeystorePassword?: boolean;
+ connection?: { id: string; name: string } | null;
lastSeenAt: string;
createdAt: string;
updatedAt: string;
@@ -210,6 +246,7 @@ export type TGetPkiInstallationDTO = {
export type TUpdatePkiInstallationDTO = {
installationId: string;
name?: string;
+ keystorePassword?: string | null;
};
export type TDeletePkiInstallationDTO = {
diff --git a/frontend/src/pages/cert-manager/DiscoveryDetailsByIDPage/DiscoveryDetailsByIDPage.tsx b/frontend/src/pages/cert-manager/DiscoveryDetailsByIDPage/DiscoveryDetailsByIDPage.tsx
index d079b6913b..4710ccde65 100644
--- a/frontend/src/pages/cert-manager/DiscoveryDetailsByIDPage/DiscoveryDetailsByIDPage.tsx
+++ b/frontend/src/pages/cert-manager/DiscoveryDetailsByIDPage/DiscoveryDetailsByIDPage.tsx
@@ -34,7 +34,7 @@ import {
import { ProjectType } from "@app/hooks/api/projects/types";
import { usePopUp } from "@app/hooks/usePopUp";
-import { DiscoveryJobModal } from "../DiscoveryPage/components/DiscoveryJobModal";
+import { DiscoveryJobSheet } from "../DiscoveryPage/components/DiscoveryJobSheet";
import {
DiscoveryDetailsSection,
DiscoveryInstallationsSection,
@@ -190,7 +190,7 @@ const Page = () => {
</div>
</div>
- <DiscoveryJobModal
+ <DiscoveryJobSheet
isOpen={popUp.editJob.isOpen}
onClose={() => handlePopUpClose("editJob")}
projectId={projectId}
diff --git a/frontend/src/pages/cert-manager/DiscoveryDetailsByIDPage/components/DiscoveryDetailsSection.tsx b/frontend/src/pages/cert-manager/DiscoveryDetailsByIDPage/components/DiscoveryDetailsSection.tsx
index c79be876e2..dd55032c70 100644
--- a/frontend/src/pages/cert-manager/DiscoveryDetailsByIDPage/components/DiscoveryDetailsSection.tsx
+++ b/frontend/src/pages/cert-manager/DiscoveryDetailsByIDPage/components/DiscoveryDetailsSection.tsx
@@ -12,7 +12,8 @@ import {
DetailLabel,
DetailValue
} from "@app/components/v3";
-import { PkiDiscoveryTypeLabels, TPkiDiscovery } from "@app/hooks/api";
+import { PKI_DISCOVERY_TYPE_MAP } from "@app/helpers/pkiDiscovery";
+import { TPkiDiscovery } from "@app/hooks/api";
import { getDiscoveryStatusBadge } from "@app/pages/cert-manager/pki-discovery-utils";
type Props = {
@@ -35,7 +36,7 @@ export const DiscoveryDetailsSection = ({ discovery }: Props) => {
<Detail>
<DetailLabel>Type</DetailLabel>
<DetailValue>
- {PkiDiscoveryTypeLabels[discovery.discoveryType] || discovery.discoveryType}
+ {PKI_DISCOVERY_TYPE_MAP[discovery.discoveryType]?.name ?? discovery.discoveryType}
</DetailValue>
</Detail>
{discovery.description && (
diff --git a/frontend/src/pages/cert-manager/DiscoveryDetailsByIDPage/components/DiscoveryInstallationsSection.tsx b/frontend/src/pages/cert-manager/DiscoveryDetailsByIDPage/components/DiscoveryInstallationsSection.tsx
index 1fbedfb756..86f5abad2d 100644
--- a/frontend/src/pages/cert-manager/DiscoveryDetailsByIDPage/components/DiscoveryInstallationsSection.tsx
+++ b/frontend/src/pages/cert-manager/DiscoveryDetailsByIDPage/components/DiscoveryInstallationsSection.tsx
@@ -100,7 +100,7 @@ export const DiscoveryInstallationsSection = ({ discoveryId, projectId, isScanRu
})
}
>
- <TableCell>{getEndpoint(installation)}</TableCell>
+ <TableCell>{installation.name || getEndpoint(installation)}</TableCell>
<TableCell>{installation.primaryCertName || "N/A"}</TableCell>
<TableCell>{getGatewayLabel(installation) || "N/A"}</TableCell>
<TableCell>
diff --git a/frontend/src/pages/cert-manager/DiscoveryDetailsByIDPage/components/DiscoveryTargetSection.tsx b/frontend/src/pages/cert-manager/DiscoveryDetailsByIDPage/components/DiscoveryTargetSection.tsx
index 1284f264d4..23894c6e0d 100644
--- a/frontend/src/pages/cert-manager/DiscoveryDetailsByIDPage/components/DiscoveryTargetSection.tsx
+++ b/frontend/src/pages/cert-manager/DiscoveryDetailsByIDPage/components/DiscoveryTargetSection.tsx
@@ -8,16 +8,88 @@ import {
Detail,
DetailGroup,
DetailLabel,
- DetailValue
+ DetailValue,
+ OverflowBadgeList
} from "@app/components/v3";
-import { TPkiDiscovery } from "@app/hooks/api";
-import { parsePorts } from "@app/pages/cert-manager/pki-discovery-utils";
+import { PkiDiscoveryType, TPkiDiscovery } from "@app/hooks/api";
+import { getItemLabel, parsePorts } from "@app/pages/cert-manager/pki-discovery-utils";
type Props = {
discovery: TPkiDiscovery;
};
+const LinuxServerTargetSection = ({ discovery }: Props) => {
+ const { targetConfig } = discovery;
+ const connectionsById = new Map((discovery.connections ?? []).map((c) => [c.id, c.name]));
+ const connectionIds = targetConfig.connectionIds ?? [];
+
+ return (
+ <Card>
+ <CardHeader className="border-b">
+ <CardTitle>Target Configuration</CardTitle>
+ <CardDescription>Servers and folders scanned by this discovery job</CardDescription>
+ </CardHeader>
+ <CardContent>
+ <DetailGroup>
+ <Detail>
+ <DetailLabel>SSH Connections</DetailLabel>
+ <DetailValue>
+ <OverflowBadgeList
+ items={connectionIds}
+ getKey={(id) => id}
+ getLabel={(id) => connectionsById.get(id) ?? "Deleted connection"}
+ />
+ </DetailValue>
+ </Detail>
+ <Detail>
+ <DetailLabel>Search Folders</DetailLabel>
+ <DetailValue>
+ <OverflowBadgeList
+ items={targetConfig.searchFolderPaths ?? []}
+ getKey={getItemLabel}
+ getLabel={getItemLabel}
+ />
+ </DetailValue>
+ </Detail>
+ {Boolean(targetConfig.skipFolderPaths?.length) && (
+ <Detail>
+ <DetailLabel>Skip Folders</DetailLabel>
+ <DetailValue>
+ <OverflowBadgeList
+ items={targetConfig.skipFolderPaths ?? []}
+ getKey={getItemLabel}
+ getLabel={getItemLabel}
+ />
+ </DetailValue>
+ </Detail>
+ )}
+ <Detail>
+ <DetailLabel>Folder Depth</DetailLabel>
+ <DetailValue>{targetConfig.maxFolderDepth}</DetailValue>
+ </Detail>
+ <Detail>
+ <DetailLabel>Largest File</DetailLabel>
+ <DetailValue>{targetConfig.maxFileSizeKb} KB</DetailValue>
+ </Detail>
+ <Detail>
+ <DetailLabel>Import CA Certificates Found on Their Own</DetailLabel>
+ <DetailValue>
+ <Badge variant={targetConfig.importStandaloneCaCertificates ? "success" : "neutral"}>
+ {targetConfig.importStandaloneCaCertificates ? "Enabled" : "Disabled"}
+ </Badge>
+ </DetailValue>
+ </Detail>
+ </DetailGroup>
+ </CardContent>
+ </Card>
+ );
+};
+
export const DiscoveryTargetSection = ({ discovery }: Props) => {
+ if (discovery.discoveryType === PkiDiscoveryType.LinuxServer) {
+ return <LinuxServerTargetSection discovery={discovery} />;
+ }
+
const { targetConfig } = discovery;
const { ports: portsStr } = targetConfig;
const domains = targetConfig.domains || [];
diff --git a/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobModal.tsx b/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobModal.tsx
deleted file mode 100644
index 868423bddc..0000000000
--- a/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobModal.tsx
+++ /dev/null
@@ -1,511 +0,0 @@
-import { useEffect } from "react";
-import { Controller, useForm } from "react-hook-form";
-import { zodResolver } from "@hookform/resolvers/zod";
-import { z } from "zod";
-
-import {
- Button,
- FormControl,
- Input,
- Modal,
- ModalContent,
- Select,
- SelectItem,
- Switch,
- TextArea
-} from "@app/components/v2";
-import { GatewayPicker } from "@app/components/v3";
-import { isInfisicalCloud } from "@app/helpers/platform";
-import {
- PkiDiscoveryType,
- TPkiDiscovery,
- useCreatePkiDiscovery,
- useUpdatePkiDiscovery
-} from "@app/hooks/api";
-
-type Props = {
- isOpen: boolean;
- onClose: () => void;
- projectId: string;
- discovery?: TPkiDiscovery;
-};
-
-const MAX_PORTS = 5;
-const MAX_IPS = 256;
-const MAX_DOMAINS = 20;
-const MIN_CIDR_PREFIX = 24;
-const DEFAULT_TLS_PORTS = "443,8443,636,993,995";
-
-const countPorts = (portsStr: string): number => {
- if (!portsStr.trim()) return 0;
-
- const parts = portsStr.split(",").map((p) => p.trim());
-
- return parts.reduce((count, part) => {
- if (part.includes("-")) {
- const [startStr, endStr] = part.split("-").map((p) => p.trim());
- const start = parseInt(startStr, 10);
- const end = parseInt(endStr, 10);
- if (!Number.isNaN(start) && !Number.isNaN(end)) {
- return count + end - start + 1;
- }
- } else {
- const port = parseInt(part, 10);
- if (!Number.isNaN(port)) return count + 1;
- }
- return count;
- }, 0);
-};
-
-const validatePorts = (portsStr: string): { valid: boolean; error?: string } => {
- if (!portsStr.trim()) {
- return { valid: false, error: "Ports are required" };
- }
-
- const parts = portsStr.split(",").map((p) => p.trim());
-
- const invalidPart = parts.find((part) => {
- if (part.includes("-")) {
- const [startStr, endStr] = part.split("-").map((p) => p.trim());
- const start = parseInt(startStr, 10);
- const end = parseInt(endStr, 10);
- return Number.isNaN(start) || Number.isNaN(end) || start < 1 || end > 65535 || start > end;
- }
- const port = parseInt(part, 10);
- return Number.isNaN(port) || port < 1 || port > 65535;
- });
-
- if (invalidPart) {
- if (invalidPart.includes("-")) {
- return { valid: false, error: `Invalid port range: ${invalidPart}` };
- }
- return { valid: false, error: `Invalid port: ${invalidPart}` };
- }
-
- const portCount = countPorts(portsStr);
- if (portCount > MAX_PORTS) {
- return { valid: false, error: `Maximum ${MAX_PORTS} ports allowed (you have ${portCount})` };
- }
-
- return { valid: true };
-};
-
-const validateTargets = (targetsStr: string): { valid: boolean; error?: string } => {
- const targets = targetsStr
- .split(/[\n,]/)
- .map((t) => t.trim())
- .filter(Boolean);
-
- if (targets.length === 0) {
- return { valid: false, error: "At least one target is required" };
- }
-
- const cidrRanges = targets.filter((t) => t.includes("/"));
- const singleIps = targets.filter((t) => !t.includes("/") && /^\d/.test(t));
- const domains = targets.filter((t) => /[a-zA-Z]/.test(t) && !t.includes("/"));
-
- const wildcardDomains = domains.filter((d) => d.startsWith("*"));
- if (wildcardDomains.length > 0) {
- return {
- valid: false,
- error: "Wildcard domains are not supported. Please enter specific domain names."
- };
- }
-
- const invalidCidr = cidrRanges.find((cidr) => {
- const prefixMatch = cidr.match(/\/(\d+)$/);
- if (prefixMatch) {
- const prefix = parseInt(prefixMatch[1], 10);
- return prefix < MIN_CIDR_PREFIX;
- }
- return false;
- });
-
- if (invalidCidr) {
- return {
- valid: false,
- error: `CIDR range too large: ${invalidCidr}. Maximum is /${MIN_CIDR_PREFIX} (256 IPs)`
- };
- }
-
- const totalIpCount = cidrRanges.reduce((count, cidr) => {
- const prefixMatch = cidr.match(/\/(\d+)$/);
- if (prefixMatch) {
- return count + 2 ** (32 - parseInt(prefixMatch[1], 10));
- }
- return count;
- }, singleIps.length);
-
- if (totalIpCount > MAX_IPS) {
- return {
- valid: false,
- error: `Maximum ${MAX_IPS} total IPs allowed (including expanded CIDR ranges)`
- };
- }
-
- if (domains.length > MAX_DOMAINS) {
- return { valid: false, error: `Maximum ${MAX_DOMAINS} domains allowed per discovery` };
- }
-
- return { valid: true };
-};
-
-const formSchema = z.object({
- name: z
- .string()
- .trim()
- .min(1, "Name is required")
- .max(100, "Name must be less than 100 characters")
- .regex(/^[a-z0-9-]+$/, "Name must contain only lowercase letters, numbers, and hyphens"),
- description: z.string().max(255).optional(),
- targets: z
- .string()
- .min(1, "At least one target is required")
- .superRefine((val, ctx) => {
- const result = validateTargets(val);
- if (!result.valid) {
- ctx.addIssue({ code: z.ZodIssueCode.custom, message: result.error });
- }
- }),
- ports: z
- .string()
- .min(1, "Ports are required")
- .superRefine((val, ctx) => {
- const result = validatePorts(val);
- if (!result.valid) {
- ctx.addIssue({ code: z.ZodIssueCode.custom, message: result.error });
- }
- }),
- gatewayId: z.string().optional().nullable(),
- gatewayPoolId: z.string().optional().nullable(),
- isAutoScanEnabled: z.boolean(),
- scanIntervalDays: z.number().min(1).max(365).optional()
-});
-
-type FormData = z.infer<typeof formSchema>;
-
-const parseTargets = (targetsStr: string): { domains: string[]; ipRanges: string[] } => {
- const targets = targetsStr
- .split(/[\n,]/)
- .map((t) => t.trim())
- .filter(Boolean);
-
- const domains: string[] = [];
- const ipRanges: string[] = [];
-
- targets.forEach((target) => {
- if (/[a-zA-Z]/.test(target) && !target.includes("/")) {
- domains.push(target);
- } else {
- ipRanges.push(target);
- }
- });
-
- return { domains, ipRanges };
-};
-
-const formatTargets = (discovery?: TPkiDiscovery): string => {
- if (!discovery) return "";
- const targets: string[] = [];
- if (discovery.targetConfig.domains) {
- targets.push(...discovery.targetConfig.domains);
- }
- if (discovery.targetConfig.ipRanges) {
- targets.push(...discovery.targetConfig.ipRanges);
- }
- return targets.join("\n");
-};
-
-const formatPorts = (discovery?: TPkiDiscovery): string => {
- if (!discovery?.targetConfig.ports) return "";
- return discovery.targetConfig.ports;
-};
-
-export const DiscoveryJobModal = ({ isOpen, onClose, projectId, discovery }: Props) => {
- const isEditing = Boolean(discovery);
-
- const {
- control,
- handleSubmit,
- reset,
- watch,
- setValue,
- formState: { isSubmitting }
- } = useForm<FormData>({
- resolver: zodResolver(formSchema),
- defaultValues: {
- name: "",
- description: "",
- targets: "",
- ports: DEFAULT_TLS_PORTS,
- gatewayId: null,
- gatewayPoolId: null,
- isAutoScanEnabled: false,
- scanIntervalDays: 7
- }
- });
-
- const createDiscovery = useCreatePkiDiscovery();
- const updateDiscovery = useUpdatePkiDiscovery();
-
- const isAutoScanEnabled = watch("isAutoScanEnabled");
-
- useEffect(() => {
- if (isOpen) {
- if (discovery) {
- reset({
- name: discovery.name,
- description: discovery.description || "",
- targets: formatTargets(discovery),
- ports: formatPorts(discovery),
- gatewayId: discovery.gatewayId,
- gatewayPoolId: discovery.gatewayPoolId,
- isAutoScanEnabled: discovery.isAutoScanEnabled,
- scanIntervalDays: discovery.scanIntervalDays || 7
- });
- } else {
- reset({
- name: "",
- description: "",
- targets: "",
- ports: DEFAULT_TLS_PORTS,
- gatewayId: null,
- gatewayPoolId: null,
- isAutoScanEnabled: false,
- scanIntervalDays: 7
- });
- }
- }
- }, [isOpen, discovery, reset]);
-
- const onSubmit = async (data: FormData) => {
- const { domains, ipRanges } = parseTargets(data.targets);
- const ports = data.ports?.trim();
-
- if (domains.length === 0 && ipRanges.length === 0) {
- return;
- }
-
- if (!ports) {
- return;
- }
-
- try {
- if (isEditing && discovery) {
- await updateDiscovery.mutateAsync({
- discoveryId: discovery.id,
- name: data.name,
- description: data.description || null,
- targetConfig: {
- domains: domains.length > 0 ? domains : undefined,
- ipRanges: ipRanges.length > 0 ? ipRanges : undefined,
- ports
- },
- gatewayId: data.gatewayPoolId ? null : (data.gatewayId ?? null),
- gatewayPoolId: data.gatewayPoolId ?? null,
- isAutoScanEnabled: data.isAutoScanEnabled,
- scanIntervalDays: data.isAutoScanEnabled ? data.scanIntervalDays : null
- });
- } else {
- await createDiscovery.mutateAsync({
- projectId,
- name: data.name,
- description: data.description,
- discoveryType: PkiDiscoveryType.Network,
- targetConfig: {
- domains: domains.length > 0 ? domains : undefined,
- ipRanges: ipRanges.length > 0 ? ipRanges : undefined,
- ports
- },
- gatewayId: data.gatewayPoolId ? undefined : (data.gatewayId ?? undefined),
- gatewayPoolId: data.gatewayPoolId ?? undefined,
- isAutoScanEnabled: data.isAutoScanEnabled,
- scanIntervalDays: data.isAutoScanEnabled ? data.scanIntervalDays : undefined
- });
- }
- onClose();
- } catch {
- // Error handled by mutation
- }
- };
-
- return (
- <Modal isOpen={isOpen} onOpenChange={(open) => !open && onClose()}>
- <ModalContent
- title={isEditing ? "Edit Discovery Job" : "Create Discovery Job"}
- subTitle={
- isEditing
- ? "Update the configuration for this discovery job"
- : "Configure a new certificate discovery job to scan your infrastructure"
- }
- >
- <form onSubmit={handleSubmit(onSubmit)}>
- <Controller
- name="name"
- control={control}
- render={({ field, fieldState: { error } }) => (
- <FormControl
- label="Name"
- isRequired
- isError={Boolean(error)}
- errorText={error?.message}
- >
- <Input
- {...field}
- placeholder="my-discovery-job"
- autoComplete="off"
- name="discovery-job-name"
- />
- </FormControl>
- )}
- />
-
- <Controller
- name="description"
- control={control}
- render={({ field, fieldState: { error } }) => (
- <FormControl label="Description" isError={Boolean(error)} errorText={error?.message}>
- <TextArea
- {...field}
- placeholder="Optional description for this discovery job"
- rows={2}
- />
- </FormControl>
- )}
- />
-
- <Controller
- name="targets"
- control={control}
- render={({ field, fieldState: { error } }) => (
- <FormControl
- label="Targets"
- isRequired
- isError={Boolean(error)}
- tooltipText={`Domains or IP addresses to scan for TLS certificates. Up to ${MAX_DOMAINS} domains or ${MAX_IPS} IPs. Supports individual IPs, CIDR ranges (max /${MIN_CIDR_PREFIX} each), or a mix of both.`}
- errorText={error?.message}
- >
- <TextArea
- {...field}
- placeholder="example.com, api.example.com, 192.168.1.0/24"
- rows={3}
- />
- </FormControl>
- )}
- />
-
- <Controller
- name="ports"
- control={control}
- render={({ field, fieldState: { error } }) => (
- <FormControl
- label="Ports"
- isRequired
- isError={Boolean(error)}
- tooltipText={`TCP ports to scan for TLS certificates. Specify up to ${MAX_PORTS} ports as comma-separated values (e.g. 443, 8443) or ranges (e.g. 8000-8010). Common TLS ports: 443 (HTTPS), 8443, 636 (LDAPS), 993 (IMAPS), 995 (POP3S), 465 (SMTPS).`}
- errorText={error?.message}
- >
- <Input {...field} placeholder={DEFAULT_TLS_PORTS} />
- </FormControl>
- )}
- />
-
- <Controller
- name="gatewayId"
- control={control}
- render={() => {
- const gatewayIdVal = watch("gatewayId");
- const gatewayPoolIdVal = watch("gatewayPoolId");
- return (
- <FormControl
- label="Gateway"
- tooltipClassName="max-w-lg py-3"
- tooltipText={
- <div className="flex flex-col gap-3">
- <p>
- Use a gateway to discover certificates on private networks that are not
- directly accessible from the internet. The gateway acts as a proxy, routing
- scan traffic through your infrastructure.
- </p>
- {!isInfisicalCloud() && (
- <p>
- Alternatively, you can set the{" "}
- <span className="font-medium text-foreground-soft">
- ALLOW_INTERNAL_IP_CONNECTIONS
- </span>{" "}
- environment variable to <span className="font-medium">true</span> on your
- instance to scan private networks directly without a gateway.
- </p>
- )}
- </div>
- }
- >
- <GatewayPicker
- value={{
- gatewayId: gatewayIdVal ?? null,
- gatewayPoolId: gatewayPoolIdVal ?? null
- }}
- onChange={({ gatewayId, gatewayPoolId }) => {
- setValue("gatewayId", gatewayId, { shouldDirty: true });
- setValue("gatewayPoolId", gatewayPoolId, { shouldDirty: true });
- }}
- className="w-full"
- />
- </FormControl>
- );
- }}
- />
-
- <Controller
- name="isAutoScanEnabled"
- control={control}
- render={({ field }) => (
- <FormControl>
- <Switch
- id="auto-scan"
- className="mr-2 ml-0 bg-muted/80 shadow-inner data-[state=checked]:bg-success/80"
- containerClassName="flex-row-reverse w-fit"
- thumbClassName="bg-surface-raised"
- isChecked={field.value}
- onCheckedChange={field.onChange}
- >
- Auto Scan
- </Switch>
- </FormControl>
- )}
- />
-
- {isAutoScanEnabled && (
- <Controller
- name="scanIntervalDays"
- control={control}
- render={({ field }) => (
- <FormControl label="Scan Interval">
- <Select
- value={String(field.value)}
- onValueChange={(val) => field.onChange(parseInt(val, 10))}
- className="w-full"
- >
- <SelectItem value="1">Daily</SelectItem>
- <SelectItem value="7">Weekly</SelectItem>
- <SelectItem value="14">Every 2 weeks</SelectItem>
- <SelectItem value="30">Monthly</SelectItem>
- </Select>
- </FormControl>
- )}
- />
- )}
-
- <div className="mt-6 flex justify-end gap-2">
- <Button variant="plain" colorSchema="secondary" onClick={onClose}>
- Cancel
- </Button>
- <Button type="submit" isLoading={isSubmitting} colorSchema="primary">
- {isEditing ? "Update" : "Create"}
- </Button>
- </div>
- </form>
- </ModalContent>
- </Modal>
- );
-};
diff --git a/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/DiscoveryDetailsFields.tsx b/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/DiscoveryDetailsFields.tsx
new file mode 100644
index 0000000000..b045de01f4
--- /dev/null
+++ b/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/DiscoveryDetailsFields.tsx
@@ -0,0 +1,119 @@
+import { Controller, useFormContext } from "react-hook-form";
+
+import {
+ Field,
+ FieldContent,
+ FieldDescription,
+ FieldError,
+ FieldLabel,
+ Input,
+ Label,
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+ TextArea,
+ Toggle
+} from "@app/components/v3";
+
+import { TDiscoveryJobForm } from "./discovery-job-form-schema";
+
+export const SCAN_INTERVAL_OPTIONS = [
+ { value: 1, label: "Daily" },
+ { value: 7, label: "Weekly" },
+ { value: 14, label: "Every 2 weeks" },
+ { value: 30, label: "Monthly" }
+];
+
+export const DiscoveryDetailsFields = () => {
+ const { control, watch } = useFormContext<TDiscoveryJobForm>();
+ const isAutoScanEnabled = watch("isAutoScanEnabled");
+
+ return (
+ <>
+ <Controller
+ control={control}
+ name="name"
+ render={({ field: { value, onChange }, fieldState: { error } }) => (
+ <Field className="mb-4">
+ <FieldLabel>Name</FieldLabel>
+ <Input
+ value={value ?? ""}
+ onChange={onChange}
+ placeholder="my-discovery-job"
+ isError={Boolean(error)}
+ autoComplete="off"
+ name="discovery-job-name"
+ />
+ {!error?.message && (
+ <FieldDescription>Lowercase letters, numbers and hyphens</FieldDescription>
+ )}
+ <FieldError errors={[error]} />
+ </Field>
+ )}
+ />
+ <Controller
+ control={control}
+ name="description"
+ render={({ field: { value, onChange }, fieldState: { error } }) => (
+ <Field className="mb-4">
+ <FieldLabel>
+ Description <span className="text-muted">(optional)</span>
+ </FieldLabel>
+ <TextArea
+ value={value ?? ""}
+ onChange={onChange}
+ placeholder="Describe what this job looks for..."
+ className="resize-none"
+ rows={3}
+ isError={Boolean(error)}
+ />
+ <FieldError errors={[error]} />
+ </Field>
+ )}
+ />
+ <Controller
+ control={control}
+ name="isAutoScanEnabled"
+ render={({ field: { value, onChange } }) => (
+ <Field orientation="horizontal" className="mb-4">
+ <FieldContent>
+ <Label htmlFor="auto-scan-enabled">Scan on a Schedule</Label>
+ <FieldDescription>Turn off to only scan when you start it.</FieldDescription>
+ </FieldContent>
+ <Toggle
+ id="auto-scan-enabled"
+ variant="project"
+ checked={value}
+ onCheckedChange={onChange}
+ />
+ </Field>
+ )}
+ />
+ {isAutoScanEnabled && (
+ <Controller
+ control={control}
+ name="scanIntervalDays"
+ render={({ field: { value, onChange } }) => (
+ <Field className="mb-4">
+ <FieldLabel>Scan Interval</FieldLabel>
+ <Select value={String(value)} onValueChange={(next) => onChange(Number(next))}>
+ <SelectTrigger className="w-full">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent position="popper">
+ {SCAN_INTERVAL_OPTIONS.map((option) => (
+ <SelectItem key={option.value} value={String(option.value)}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </Field>
+ )}
+ />
+ )}
+ </>
+ );
+};
diff --git a/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/DiscoveryJobForm.tsx b/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/DiscoveryJobForm.tsx
new file mode 100644
index 0000000000..27e1229a88
--- /dev/null
+++ b/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/DiscoveryJobForm.tsx
@@ -0,0 +1,302 @@
+import { useEffect, useState } from "react";
+import { FieldPath, FormProvider, useForm } from "react-hook-form";
+import { zodResolver } from "@hookform/resolvers/zod";
+
+import {
+ Button,
+ DocumentationLinkBadge,
+ Stepper,
+ StepperList,
+ StepperStep
+} from "@app/components/v3";
+import { getDiscoveryDocsUrl, PKI_DISCOVERY_TYPE_MAP } from "@app/helpers/pkiDiscovery";
+import { useCreatePkiDiscovery, useUpdatePkiDiscovery } from "@app/hooks/api";
+import {
+ PkiDiscoveryType,
+ TPkiDiscovery,
+ TPkiDiscoveryTargetConfig
+} from "@app/hooks/api/pkiDiscovery/types";
+
+import {
+ DiscoveryJobFormSchema,
+ getDefaultFormValues,
+ parseTargets,
+ TDiscoveryJobForm
+} from "./discovery-job-form-schema";
+import { DiscoveryDetailsFields } from "./DiscoveryDetailsFields";
+import { DiscoveryReviewFields } from "./DiscoveryReviewFields";
+import { LinuxServerFoldersFields } from "./LinuxServerFoldersFields";
+import { LinuxServerHostsFields } from "./LinuxServerHostsFields";
+import { LinuxServerOptionsFields } from "./LinuxServerOptionsFields";
+import { NetworkTargetFields } from "./NetworkTargetFields";
+
+type Props = {
+ discoveryType: PkiDiscoveryType;
+ projectId: string;
+ discovery?: TPkiDiscovery;
+ onComplete: () => void;
+ onCancel: () => void;
+ onDirtyChange: (isDirty: boolean) => void;
+};
+
+enum DiscoveryJobStep {
+ Targets = "targets",
+ Hosts = "hosts",
+ Folders = "folders",
+ Options = "options",
+ Details = "details",
+ Review = "review"
+}
+
+const STEP_META: Record<
+ DiscoveryJobStep,
+ { name: string; short: string; subtitle: string; rightDescription: string }
+> = {
+ [DiscoveryJobStep.Targets]: {
+ name: "Targets",
+ short: "What to scan",
+ subtitle: "Choose the domains, IP ranges and ports to check.",
+ rightDescription:
+ "Each target is checked on every port listed. Any certificate served over TLS is imported with its chain.\n\nUse a gateway when the targets are on a private network."
+ },
+ [DiscoveryJobStep.Hosts]: {
+ name: "Hosts",
+ short: "Servers to scan",
+ subtitle: "Pick the SSH connections for the servers to scan.",
+ rightDescription:
+ "Each SSH connection is one server. The scan runs from the gateway on that connection.\n\nOnly SSH connections that use a gateway can be selected."
+ },
+ [DiscoveryJobStep.Folders]: {
+ name: "Where to Look",
+ short: "Folders to search",
+ subtitle: "Choose the folders to search and the ones to leave out.",
+ rightDescription:
+ "Only files with certificate extensions are opened, such as .pem, .crt, .cer, .der, .p7b, .pfx, .p12, .jks and .keystore.\n\nThe SSH user needs read access to these folders. Give it access through a group or ACL, or allow it to run find, readlink and head with sudo without a password. Folders it still cannot read are listed in the scan."
+ },
+ [DiscoveryJobStep.Options]: {
+ name: "Options",
+ short: "Limits and CA certificates",
+ subtitle: "Set how deep to search and what to import.",
+ rightDescription:
+ "Private keys aren't imported.\n\nKeystores protected by a password are listed as locked. Set the password on the installation and that file is scanned again."
+ },
+ [DiscoveryJobStep.Details]: {
+ name: "Details",
+ short: "Name and schedule",
+ subtitle: "Name this job and choose when it runs.",
+ rightDescription: "A scheduled job runs again at the chosen interval."
+ },
+ [DiscoveryJobStep.Review]: {
+ name: "Review",
+ short: "Confirm and save",
+ subtitle: "Check the settings and save the job.",
+ rightDescription: "Every setting can be edited later from the job."
+ }
+};
+
+const STEP_FIELDS: Record<DiscoveryJobStep, FieldPath<TDiscoveryJobForm>[]> = {
+ [DiscoveryJobStep.Targets]: ["targets", "ports", "gatewayId", "gatewayPoolId"],
+ [DiscoveryJobStep.Hosts]: ["connections"],
+ [DiscoveryJobStep.Folders]: ["searchFolderPaths", "skipFolderPaths"],
+ [DiscoveryJobStep.Options]: ["maxFolderDepth", "maxFileSizeKb", "importStandaloneCaCertificates"],
+ [DiscoveryJobStep.Details]: ["name", "description", "isAutoScanEnabled", "scanIntervalDays"],
+ [DiscoveryJobStep.Review]: []
+};
+
+const getSteps = (type: PkiDiscoveryType): DiscoveryJobStep[] =>
+ type === PkiDiscoveryType.LinuxServer
+ ? [
+ DiscoveryJobStep.Hosts,
+ DiscoveryJobStep.Folders,
+ DiscoveryJobStep.Options,
+ DiscoveryJobStep.Details,
+ DiscoveryJobStep.Review
+ ]
+ : [DiscoveryJobStep.Targets, DiscoveryJobStep.Details, DiscoveryJobStep.Review];
+
+const buildTargetConfig = (form: TDiscoveryJobForm): TPkiDiscoveryTargetConfig => {
+ if (form.discoveryType === PkiDiscoveryType.LinuxServer) {
+ return {
+ connectionIds: form.connections.map((c) => c.id),
+ searchFolderPaths: form.searchFolderPaths,
+ skipFolderPaths: form.skipFolderPaths,
+ maxFolderDepth: form.maxFolderDepth,
+ maxFileSizeKb: form.maxFileSizeKb,
+ importStandaloneCaCertificates: form.importStandaloneCaCertificates
+ };
+ }
+ const { domains, ipRanges } = parseTargets(form.targets);
+ return {
+ domains: domains.length ? domains : undefined,
+ ipRanges: ipRanges.length ? ipRanges : undefined,
+ ports: form.ports.trim()
+ };
+};
+
+export const DiscoveryJobForm = ({
+ discoveryType,
+ projectId,
+ discovery,
+ onComplete,
+ onCancel,
+ onDirtyChange
+}: Props) => {
+ const isEditing = Boolean(discovery);
+ const createDiscovery = useCreatePkiDiscovery();
+ const updateDiscovery = useUpdatePkiDiscovery();
+ const [stepIndex, setStepIndex] = useState(0);
+
+ const formMethods = useForm<TDiscoveryJobForm>({
+ resolver: zodResolver(DiscoveryJobFormSchema),
+ defaultValues: getDefaultFormValues(discoveryType, discovery),
+ mode: "onChange",
+ reValidateMode: "onChange"
+ });
+
+ const { handleSubmit, trigger, formState } = formMethods;
+ const isPending = createDiscovery.isPending || updateDiscovery.isPending;
+
+ const steps = getSteps(discoveryType);
+ const currentKey = steps[stepIndex];
+ const currentStep = STEP_META[currentKey];
+ const isFinalStep = stepIndex === steps.length - 1;
+
+ useEffect(() => {
+ onDirtyChange(formState.isDirty);
+ }, [formState.isDirty]);
+
+ const onSubmit = async (form: TDiscoveryJobForm) => {
+ const isNetwork = form.discoveryType === PkiDiscoveryType.Network;
+ const gatewayPoolId = isNetwork ? form.gatewayPoolId || null : null;
+ const gatewayId = isNetwork ? form.gatewayId || null : null;
+ const payload = {
+ name: form.name,
+ targetConfig: buildTargetConfig(form),
+ isAutoScanEnabled: form.isAutoScanEnabled
+ };
+
+ if (discovery) {
+ await updateDiscovery.mutateAsync({
+ ...payload,
+ discoveryId: discovery.id,
+ description: form.description || null,
+ ...(isNetwork && { gatewayId, gatewayPoolId }),
+ scanIntervalDays: form.isAutoScanEnabled ? form.scanIntervalDays : null
+ });
+ } else {
+ await createDiscovery.mutateAsync({
+ ...payload,
+ projectId,
+ description: form.description || undefined,
+ discoveryType: form.discoveryType,
+ gatewayId: gatewayId ?? undefined,
+ gatewayPoolId: gatewayPoolId ?? undefined,
+ scanIntervalDays: form.isAutoScanEnabled ? form.scanIntervalDays : undefined
+ });
+ }
+ onComplete();
+ };
+
+ const handleNext = async () => {
+ if (isFinalStep) {
+ await handleSubmit(onSubmit)().catch(() => undefined);
+ return;
+ }
+ const isValid = await trigger(STEP_FIELDS[currentKey]);
+ if (isValid) setStepIndex((prev) => prev + 1);
+ };
+
+ const handleBack = () => {
+ if (stepIndex === 0) {
+ onCancel();
+ return;
+ }
+ setStepIndex((prev) => prev - 1);
+ };
+
+ return (
+ <form
+ onSubmit={(e) => e.preventDefault()}
+ className="flex min-h-0 flex-1 flex-col overflow-hidden"
+ >
+ <FormProvider {...formMethods}>
+ <div className="flex min-h-0 flex-1 overflow-hidden">
+ <aside className="flex w-60 shrink-0 flex-col border-r border-border px-5 py-6">
+ <p className="mb-5 text-[11px] font-medium tracking-wider text-muted uppercase">
+ Setup steps
+ </p>
+ <Stepper
+ activeStep={stepIndex}
+ orientation="vertical"
+ onStepChange={(index) => {
+ if (index < stepIndex) setStepIndex(index);
+ }}
+ >
+ <StepperList>
+ {steps.map((key, index) => (
+ <StepperStep
+ key={key}
+ index={index}
+ title={STEP_META[key].name}
+ description={STEP_META[key].short}
+ />
+ ))}
+ </StepperList>
+ </Stepper>
+ </aside>
+
+ <div className="flex min-w-0 flex-1 flex-col gap-y-2 overflow-y-auto px-8 py-6">
+ <div className="mb-6">
+ <h2 className="text-lg font-normal text-foreground">{currentStep.name}</h2>
+ <p className="mt-1 text-sm text-muted">{currentStep.subtitle}</p>
+ </div>
+ {currentKey === DiscoveryJobStep.Targets && <NetworkTargetFields />}
+ {currentKey === DiscoveryJobStep.Hosts && <LinuxServerHostsFields />}
+ {currentKey === DiscoveryJobStep.Folders && <LinuxServerFoldersFields />}
+ {currentKey === DiscoveryJobStep.Options && <LinuxServerOptionsFields />}
+ {currentKey === DiscoveryJobStep.Details && <DiscoveryDetailsFields />}
+ {currentKey === DiscoveryJobStep.Review && <DiscoveryReviewFields />}
+ </div>
+
+ <aside className="hidden w-80 shrink-0 flex-col gap-4 overflow-y-auto border-l border-border px-6 py-6 lg:flex">
+ <div className="mb-auto">
+ <div className="flex items-center justify-between gap-2">
+ <p className="text-[11px] font-medium tracking-wider text-muted uppercase">
+ Step {stepIndex + 1} · {currentStep.name}
+ </p>
+ <DocumentationLinkBadge href={getDiscoveryDocsUrl(discoveryType)} />
+ </div>
+ <p className="mt-4 text-sm font-semibold text-foreground">What this step does</p>
+ {currentStep.rightDescription.split("\n\n").map((paragraph) => (
+ <p key={paragraph} className="mt-2 text-sm leading-relaxed text-muted">
+ {paragraph}
+ </p>
+ ))}
+ </div>
+ </aside>
+ </div>
+ </FormProvider>
+
+ <div className="flex shrink-0 items-center justify-between gap-3 border-t border-border px-6 py-4">
+ <span className="text-xs text-muted">
+ {PKI_DISCOVERY_TYPE_MAP[discoveryType].name} · Step {stepIndex + 1} of {steps.length}
+ </span>
+ <div className="flex items-center gap-3">
+ <Button type="button" variant="outline" onClick={handleBack}>
+ {stepIndex === 0 ? "Cancel" : "Back"}
+ </Button>
+ <Button
+ type="button"
+ variant="project"
+ onClick={handleNext}
+ isPending={isFinalStep && isPending}
+ isDisabled={isFinalStep && isPending}
+ >
+ {!isFinalStep && "Continue"}
+ {isFinalStep && (isEditing ? "Save Changes" : "Create Job")}
+ </Button>
+ </div>
+ </div>
+ </form>
+ );
+};
diff --git a/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/DiscoveryJobSheet.tsx b/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/DiscoveryJobSheet.tsx
new file mode 100644
index 0000000000..6bcf4a5435
--- /dev/null
+++ b/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/DiscoveryJobSheet.tsx
@@ -0,0 +1,123 @@
+import { useEffect, useState } from "react";
+import { ArrowLeftIcon } from "lucide-react";
+
+import {
+ Button,
+ DiscardChangesAlertDialog,
+ Sheet,
+ SheetContent,
+ SheetDescription,
+ SheetHeader,
+ SheetTitle
+} from "@app/components/v3";
+import { PKI_DISCOVERY_TYPE_MAP } from "@app/helpers/pkiDiscovery";
+import { PkiDiscoveryType, TPkiDiscovery } from "@app/hooks/api/pkiDiscovery/types";
+import { useDiscardChangesGuard } from "@app/hooks/useDiscardChangesGuard";
+
+import { DiscoveryJobForm } from "./DiscoveryJobForm";
+import { DiscoveryTypeIcon } from "./DiscoveryTypeIcon";
+import { DiscoveryTypeSelect } from "./DiscoveryTypeSelect";
+
+type Props = {
+ isOpen: boolean;
+ onClose: () => void;
+ projectId: string;
+ discovery?: TPkiDiscovery;
+};
+
+export const DiscoveryJobSheet = ({ isOpen, onClose, projectId, discovery }: Props) => {
+ const [selectedType, setSelectedType] = useState<PkiDiscoveryType | null>(
+ discovery?.discoveryType ?? null
+ );
+ const [isDirty, setIsDirty] = useState(false);
+
+ useEffect(() => {
+ if (!isOpen) return;
+ setSelectedType(discovery?.discoveryType ?? null);
+ setIsDirty(false);
+ }, [isOpen, discovery]);
+
+ const closeSheet = () => {
+ setIsDirty(false);
+ onClose();
+ };
+
+ const { confirmDiscard, isDiscardDialogOpen, requestDiscard, setIsDiscardDialogOpen } =
+ useDiscardChangesGuard({ isDirty, onDiscard: closeSheet });
+
+ const handleOpenChange = (nextOpen: boolean) => {
+ if (!nextOpen) requestDiscard();
+ };
+
+ const showBack = !discovery && Boolean(selectedType);
+
+ const renderBody = () => {
+ if (selectedType) {
+ return (
+ <DiscoveryJobForm
+ key={`${selectedType}-${discovery?.id ?? "new"}`}
+ discoveryType={selectedType}
+ projectId={projectId}
+ discovery={discovery}
+ onComplete={closeSheet}
+ onCancel={() => (discovery ? requestDiscard() : setSelectedType(null))}
+ onDirtyChange={setIsDirty}
+ />
+ );
+ }
+ return (
+ <div className="flex min-h-0 flex-1 flex-col overflow-y-auto p-6">
+ <DiscoveryTypeSelect onSelect={setSelectedType} />
+ </div>
+ );
+ };
+
+ return (
+ <>
+ <Sheet open={isOpen} onOpenChange={handleOpenChange}>
+ <SheetContent size="workspace" className="flex h-full max-h-full flex-col gap-y-0 p-0">
+ <SheetHeader className="border-b">
+ {selectedType ? (
+ <>
+ {showBack && (
+ <Button
+ variant="link"
+ size="xs"
+ className="mb-1 w-fit px-0"
+ onClick={() => {
+ setSelectedType(null);
+ setIsDirty(false);
+ }}
+ >
+ <ArrowLeftIcon />
+ Select Another Type
+ </Button>
+ )}
+ <SheetTitle className="flex items-center gap-2">
+ <DiscoveryTypeIcon type={selectedType} className="size-5" />
+ {discovery
+ ? `Edit ${discovery.name}`
+ : `New ${PKI_DISCOVERY_TYPE_MAP[selectedType].name} Discovery Job`}
+ </SheetTitle>
+ </>
+ ) : (
+ <>
+ <SheetTitle>New Discovery Job</SheetTitle>
+ <SheetDescription>Choose where to look for certificates.</SheetDescription>
+ </>
+ )}
+ </SheetHeader>
+ {renderBody()}
+ </SheetContent>
+ </Sheet>
+
+ <DiscardChangesAlertDialog
+ open={isDiscardDialogOpen}
+ onOpenChange={setIsDiscardDialogOpen}
+ onDiscard={confirmDiscard}
+ title="Discard Discovery Job?"
+ description="Your changes to this discovery job will be lost."
+ />
+ </>
+ );
+};
diff --git a/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/DiscoveryReviewFields.tsx b/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/DiscoveryReviewFields.tsx
new file mode 100644
index 0000000000..e7bef72a8a
--- /dev/null
+++ b/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/DiscoveryReviewFields.tsx
@@ -0,0 +1,107 @@
+import { ReactNode } from "react";
+import { useFormContext } from "react-hook-form";
+
+import {
+ Badge,
+ Detail,
+ DetailGroup,
+ DetailGroupHeader,
+ DetailLabel,
+ DetailValue,
+ OverflowBadgeList
+} from "@app/components/v3";
+import { PKI_DISCOVERY_TYPE_MAP } from "@app/helpers/pkiDiscovery";
+import { PkiDiscoveryType } from "@app/hooks/api/pkiDiscovery/types";
+import { getItemLabel } from "@app/pages/cert-manager/pki-discovery-utils";
+
+import { parseTargets, TDiscoveryJobForm } from "./discovery-job-form-schema";
+import { SCAN_INTERVAL_OPTIONS } from "./DiscoveryDetailsFields";
+
+const ReviewDetail = ({ label, children }: { label: string; children?: ReactNode }) => (
+ <Detail>
+ <DetailLabel>{label}</DetailLabel>
+ <DetailValue>{children || <span className="text-muted">None</span>}</DetailValue>
+ </Detail>
+);
+
+const ReviewBadgesDetail = ({ label, items }: { label: string; items: string[] }) => (
+ <Detail className="w-full min-w-0">
+ <DetailLabel>{label}</DetailLabel>
+ <DetailValue>
+ {items.length ? (
+ <OverflowBadgeList items={items} getKey={getItemLabel} getLabel={getItemLabel} />
+ ) : (
+ <span className="text-muted">None</span>
+ )}
+ </DetailValue>
+ </Detail>
+);
+
+const ReviewGroup = ({ title, children }: { title: string; children: ReactNode }) => (
+ <DetailGroup>
+ <DetailGroupHeader className="border-b border-border pb-2">{title}</DetailGroupHeader>
+ <div className="flex flex-wrap gap-x-8 gap-y-4">{children}</div>
+ </DetailGroup>
+);
+
+export const DiscoveryReviewFields = () => {
+ const { watch } = useFormContext<TDiscoveryJobForm>();
+ const values = watch();
+
+ let gatewayLabel: string | undefined;
+ if (values.discoveryType === PkiDiscoveryType.Network) {
+ if (values.gatewayPoolId) gatewayLabel = "Gateway pool";
+ else if (values.gatewayId) gatewayLabel = "Gateway";
+ }
+
+ const networkTargets =
+ values.discoveryType === PkiDiscoveryType.Network ? parseTargets(values.targets) : null;
+
+ const scheduleLabel = values.isAutoScanEnabled
+ ? SCAN_INTERVAL_OPTIONS.find((option) => option.value === values.scanIntervalDays)?.label
+ : "Manual only";
+
+ return (
+ <div className="mb-4 flex flex-col gap-y-8">
+ {values.discoveryType === PkiDiscoveryType.Network && (
+ <ReviewGroup title="Targets">
+ <ReviewBadgesDetail label="Domains" items={networkTargets?.domains ?? []} />
+ <ReviewBadgesDetail label="IP Ranges" items={networkTargets?.ipRanges ?? []} />
+ <ReviewDetail label="Ports">{values.ports}</ReviewDetail>
+ <ReviewDetail label="Gateway">{gatewayLabel}</ReviewDetail>
+ </ReviewGroup>
+ )}
+ {values.discoveryType === PkiDiscoveryType.LinuxServer && (
+ <>
+ <ReviewGroup title="Hosts">
+ <ReviewBadgesDetail
+ label="SSH Connections"
+ items={values.connections.map((connection) => connection.name)}
+ />
+ </ReviewGroup>
+ <ReviewGroup title="Where to Look">
+ <ReviewBadgesDetail label="Search Folders" items={values.searchFolderPaths} />
+ <ReviewBadgesDetail label="Skip Folders" items={values.skipFolderPaths} />
+ </ReviewGroup>
+ <ReviewGroup title="Options">
+ <ReviewDetail label="Folder Depth">{String(values.maxFolderDepth)}</ReviewDetail>
+ <ReviewDetail label="Largest File">{`${values.maxFileSizeKb} KB`}</ReviewDetail>
+ <ReviewDetail label="Import CA Certificates Found on Their Own">
+ <Badge variant={values.importStandaloneCaCertificates ? "success" : "neutral"}>
+ {values.importStandaloneCaCertificates ? "Enabled" : "Disabled"}
+ </Badge>
+ </ReviewDetail>
+ </ReviewGroup>
+ </>
+ )}
+ <ReviewGroup title="Details">
+ <ReviewDetail label="Type">
+ {PKI_DISCOVERY_TYPE_MAP[values.discoveryType].name}
+ </ReviewDetail>
+ <ReviewDetail label="Name">{values.name}</ReviewDetail>
+ <ReviewDetail label="Schedule">{scheduleLabel}</ReviewDetail>
+ <ReviewDetail label="Description">{values.description}</ReviewDetail>
+ </ReviewGroup>
+ </div>
+ );
+};
diff --git a/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/DiscoveryTypeIcon.tsx b/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/DiscoveryTypeIcon.tsx
new file mode 100644
index 0000000000..474531e690
--- /dev/null
+++ b/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/DiscoveryTypeIcon.tsx
@@ -0,0 +1,19 @@
+import { GlobeIcon } from "lucide-react";
+
+import { ProviderIcon } from "@app/components/v3/platform/ProviderIcon";
+import { PKI_DISCOVERY_TYPE_MAP } from "@app/helpers/pkiDiscovery";
+import { PkiDiscoveryType } from "@app/hooks/api/pkiDiscovery/types";
+
+export const DiscoveryTypeIcon = ({
+ type,
+ className = "h-6 w-6"
+}: {
+ type: PkiDiscoveryType;
+ className?: string;
+}) => {
+ const { name, image } = PKI_DISCOVERY_TYPE_MAP[type];
+ if (!image) return <GlobeIcon className={`${className} text-muted`} />;
+ return (
+ <ProviderIcon icon={image} alt={`${name} logo`} className={`${className} object-contain`} />
+ );
+};
diff --git a/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/DiscoveryTypeSelect.tsx b/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/DiscoveryTypeSelect.tsx
new file mode 100644
index 0000000000..6d48411c23
--- /dev/null
+++ b/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/DiscoveryTypeSelect.tsx
@@ -0,0 +1,37 @@
+import { PKI_DISCOVERY_TYPE_MAP } from "@app/helpers/pkiDiscovery";
+import { PkiDiscoveryType } from "@app/hooks/api/pkiDiscovery/types";
+
+import { DiscoveryTypeIcon } from "./DiscoveryTypeIcon";
+
+type Props = {
+ onSelect: (type: PkiDiscoveryType) => void;
+};
+
+export const DiscoveryTypeSelect = ({ onSelect }: Props) => (
+ <div className="grid grid-cols-1 gap-3 sm:grid-cols-2">
+ {Object.values(PkiDiscoveryType).map((type) => {
+ const { name, category, description } = PKI_DISCOVERY_TYPE_MAP[type];
+ return (
+ <button
+ key={type}
+ type="button"
+ onClick={() => onSelect(type)}
+ className="group flex cursor-pointer flex-col gap-3 rounded-md border border-border bg-card p-4 text-left transition-colors hover:border-border-strong hover:bg-surface-hover/50"
+ >
+ <div className="flex items-start justify-between gap-2">
+ <div className="flex h-9 w-9 items-center justify-center rounded-md bg-surface-hover">
+ <DiscoveryTypeIcon type={type} />
+ </div>
+ <span className="text-[10px] font-medium tracking-wider text-muted uppercase">
+ {category}
+ </span>
+ </div>
+ <div className="flex flex-col gap-1">
+ <p className="text-sm font-semibold text-foreground">{name}</p>
+ <p className="text-xs leading-relaxed text-muted">{description}</p>
+ </div>
+ </button>
+ );
+ })}
+ </div>
+);
diff --git a/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/LinuxServerFoldersFields.tsx b/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/LinuxServerFoldersFields.tsx
new file mode 100644
index 0000000000..6821f82995
--- /dev/null
+++ b/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/LinuxServerFoldersFields.tsx
@@ -0,0 +1,81 @@
+import { useState } from "react";
+import { Controller, useFormContext } from "react-hook-form";
+
+import { Field, FieldDescription, FieldError, FieldLabel, TagsInput } from "@app/components/v3";
+
+import {
+ MAX_SEARCH_FOLDERS,
+ MAX_SKIP_FOLDERS,
+ TLinuxServerDiscoveryJobForm,
+ validateLinuxFolder
+} from "./discovery-job-form-schema";
+
+const FolderListField = ({
+ name,
+ label,
+ description,
+ placeholder,
+ maxFolders
+}: {
+ name: "searchFolderPaths" | "skipFolderPaths";
+ label: string;
+ description: string;
+ placeholder: string;
+ maxFolders: number;
+}) => {
+ const { control } = useFormContext<TLinuxServerDiscoveryJobForm>();
+ const [tagError, setTagError] = useState<string | null>(null);
+
+ return (
+ <Controller
+ control={control}
+ name={name}
+ render={({ field: { value, onChange }, fieldState: { error } }) => {
+ const message = tagError ?? error?.message;
+ return (
+ <Field className="mb-4">
+ <FieldLabel>{label}</FieldLabel>
+ <TagsInput
+ value={value ?? []}
+ onValueChange={onChange}
+ validateTag={(tag, existing) => {
+ if (existing.includes(tag)) return "This folder is already in the list";
+ if (existing.length >= maxFolders)
+ return `Add up to ${maxFolders} ${label.toLowerCase()}`;
+ return validateLinuxFolder(tag);
+ }}
+ onValidationError={setTagError}
+ placeholder={placeholder}
+ isError={Boolean(message)}
+ className="font-mono"
+ />
+ {message ? (
+ <FieldError>{message}</FieldError>
+ ) : (
+ <FieldDescription>{description}</FieldDescription>
+ )}
+ </Field>
+ );
+ }}
+ />
+ );
+};
+
+export const LinuxServerFoldersFields = () => (
+ <>
+ <FolderListField
+ name="searchFolderPaths"
+ label="Search Folders"
+ placeholder="Add a folder and press Enter"
+ description="Absolute paths searched on every server. Subfolders are included."
+ maxFolders={MAX_SEARCH_FOLDERS}
+ />
+ <FolderListField
+ name="skipFolderPaths"
+ label="Skip Folders"
+ placeholder="Add a folder and press Enter"
+ description="Folders left out of the search. /proc, /sys and /dev are always skipped."
+ maxFolders={MAX_SKIP_FOLDERS}
+ />
+ </>
+);
diff --git a/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/LinuxServerHostsFields.tsx b/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/LinuxServerHostsFields.tsx
new file mode 100644
index 0000000000..ffb7349579
--- /dev/null
+++ b/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/LinuxServerHostsFields.tsx
@@ -0,0 +1,135 @@
+import { Controller, useFormContext } from "react-hook-form";
+import { Info } from "lucide-react";
+
+import { AppConnectionOptionContent } from "@app/components/app-connections";
+import {
+ Combobox,
+ Field,
+ FieldContent,
+ FieldDescription,
+ FieldError,
+ FieldLabel
+} from "@app/components/v3";
+import { ProjectPermissionSub, useProject, useProjectPermission } from "@app/context";
+import { ProjectPermissionAppConnectionActions } from "@app/context/ProjectPermissionContext/types";
+import { usePopUp } from "@app/hooks";
+import {
+ TAvailableAppConnection,
+ useListAvailableAppConnectionsForApps
+} from "@app/hooks/api/appConnections";
+import { AppConnection } from "@app/hooks/api/appConnections/enums";
+import { AddAppConnectionModal } from "@app/pages/organization/AppConnections/AppConnectionsPage/components";
+
+import { TLinuxServerDiscoveryJobForm } from "./discovery-job-form-schema";
+
+type TConnectionOption = Pick<TAvailableAppConnection, "id" | "name"> &
+ Partial<TAvailableAppConnection>;
+
+const CREATE_OPTION_ID = "_create";
+
+export const LinuxServerHostsFields = () => {
+ const { permission } = useProjectPermission();
+ const { currentProject } = useProject();
+ const { control, getValues, setValue } = useFormContext<TLinuxServerDiscoveryJobForm>();
+ const { popUp, handlePopUpToggle, handlePopUpOpen } = usePopUp(["addConnection"] as const);
+
+ const { connections, isPending } = useListAvailableAppConnectionsForApps(
+ [AppConnection.SSH],
+ currentProject.id
+ );
+
+ const canCreateConnection = permission.can(
+ ProjectPermissionAppConnectionActions.Create,
+ ProjectPermissionSub.AppConnections
+ );
+
+ const connectionsById = new Map<string, TConnectionOption>(
+ connections.map((connection) => [connection.id, connection])
+ );
+ const resolveOption = (option: TConnectionOption) => connectionsById.get(option.id) ?? option;
+ const isMissingGateway = (option: TConnectionOption) => {
+ const connection = resolveOption(option);
+ return connection.id !== CREATE_OPTION_ID && !connection.gatewayId && !connection.gatewayPoolId;
+ };
+ const connectionOptions: TConnectionOption[] = [
+ ...(canCreateConnection ? [{ id: CREATE_OPTION_ID, name: "Create SSH Connection" }] : []),
+ ...connections.filter((connection) => !isMissingGateway(connection)),
+ ...connections.filter(isMissingGateway)
+ ];
+
+ return (
+ <>
+ <Controller
+ control={control}
+ name="connections"
+ render={({ field: { value, onChange }, fieldState: { error } }) => (
+ <Field className="mb-4">
+ <FieldLabel>SSH Connections</FieldLabel>
+ <FieldContent>
+ <Combobox
+ multiple
+ value={value}
+ onValueChange={(next) => {
+ if (next.some((option) => option.id === CREATE_OPTION_ID)) {
+ handlePopUpOpen("addConnection");
+ return;
+ }
+ onChange(next.map(({ id, name }) => ({ id, name })));
+ }}
+ isLoading={isPending}
+ isError={Boolean(error)}
+ options={connectionOptions}
+ placeholder="Select connections..."
+ getOptionLabel={(option) => option.name}
+ getOptionValue={(option) => option.id}
+ isOptionDisabled={isMissingGateway}
+ renderOption={(option) => (
+ <AppConnectionOptionContent
+ data={resolveOption(option)}
+ createLabel="Create SSH Connection"
+ isOnlyOption={option.id === CREATE_OPTION_ID && connectionOptions.length === 1}
+ label={
+ isMissingGateway(option) && (
+ <span className="mr-2 shrink-0 text-xs text-muted">No gateway</span>
+ )
+ }
+ />
+ )}
+ includeMissingSelectedOptions
+ modal
+ />
+ {!error?.message && (
+ <FieldDescription>
+ Each connection is one server. It must use a gateway, and the scan runs from that
+ gateway.
+ </FieldDescription>
+ )}
+ <FieldError errors={[error]} />
+ </FieldContent>
+ </Field>
+ )}
+ />
+ {!isPending && !connections.length && !canCreateConnection && (
+ <p className="mt-2 flex items-center gap-1.5 text-xs text-warning">
+ <Info className="size-3.5" />
+ You do not have access to any SSH Connections. Contact an admin to create one.
+ </p>
+ )}
+ <AddAppConnectionModal
+ isOpen={popUp.addConnection.isOpen}
+ onOpenChange={(isOpen) => handlePopUpToggle("addConnection", isOpen)}
+ projectType={currentProject.type}
+ projectId={currentProject.id}
+ app={AppConnection.SSH}
+ onComplete={(connection) => {
+ const existing = getValues("connections") ?? [];
+ if (existing.some((c) => c.id === connection.id)) return;
+ setValue("connections", [...existing, { id: connection.id, name: connection.name }], {
+ shouldDirty: true,
+ shouldValidate: true
+ });
+ }}
+ />
+ </>
+ );
+};
diff --git a/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/LinuxServerOptionsFields.tsx b/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/LinuxServerOptionsFields.tsx
new file mode 100644
index 0000000000..6d16553255
--- /dev/null
+++ b/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/LinuxServerOptionsFields.tsx
@@ -0,0 +1,86 @@
+import { Controller, useFormContext } from "react-hook-form";
+
+import {
+ Field,
+ FieldContent,
+ FieldDescription,
+ FieldError,
+ FieldLabel,
+ Input,
+ Label,
+ Toggle
+} from "@app/components/v3";
+import { MAX_FILE_SIZE_KB, MAX_FOLDER_DEPTH } from "@app/helpers/pkiDiscovery";
+
+import { TLinuxServerDiscoveryJobForm } from "./discovery-job-form-schema";
+
+const NUMBER_FIELDS = [
+ {
+ name: "maxFolderDepth",
+ label: "Folder Depth",
+ max: MAX_FOLDER_DEPTH,
+ description: "How many levels below each search folder"
+ },
+ {
+ name: "maxFileSizeKb",
+ label: "Largest File (KB)",
+ max: MAX_FILE_SIZE_KB,
+ description: "Bigger files are skipped and listed in the scan."
+ }
+] as const;
+
+export const LinuxServerOptionsFields = () => {
+ const { control } = useFormContext<TLinuxServerDiscoveryJobForm>();
+
+ return (
+ <>
+ <div className="mb-4 grid grid-cols-2 gap-4">
+ {NUMBER_FIELDS.map(({ name, label, max, description }) => (
+ <Controller
+ key={name}
+ control={control}
+ name={name}
+ render={({ field: { value, onChange }, fieldState: { error } }) => (
+ <Field>
+ <FieldLabel>{label}</FieldLabel>
+ <Input
+ type="number"
+ min={1}
+ max={max}
+ value={value ?? ""}
+ onChange={(e) => onChange(e.target.value === "" ? null : Number(e.target.value))}
+ isError={Boolean(error)}
+ />
+ {!error?.message && <FieldDescription>{description}</FieldDescription>}
+ <FieldError errors={[error]} />
+ </Field>
+ )}
+ />
+ ))}
+ </div>
+ <Controller
+ control={control}
+ name="importStandaloneCaCertificates"
+ render={({ field: { value, onChange } }) => (
+ <Field orientation="horizontal" className="mb-4">
+ <FieldContent>
+ <Label htmlFor="import-standalone-ca">
+ Import CA Certificates Found on Their Own
+ </Label>
+ <FieldDescription>
+ A leaf certificate always comes in with its chain. Turn this on to also import CA
+ certificates from files that hold no leaf, such as trust bundles.
+ </FieldDescription>
+ </FieldContent>
+ <Toggle
+ id="import-standalone-ca"
+ variant="project"
+ checked={value}
+ onCheckedChange={onChange}
+ />
+ </Field>
+ )}
+ />
+ </>
+ );
+};
diff --git a/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/NetworkTargetFields.tsx b/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/NetworkTargetFields.tsx
new file mode 100644
index 0000000000..2c7df7df3b
--- /dev/null
+++ b/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/NetworkTargetFields.tsx
@@ -0,0 +1,96 @@
+import { Controller, useFormContext } from "react-hook-form";
+
+import {
+ Field,
+ FieldDescription,
+ FieldError,
+ FieldLabel,
+ GatewayPicker,
+ Input,
+ TextArea
+} from "@app/components/v3";
+import { isInfisicalCloud } from "@app/helpers/platform";
+
+import {
+ DEFAULT_TLS_PORTS,
+ MAX_DOMAINS,
+ MAX_IPS,
+ MAX_PORTS,
+ MIN_CIDR_PREFIX,
+ TNetworkDiscoveryJobForm
+} from "./discovery-job-form-schema";
+
+export const NetworkTargetFields = () => {
+ const { control, watch, setValue } = useFormContext<TNetworkDiscoveryJobForm>();
+ const gatewayId = watch("gatewayId");
+ const gatewayPoolId = watch("gatewayPoolId");
+
+ return (
+ <>
+ <Controller
+ control={control}
+ name="targets"
+ render={({ field: { value, onChange }, fieldState: { error } }) => (
+ <Field className="mb-4">
+ <FieldLabel>Targets</FieldLabel>
+ <TextArea
+ value={value ?? ""}
+ onChange={onChange}
+ placeholder={"example.com\napi.example.com\n192.168.1.0/24"}
+ className="resize-none font-mono"
+ rows={5}
+ isError={Boolean(error)}
+ />
+ {!error?.message && (
+ <FieldDescription>
+ Domains, IP addresses or CIDR ranges, one per line. Up to {MAX_DOMAINS} domains or{" "}
+ {MAX_IPS} IPs, and CIDR ranges up to /{MIN_CIDR_PREFIX}.
+ </FieldDescription>
+ )}
+ <FieldError errors={[error]} />
+ </Field>
+ )}
+ />
+ <Controller
+ control={control}
+ name="ports"
+ render={({ field: { value, onChange }, fieldState: { error } }) => (
+ <Field className="mb-4">
+ <FieldLabel>Ports</FieldLabel>
+ <Input
+ value={value ?? ""}
+ onChange={onChange}
+ placeholder={DEFAULT_TLS_PORTS}
+ isError={Boolean(error)}
+ autoComplete="off"
+ />
+ {!error?.message && (
+ <FieldDescription>
+ Up to {MAX_PORTS} ports, comma separated. Ranges like 8000-8004 are allowed.
+ </FieldDescription>
+ )}
+ <FieldError errors={[error]} />
+ </Field>
+ )}
+ />
+ <Field className="mb-4">
+ <FieldLabel>
+ Gateway <span className="text-muted">(optional)</span>
+ </FieldLabel>
+ <GatewayPicker
+ value={{ gatewayId: gatewayId ?? null, gatewayPoolId: gatewayPoolId ?? null }}
+ onChange={(next) => {
+ setValue("gatewayId", next.gatewayId, { shouldDirty: true });
+ setValue("gatewayPoolId", next.gatewayPoolId, { shouldDirty: true });
+ }}
+ className="w-full"
+ />
+ <FieldDescription>
+ Use a gateway to reach targets on a private network.
+ {!isInfisicalCloud() &&
+ " Self-hosted instances can also set ALLOW_INTERNAL_IP_CONNECTIONS=true to scan private networks without one."}
+ </FieldDescription>
+ </Field>
+ </>
+ );
+};
diff --git a/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/discovery-job-form-schema.ts b/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/discovery-job-form-schema.ts
new file mode 100644
index 0000000000..9424648f05
--- /dev/null
+++ b/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/discovery-job-form-schema.ts
@@ -0,0 +1,202 @@
+import { z } from "zod";
+
+import {
+ DEFAULT_LINUX_SEARCH_FOLDERS,
+ DEFAULT_MAX_FILE_SIZE_KB,
+ DEFAULT_MAX_FOLDER_DEPTH,
+ MAX_FILE_SIZE_KB,
+ MAX_FOLDER_DEPTH
+} from "@app/helpers/pkiDiscovery";
+import { PkiDiscoveryType, TPkiDiscovery } from "@app/hooks/api/pkiDiscovery/types";
+import { slugSchema } from "@app/lib/schemas/slugSchema";
+
+export const MAX_PORTS = 5;
+export const MAX_IPS = 256;
+export const MAX_DOMAINS = 20;
+export const MIN_CIDR_PREFIX = 24;
+export const DEFAULT_TLS_PORTS = "443,8443,636,993,995";
+const MAX_LINUX_CONNECTIONS = 100;
+export const MAX_SEARCH_FOLDERS = 20;
+export const MAX_SKIP_FOLDERS = 50;
+
+const validatePorts = (portsStr: string): string | null => {
+ if (!portsStr.trim()) return "Ports are required";
+ const ranges = portsStr.split(",").map((rawPart) => {
+ const part = rawPart.trim();
+ const [start, end = start] = part.split("-").map((p) => parseInt(p.trim(), 10));
+ return { part, start, end };
+ });
+ const invalid = ranges.find(
+ ({ start, end }) =>
+ Number.isNaN(start) || Number.isNaN(end) || start < 1 || end > 65535 || start > end
+ );
+ if (invalid) {
+ return invalid.part.includes("-")
+ ? `Invalid port range: ${invalid.part}`
+ : `Invalid port: ${invalid.part}`;
+ }
+ const portCount = ranges.reduce((count, { start, end }) => count + end - start + 1, 0);
+ if (portCount > MAX_PORTS) return `Maximum ${MAX_PORTS} ports allowed (you have ${portCount})`;
+ return null;
+};
+
+const splitTargets = (targetsStr: string) =>
+ targetsStr
+ .split(/[\n,]/)
+ .map((t) => t.trim())
+ .filter(Boolean);
+
+const validateTargets = (targetsStr: string): string | null => {
+ const targets = splitTargets(targetsStr);
+ if (targets.length === 0) return "At least one target is required";
+
+ const cidrRanges = targets.filter((t) => t.includes("/"));
+ const singleIps = targets.filter((t) => !t.includes("/") && /^\d/.test(t));
+ const domains = targets.filter((t) => /[a-zA-Z]/.test(t) && !t.includes("/"));
+
+ if (domains.some((d) => d.startsWith("*"))) {
+ return "Wildcard domains aren't supported";
+ }
+
+ const invalidCidr = cidrRanges.find((cidr) => {
+ const prefixMatch = cidr.match(/\/(\d+)$/);
+ return prefixMatch ? parseInt(prefixMatch[1], 10) < MIN_CIDR_PREFIX : false;
+ });
+ if (invalidCidr) {
+ return `CIDR range too large: ${invalidCidr}. Maximum is /${MIN_CIDR_PREFIX} (256 IPs)`;
+ }
+
+ const totalIpCount = cidrRanges.reduce((count, cidr) => {
+ const prefixMatch = cidr.match(/\/(\d+)$/);
+ return prefixMatch ? count + 2 ** (32 - parseInt(prefixMatch[1], 10)) : count;
+ }, singleIps.length);
+ if (totalIpCount > MAX_IPS) {
+ return `Maximum ${MAX_IPS} total IPs allowed (including expanded CIDR ranges)`;
+ }
+ if (domains.length > MAX_DOMAINS) return `Maximum ${MAX_DOMAINS} domains allowed per discovery`;
+ return null;
+};
+
+export const parseTargets = (targetsStr: string) => {
+ const domains: string[] = [];
+ const ipRanges: string[] = [];
+ splitTargets(targetsStr).forEach((target) => {
+ if (/[a-zA-Z]/.test(target) && !target.includes("/")) domains.push(target);
+ else ipRanges.push(target);
+ });
+ return { domains, ipRanges };
+};
+
+const isAbsoluteFolder = (value: string) =>
+ value.startsWith("/") && !/[\r\n]/.test(value) && !/(^|\/)\.\.(\/|$)/.test(value);
+
+export const validateLinuxFolder = (value: string) => {
+ if (!isAbsoluteFolder(value)) return "Use an absolute folder path, for example /etc/ssl";
+ if (value.length > 1024) return "Folder paths can be at most 1024 characters";
+ return null;
+};
+
+const boundedInt = (max: number, requiredMessage: string, rangeMessage: string) =>
+ z
+ .number({ required_error: requiredMessage, invalid_type_error: requiredMessage })
+ .int(rangeMessage)
+ .min(1, rangeMessage)
+ .max(max, rangeMessage);
+
+const BaseSchema = z.object({
+ name: slugSchema({ field: "Name", max: 100 }),
+ description: z.string().trim().max(255, "Description can be at most 255 characters").optional(),
+ isAutoScanEnabled: z.boolean(),
+ scanIntervalDays: z
+ .number()
+ .min(1, "Enter an interval between 1 and 365 days")
+ .max(365, "Enter an interval between 1 and 365 days")
+});
+
+const NetworkSchema = BaseSchema.extend({
+ discoveryType: z.literal(PkiDiscoveryType.Network),
+ targets: z.string().superRefine((val, ctx) => {
+ const error = validateTargets(val);
+ if (error) ctx.addIssue({ code: z.ZodIssueCode.custom, message: error });
+ }),
+ ports: z.string().superRefine((val, ctx) => {
+ const error = validatePorts(val);
+ if (error) ctx.addIssue({ code: z.ZodIssueCode.custom, message: error });
+ }),
+ gatewayId: z.string().nullable().optional(),
+ gatewayPoolId: z.string().nullable().optional()
+});
+
+const LinuxServerSchema = BaseSchema.extend({
+ discoveryType: z.literal(PkiDiscoveryType.LinuxServer),
+ connections: z
+ .array(z.object({ id: z.string(), name: z.string() }))
+ .min(1, "Select at least one SSH connection")
+ .max(MAX_LINUX_CONNECTIONS, `Select up to ${MAX_LINUX_CONNECTIONS} SSH connections`),
+ searchFolderPaths: z
+ .array(z.string())
+ .min(1, "Add at least one folder to search")
+ .max(MAX_SEARCH_FOLDERS, `Add up to ${MAX_SEARCH_FOLDERS} search folders`),
+ skipFolderPaths: z
+ .array(z.string())
+ .max(MAX_SKIP_FOLDERS, `Add up to ${MAX_SKIP_FOLDERS} skip folders`),
+ maxFolderDepth: boundedInt(
+ MAX_FOLDER_DEPTH,
+ "Enter how many folder levels to search",
+ `Enter a depth between 1 and ${MAX_FOLDER_DEPTH}`
+ ),
+ maxFileSizeKb: boundedInt(
+ MAX_FILE_SIZE_KB,
+ "Enter the largest file size to read, in KB",
+ `Enter a size between 1 and ${MAX_FILE_SIZE_KB} KB`
+ ),
+ importStandaloneCaCertificates: z.boolean()
+});
+
+export const DiscoveryJobFormSchema = z.discriminatedUnion("discoveryType", [
+ NetworkSchema,
+ LinuxServerSchema
+]);
+
+export type TDiscoveryJobForm = z.infer<typeof DiscoveryJobFormSchema>;
+export type TNetworkDiscoveryJobForm = z.infer<typeof NetworkSchema>;
+export type TLinuxServerDiscoveryJobForm = z.infer<typeof LinuxServerSchema>;
+
+export const getDefaultFormValues = (
+ type: PkiDiscoveryType,
+ discovery?: TPkiDiscovery
+): Partial<TDiscoveryJobForm> => {
+ const base = {
+ name: discovery?.name ?? "",
+ description: discovery?.description ?? "",
+ isAutoScanEnabled: discovery?.isAutoScanEnabled ?? false,
+ scanIntervalDays: discovery?.scanIntervalDays ?? 7
+ };
+
+ if (type === PkiDiscoveryType.LinuxServer) {
+ const config = discovery?.targetConfig;
+ return {
+ ...base,
+ discoveryType: PkiDiscoveryType.LinuxServer,
+ connections: discovery?.connections ?? [],
+ searchFolderPaths: config?.searchFolderPaths ?? DEFAULT_LINUX_SEARCH_FOLDERS,
+ skipFolderPaths: config?.skipFolderPaths ?? [],
+ maxFolderDepth: config?.maxFolderDepth ?? DEFAULT_MAX_FOLDER_DEPTH,
+ maxFileSizeKb: config?.maxFileSizeKb ?? DEFAULT_MAX_FILE_SIZE_KB,
+ importStandaloneCaCertificates: config?.importStandaloneCaCertificates ?? false
+ };
+ }
+
+ const targets = [
+ ...(discovery?.targetConfig.domains ?? []),
+ ...(discovery?.targetConfig.ipRanges ?? [])
+ ].join("\n");
+ return {
+ ...base,
+ discoveryType: PkiDiscoveryType.Network,
+ targets,
+ ports: discovery?.targetConfig.ports ?? DEFAULT_TLS_PORTS,
+ gatewayId: discovery?.gatewayId ?? null,
+ gatewayPoolId: discovery?.gatewayPoolId ?? null
+ };
+};
diff --git a/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/index.ts b/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/index.ts
new file mode 100644
index 0000000000..d96bc18420
--- /dev/null
+++ b/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobSheet/index.ts
@@ -0,0 +1 @@
+export { DiscoveryJobSheet } from "./DiscoveryJobSheet";
diff --git a/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobsTab.tsx b/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobsTab.tsx
index 5bcdea10fc..ef45e767a7 100644
--- a/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobsTab.tsx
+++ b/frontend/src/pages/cert-manager/DiscoveryPage/components/DiscoveryJobsTab.tsx
@@ -5,7 +5,6 @@ import { MoreHorizontalIcon, PlusIcon, RefreshCwIcon, SearchIcon } from "lucide-
import { UpgradePlanModal } from "@app/components/license/UpgradePlanModal";
import { ProjectPermissionCan } from "@app/components/permissions";
-import { HoverCard, HoverCardContent, HoverCardTrigger, Tag } from "@app/components/v2";
import {
Button,
Card,
@@ -26,6 +25,7 @@ import {
InputGroup,
InputGroupAddon,
InputGroupInput,
+ OverflowBadgeList,
Pagination,
Skeleton,
Table,
@@ -41,8 +41,10 @@ import {
useOrganization,
useSubscription
} from "@app/context";
+import { PKI_DISCOVERY_TYPE_MAP } from "@app/helpers/pkiDiscovery";
import {
PkiDiscoveryScanStatus,
+ PkiDiscoveryType,
TPkiDiscovery,
useDeletePkiDiscovery,
useListPkiDiscoveries,
@@ -50,17 +52,36 @@ import {
} from "@app/hooks/api";
import { useDebounce } from "@app/hooks/useDebounce";
import { usePopUp } from "@app/hooks/usePopUp";
-import { getDiscoveryStatusBadge, parsePorts } from "@app/pages/cert-manager/pki-discovery-utils";
+import {
+ getDiscoveryStatusBadge,
+ getItemLabel,
+ parsePorts
+} from "@app/pages/cert-manager/pki-discovery-utils";
+import { DiscoveryTypeIcon } from "./DiscoveryJobSheet/DiscoveryTypeIcon";
import { DeleteDiscoveryModal } from "./DeleteDiscoveryModal";
-import { DiscoveryJobModal } from "./DiscoveryJobModal";
+import { DiscoveryJobSheet } from "./DiscoveryJobSheet";
type Props = {
projectId: string;
};
const PAGE_SIZE = 25;
-const MAX_PORTS_TO_SHOW = 2;
+
+const getScopeItems = (discovery: TPkiDiscovery) => {
+ if (discovery.discoveryType === PkiDiscoveryType.LinuxServer) {
+ return discovery.targetConfig.searchFolderPaths ?? [];
+ }
+ const ports = parsePorts(discovery.targetConfig.ports);
+ return ports.length ? ports : ["443"];
+};
+
+const getTargetItems = (discovery: TPkiDiscovery) => {
+ if (discovery.discoveryType === PkiDiscoveryType.LinuxServer) {
+ return (discovery.connections ?? []).map((connection) => connection.name);
+ }
+ return [...(discovery.targetConfig.domains ?? []), ...(discovery.targetConfig.ipRanges ?? [])];
+};
export const DiscoveryJobsTab = ({ projectId }: Props) => {
const navigate = useNavigate();
@@ -120,61 +141,13 @@ export const DiscoveryJobsTab = ({ projectId }: Props) => {
handlePopUpClose("deleteJob");
};
- const getTargetDisplay = (discovery: TPkiDiscovery) => {
- const targets: string[] = [];
- if (discovery.targetConfig.domains?.length) {
- targets.push(...discovery.targetConfig.domains.slice(0, 2));
- }
- if (discovery.targetConfig.ipRanges?.length) {
- targets.push(...discovery.targetConfig.ipRanges.slice(0, 2));
- }
- const display = targets.slice(0, 2).join(", ");
- const total =
- (discovery.targetConfig.domains?.length || 0) +
- (discovery.targetConfig.ipRanges?.length || 0);
- return total > 2 ? `${display} +${total - 2} more` : display;
- };
-
- const renderPortsBadges = (discovery: TPkiDiscovery) => {
- const ports = parsePorts(discovery.targetConfig.ports);
-
- if (ports.length === 0) {
- return <Tag>443</Tag>;
- }
-
- const visiblePorts = ports.slice(0, MAX_PORTS_TO_SHOW);
- const remainingPorts = ports.slice(MAX_PORTS_TO_SHOW);
-
- return (
- <div className="flex items-center gap-1">
- {visiblePorts.map((port) => (
- <Tag key={port}>{port}</Tag>
- ))}
- {remainingPorts.length > 0 && (
- <HoverCard>
- <HoverCardTrigger>
- <Tag>+{remainingPorts.length}</Tag>
- </HoverCardTrigger>
- <HoverCardContent className="border border-border-cool bg-surface-raised p-3">
- <div className="flex flex-wrap gap-1">
- {remainingPorts.map((port) => (
- <Tag key={port}>{port}</Tag>
- ))}
- </div>
- </HoverCardContent>
- </HoverCard>
- )}
- </div>
- );
- };
-
return (
<Card>
<CardHeader>
<CardTitle>Discovery Jobs</CardTitle>
<CardDescription>
- Configure scans to run on a schedule and find certificates on the domains and IP addresses
- you select.
+ Configure scans to find certificates served on your network or stored in files on your
+ servers.
</CardDescription>
<CardAction>
<ProjectPermissionCan
@@ -199,7 +172,7 @@ export const DiscoveryJobsTab = ({ projectId }: Props) => {
<InputGroupInput
value={searchFilter}
onChange={(e) => setSearchFilter(e.target.value)}
- placeholder="Search by name, domain, or IP…"
+ placeholder="Search by name or description…"
/>
</InputGroup>
</div>
@@ -216,8 +189,8 @@ export const DiscoveryJobsTab = ({ projectId }: Props) => {
<EmptyHeader>
<EmptyTitle>No discovery jobs defined</EmptyTitle>
<EmptyDescription>
- Define a job to scan domains or IP ranges and surface the certificates running on
- them.
+ Define a job to scan your network or your servers and surface the certificates it
+ finds.
</EmptyDescription>
</EmptyHeader>
</Empty>
@@ -227,8 +200,9 @@ export const DiscoveryJobsTab = ({ projectId }: Props) => {
<TableHeader>
<TableRow>
<TableHead>Name</TableHead>
+ <TableHead>Type</TableHead>
<TableHead>Target</TableHead>
- <TableHead>Ports</TableHead>
+ <TableHead>Ports / Folders</TableHead>
<TableHead>Status</TableHead>
<TableHead>Last Scan</TableHead>
<TableHead className="w-5" />
@@ -251,10 +225,26 @@ export const DiscoveryJobsTab = ({ projectId }: Props) => {
}
>
<TableCell>{discovery.name}</TableCell>
- <TableCell className="max-w-[200px] truncate">
- {getTargetDisplay(discovery)}
+ <TableCell>
+ <div className="flex items-center gap-2">
+ <DiscoveryTypeIcon type={discovery.discoveryType} className="size-4" />
+ {PKI_DISCOVERY_TYPE_MAP[discovery.discoveryType]?.name}
+ </div>
+ </TableCell>
+ <TableCell className="max-w-[200px]">
+ <OverflowBadgeList
+ items={getTargetItems(discovery)}
+ getKey={getItemLabel}
+ getLabel={getItemLabel}
+ />
+ </TableCell>
+ <TableCell className="max-w-[200px]">
+ <OverflowBadgeList
+ items={getScopeItems(discovery)}
+ getKey={getItemLabel}
+ getLabel={getItemLabel}
+ />
</TableCell>
- <TableCell>{renderPortsBadges(discovery)}</TableCell>
<TableCell>
{getDiscoveryStatusBadge(
discovery.lastScanStatus,
@@ -343,13 +333,13 @@ export const DiscoveryJobsTab = ({ projectId }: Props) => {
)}
</CardContent>
- <DiscoveryJobModal
+ <DiscoveryJobSheet
isOpen={popUp.createJob.isOpen}
onClose={() => handlePopUpClose("createJob")}
projectId={projectId}
/>
- <DiscoveryJobModal
+ <DiscoveryJobSheet
isOpen={popUp.editJob.isOpen}
onClose={() => handlePopUpClose("editJob")}
projectId={projectId}
diff --git a/frontend/src/pages/cert-manager/DiscoveryPage/components/EditInstallationModal.tsx b/frontend/src/pages/cert-manager/DiscoveryPage/components/EditInstallationModal.tsx
index f43386cc39..c35972042f 100644
--- a/frontend/src/pages/cert-manager/DiscoveryPage/components/EditInstallationModal.tsx
+++ b/frontend/src/pages/cert-manager/DiscoveryPage/components/EditInstallationModal.tsx
@@ -3,8 +3,22 @@ import { Controller, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
-import { Button, FormControl, Input, Modal, ModalContent } from "@app/components/v2";
+import {
+ Button,
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ Field,
+ FieldDescription,
+ FieldError,
+ FieldLabel,
+ Input
+} from "@app/components/v3";
import { TPkiInstallation, useUpdatePkiInstallation } from "@app/hooks/api";
+import { getEndpoint } from "@app/pages/cert-manager/pki-discovery-utils";
type Props = {
isOpen: boolean;
@@ -14,7 +28,7 @@ type Props = {
};
const formSchema = z.object({
- name: z.string().max(255).optional()
+ name: z.string().trim().max(255)
});
type FormData = z.infer<typeof formSchema>;
@@ -24,84 +38,77 @@ export const EditInstallationModal = ({ isOpen, onClose, projectId, installation
control,
handleSubmit,
reset,
- formState: { errors, isSubmitting }
+ formState: { isSubmitting }
} = useForm<FormData>({
resolver: zodResolver(formSchema),
- defaultValues: {
- name: ""
- }
+ defaultValues: { name: "" }
});
const updateInstallation = useUpdatePkiInstallation();
useEffect(() => {
- if (isOpen && installation) {
- reset({
- name: installation.name || ""
- });
- }
+ if (isOpen && installation) reset({ name: installation.name || "" });
}, [isOpen, installation, reset]);
- const onSubmit = async (data: FormData) => {
- if (!installation) return;
+ if (!installation) return null;
- try {
- await updateInstallation.mutateAsync({
- installationId: installation.id,
- projectId,
- name: data.name || undefined
- });
- onClose();
- } catch {
- // Error handled by mutation
- }
+ const onSubmit = async ({ name }: FormData) => {
+ await updateInstallation.mutateAsync({
+ installationId: installation.id,
+ projectId,
+ name: name || undefined
+ });
+ onClose();
};
- if (!installation) return null;
-
return (
- <Modal isOpen={isOpen} onOpenChange={(open) => !open && onClose()}>
- <ModalContent title="Edit Installation" subTitle="Update the name for this installation">
- <form onSubmit={handleSubmit(onSubmit)}>
- <div className="mb-4 rounded bg-surface-hover p-3">
- <p className="text-sm text-label">
- <span className="font-medium">Location:</span>{" "}
- {installation.locationDetails.fqdn ||
- installation.locationDetails.ipAddress ||
- "Unknown"}
- {installation.locationDetails.port && `:${installation.locationDetails.port}`}
- </p>
- </div>
-
+ <Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>Edit Installation</DialogTitle>
+ <DialogDescription>
+ Rename the installation at{" "}
+ <span className="font-mono break-all text-foreground">{getEndpoint(installation)}</span>
+ .
+ </DialogDescription>
+ </DialogHeader>
+ <form onSubmit={(e) => handleSubmit(onSubmit)(e).catch(() => undefined)}>
<Controller
- name="name"
control={control}
- render={({ field }) => (
- <FormControl
- label="Name"
- helperText="Optional friendly name for this installation"
- errorText={errors.name?.message}
- >
+ name="name"
+ render={({ field, fieldState: { error } }) => (
+ <Field>
+ <FieldLabel>Name</FieldLabel>
<Input
{...field}
placeholder="My Web Server"
autoComplete="off"
- name="certificate-installation-name"
+ isError={Boolean(error)}
/>
- </FormControl>
+ {!error?.message && (
+ <FieldDescription>
+ A friendly name shown in the installations list
+ </FieldDescription>
+ )}
+ <FieldError errors={[error]} />
+ </Field>
)}
/>
-
- <div className="mt-6 flex justify-end gap-2">
- <Button variant="plain" colorSchema="secondary" onClick={onClose}>
+ <DialogFooter className="mt-6">
+ <Button type="button" variant="outline" onClick={onClose}>
Cancel
</Button>
- <Button type="submit" isLoading={isSubmitting} colorSchema="primary">
- Update
+ <Button
+ type="submit"
+ variant="project"
+ isPending={isSubmitting}
+ isDisabled={isSubmitting}
+ >
+ Save
</Button>
- </div>
+ </DialogFooter>
</form>
- </ModalContent>
- </Modal>
+ </DialogContent>
+ </Dialog>
);
};
diff --git a/frontend/src/pages/cert-manager/DiscoveryPage/components/InstallationsTab.tsx b/frontend/src/pages/cert-manager/DiscoveryPage/components/InstallationsTab.tsx
index 61b5906a8f..50b5c612e3 100644
--- a/frontend/src/pages/cert-manager/DiscoveryPage/components/InstallationsTab.tsx
+++ b/frontend/src/pages/cert-manager/DiscoveryPage/components/InstallationsTab.tsx
@@ -41,12 +41,22 @@ import {
useDeletePkiInstallation,
useListPkiInstallations
} from "@app/hooks/api";
+import { PkiDiscoveryType } from "@app/hooks/api/pkiDiscovery/types";
import { useDebounce } from "@app/hooks/useDebounce";
import { usePopUp } from "@app/hooks/usePopUp";
-import { getEndpoint, getGatewayLabel } from "@app/pages/cert-manager/pki-discovery-utils";
+import {
+ canSetKeystorePassword,
+ getEndpoint,
+ getGatewayLabel,
+ getKeystoreStatusBadge,
+ isHostFileInstallation,
+ useCanRescanPkiInstallations
+} from "@app/pages/cert-manager/pki-discovery-utils";
+import { DiscoveryTypeIcon } from "./DiscoveryJobSheet/DiscoveryTypeIcon";
import { DeleteInstallationModal } from "./DeleteInstallationModal";
import { EditInstallationModal } from "./EditInstallationModal";
+import { SetKeystorePasswordDialog } from "./SetKeystorePasswordDialog";
type Props = {
projectId: string;
@@ -61,9 +71,12 @@ export const InstallationsTab = ({ projectId }: Props) => {
const [searchFilter, setSearchFilter] = useState("");
const [debouncedSearch] = useDebounce(searchFilter, 300);
+ const canRescanInstallations = useCanRescanPkiInstallations();
+
const { popUp, handlePopUpOpen, handlePopUpClose, handlePopUpToggle } = usePopUp([
"editInstallation",
- "deleteInstallation"
+ "deleteInstallation",
+ "setKeystorePassword"
] as const);
const { data, isPending } = useListPkiInstallations({
@@ -93,7 +106,8 @@ export const InstallationsTab = ({ projectId }: Props) => {
<CardHeader>
<CardTitle>Installations</CardTitle>
<CardDescription>
- Every place a certificate was found during a scan, identified by its host and port.
+ Every place a certificate was found during a scan, identified by its host and port or its
+ host and file path.
</CardDescription>
</CardHeader>
<CardContent>
@@ -105,7 +119,7 @@ export const InstallationsTab = ({ projectId }: Props) => {
<InputGroupInput
value={searchFilter}
onChange={(e) => setSearchFilter(e.target.value)}
- placeholder="Search by name, IP, or domain…"
+ placeholder="Search by name, host, IP, domain, or path…"
/>
</InputGroup>
</div>
@@ -156,7 +170,22 @@ export const InstallationsTab = ({ projectId }: Props) => {
})
}
>
- <TableCell>{installation.name || getEndpoint(installation)}</TableCell>
+ <TableCell>
+ <div className="flex items-center gap-2">
+ <DiscoveryTypeIcon
+ type={
+ isHostFileInstallation(installation)
+ ? PkiDiscoveryType.LinuxServer
+ : PkiDiscoveryType.Network
+ }
+ className="size-4 shrink-0"
+ />
+ <span className="truncate">
+ {installation.name || getEndpoint(installation)}
+ </span>
+ {getKeystoreStatusBadge(installation)}
+ </div>
+ </TableCell>
<TableCell>
{installation.primaryCertName || <span className="text-accent">—</span>}
</TableCell>
@@ -188,6 +217,16 @@ export const InstallationsTab = ({ projectId }: Props) => {
</DropdownMenuItem>
)}
</ProjectPermissionCan>
+ {canSetKeystorePassword(installation) && (
+ <DropdownMenuItem
+ isDisabled={!canRescanInstallations}
+ onClick={() => handlePopUpOpen("setKeystorePassword", installation)}
+ >
+ {installation.hasKeystorePassword
+ ? "Change Password"
+ : "Set Password"}
+ </DropdownMenuItem>
+ )}
<ProjectPermissionCan
I={ProjectPermissionPkiCertificateInstallationActions.Delete}
a={ProjectPermissionSub.PkiCertificateInstallations}
@@ -231,6 +270,13 @@ export const InstallationsTab = ({ projectId }: Props) => {
installation={popUp.editInstallation.data as TPkiInstallation | undefined}
/>
+ <SetKeystorePasswordDialog
+ isOpen={popUp.setKeystorePassword.isOpen}
+ onOpenChange={(isOpen) => handlePopUpToggle("setKeystorePassword", isOpen)}
+ projectId={projectId}
+ installation={popUp.setKeystorePassword.data as TPkiInstallation | undefined}
+ />
+
<DeleteInstallationModal
isOpen={popUp.deleteInstallation.isOpen}
onOpenChange={(isOpen) => handlePopUpToggle("deleteInstallation", isOpen)}
diff --git a/frontend/src/pages/cert-manager/DiscoveryPage/components/SetKeystorePasswordDialog.tsx b/frontend/src/pages/cert-manager/DiscoveryPage/components/SetKeystorePasswordDialog.tsx
new file mode 100644
index 0000000000..ec31c6e536
--- /dev/null
+++ b/frontend/src/pages/cert-manager/DiscoveryPage/components/SetKeystorePasswordDialog.tsx
@@ -0,0 +1,122 @@
+import { useEffect, useState } from "react";
+import { EyeIcon, EyeOffIcon } from "lucide-react";
+
+import {
+ Button,
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ Field,
+ FieldDescription,
+ FieldLabel,
+ InputGroup,
+ InputGroupAddon,
+ InputGroupButton,
+ InputGroupInput
+} from "@app/components/v3";
+import { TPkiInstallation, useUpdatePkiInstallation } from "@app/hooks/api";
+
+const MAX_PASSWORD_LENGTH = 1024;
+
+type Props = {
+ isOpen: boolean;
+ onOpenChange: (isOpen: boolean) => void;
+ projectId: string;
+ installation?: TPkiInstallation;
+ onSaved?: () => void;
+};
+
+export const SetKeystorePasswordDialog = ({
+ isOpen,
+ onOpenChange,
+ projectId,
+ installation,
+ onSaved
+}: Props) => {
+ const [password, setPassword] = useState("");
+ const [isRevealed, setIsRevealed] = useState(false);
+ const updateInstallation = useUpdatePkiInstallation();
+
+ useEffect(() => {
+ if (!isOpen) return;
+ setPassword("");
+ setIsRevealed(false);
+ }, [isOpen]);
+
+ if (!installation) return null;
+
+ const isChange = Boolean(installation.hasKeystorePassword);
+ const filePath = installation.locationDetails.filePath ?? installation.name ?? "";
+
+ const handleSave = async () => {
+ await updateInstallation.mutateAsync({
+ installationId: installation.id,
+ keystorePassword: password,
+ projectId
+ });
+ onSaved?.();
+ onOpenChange(false);
+ };
+
+ return (
+ <Dialog open={isOpen} onOpenChange={onOpenChange}>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>{isChange ? "Change Password" : "Set Password"}</DialogTitle>
+ <DialogDescription>
+ The password for <span className="font-mono text-foreground">{filePath}</span>. The file
+ is scanned again as soon as you save.
+ </DialogDescription>
+ </DialogHeader>
+ <form
+ onSubmit={(e) => {
+ e.preventDefault();
+ handleSave().catch(() => undefined);
+ }}
+ >
+ <Field>
+ <FieldLabel>Keystore Password</FieldLabel>
+ <InputGroup>
+ <InputGroupInput
+ type={isRevealed ? "text" : "password"}
+ value={password}
+ maxLength={MAX_PASSWORD_LENGTH}
+ onChange={(e) => setPassword(e.target.value)}
+ autoComplete="new-password"
+ autoFocus
+ />
+ <InputGroupAddon align="inline-end">
+ <InputGroupButton
+ size="xs"
+ aria-label={isRevealed ? "Hide password" : "Show password"}
+ onClick={() => setIsRevealed((prev) => !prev)}
+ >
+ {isRevealed ? <EyeOffIcon /> : <EyeIcon />}
+ </InputGroupButton>
+ </InputGroupAddon>
+ </InputGroup>
+ <FieldDescription>
+ Stored encrypted and only used to open this file. Private keys aren&apos;t imported.
+ </FieldDescription>
+ </Field>
+ <DialogFooter className="mt-6">
+ <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
+ Cancel
+ </Button>
+ <Button
+ type="submit"
+ variant="project"
+ isDisabled={!password || updateInstallation.isPending}
+ isPending={updateInstallation.isPending}
+ >
+ Save
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+ );
+};
diff --git a/frontend/src/pages/cert-manager/DiscoveryPage/components/index.ts b/frontend/src/pages/cert-manager/DiscoveryPage/components/index.ts
index 16e64979e3..d0e83216d5 100644
--- a/frontend/src/pages/cert-manager/DiscoveryPage/components/index.ts
+++ b/frontend/src/pages/cert-manager/DiscoveryPage/components/index.ts
@@ -1,6 +1,6 @@
export { DeleteDiscoveryModal } from "./DeleteDiscoveryModal";
export { DeleteInstallationModal } from "./DeleteInstallationModal";
-export { DiscoveryJobModal } from "./DiscoveryJobModal";
export { DiscoveryJobsTab } from "./DiscoveryJobsTab";
export { EditInstallationModal } from "./EditInstallationModal";
export { InstallationsTab } from "./InstallationsTab";
+export { SetKeystorePasswordDialog } from "./SetKeystorePasswordDialog";
diff --git a/frontend/src/pages/cert-manager/InstallationDetailsByIDPage/InstallationDetailsByIDPage.tsx b/frontend/src/pages/cert-manager/InstallationDetailsByIDPage/InstallationDetailsByIDPage.tsx
index 0b69eb86c7..bc6eecb475 100644
--- a/frontend/src/pages/cert-manager/InstallationDetailsByIDPage/InstallationDetailsByIDPage.tsx
+++ b/frontend/src/pages/cert-manager/InstallationDetailsByIDPage/InstallationDetailsByIDPage.tsx
@@ -1,15 +1,29 @@
+import { useState } from "react";
import { Helmet } from "react-helmet";
import { Link, useNavigate, useParams } from "@tanstack/react-router";
-import { ChevronLeftIcon, EllipsisIcon } from "lucide-react";
+import {
+ ChevronLeftIcon,
+ CircleAlertIcon,
+ EllipsisIcon,
+ LockIcon,
+ TriangleAlertIcon
+} from "lucide-react";
import { ProjectPermissionCan } from "@app/components/permissions";
import { DeleteActionModal } from "@app/components/v2";
import {
+ Alert,
+ AlertDescription,
+ AlertTitle,
Button,
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
+ Empty,
+ EmptyContent,
+ EmptyDescription,
+ EmptyMedia,
PageHeader,
PageLoader
} from "@app/components/v3";
@@ -19,25 +33,50 @@ import {
useOrganization,
useProject
} from "@app/context";
-import { useDeletePkiInstallation, useGetPkiInstallation } from "@app/hooks/api";
+import { PkiKeystoreStatus, useDeletePkiInstallation, useGetPkiInstallation } from "@app/hooks/api";
import { ProjectType } from "@app/hooks/api/projects/types";
import { usePopUp } from "@app/hooks/usePopUp";
+import {
+ canSetKeystorePassword,
+ getEndpoint,
+ useCanRescanPkiInstallations
+} from "@app/pages/cert-manager/pki-discovery-utils";
+import { 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();
const { currentOrg } = useOrganization();
const navigate = useNavigate();
const { installationId, projectId, orgId } = useParams({
from: "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/discovery/installations/$installationId"
});
- const { data: installation, isLoading } = useGetPkiInstallation({ installationId });
+ const [pendingRescan, setPendingRescan] = useState<{
+ previousCheckedAt?: string;
+ startedAt: number;
+ } | null>(null);
+ const { data: installation, isLoading } = useGetPkiInstallation(
+ { installationId },
+ {
+ refetchInterval: (current) =>
+ pendingRescan &&
+ current?.metadata?.lastCheckedAt === pendingRescan.previousCheckedAt &&
+ Date.now() - pendingRescan.startedAt < RESCAN_POLL_TIMEOUT_MS
+ ? RESCAN_POLL_INTERVAL_MS
+ : false
+ }
+ );
const deleteInstallation = useDeletePkiInstallation();
const { popUp, handlePopUpOpen, handlePopUpClose, handlePopUpToggle } = usePopUp([
- "deleteInstallation"
+ "deleteInstallation",
+ "setKeystorePassword"
] as const);
if (isLoading) {
@@ -65,12 +104,12 @@ const Page = () => {
}
};
- const displayName =
- installation.name ||
- installation.locationDetails.fqdn ||
- (installation.locationDetails.ipAddress
- ? `${installation.locationDetails.ipAddress}:${installation.locationDetails.port || 443}`
- : "Installation");
+ const displayName = installation.name || getEndpoint(installation);
+ const isPasswordSettable = canSetKeystorePassword(installation);
+ const keystoreStatus = installation.metadata?.keystoreStatus;
+ const passwordActionLabel = installation.hasKeystorePassword ? "Change Password" : "Set Password";
+
+ const openPasswordDialog = () => handlePopUpOpen("setKeystorePassword");
return (
<div className="mx-auto flex flex-col justify-between text-foreground-inverse">
@@ -98,6 +137,11 @@ const Page = () => {
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
+ {isPasswordSettable && (
+ <DropdownMenuItem isDisabled={!canRescanInstallation} onClick={openPasswordDialog}>
+ {passwordActionLabel}
+ </DropdownMenuItem>
+ )}
<ProjectPermissionCan
I={ProjectPermissionPkiCertificateInstallationActions.Delete}
a={ProjectPermissionSub.PkiCertificateInstallations}
@@ -116,16 +160,73 @@ const Page = () => {
</DropdownMenu>
</PageHeader>
+ {keystoreStatus === PkiKeystoreStatus.PasswordFailed && (
+ <Alert variant="danger" className="mb-5">
+ <CircleAlertIcon />
+ <AlertTitle>The saved password did not open this keystore</AlertTitle>
+ <AlertDescription>
+ {installation.metadata?.lastError ||
+ "Change the password and the file is scanned again."}
+ </AlertDescription>
+ </Alert>
+ )}
+ {keystoreStatus !== PkiKeystoreStatus.PasswordFailed &&
+ installation.metadata?.lastError && (
+ <Alert variant="warning" className="mb-5">
+ <TriangleAlertIcon />
+ <AlertTitle>The last read of this file failed</AlertTitle>
+ <AlertDescription>{installation.metadata.lastError}</AlertDescription>
+ </Alert>
+ )}
<div className="flex flex-col gap-5 lg:flex-row">
<div className="w-full lg:max-w-[24rem]">
<InstallationDetailsSection installation={installation} />
</div>
<div className="flex flex-1 flex-col gap-y-5">
- <InstallationCertificatesSection certificates={installation.certificates || []} />
+ <InstallationCertificatesSection
+ certificates={installation.certificates || []}
+ emptyState={
+ keystoreStatus === PkiKeystoreStatus.Locked ||
+ keystoreStatus === PkiKeystoreStatus.PasswordFailed ? (
+ <Empty>
+ <EmptyMedia variant="icon">
+ <LockIcon />
+ </EmptyMedia>
+ <EmptyDescription>
+ {keystoreStatus === PkiKeystoreStatus.Locked
+ ? "This keystore needs a password before its certificates can be read."
+ : "The certificates in this keystore can be read once the right password is saved."}
+ </EmptyDescription>
+ <EmptyContent>
+ <Button
+ variant="project"
+ isDisabled={!canRescanInstallation}
+ onClick={openPasswordDialog}
+ >
+ {passwordActionLabel}
+ </Button>
+ </EmptyContent>
+ </Empty>
+ ) : undefined
+ }
+ />
</div>
</div>
</div>
+ <SetKeystorePasswordDialog
+ isOpen={popUp.setKeystorePassword.isOpen}
+ onOpenChange={(isOpen) => handlePopUpToggle("setKeystorePassword", isOpen)}
+ onSaved={() =>
+ setPendingRescan({
+ previousCheckedAt: installation.metadata?.lastCheckedAt,
+ startedAt: Date.now()
+ })
+ }
+ projectId={projectId}
+ installation={installation}
+ />
+
<DeleteActionModal
isOpen={popUp.deleteInstallation.isOpen}
title="Are you sure you want to delete this installation?"
diff --git a/frontend/src/pages/cert-manager/InstallationDetailsByIDPage/components/InstallationCertificatesSection.tsx b/frontend/src/pages/cert-manager/InstallationDetailsByIDPage/components/InstallationCertificatesSection.tsx
index 4a72ae31de..6be8dd3c74 100644
--- a/frontend/src/pages/cert-manager/InstallationDetailsByIDPage/components/InstallationCertificatesSection.tsx
+++ b/frontend/src/pages/cert-manager/InstallationDetailsByIDPage/components/InstallationCertificatesSection.tsx
@@ -1,4 +1,5 @@
/* eslint-disable no-nested-ternary */
+import { ReactNode } from "react";
import { useNavigate, useParams } from "@tanstack/react-router";
import { format } from "date-fns";
@@ -27,9 +28,10 @@ import { getCertValidUntilBadgeDetails } from "../../CertificatesPage/components
type Props = {
certificates: TPkiInstallationCert[];
+ emptyState?: ReactNode;
};
-export const InstallationCertificatesSection = ({ certificates }: Props) => {
+export const InstallationCertificatesSection = ({ certificates, emptyState }: Props) => {
const navigate = useNavigate();
const { orgId, projectId } = useParams({
from: "/_authenticate/_inject-org-details/_org-layout/organizations/$orgId/projects/cert-manager/$projectId/_cert-manager-layout/discovery/installations/$installationId"
@@ -42,7 +44,9 @@ export const InstallationCertificatesSection = ({ certificates }: Props) => {
<CardDescription>Certificates found on this installation</CardDescription>
</CardHeader>
<CardContent className="p-0">
- {certificates.length === 0 ? (
+ {certificates.length === 0 && emptyState ? (
+ emptyState
+ ) : certificates.length === 0 ? (
<Empty>
<EmptyHeader>
<EmptyTitle>No certificates found on this installation</EmptyTitle>
diff --git a/frontend/src/pages/cert-manager/InstallationDetailsByIDPage/components/InstallationDetailsSection.tsx b/frontend/src/pages/cert-manager/InstallationDetailsByIDPage/components/InstallationDetailsSection.tsx
index 6c67ee2b2d..b9f64d1a87 100644
--- a/frontend/src/pages/cert-manager/InstallationDetailsByIDPage/components/InstallationDetailsSection.tsx
+++ b/frontend/src/pages/cert-manager/InstallationDetailsByIDPage/components/InstallationDetailsSection.tsx
@@ -1,6 +1,7 @@
import { format } from "date-fns";
import {
+ Badge,
Card,
CardContent,
CardDescription,
@@ -11,7 +12,15 @@ import {
DetailLabel,
DetailValue
} from "@app/components/v3";
-import { TPkiInstallation } from "@app/hooks/api";
+import {
+ PkiCertificateFileFormatLabels,
+ PkiInstallationLocationType,
+ TPkiInstallation
+} from "@app/hooks/api";
+import {
+ getKeystoreStatusBadge,
+ isHostFileInstallation
+} from "@app/pages/cert-manager/pki-discovery-utils";
type Props = {
installation: TPkiInstallation;
@@ -20,6 +29,8 @@ type Props = {
export const InstallationDetailsSection = ({ installation }: Props) => {
const { locationDetails } = installation;
const endpoint = locationDetails.fqdn || locationDetails.ipAddress;
+ const isHostFile = isHostFileInstallation(installation);
+ const isKeystore = installation.locationType === PkiInstallationLocationType.Keystore;
return (
<div className="flex w-full flex-col gap-5">
@@ -36,7 +47,56 @@ export const InstallationDetailsSection = ({ installation }: Props) => {
{installation.name || <span className="text-muted">-</span>}
</DetailValue>
</Detail>
- {endpoint && (
+ {isHostFile && (
+ <>
+ <Detail>
+ <DetailLabel>Host</DetailLabel>
+ <DetailValue>
+ {locationDetails.hostname || <span className="text-muted">-</span>}
+ </DetailValue>
+ </Detail>
+ <Detail>
+ <DetailLabel>Address</DetailLabel>
+ <DetailValue>
+ {locationDetails.hostIdentifier || <span className="text-muted">-</span>}
+ </DetailValue>
+ </Detail>
+ <Detail>
+ <DetailLabel>Path</DetailLabel>
+ <DetailValue className="font-mono break-all">
+ {locationDetails.filePath}
+ </DetailValue>
+ </Detail>
+ <Detail>
+ <DetailLabel>Connection</DetailLabel>
+ <DetailValue>
+ {installation.connection?.name || <span className="text-muted">-</span>}
+ </DetailValue>
+ </Detail>
+ {locationDetails.format && (
+ <Detail>
+ <DetailLabel>Format</DetailLabel>
+ <DetailValue>
+ {PkiCertificateFileFormatLabels[locationDetails.format]}
+ </DetailValue>
+ </Detail>
+ )}
+ </>
+ )}
+ {isKeystore && (
+ <Detail>
+ <DetailLabel>Keystore Password</DetailLabel>
+ <DetailValue>
+ {getKeystoreStatusBadge(installation) ??
+ (installation.hasKeystorePassword ? (
+ <Badge variant="success">Set</Badge>
+ ) : (
+ <span className="text-muted">Not needed</span>
+ ))}
+ </DetailValue>
+ </Detail>
+ )}
+ {endpoint && !isHostFile && (
<Detail>
<DetailLabel>Endpoint</DetailLabel>
<DetailValue>
diff --git a/frontend/src/pages/cert-manager/pki-discovery-utils.tsx b/frontend/src/pages/cert-manager/pki-discovery-utils.tsx
index a78a6ce8fe..50b09b9bca 100644
--- a/frontend/src/pages/cert-manager/pki-discovery-utils.tsx
+++ b/frontend/src/pages/cert-manager/pki-discovery-utils.tsx
@@ -1,13 +1,32 @@
import { Badge } from "@app/components/v3";
-import { PkiDiscoveryScanStatus, TPkiInstallation } from "@app/hooks/api";
+import {
+ ProjectPermissionPkiCertificateInstallationActions,
+ ProjectPermissionPkiDiscoveryActions,
+ ProjectPermissionSub,
+ useProjectPermission
+} from "@app/context";
+import {
+ PkiCertificateFileFormat,
+ PkiDiscoveryScanStatus,
+ PkiInstallationLocationType,
+ PkiKeystoreStatus,
+ TPkiInstallation
+} from "@app/hooks/api";
export const getGatewayLabel = (installation: TPkiInstallation): string | null => {
const { gatewayName } = installation.locationDetails;
return gatewayName || null;
};
+export const isHostFileInstallation = (installation: TPkiInstallation) =>
+ installation.locationType === PkiInstallationLocationType.Filesystem ||
+ installation.locationType === PkiInstallationLocationType.Keystore;
+
export const getEndpoint = (installation: TPkiInstallation): string => {
- const { ipAddress, fqdn, port } = installation.locationDetails;
+ const { ipAddress, fqdn, port, hostIdentifier, filePath } = installation.locationDetails;
+ if (isHostFileInstallation(installation) && filePath) {
+ return hostIdentifier ? `${hostIdentifier}:${filePath}` : filePath;
+ }
const host = fqdn || ipAddress;
if (host) {
return `${host}:${port || 443}`;
@@ -64,3 +83,39 @@ export const getScanStatusBadge = (status: string) => {
return <Badge variant="neutral">{status}</Badge>;
}
};
+
+export const getKeystoreStatusBadge = (installation: TPkiInstallation) => {
+ switch (installation.metadata?.keystoreStatus) {
+ case PkiKeystoreStatus.Locked:
+ return <Badge variant="warning">Locked</Badge>;
+ case PkiKeystoreStatus.PasswordFailed:
+ return <Badge variant="danger">Password Failed</Badge>;
+ default:
+ return null;
+ }
+};
+
+export const canSetKeystorePassword = (installation: TPkiInstallation) => {
+ if (installation.locationType !== PkiInstallationLocationType.Keystore) return false;
+ const { format } = installation.locationDetails;
+ if (format && format !== PkiCertificateFileFormat.Pkcs12) return false;
+ const status = installation.metadata?.keystoreStatus;
+ return (
+ Boolean(installation.hasKeystorePassword) ||
+ status === PkiKeystoreStatus.Locked ||
+ status === PkiKeystoreStatus.PasswordFailed
+ );
+};
+
+export const useCanRescanPkiInstallations = () => {
+ const { permission } = useProjectPermission();
+ return (
+ permission.can(
+ ProjectPermissionPkiCertificateInstallationActions.Edit,
+ ProjectPermissionSub.PkiCertificateInstallations
+ ) &&
+ permission.can(ProjectPermissionPkiDiscoveryActions.RunScan, ProjectPermissionSub.PkiDiscovery)
+ );
+};
+
+export const getItemLabel = (item: string) => item;