Skip to content

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

feat(pki-sync): allow one LDAP connection to back many Linux and Windows syncs

Carlos Monastyrski0d4e37bcd6d7
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 14a0c90f5c..b7cbfee47a 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -4544,6 +4544,8 @@ interface CreatePkiSyncEvent {
destination: string;
applicationId?: string;
connectionId?: string;
+ connectionName?: string;
+ targetHost?: string;
hasCredentials?: boolean;
hasPostSyncCommand?: boolean;
hasHealthCheckCommand?: boolean;
@@ -4556,6 +4558,10 @@ interface UpdatePkiSyncEvent {
pkiSyncId: string;
name: string;
applicationId?: string;
+ destination?: string;
+ connectionId?: string;
+ connectionName?: string;
+ targetHost?: string;
hasPostSyncCommand?: boolean;
hasHealthCheckCommand?: boolean;
};
diff --git a/backend/src/ee/services/license/license-fns.ts b/backend/src/ee/services/license/license-fns.ts
index dcc8357467..f8141815f0 100644
--- a/backend/src/ee/services/license/license-fns.ts
+++ b/backend/src/ee/services/license/license-fns.ts
@@ -106,7 +106,7 @@ export const getDefaultOnPremFeatures = (): TFeatureSet => ({
enforceMfa: false,
projectTemplates: false,
kmip: false,
- gateway: false,
+ gateway: true,
gatewayPool: false,
pamSlackNotifications: false,
secretScanning: false,
diff --git a/backend/src/ee/services/pam-account/pam-account-schemas.ts b/backend/src/ee/services/pam-account/pam-account-schemas.ts
index c537e55b09..1ff0fa77be 100644
--- a/backend/src/ee/services/pam-account/pam-account-schemas.ts
+++ b/backend/src/ee/services/pam-account/pam-account-schemas.ts
@@ -6,6 +6,7 @@ import { promisify } from "util";
import { z } from "zod";
import { BadRequestError } from "@app/lib/errors";
+import { netbiosFromDomainFqdn } from "@app/lib/ldap/ldap-search-fns";
import { GcpServiceAccountAuthMethod, PamAccountType, PamPostgresAuthMethod, PamSshAuthMethod } from "../pam/pam-enums";
import { getApplicablePolicies, PamPolicyDescriptorSchema } from "../pam/pam-policies";
@@ -954,14 +955,14 @@ export const isDomainQualifiedUsername = (username: string) => username.includes
// Domain-qualifies a bare username to `NETBIOS\user` for RDP/NLA; already-qualified forms pass through
export const qualifyUsernameWithDomain = (username: string, domainFqdn: string) => {
if (isDomainQualifiedUsername(username)) return username;
- return `${domainFqdn.split(".")[0].toUpperCase()}\\${username}`;
+ return `${netbiosFromDomainFqdn(domainFqdn)}\\${username}`;
};
// Normalizes any form to a NetBIOS `DOMAIN\user` login
export const toNetbiosUsername = (username: string, domainFqdn: string) => {
if (username.includes("\\")) return username;
const localPart = username.includes("@") ? username.split("@")[0] : username;
- return `${domainFqdn.split(".")[0].toUpperCase()}\\${localPart}`;
+ return `${netbiosFromDomainFqdn(domainFqdn)}\\${localPart}`;
};
// -- Account accessibility
diff --git a/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-factory.ts b/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-factory.ts
index 50ad5ad1ae..291f2329ea 100644
--- a/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-factory.ts
+++ b/backend/src/ee/services/pam-discovery/active-directory/active-directory-discovery-factory.ts
@@ -6,6 +6,7 @@ import RE2 from "re2";
import { BadRequestError } from "@app/lib/errors";
import { WinRmRpcEndpoint } from "@app/lib/gateway-v2/winrm-rpc";
+import { buildDomainBaseDN, getLdapAttribute, getLdapAttributeBuffer, searchLdap } from "@app/lib/ldap/ldap-search-fns";
import { logger } from "@app/lib/logger";
import { TGatewayV2ServiceFactory } from "../../gateway-v2/gateway-v2-service";
@@ -26,17 +27,10 @@ const LDAP_PAGE_SIZE = 500;
const TRAILING_HYPHENS_REGEX = new RE2(/-+$/);
type TGatewayDep = Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
-type TLdapAttribute = { type: string; values: string[]; buffers: Buffer[] };
type TLdapComputer = { cn: string; dNSHostName: string; objectGUID: string; resolvedIp?: string };
type TLdapUser = { sAMAccountName: string; objectGUID: string };
type TWinRmLocalUser = { Name: string };
-const buildDomainDN = (domainFqdn: string) =>
- domainFqdn
- .split(".")
- .map((part) => `DC=${part}`)
- .join(",");
-
const parseObjectGUID = (buf: Buffer | undefined): string => {
if (buf && buf.length === 16) {
const hex = buf.toString("hex");
@@ -51,35 +45,6 @@ const parseObjectGUID = (buf: Buffer | undefined): string => {
return "";
};
-const getAttr = (entry: ldapjs.SearchEntry, name: string): string =>
- (entry as unknown as { attributes: TLdapAttribute[] }).attributes?.find(
- (a) => a.type.toLowerCase() === name.toLowerCase()
- )?.values?.[0] ?? "";
-
-const getAttrBuffer = (entry: ldapjs.SearchEntry, name: string): Buffer | undefined =>
- (entry as unknown as { attributes: TLdapAttribute[] }).attributes?.find(
- (a) => a.type.toLowerCase() === name.toLowerCase()
- )?.buffers?.[0];
-
-const ldapSearch = (client: ldapjs.Client, baseDN: string, filter: string, attributes: string[]) =>
- new Promise<ldapjs.SearchEntry[]>((resolve, reject) => {
- const results: ldapjs.SearchEntry[] = [];
- client.search(
- baseDN,
- { filter, scope: "sub", attributes, paged: { pageSize: LDAP_PAGE_SIZE }, timeLimit: LDAP_TIMEOUT / 1000 },
- (err, res) => {
- if (err) return reject(err);
- res.on("searchEntry", (entry) => results.push(entry));
- res.on("error", reject);
- res.on("end", (result) =>
- result?.status !== 0
- ? reject(new Error(`LDAP search failed with status ${result?.status}`))
- : resolve(results)
- );
- }
- );
- });
-
type TAdConnection = {
domain: string;
dcAddress: string;
@@ -318,7 +283,7 @@ export const activeDirectoryDiscoveryFactory: TPamDiscoveryFactory = ({
const scan = async (signal: AbortSignal): Promise<TDiscoveryScanResult> => {
const domain = connectionDetails.domain.toLowerCase();
- const baseDN = buildDomainDN(connectionDetails.domain);
+ const baseDN = buildDomainBaseDN(connectionDetails.domain);
const machineErrors: TDiscoveryMachineError[] = [];
const dependencies: TDiscoveredDependency[] = [];
const scannedDependencyMachines: string[] = [];
@@ -331,29 +296,34 @@ export const activeDirectoryDiscoveryFactory: TPamDiscoveryFactory = ({
computers: TLdapComputer[];
netbiosName: string | null;
}>(conn, credentials, gatewayId, gatewayV2Service, async (client) => {
- const userEntries = await ldapSearch(client, baseDN, "(&(objectClass=user)(objectCategory=person))", [
- "sAMAccountName",
- "objectGUID"
- ]);
+ const userEntries = await searchLdap(client, {
+ baseDN,
+ filter: "(&(objectClass=user)(objectCategory=person))",
+ attributes: ["sAMAccountName", "objectGUID"],
+ pageSize: LDAP_PAGE_SIZE,
+ timeLimitSeconds: LDAP_TIMEOUT / 1000
+ });
const parsedUsers = userEntries
.map((entry) => ({
- sAMAccountName: getAttr(entry, "sAMAccountName"),
- objectGUID: parseObjectGUID(getAttrBuffer(entry, "objectGUID"))
+ sAMAccountName: getLdapAttribute(entry, "sAMAccountName"),
+ objectGUID: parseObjectGUID(getLdapAttributeBuffer(entry, "objectGUID"))
}))
.filter((u) => u.sAMAccountName && u.objectGUID);
if (!enumerateComputers) return { users: parsedUsers, computers: [] as TLdapComputer[], netbiosName: null };
- const computerEntries = await ldapSearch(client, baseDN, "(&(objectClass=computer)(operatingSystem=*Server*))", [
- "cn",
- "dNSHostName",
- "objectGUID"
- ]);
+ const computerEntries = await searchLdap(client, {
+ baseDN,
+ filter: "(&(objectClass=computer)(operatingSystem=*Server*))",
+ attributes: ["cn", "dNSHostName", "objectGUID"],
+ pageSize: LDAP_PAGE_SIZE,
+ timeLimitSeconds: LDAP_TIMEOUT / 1000
+ });
const parsedComputers = computerEntries
.map((entry) => ({
- cn: getAttr(entry, "cn"),
- dNSHostName: getAttr(entry, "dNSHostName"),
- objectGUID: parseObjectGUID(getAttrBuffer(entry, "objectGUID"))
+ cn: getLdapAttribute(entry, "cn"),
+ dNSHostName: getLdapAttribute(entry, "dNSHostName"),
+ objectGUID: parseObjectGUID(getLdapAttributeBuffer(entry, "objectGUID"))
}))
.filter((c) => (c.dNSHostName || c.cn) && c.objectGUID);
@@ -361,13 +331,14 @@ export const activeDirectoryDiscoveryFactory: TPamDiscoveryFactory = ({
// the Partitions container so a NETBIOS\user run-as isn't wrongly rejected and its dependencies dropped.
let resolvedNetbios: string | null = null;
try {
- const partitions = await ldapSearch(
- client,
- `CN=Partitions,CN=Configuration,${baseDN}`,
- `(&(objectClass=crossRef)(nETBIOSName=*)(nCName=${baseDN}))`,
- ["nETBIOSName"]
- );
- resolvedNetbios = partitions.length ? getAttr(partitions[0], "nETBIOSName") || null : null;
+ const partitions = await searchLdap(client, {
+ baseDN: `CN=Partitions,CN=Configuration,${baseDN}`,
+ filter: `(&(objectClass=crossRef)(nETBIOSName=*)(nCName=${baseDN}))`,
+ attributes: ["nETBIOSName"],
+ pageSize: LDAP_PAGE_SIZE,
+ timeLimitSeconds: LDAP_TIMEOUT / 1000
+ });
+ resolvedNetbios = partitions.length ? getLdapAttribute(partitions[0], "nETBIOSName") || null : null;
} catch (err) {
logger.warn(err, `PAM AD discovery could not read the NetBIOS name; using the DNS label [domain=${domain}]`);
}
diff --git a/backend/src/ee/services/pam-discovery/pam-discovery-targets.ts b/backend/src/ee/services/pam-discovery/pam-discovery-targets.ts
index 0102126d0a..7ac7a0b0a0 100644
--- a/backend/src/ee/services/pam-discovery/pam-discovery-targets.ts
+++ b/backend/src/ee/services/pam-discovery/pam-discovery-targets.ts
@@ -1,25 +1,19 @@
import net from "node:net";
import { Netmask } from "netmask";
-import RE2 from "re2";
import { z } from "zod";
import { BadRequestError } from "@app/lib/errors";
import { isValidIpOrCidr } from "@app/lib/ip";
+import { isValidHostname } from "@app/lib/validator/validate-hostname";
export const MAX_TARGET_HOSTS = 65536;
-const HOSTNAME_REGEX = new RE2(
- /^[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/
-);
-
const isValidIpv4Target = (value: string) => {
const base = value.includes("/") ? value.split("/")[0] : value;
return net.isIPv4(base) && isValidIpOrCidr(value);
};
-const isValidHostname = (value: string) => value.length <= 253 && HOSTNAME_REGEX.test(value);
-
const isValidTarget = (value: string) => isValidIpv4Target(value) || isValidHostname(value);
const isValidHost = (value: string) => (net.isIPv4(value) && isValidIpOrCidr(value)) || isValidHostname(value);
diff --git a/backend/src/ee/services/permission/default-roles.ts b/backend/src/ee/services/permission/default-roles.ts
index 816c363b7b..ad0b15fcb1 100644
--- a/backend/src/ee/services/permission/default-roles.ts
+++ b/backend/src/ee/services/permission/default-roles.ts
@@ -296,7 +296,8 @@ const buildAdminPermissionRules = () => {
ProjectPermissionPkiSyncActions.ImportCertificates,
ProjectPermissionPkiSyncActions.RemoveCertificates,
ProjectPermissionPkiSyncActions.SetPostSyncCommand,
- ProjectPermissionPkiSyncActions.SetHealthCheckCommand
+ ProjectPermissionPkiSyncActions.SetHealthCheckCommand,
+ ProjectPermissionPkiSyncActions.SetTargetHost
],
ProjectPermissionSub.PkiSyncs
);
@@ -865,7 +866,8 @@ const buildApplicationAdminPermissionRules = () => {
ResourcePermissionPkiSyncActions.ImportCertificates,
ResourcePermissionPkiSyncActions.RemoveCertificates,
ResourcePermissionPkiSyncActions.SetPostSyncCommand,
- ResourcePermissionPkiSyncActions.SetHealthCheckCommand
+ ResourcePermissionPkiSyncActions.SetHealthCheckCommand,
+ ResourcePermissionPkiSyncActions.SetTargetHost
],
ResourcePermissionSub.PkiSyncs
);
diff --git a/backend/src/ee/services/permission/project-permission.ts b/backend/src/ee/services/permission/project-permission.ts
index 3af2b5823d..9c34b0606d 100644
--- a/backend/src/ee/services/permission/project-permission.ts
+++ b/backend/src/ee/services/permission/project-permission.ts
@@ -171,7 +171,8 @@ export enum ProjectPermissionPkiSyncActions {
ImportCertificates = "import-certificates",
RemoveCertificates = "remove-certificates",
SetPostSyncCommand = "set-post-sync-command",
- SetHealthCheckCommand = "set-health-check-command"
+ SetHealthCheckCommand = "set-health-check-command",
+ SetTargetHost = "set-target-host"
}
export enum ProjectPermissionPkiDiscoveryActions {
diff --git a/backend/src/ee/services/permission/resource-permission.ts b/backend/src/ee/services/permission/resource-permission.ts
index ff2fd60b2a..731494e510 100644
--- a/backend/src/ee/services/permission/resource-permission.ts
+++ b/backend/src/ee/services/permission/resource-permission.ts
@@ -101,7 +101,8 @@ export enum ResourcePermissionPkiSyncActions {
ImportCertificates = "import-certificates",
RemoveCertificates = "remove-certificates",
SetPostSyncCommand = "set-post-sync-command",
- SetHealthCheckCommand = "set-health-check-command"
+ SetHealthCheckCommand = "set-health-check-command",
+ SetTargetHost = "set-target-host"
}
export type ResourcePermissionSet =
diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.ts
index c4d2828cc8..01f8088d12 100644
--- a/backend/src/keystore/keystore.ts
+++ b/backend/src/keystore/keystore.ts
@@ -58,8 +58,13 @@ export const KeyStorePrefixes = {
`sync-integration-last-run-${projectId}-${environmentSlug}-${secretPath}` as const,
SecretSyncLock: (syncId: string) => `secret-sync-mutex-${syncId}` as const,
PkiSyncLock: (syncId: string) => `pki-sync-mutex-${syncId}` as const,
- AppConnectionConcurrentJobs: (connectionId: string) => `app-connection-concurrency-${connectionId}` as const,
- AppConnectionCommandLock: (connectionId: string) => `app-connection-command-mutex-${connectionId}` as const,
+ AppConnectionConcurrentJobs: (connectionId: string, targetHost?: string) =>
+ `app-connection-concurrency-${connectionId}${targetHost ? `-${targetHost.toLowerCase()}` : ""}` as const,
+ AppConnectionCommandLock: (connectionId: string, targetHost?: string) =>
+ `app-connection-command-mutex-${connectionId}${targetHost ? `-${targetHost.toLowerCase()}` : ""}` as const,
+ LdapHostLogin: (fingerprint: string) => `ldap-host-login-${fingerprint}` as const,
+ LdapDirectoryMachines: (connectionId: string, search: string, limit: number) =>
+ `ldap-directory-machines-${connectionId}-${limit}-${search}` as const,
SecretRotationLock: (rotationId: string) => `secret-rotation-v2-mutex-${rotationId}` as const,
PamAccountRotationLock: (accountId: string) => `pam-account-rotation-mutex-${accountId}` as const,
SecretScanningLock: (dataSourceId: string, resourceExternalId: string) =>
@@ -196,6 +201,9 @@ export const KeyStorePrefixes = {
};
export const KeyStoreTtls = {
+ LdapDirectoryMachinesInSeconds: 60,
+ LdapHostLoginInSeconds: 3600,
+ LdapGuessedHostLoginInSeconds: 30,
SetSyncSecretIntegrationLastRunTimestampInSeconds: 60,
SetSecretSyncLastRunTimestampInSeconds: 60,
AccessTokenStatusUpdateInSeconds: 120,
diff --git a/backend/src/lib/ldap/ldap-search-fns.test.ts b/backend/src/lib/ldap/ldap-search-fns.test.ts
new file mode 100644
index 0000000000..60b1e446ae
--- /dev/null
+++ b/backend/src/lib/ldap/ldap-search-fns.test.ts
@@ -0,0 +1,188 @@
+import { EventEmitter } from "node:events";
+
+import {
+ buildDomainBaseDN,
+ escapeLdapFilterValue,
+ getLdapAttribute,
+ getLdapAttributeBuffer,
+ netbiosFromDomainFqdn,
+ searchLdap
+} from "./ldap-search-fns";
+
+const NUL = String.fromCharCode(0);
+
+type TCapturedSearch = { baseDN: string; options: Record<string, unknown> };
+
+const buildClient = (script: (res: EventEmitter) => void, captured: TCapturedSearch[]) =>
+ ({
+ search: (baseDN: string, options: Record<string, unknown>, cb: (err: Error | null, res: EventEmitter) => void) => {
+ captured.push({ baseDN, options });
+ const res = new EventEmitter();
+ cb(null, res);
+ setImmediate(() => script(res));
+ }
+ }) as never;
+
+const entry = (attributes: { type: string; values: string[]; buffers: Buffer[] }[]) => ({ attributes }) as never;
+
+describe("getLdapAttribute", () => {
+ test("matches the attribute name case insensitively", () => {
+ const e = entry([{ type: "dNSHostName", values: ["web01.corp.example.com"], buffers: [] }]);
+ expect(getLdapAttribute(e, "dnshostname")).toBe("web01.corp.example.com");
+ });
+
+ test("returns an empty string when the attribute is absent", () => {
+ expect(getLdapAttribute(entry([]), "cn")).toBe("");
+ });
+
+ test("reads raw bytes for binary attributes", () => {
+ const buf = Buffer.from([1, 2, 3]);
+ const e = entry([{ type: "objectGUID", values: [], buffers: [buf] }]);
+ expect(getLdapAttributeBuffer(e, "objectguid")).toBe(buf);
+ expect(getLdapAttributeBuffer(entry([]), "objectGUID")).toBeUndefined();
+ });
+});
+
+describe("buildDomainBaseDN", () => {
+ test("maps every label to a DC component", () => {
+ expect(buildDomainBaseDN("corp.example.com")).toBe("DC=corp,DC=example,DC=com");
+ });
+
+ test("handles a single label and ignores empty ones", () => {
+ expect(buildDomainBaseDN("corp")).toBe("DC=corp");
+ expect(buildDomainBaseDN("corp..com")).toBe("DC=corp,DC=com");
+ });
+});
+
+describe("searchLdap", () => {
+ test("defaults match the behaviour PAM discovery relied on before extraction", async () => {
+ const captured: TCapturedSearch[] = [];
+ const client = buildClient((res) => res.emit("end", { status: 0 }), captured);
+
+ await searchLdap(client, {
+ baseDN: "DC=corp,DC=example,DC=com",
+ filter: "(objectClass=user)",
+ attributes: ["cn"],
+ pageSize: 500,
+ timeLimitSeconds: 30
+ });
+
+ expect(captured[0].options).toEqual({
+ filter: "(objectClass=user)",
+ scope: "sub",
+ attributes: ["cn"],
+ timeLimit: 30,
+ paged: { pageSize: 500 }
+ });
+ expect(captured[0].options).not.toHaveProperty("sizeLimit");
+ });
+
+ test("omits the paging control when no page size is given", async () => {
+ const captured: TCapturedSearch[] = [];
+ const client = buildClient((res) => res.emit("end", { status: 0 }), captured);
+
+ await searchLdap(client, {
+ baseDN: "DC=corp",
+ filter: "(objectCategory=computer)",
+ attributes: ["cn"],
+ sizeLimit: 50,
+ timeLimitSeconds: 15
+ });
+
+ expect(captured[0].options).not.toHaveProperty("paged");
+ expect(captured[0].options.sizeLimit).toBe(50);
+ });
+
+ test("rejects sizeLimitExceeded unless the caller opted in", async () => {
+ const captured: TCapturedSearch[] = [];
+ const sizeLimitError = Object.assign(new Error("Size Limit Exceeded"), { code: 4 });
+
+ const strict = buildClient((res) => res.emit("error", sizeLimitError), captured);
+ await expect(
+ searchLdap(strict, { baseDN: "DC=corp", filter: "(cn=*)", attributes: [], timeLimitSeconds: 30 })
+ ).rejects.toThrow(/Size Limit Exceeded/);
+
+ const lenient = buildClient((res) => {
+ res.emit("searchEntry", entry([{ type: "cn", values: ["web01"], buffers: [] }]));
+ res.emit("error", sizeLimitError);
+ }, captured);
+ const entries = await searchLdap(lenient, {
+ baseDN: "DC=corp",
+ filter: "(cn=*)",
+ attributes: [],
+ timeLimitSeconds: 15,
+ acceptSizeLimitExceeded: true
+ });
+ expect(entries).toHaveLength(1);
+ });
+
+ test("a non-sizeLimit error still rejects even when the caller opted in", async () => {
+ const captured: TCapturedSearch[] = [];
+ const client = buildClient((res) => res.emit("error", Object.assign(new Error("Busy"), { code: 51 })), captured);
+ await expect(
+ searchLdap(client, {
+ baseDN: "DC=corp",
+ filter: "(cn=*)",
+ attributes: [],
+ timeLimitSeconds: 15,
+ acceptSizeLimitExceeded: true
+ })
+ ).rejects.toThrow(/Busy/);
+ });
+
+ test("collects entries and lets a caller map failures into its own error type", async () => {
+ const captured: TCapturedSearch[] = [];
+ const client = buildClient((res) => {
+ res.emit("searchEntry", entry([{ type: "cn", values: ["web01"], buffers: [] }]));
+ res.emit("end", { status: 0 });
+ }, captured);
+
+ const entries = await searchLdap(client, {
+ baseDN: "DC=corp",
+ filter: "(cn=*)",
+ attributes: ["cn"],
+ timeLimitSeconds: 15
+ });
+ expect(entries).toHaveLength(1);
+ expect(getLdapAttribute(entries[0], "cn")).toBe("web01");
+
+ const failing = buildClient((res) => res.emit("end", { status: 32 }), captured);
+ await expect(
+ searchLdap(failing, {
+ baseDN: "DC=corp",
+ filter: "(cn=*)",
+ attributes: [],
+ timeLimitSeconds: 15,
+ mapError: ({ status }) => new Error(`mapped:${status}`)
+ })
+ ).rejects.toThrow("mapped:32");
+ });
+});
+
+describe("escapeLdapFilterValue", () => {
+ test("escapes every character that is special in an LDAP filter", () => {
+ expect(escapeLdapFilterValue("web*01")).toBe("web\\2a01");
+ expect(escapeLdapFilterValue("a(b)c")).toBe("a\\28b\\29c");
+ expect(escapeLdapFilterValue("back\\slash")).toBe("back\\5cslash");
+ expect(escapeLdapFilterValue(`nul${NUL}end`)).toBe("nul\\00end");
+ });
+
+ test("neutralizes a filter injection attempt", () => {
+ expect(escapeLdapFilterValue("*)(objectClass=*")).toBe("\\2a\\29\\28objectClass=\\2a");
+ });
+
+ test("escapes the backslash before the characters whose escapes introduce one", () => {
+ expect(escapeLdapFilterValue("\\*")).toBe("\\5c\\2a");
+ });
+
+ test("leaves an ordinary host name untouched", () => {
+ expect(escapeLdapFilterValue("server01.corp.example.com")).toBe("server01.corp.example.com");
+ });
+});
+
+describe("netbiosFromDomainFqdn", () => {
+ test("uppercases the first label", () => {
+ expect(netbiosFromDomainFqdn("corp.example.com")).toBe("CORP");
+ expect(netbiosFromDomainFqdn("corp")).toBe("CORP");
+ });
+});
diff --git a/backend/src/lib/ldap/ldap-search-fns.ts b/backend/src/lib/ldap/ldap-search-fns.ts
new file mode 100644
index 0000000000..5e2ab965f3
--- /dev/null
+++ b/backend/src/lib/ldap/ldap-search-fns.ts
@@ -0,0 +1,90 @@
+import ldap from "@infisical/ldapjs";
+import RE2 from "re2";
+
+const LDAP_SIZE_LIMIT_EXCEEDED = 4;
+
+type TLdapAttribute = { type: string; values: string[]; buffers: Buffer[] };
+
+export const getLdapAttribute = (entry: ldap.SearchEntry, name: string): string =>
+ (entry as unknown as { attributes: TLdapAttribute[] }).attributes?.find(
+ (attribute) => attribute.type.toLowerCase() === name.toLowerCase()
+ )?.values?.[0] ?? "";
+
+export const getLdapAttributeBuffer = (entry: ldap.SearchEntry, name: string): Buffer | undefined =>
+ (entry as unknown as { attributes: TLdapAttribute[] }).attributes?.find(
+ (attribute) => attribute.type.toLowerCase() === name.toLowerCase()
+ )?.buffers?.[0];
+
+export const buildDomainBaseDN = (domainFqdn: string): string =>
+ domainFqdn
+ .split(".")
+ .filter(Boolean)
+ .map((label) => `DC=${label}`)
+ .join(",");
+
+const NUL_CHARACTER = String.fromCharCode(0);
+const LDAP_FILTER_SPECIAL_CHARACTERS = new RE2("[\\\\*()\\x00]", "g");
+const LDAP_FILTER_ESCAPES: Record<string, string> = {
+ "\\": "\\5c",
+ "*": "\\2a",
+ "(": "\\28",
+ ")": "\\29",
+ [NUL_CHARACTER]: "\\00"
+};
+
+export const escapeLdapFilterValue = (value: string): string =>
+ value.replace(LDAP_FILTER_SPECIAL_CHARACTERS, (character) => LDAP_FILTER_ESCAPES[character]);
+
+export const netbiosFromDomainFqdn = (domainFqdn: string): string => domainFqdn.split(".")[0].toUpperCase();
+
+export type TLdapSearchOptions = {
+ baseDN: string;
+ filter: string;
+ attributes: string[];
+ timeLimitSeconds: number;
+ scope?: "base" | "one" | "sub";
+ sizeLimit?: number;
+ pageSize?: number;
+ acceptSizeLimitExceeded?: boolean;
+ mapError?: (input: { err?: Error; status?: number }) => Error;
+};
+
+const defaultMapError = ({ err, status }: { err?: Error; status?: number }) =>
+ err ?? new Error(`LDAP search failed with status ${status}`);
+
+export const searchLdap = (client: ldap.Client, options: TLdapSearchOptions): Promise<ldap.SearchEntry[]> =>
+ new Promise((resolve, reject) => {
+ const mapError = options.mapError ?? defaultMapError;
+ const entries: ldap.SearchEntry[] = [];
+
+ client.search(
+ options.baseDN,
+ {
+ filter: options.filter,
+ scope: options.scope ?? "sub",
+ attributes: options.attributes,
+ timeLimit: options.timeLimitSeconds,
+ ...(options.sizeLimit === undefined ? {} : { sizeLimit: options.sizeLimit }),
+ ...(options.pageSize === undefined ? {} : { paged: { pageSize: options.pageSize } })
+ },
+ (err, res) => {
+ if (err) {
+ reject(mapError({ err }));
+ return;
+ }
+ res.on("searchEntry", (entry) => entries.push(entry));
+ res.on("error", (streamErr: Error & { code?: number }) => {
+ if (options.acceptSizeLimitExceeded && streamErr?.code === LDAP_SIZE_LIMIT_EXCEEDED) {
+ resolve(entries);
+ return;
+ }
+ reject(mapError({ err: streamErr }));
+ });
+ res.on("end", (result) => {
+ const status = result?.status;
+ if (status === 0) resolve(entries);
+ else reject(mapError({ status }));
+ });
+ }
+ );
+ });
diff --git a/backend/src/lib/validator/validate-hostname.test.ts b/backend/src/lib/validator/validate-hostname.test.ts
new file mode 100644
index 0000000000..47c4e21a0f
--- /dev/null
+++ b/backend/src/lib/validator/validate-hostname.test.ts
@@ -0,0 +1,36 @@
+import { HOSTNAME_MAX_LENGTH, isValidHostname } from "./validate-hostname";
+
+describe("isValidHostname", () => {
+ test.each([
+ ["server01", true],
+ ["server01.corp.example.com", true],
+ ["EC2AMAZ-8V4780K.corp.example.com", true],
+ ["10.0.0.5", true],
+ ["a", true],
+ ["1corp.example.com", true],
+ ["corp-1.example.com", true]
+ ])("accepts %s", (value, expected) => {
+ expect(isValidHostname(value)).toBe(expected);
+ });
+
+ test.each([
+ ["", false],
+ ["-leading.example.com", false],
+ ["trailing-.example.com", false],
+ ["under_score.example.com", false],
+ ["server01.corp.example.com:5986", false],
+ ["has space", false],
+ ["fe80::1", false],
+ ["corp..example.com", false]
+ ])("rejects %s", (value, expected) => {
+ expect(isValidHostname(value)).toBe(expected);
+ });
+
+ test("caps the total length", () => {
+ const label = "a".repeat(61);
+ const long = [label, label, label, label, label].join(".");
+ expect(long.length).toBeGreaterThan(HOSTNAME_MAX_LENGTH);
+ expect(isValidHostname(long)).toBe(false);
+ expect(isValidHostname(`${label}.${label}.${label}`)).toBe(true);
+ });
+});
diff --git a/backend/src/lib/validator/validate-hostname.ts b/backend/src/lib/validator/validate-hostname.ts
new file mode 100644
index 0000000000..4abcb290ed
--- /dev/null
+++ b/backend/src/lib/validator/validate-hostname.ts
@@ -0,0 +1,11 @@
+import RE2 from "re2";
+
+const HOSTNAME_MAX_LENGTH = 253;
+
+const HOSTNAME_REGEX = new RE2(
+ /^[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/
+);
+
+export const isValidHostname = (value: string) => value.length <= HOSTNAME_MAX_LENGTH && HOSTNAME_REGEX.test(value);
+
+export { HOSTNAME_MAX_LENGTH };
diff --git a/backend/src/server/routes/v1/app-connection-routers/ldap-connection-router.ts b/backend/src/server/routes/v1/app-connection-routers/ldap-connection-router.ts
index d415707cca..64db9d0742 100644
--- a/backend/src/server/routes/v1/app-connection-routers/ldap-connection-router.ts
+++ b/backend/src/server/routes/v1/app-connection-routers/ldap-connection-router.ts
@@ -1,9 +1,16 @@
+import { z } from "zod";
+
+import { readLimit } from "@app/server/config/rateLimiter";
+import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
import {
CreateLdapConnectionSchema,
+ DIRECTORY_MACHINE_LIST_DEFAULT_LIMIT,
+ DIRECTORY_MACHINE_LIST_MAX_LIMIT,
SanitizedLdapConnectionSchema,
UpdateLdapConnectionSchema
} from "@app/services/app-connection/ldap";
+import { AuthMode } from "@app/services/auth/auth-type";
import { registerAppConnectionEndpoints } from "./app-connection-endpoints";
@@ -15,4 +22,54 @@ export const registerLdapConnectionRouter = async (server: FastifyZodProvider) =
createSchema: CreateLdapConnectionSchema,
updateSchema: UpdateLdapConnectionSchema
});
+
+ server.route({
+ method: "GET",
+ url: `/:connectionId/machines`,
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ operationId: "listLdapDirectoryMachines",
+ params: z.object({
+ connectionId: z.string().uuid().describe("The ID of the LDAP Connection to list machines from.")
+ }),
+ querystring: z.object({
+ search: z
+ .string()
+ .trim()
+ .max(255)
+ .optional()
+ .describe("Filter machines whose name or DNS host name begins with this value."),
+ limit: z.coerce
+ .number()
+ .int()
+ .min(1)
+ .max(DIRECTORY_MACHINE_LIST_MAX_LIMIT)
+ .default(DIRECTORY_MACHINE_LIST_DEFAULT_LIMIT)
+ .describe("The maximum number of machines to return.")
+ }),
+ response: {
+ 200: z.object({
+ machines: z
+ .object({
+ hostname: z.string().describe("The machine's DNS host name, or its common name if it has none.")
+ })
+ .array()
+ .describe("Machines read from the directory, offered as suggestions for a sync's target host.")
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
+ handler: async (req) => {
+ const { connectionId } = req.params;
+ const { search, limit } = req.query;
+ const machines = await server.services.appConnection.ldap.listMachines(
+ connectionId,
+ { search, limit },
+ req.permission
+ );
+ return { machines };
+ }
+ });
};
diff --git a/backend/src/server/routes/v1/pki-sync-routers/pki-sync-endpoints.ts b/backend/src/server/routes/v1/pki-sync-routers/pki-sync-endpoints.ts
index 5f434d7d27..c0893b3bb4 100644
--- a/backend/src/server/routes/v1/pki-sync-routers/pki-sync-endpoints.ts
+++ b/backend/src/server/routes/v1/pki-sync-routers/pki-sync-endpoints.ts
@@ -9,6 +9,7 @@ import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { AuthMode } from "@app/services/auth/auth-type";
import { PkiSync, PkiSyncStatus } from "@app/services/pki-sync/pki-sync-enums";
import { PKI_SYNC_NAME_MAP } from "@app/services/pki-sync/pki-sync-maps";
+import { getPkiSyncTargetHost } from "@app/services/pki-sync/pki-sync-target-host-fns";
import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
export const registerSyncPkiEndpoints = ({
@@ -169,6 +170,8 @@ export const registerSyncPkiEndpoints = ({
req.permission
);
+ const targetHost = getPkiSyncTargetHost(pkiSync.destinationConfig);
+
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
projectId: pkiSync.projectId,
@@ -179,6 +182,8 @@ export const registerSyncPkiEndpoints = ({
name: pkiSync.name,
destination,
connectionId: pkiSync.connectionId,
+ connectionName: pkiSync.appConnectionName,
+ ...(targetHost && { targetHost }),
hasCredentials: Boolean(req.body.credentials?.exportPassword),
hasPostSyncCommand: Boolean(req.body.syncOptions?.postSyncCommand),
hasHealthCheckCommand: Boolean(req.body.syncOptions?.healthCheckCommand),
@@ -228,6 +233,8 @@ export const registerSyncPkiEndpoints = ({
const pkiSync = await server.services.pkiSync.updatePkiSync({ ...req.body, id: pkiSyncId }, req.permission);
+ const targetHost = getPkiSyncTargetHost(pkiSync.destinationConfig);
+
await server.services.auditLog.createAuditLog({
...req.auditLogInfo,
projectId: pkiSync.projectId,
@@ -237,6 +244,10 @@ export const registerSyncPkiEndpoints = ({
pkiSyncId,
name: pkiSync.name,
...(pkiSync.applicationId && { applicationId: pkiSync.applicationId }),
+ destination: pkiSync.destination,
+ connectionId: pkiSync.connectionId,
+ connectionName: pkiSync.appConnectionName,
+ ...(targetHost && { targetHost }),
hasPostSyncCommand: Boolean(pkiSync.syncOptions?.postSyncCommand),
hasHealthCheckCommand: Boolean(pkiSync.syncOptions?.healthCheckCommand)
}
diff --git a/backend/src/server/routes/v1/pki-sync-routers/pki-sync-router.ts b/backend/src/server/routes/v1/pki-sync-routers/pki-sync-router.ts
index b42f1f30d9..f466fcc443 100644
--- a/backend/src/server/routes/v1/pki-sync-routers/pki-sync-router.ts
+++ b/backend/src/server/routes/v1/pki-sync-routers/pki-sync-router.ts
@@ -74,6 +74,7 @@ export const PkiSyncSchema = z.object({
const PkiSyncOptionsSchema = z.object({
name: z.string(),
connection: z.nativeEnum(AppConnection),
+ additionalConnections: z.nativeEnum(AppConnection).array().optional(),
destination: z.nativeEnum(PkiSync),
canImportCertificates: z.boolean(),
canRemoveCertificates: z.boolean(),
diff --git a/backend/src/services/app-connection/app-connection-fns.ts b/backend/src/services/app-connection/app-connection-fns.ts
index b815b83412..ad8deaf785 100644
--- a/backend/src/services/app-connection/app-connection-fns.ts
+++ b/backend/src/services/app-connection/app-connection-fns.ts
@@ -335,6 +335,7 @@ const PKI_APP_CONNECTIONS = [
AppConnection.GoDaddy,
AppConnection.SSH,
AppConnection.WinRM,
+ AppConnection.LDAP,
AppConnection.NutanixPrismCentral,
AppConnection.MicrosoftIntune
];
diff --git a/backend/src/services/app-connection/app-connection-service.ts b/backend/src/services/app-connection/app-connection-service.ts
index 2aa6d2da80..a89cd356d5 100644
--- a/backend/src/services/app-connection/app-connection-service.ts
+++ b/backend/src/services/app-connection/app-connection-service.ts
@@ -136,6 +136,7 @@ import { kempLoadMasterConnectionService } from "./kemp-loadmaster/kemp-loadmast
import { ValidateLaravelForgeConnectionCredentialsSchema } from "./laravel-forge";
import { laravelForgeConnectionService } from "./laravel-forge/laravel-forge-connection-service";
import { ValidateLdapConnectionCredentialsSchema } from "./ldap";
+import { ldapConnectionService } from "./ldap/ldap-connection-service";
import { ValidateLiteLLMConnectionCredentialsSchema } from "./litellm";
import { liteLLMConnectionService } from "./litellm/litellm-connection-service";
import { ValidateMicrosoftIntuneConnectionCredentialsSchema } from "./microsoft-intune";
@@ -217,7 +218,7 @@ export type TAppConnectionServiceFactoryDep = {
appConnectionCredentialRotationService: TAppConnectionCredentialRotationServiceFactory;
identityUaDAL: Pick<TIdentityUaDALFactory, "findOne">;
gitHubAppDAL: Pick<TGitHubAppDALFactory, "findOne" | "upsertConnectionLink">;
- keyStore: Pick<TKeyStoreFactory, "setItemWithExpiryNX" | "deleteItem">;
+ keyStore: Pick<TKeyStoreFactory, "setItemWithExpiryNX" | "deleteItem" | "getItem" | "setItemWithExpiry">;
};
export type TAppConnectionServiceFactory = ReturnType<typeof appConnectionServiceFactory>;
@@ -1144,20 +1145,16 @@ export const appConnectionServiceFactory = ({
};
const connectAppConnectionById = async <T extends TAppConnection>(
- app: AppConnection,
+ app: AppConnection | AppConnection[],
connectionId: string,
actor: OrgServiceActor
) => {
+ const allowedApps = Array.isArray(app) ? app : [app];
const appConnection = await appConnectionDAL.findById(connectionId);
if (!appConnection) throw new NotFoundError({ message: `Could not find App Connection with ID ${connectionId}` });
- await enterpriseAppCheck(
- licenseService,
- app,
- actor.orgId,
- "Failed to connect app due to plan restriction. Upgrade plan to access enterprise app connections."
- );
+ const connectionApp = appConnection.app as AppConnection;
if (appConnection.projectId) {
const { permission } = await permissionService.getProjectPermission({
@@ -1189,13 +1186,22 @@ export const appConnectionServiceFactory = ({
);
}
- if (appConnection.app !== app)
+ if (!allowedApps.includes(connectionApp))
throw new BadRequestError({
message: `${
- APP_CONNECTION_NAME_MAP[appConnection.app as AppConnection]
- } Connection with ID ${connectionId} cannot be used to connect to ${APP_CONNECTION_NAME_MAP[app]}`
+ APP_CONNECTION_NAME_MAP[connectionApp]
+ } Connection with ID ${connectionId} cannot be used to connect to ${allowedApps
+ .map((allowedApp) => APP_CONNECTION_NAME_MAP[allowedApp])
+ .join(" or ")}`
});
+ await enterpriseAppCheck(
+ licenseService,
+ connectionApp,
+ actor.orgId,
+ "Failed to connect app due to plan restriction. Upgrade plan to access enterprise app connections."
+ );
+
const connectionProject = appConnection.projectId
? await projectDAL.findProjectById(appConnection.projectId)
: null;
@@ -1394,6 +1400,7 @@ export const appConnectionServiceFactory = ({
venafi: venafiConnectionService(connectAppConnectionById),
azureAdcs: azureAdcsConnectionService(connectAppConnectionById),
adcs: adcsConnectionService(connectAppConnectionById, gatewayV2Service, gatewayPoolService),
+ ldap: ldapConnectionService(connectAppConnectionById, gatewayV2Service, gatewayPoolService, keyStore),
dnsMadeEasy: dnsMadeEasyConnectionService(connectAppConnectionById),
azureDns: azureDnsConnectionService(connectAppConnectionById),
zabbix: zabbixConnectionService(connectAppConnectionById),
diff --git a/backend/src/services/app-connection/ldap/index.ts b/backend/src/services/app-connection/ldap/index.ts
index 639879a083..5414f86555 100644
--- a/backend/src/services/app-connection/ldap/index.ts
+++ b/backend/src/services/app-connection/ldap/index.ts
@@ -2,3 +2,4 @@ export * from "./ldap-connection-enums";
export * from "./ldap-connection-fns";
export * from "./ldap-connection-schemas";
export * from "./ldap-connection-types";
+export { DIRECTORY_MACHINE_LIST_DEFAULT_LIMIT, DIRECTORY_MACHINE_LIST_MAX_LIMIT } from "./ldap-directory-fns";
diff --git a/backend/src/services/app-connection/ldap/ldap-connection-service.ts b/backend/src/services/app-connection/ldap/ldap-connection-service.ts
new file mode 100644
index 0000000000..f3bd01d792
--- /dev/null
+++ b/backend/src/services/app-connection/ldap/ldap-connection-service.ts
@@ -0,0 +1,49 @@
+import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";
+import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
+import { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/keystore";
+import { withCache } from "@app/lib/cache/with-cache";
+import { OrgServiceActor } from "@app/lib/types";
+
+import { AppConnection } from "../app-connection-enums";
+import { TLdapConnection, TLdapConnectionConfig } from "./ldap-connection-types";
+import { DIRECTORY_MACHINE_LIST_DEFAULT_LIMIT, listDirectoryMachines, TDirectoryMachine } from "./ldap-directory-fns";
+
+type TGetAppConnectionFunc = (
+ app: AppConnection,
+ connectionId: string,
+ actor: OrgServiceActor
+) => Promise<TLdapConnection>;
+
+export const ldapConnectionService = (
+ getAppConnection: TGetAppConnectionFunc,
+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">,
+ gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">,
+ keyStore: Pick<TKeyStoreFactory, "getItem" | "setItemWithExpiry">
+) => {
+ const listMachines = async (
+ connectionId: string,
+ { search, limit }: { search?: string; limit?: number },
+ actor: OrgServiceActor
+ ): Promise<TDirectoryMachine[]> => {
+ const appConnection = await getAppConnection(AppConnection.LDAP, connectionId, actor);
+
+ return withCache({
+ keyStore,
+ key: KeyStorePrefixes.LdapDirectoryMachines(
+ connectionId,
+ search?.toLowerCase() ?? "",
+ limit ?? DIRECTORY_MACHINE_LIST_DEFAULT_LIMIT
+ ),
+ ttlSeconds: KeyStoreTtls.LdapDirectoryMachinesInSeconds,
+ fetcher: () =>
+ listDirectoryMachines(
+ { config: appConnection as unknown as TLdapConnectionConfig, search, limit },
+ { gatewayV2Service, gatewayPoolService, keyStore }
+ )
+ });
+ };
+
+ return {
+ listMachines
+ };
+};
diff --git a/backend/src/services/app-connection/ldap/ldap-directory-fns.test.ts b/backend/src/services/app-connection/ldap/ldap-directory-fns.test.ts
new file mode 100644
index 0000000000..d619dd9386
--- /dev/null
+++ b/backend/src/services/app-connection/ldap/ldap-directory-fns.test.ts
@@ -0,0 +1,78 @@
+import { buildDomainBaseDN } from "@app/lib/ldap/ldap-search-fns";
+
+import { extractDomainFromDN } from "./ldap-connection-fns";
+import { parseLdapBindIdentity } from "./ldap-directory-fns";
+
+describe("parseLdapBindIdentity", () => {
+ test("derives the domain and the UPN local part, which is only a fallback for the logon name", () => {
+ expect(parseLdapBindIdentity("[email protected]")).toEqual({
+ domainFqdn: "corp.example.com",
+ accountName: "svc-certs"
+ });
+ });
+
+ test("the UPN local part is not assumed to be the sAMAccountName", () => {
+ expect(parseLdapBindIdentity("[email protected]").accountName).toBe("john.smith");
+ });
+
+ test("lowercases the domain but preserves the account's case", () => {
+ expect(parseLdapBindIdentity("[email protected]")).toEqual({
+ domainFqdn: "corp.example.com",
+ accountName: "Svc-Certs"
+ });
+ });
+
+ test("derives the domain from a full DN and defers the account to a directory lookup", () => {
+ expect(parseLdapBindIdentity("CN=svc-certs,OU=Service Accounts,DC=corp,DC=example,DC=com")).toEqual({
+ domainFqdn: "corp.example.com",
+ accountName: null
+ });
+ });
+
+ test("rejects a DN with no DC components, because the domain cannot be derived", () => {
+ expect(() => parseLdapBindIdentity("CN=svc-certs,OU=Service Accounts")).toThrow(/Unable to determine the domain/);
+ });
+
+ test("treats a DN containing @ inside an RDN value as a DN, not a user principal name", () => {
+ expect(parseLdapBindIdentity("[email protected],OU=Users,DC=corp,DC=example,DC=com")).toEqual({
+ domainFqdn: "corp.example.com",
+ accountName: null
+ });
+ });
+
+ test("uses the last @ when a user principal name is otherwise well formed", () => {
+ expect(parseLdapBindIdentity("[email protected]")).toEqual({
+ domainFqdn: "corp.example.com",
+ accountName: "svc.certs"
+ });
+ });
+
+ test("rejects a value that is neither a user principal name nor a DN with DC components", () => {
+ expect(() => parseLdapBindIdentity("@corp.example.com")).toThrow(/Unable to determine the domain/);
+ expect(() => parseLdapBindIdentity("svc-certs@")).toThrow(/Unable to determine the domain/);
+ });
+});
+
+describe("extractDomainFromDN", () => {
+ test("joins the DC components in order", () => {
+ expect(extractDomainFromDN("CN=svc,OU=Users,DC=corp,DC=example,DC=com")).toBe("corp.example.com");
+ });
+
+ test("is case insensitive on the attribute name and lowercases the result", () => {
+ expect(extractDomainFromDN("cn=svc,dc=CORP,dc=Example,dc=COM")).toBe("corp.example.com");
+ });
+
+ test("returns null when there is no DC component", () => {
+ expect(extractDomainFromDN("CN=svc,OU=Users")).toBeNull();
+ });
+});
+
+describe("buildDomainBaseDN", () => {
+ test("maps every domain label to a DC component", () => {
+ expect(buildDomainBaseDN("corp.example.com")).toBe("DC=corp,DC=example,DC=com");
+ });
+
+ test("handles a single-label domain", () => {
+ expect(buildDomainBaseDN("corp")).toBe("DC=corp");
+ });
+});
diff --git a/backend/src/services/app-connection/ldap/ldap-directory-fns.ts b/backend/src/services/app-connection/ldap/ldap-directory-fns.ts
new file mode 100644
index 0000000000..5a7ae82ebb
--- /dev/null
+++ b/backend/src/services/app-connection/ldap/ldap-directory-fns.ts
@@ -0,0 +1,261 @@
+import ldap from "@infisical/ldapjs";
+
+import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";
+import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
+import { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/keystore";
+import { withCache } from "@app/lib/cache/with-cache";
+import { BadRequestError } from "@app/lib/errors";
+import {
+ buildDomainBaseDN,
+ escapeLdapFilterValue,
+ getLdapAttribute,
+ netbiosFromDomainFqdn,
+ searchLdap,
+ TLdapSearchOptions
+} from "@app/lib/ldap/ldap-search-fns";
+import { logger } from "@app/lib/logger";
+import { UserPrincipalNameRegex } from "@app/lib/regex";
+import { AppConnection } from "@app/services/app-connection/app-connection-enums";
+
+import { executeWithPotentialGateway, extractDomainFromDN } from "./ldap-connection-fns";
+import { TLdapConnectionConfig } from "./ldap-connection-types";
+
+type TLdapGatewayServices = {
+ gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
+ gatewayPoolService?: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;
+ keyStore: Pick<TKeyStoreFactory, "getItem" | "setItemWithExpiry">;
+};
+
+export type TDirectoryMachine = {
+ hostname: string;
+};
+
+const LDAP_SEARCH_TIME_LIMIT_SECONDS = 15;
+export const DIRECTORY_MACHINE_LIST_DEFAULT_LIMIT = 50;
+export const DIRECTORY_MACHINE_LIST_MAX_LIMIT = 200;
+
+const searchDirectory = (
+ client: ldap.Client,
+ baseDN: string,
+ options: Pick<TLdapSearchOptions, "filter" | "attributes" | "scope" | "sizeLimit">
+) =>
+ searchLdap(client, {
+ ...options,
+ baseDN,
+ timeLimitSeconds: LDAP_SEARCH_TIME_LIMIT_SECONDS,
+ acceptSizeLimitExceeded: true,
+ mapError: ({ err, status }) =>
+ new BadRequestError({
+ message: err
+ ? `Unable to read from the directory: ${err.message}`
+ : `Unable to read from the directory: the LDAP server returned status ${status}`
+ })
+ });
+
+type TBindIdentity = {
+ domainFqdn: string;
+ accountName: string | null;
+};
+
+export class LdapTargetConfigurationError extends BadRequestError {}
+
+export const parseLdapBindIdentity = (dn: string): TBindIdentity => {
+ const trimmed = dn.trim();
+
+ if (UserPrincipalNameRegex.test(trimmed)) {
+ const separator = trimmed.lastIndexOf("@");
+ return {
+ domainFqdn: trimmed.slice(separator + 1).toLowerCase(),
+ accountName: trimmed.slice(0, separator)
+ };
+ }
+
+ const domainFqdn = extractDomainFromDN(trimmed);
+ if (!domainFqdn) {
+ throw new LdapTargetConfigurationError({
+ message:
+ "Unable to determine the domain from the LDAP connection's DN. Use a distinguished name containing DC components, or a user principal name like [email protected]"
+ });
+ }
+
+ return { domainFqdn, accountName: null };
+};
+
+const readNetbiosDomainName = async (client: ldap.Client, baseDN: string): Promise<string | null> => {
+ const entries = await searchDirectory(client, `CN=Partitions,CN=Configuration,${baseDN}`, {
+ filter: `(&(objectClass=crossRef)(nETBIOSName=*)(nCName=${escapeLdapFilterValue(baseDN)}))`,
+ attributes: ["nETBIOSName"],
+ sizeLimit: 1
+ });
+
+ return entries.length ? getLdapAttribute(entries[0], "nETBIOSName") || null : null;
+};
+
+const readAccountName = async (client: ldap.Client, dn: string): Promise<string | null> => {
+ const entries = await searchDirectory(client, dn, {
+ filter: "(objectClass=*)",
+ attributes: ["sAMAccountName"],
+ scope: "base",
+ sizeLimit: 1
+ });
+
+ return entries.length ? getLdapAttribute(entries[0], "sAMAccountName") || null : null;
+};
+
+const readAccountNameByUpn = async (client: ldap.Client, baseDN: string, upn: string): Promise<string | null> => {
+ const entries = await searchDirectory(client, baseDN, {
+ filter: `(&(objectCategory=person)(userPrincipalName=${escapeLdapFilterValue(upn)}))`,
+ attributes: ["sAMAccountName"],
+ sizeLimit: 1
+ });
+
+ return entries.length ? getLdapAttribute(entries[0], "sAMAccountName") || null : null;
+};
+
+type TLdapHostLogin = {
+ username: string;
+ isGuessed: boolean;
+};
+
+const resolveHostLoginFromDirectory = async (
+ config: TLdapConnectionConfig,
+ gatewayServices: TLdapGatewayServices
+): Promise<TLdapHostLogin> => {
+ const { domainFqdn, accountName } = parseLdapBindIdentity(config.credentials.dn);
+ const baseDN = buildDomainBaseDN(domainFqdn);
+
+ const resolved = await executeWithPotentialGateway(
+ config,
+ gatewayServices.gatewayV2Service,
+ async (client) => {
+ const [resolvedAccountName, netbiosDomainName] = await Promise.all([
+ accountName
+ ? readAccountNameByUpn(client, baseDN, config.credentials.dn).catch((err: unknown) => {
+ logger.warn(
+ { err },
+ `Unable to read the account name for the bind UPN, using its local part [domain=${domainFqdn}]`
+ );
+ return null;
+ })
+ : readAccountName(client, config.credentials.dn).catch((err: unknown) => {
+ logger.warn({ err }, `Unable to read the account name from the directory [domain=${domainFqdn}]`);
+ return null;
+ }),
+ readNetbiosDomainName(client, baseDN).catch((err: unknown) => {
+ logger.warn({ err }, `Unable to read the NetBIOS domain name from the directory [domain=${domainFqdn}]`);
+ return null;
+ })
+ ]);
+ return { netbiosDomainName, resolvedAccountName };
+ },
+ gatewayServices.gatewayPoolService
+ );
+
+ const loginAccountName = resolved.resolvedAccountName ?? accountName;
+
+ if (!loginAccountName) {
+ throw new LdapTargetConfigurationError({
+ message: `Unable to read the account name of "${config.credentials.dn}" from the directory. Set the LDAP connection's DN to a user principal name like user@${domainFqdn} instead`
+ });
+ }
+
+ return {
+ username: `${resolved.netbiosDomainName ?? netbiosFromDomainFqdn(domainFqdn)}\\${loginAccountName}`,
+ isGuessed: !resolved.netbiosDomainName || !resolved.resolvedAccountName
+ };
+};
+
+const buildHostLoginFingerprint = (config: TLdapConnectionConfig) =>
+ [
+ config.orgId,
+ config.credentials.dn.trim().toLowerCase(),
+ config.credentials.url.trim().toLowerCase(),
+ config.gatewayId ?? "",
+ config.gatewayPoolId ?? ""
+ ].join("|");
+
+const resolveLdapHostLogin = async (
+ config: TLdapConnectionConfig,
+ gatewayServices: TLdapGatewayServices
+): Promise<string> => {
+ const { username } = await withCache<TLdapHostLogin>({
+ keyStore: gatewayServices.keyStore,
+ key: KeyStorePrefixes.LdapHostLogin(buildHostLoginFingerprint(config)),
+ ttlSeconds: (result) =>
+ result.isGuessed ? KeyStoreTtls.LdapGuessedHostLoginInSeconds : KeyStoreTtls.LdapHostLoginInSeconds,
+ fetcher: () => resolveHostLoginFromDirectory(config, gatewayServices)
+ });
+
+ return username;
+};
+
+export const resolveLdapBackedHostCredentials = async (
+ {
+ connection,
+ host
+ }: {
+ connection: {
+ name: string;
+ method?: string;
+ credentials: Record<string, unknown>;
+ gatewayId?: string;
+ gatewayPoolId?: string | null;
+ orgId: string;
+ };
+ host: string | undefined;
+ },
+ gatewayServices: TLdapGatewayServices
+): Promise<{ host: string; username: string; password: string }> => {
+ if (!host) {
+ throw new LdapTargetConfigurationError({
+ message: `This sync uses the LDAP connection "${connection.name}", so it needs a target host. Set the target host on the sync to the machine it should deliver to.`
+ });
+ }
+
+ const config = {
+ app: AppConnection.LDAP,
+ method: connection.method,
+ credentials: connection.credentials,
+ gatewayId: connection.gatewayId,
+ gatewayPoolId: connection.gatewayPoolId,
+ orgId: connection.orgId
+ } as unknown as TLdapConnectionConfig;
+
+ const username = await resolveLdapHostLogin(config, gatewayServices);
+
+ return { host, username, password: config.credentials.password };
+};
+
+export const listDirectoryMachines = async (
+ {
+ config,
+ search,
+ limit = DIRECTORY_MACHINE_LIST_DEFAULT_LIMIT
+ }: { config: TLdapConnectionConfig; search?: string; limit?: number },
+ gatewayServices: TLdapGatewayServices
+): Promise<TDirectoryMachine[]> => {
+ const { domainFqdn } = parseLdapBindIdentity(config.credentials.dn);
+ const baseDN = buildDomainBaseDN(domainFqdn);
+ const cappedLimit = Math.min(limit, DIRECTORY_MACHINE_LIST_MAX_LIMIT);
+
+ const escapedSearch = search ? escapeLdapFilterValue(search) : undefined;
+ const filter = escapedSearch
+ ? `(&(objectCategory=computer)(|(cn=${escapedSearch}*)(dNSHostName=${escapedSearch}*)))`
+ : "(objectCategory=computer)";
+
+ const entries = await executeWithPotentialGateway(
+ config,
+ gatewayServices.gatewayV2Service,
+ (client) =>
+ searchDirectory(client, baseDN, {
+ filter,
+ attributes: ["cn", "dNSHostName"],
+ sizeLimit: cappedLimit
+ }),
+ gatewayServices.gatewayPoolService
+ );
+
+ return entries
+ .map((entry) => ({ hostname: getLdapAttribute(entry, "dNSHostName") || getLdapAttribute(entry, "cn") }))
+ .filter(({ hostname }) => hostname);
+};
diff --git a/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-fns.ts b/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-fns.ts
index 4286e25e54..cb63f7ed10 100644
--- a/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-fns.ts
+++ b/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-fns.ts
@@ -7,8 +7,13 @@ import { Client, SFTPWrapper } from "ssh2";
import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";
import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
+import { TKeyStoreFactory } from "@app/keystore/keystore";
import { logger } from "@app/lib/logger";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
+import {
+ LdapTargetConfigurationError,
+ resolveLdapBackedHostCredentials
+} from "@app/services/app-connection/ldap/ldap-directory-fns";
import { SshConnectionMethod } from "@app/services/app-connection/ssh/ssh-connection-enums";
import { executeSshCommandViaGateway, withSshConnection } from "@app/services/app-connection/ssh/ssh-connection-fns";
import { TSshConnectionConfig } from "@app/services/app-connection/ssh/ssh-connection-types";
@@ -43,6 +48,7 @@ type TLinuxServerPkiSyncFactoryDeps = {
>;
gatewayV2Service?: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
gatewayPoolService?: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;
+ keyStore: Pick<TKeyStoreFactory, "getItem" | "setItemWithExpiry">;
};
type TLinuxServerSyncOptions = {
@@ -60,8 +66,63 @@ type TLinuxServerSyncOptions = {
postSyncCommand?: string;
};
-const buildSshConfig = (pkiSync: THealthCheckTarget): TSshConnectionConfig => {
+type TGatewayServices = Pick<TLinuxServerPkiSyncFactoryDeps, "gatewayV2Service" | "gatewayPoolService" | "keyStore">;
+
+const DEFAULT_SSH_PORT = 22;
+
+const buildLdapBackedSshConfig = async (
+ pkiSync: THealthCheckTarget,
+ gatewayServices: TGatewayServices
+): Promise<TSshConnectionConfig> => {
+ const { connection } = pkiSync;
+ const { host, port } = pkiSync.destinationConfig as TLinuxServerPkiSyncConfig;
+
+ if (!gatewayServices.gatewayV2Service) {
+ throw new PkiSyncError({
+ shouldRetry: false,
+ message: "Reading the directory for an LDAP-backed sync requires the Gateway service."
+ });
+ }
+
+ const credentials = await resolveLdapBackedHostCredentials(
+ { connection, host },
+ {
+ gatewayV2Service: gatewayServices.gatewayV2Service,
+ gatewayPoolService: gatewayServices.gatewayPoolService,
+ keyStore: gatewayServices.keyStore
+ }
+ ).catch((err: unknown) => {
+ if (err instanceof LdapTargetConfigurationError) {
+ throw new PkiSyncError({ shouldRetry: false, message: err.message });
+ }
+ throw err;
+ });
+
+ return {
+ app: AppConnection.SSH,
+ method: SshConnectionMethod.Password,
+ credentials: { ...credentials, port: port ?? DEFAULT_SSH_PORT },
+ gatewayId: connection.gatewayId,
+ gatewayPoolId: connection.gatewayPoolId,
+ orgId: connection.orgId
+ } as TSshConnectionConfig;
+};
+
+const buildSshConfig = async (
+ pkiSync: THealthCheckTarget,
+ gatewayServices: TGatewayServices
+): Promise<TSshConnectionConfig> => {
const { connection } = pkiSync;
+
+ if (connection.app === AppConnection.LDAP) return buildLdapBackedSshConfig(pkiSync, gatewayServices);
+
+ if (connection.app !== AppConnection.SSH) {
+ throw new PkiSyncError({
+ shouldRetry: false,
+ message: `A ${connection.app} connection cannot deliver to a Linux Server sync.`
+ });
+ }
+
const credentials = connection.credentials as { privateKey?: string };
let method: SshConnectionMethod;
@@ -252,15 +313,17 @@ const executeLinuxServerHostCommand = (
timeoutMs: HOST_COMMAND_TIMEOUT_MS[kind]
});
-const runLinuxServerHealthCheckCommand = ({
+const runLinuxServerHealthCheckCommand = async ({
pkiSync,
certificateMap,
+ resolveSshConfig,
gatewayServices
}: {
pkiSync: THealthCheckTarget;
certificateMap: TCertificateMap;
- gatewayServices: Pick<TLinuxServerPkiSyncFactoryDeps, "gatewayV2Service" | "gatewayPoolService">;
-}): Promise<THealthCheckCommandResult> | undefined => {
+ resolveSshConfig: () => Promise<TSshConnectionConfig>;
+ gatewayServices: TGatewayServices;
+}): Promise<THealthCheckCommandResult | undefined> => {
const options = (pkiSync.syncOptions ?? {}) as TLinuxServerSyncOptions;
const config = pkiSync.destinationConfig as TLinuxServerPkiSyncConfig;
const exportOptions = resolveLinuxExportOptions(options);
@@ -276,11 +339,15 @@ const runLinuxServerHealthCheckCommand = ({
});
if (!plan) return undefined;
+ const sshConfig = await resolveSshConfig().catch((err: unknown) => err as Error);
+
return runHealthCheckCommand({
syncId: pkiSync.id,
secretsToRedact: [plan.context.pkcs12Password],
- execute: () =>
- executeLinuxServerHostCommand(HostCommandKind.HealthCheck, plan, buildSshConfig(pkiSync), gatewayServices)
+ execute: async () => {
+ if (sshConfig instanceof Error) throw sshConfig;
+ return executeLinuxServerHostCommand(HostCommandKind.HealthCheck, plan, sshConfig, gatewayServices);
+ }
});
};
@@ -304,7 +371,8 @@ const runLinuxServerPostSyncCommand = ({
export const linuxServerPkiSyncFactory = ({
certificateSyncDAL,
gatewayV2Service,
- gatewayPoolService
+ gatewayPoolService,
+ keyStore
}: TLinuxServerPkiSyncFactoryDeps) => {
const syncCertificates = async (
pkiSync: TPkiSyncWithCredentials,
@@ -329,12 +397,13 @@ export const linuxServerPkiSyncFactory = ({
let uploaded = 0;
let removed = 0;
- const sshConfig = buildSshConfig(pkiSync);
+ const sshConfig = await buildSshConfig(pkiSync, { gatewayV2Service, gatewayPoolService, keyStore });
const healthCheck = await runLinuxServerHealthCheckCommand({
pkiSync,
certificateMap,
- gatewayServices: { gatewayV2Service, gatewayPoolService }
+ resolveSshConfig: async () => sshConfig,
+ gatewayServices: { gatewayV2Service, gatewayPoolService, keyStore }
});
if (healthCheck && didHealthCheckFail(healthCheck)) {
logger.info(
@@ -504,7 +573,7 @@ export const linuxServerPkiSyncFactory = ({
}
if (pathsToRemove.size > 0) {
- const sshConfig = buildSshConfig(pkiSync);
+ const sshConfig = await buildSshConfig(pkiSync, { gatewayV2Service, gatewayPoolService, keyStore });
await withSshConnection(sshConfig, { gatewayV2Service, gatewayPoolService }, async (client) => {
const sftp = await openSftp(client);
for (const filePath of pathsToRemove) {
@@ -524,7 +593,8 @@ export const linuxServerPkiSyncFactory = ({
runLinuxServerHealthCheckCommand({
pkiSync,
certificateMap,
- gatewayServices: { gatewayV2Service, gatewayPoolService }
+ resolveSshConfig: () => buildSshConfig(pkiSync, { gatewayV2Service, gatewayPoolService, keyStore }),
+ gatewayServices: { gatewayV2Service, gatewayPoolService, keyStore }
});
return { syncCertificates, removeCertificates, runHealthCheck };
diff --git a/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-schemas.test.ts b/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-schemas.test.ts
index 7298a26103..eba7b21c00 100644
--- a/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-schemas.test.ts
+++ b/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-schemas.test.ts
@@ -5,6 +5,9 @@ const parseName = (certificateNameSchema: string) =>
const parsePath = (destinationPath: string) => LinuxServerPkiSyncConfigSchema.safeParse({ destinationPath }).success;
+const parseHost = (host: string) =>
+ LinuxServerPkiSyncConfigSchema.safeParse({ destinationPath: "/etc/ssl/certs", host }).success;
+
describe("Linux Server certificateNameSchema validation", () => {
test("accepts a fixed name with no placeholder (single-certificate sync)", () => {
expect(parseName("server")).toBe(true);
@@ -89,3 +92,33 @@ describe("Linux Server postSyncCommand validation", () => {
expect(LinuxServerPkiSyncOptionsSchema.safeParse({ certificateNameSchema: "server" }).success).toBe(true);
});
});
+
+describe("Linux Server target host validation", () => {
+ test("accepts a host name, an FQDN and an IPv4 address", () => {
+ expect(parseHost("server01")).toBe(true);
+ expect(parseHost("server01.corp.example.com")).toBe(true);
+ expect(parseHost("10.0.0.5")).toBe(true);
+ });
+
+ test("accepts a config with no host, because SSH connections carry their own", () => {
+ expect(LinuxServerPkiSyncConfigSchema.safeParse({ destinationPath: "/etc/ssl/certs" }).success).toBe(true);
+ });
+
+ test("rejects a host carrying a scheme, port or path", () => {
+ expect(parseHost("ssh://server01")).toBe(false);
+ expect(parseHost("server01:22")).toBe(false);
+ expect(parseHost("server01/certs")).toBe(false);
+ });
+
+ test("rejects a host with characters that are not valid in a host name", () => {
+ expect(parseHost("server 01")).toBe(false);
+ expect(parseHost("server_01")).toBe(false);
+ expect(parseHost("-server01")).toBe(false);
+ expect(parseHost("server01-")).toBe(false);
+ });
+
+ test("rejects an empty or whitespace-only host", () => {
+ expect(parseHost("")).toBe(false);
+ expect(parseHost(" ")).toBe(false);
+ });
+});
diff --git a/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-schemas.ts b/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-schemas.ts
index 4b52c05f70..fc9ce8bfae 100644
--- a/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-schemas.ts
+++ b/backend/src/services/pki-sync/linux-server/linux-server-pki-sync-schemas.ts
@@ -6,7 +6,13 @@ import { pkiDescriptionSchema } from "@app/services/certificate-common/certifica
import { buildCertificateNameSchemaTestName } from "@app/services/pki-sync/pki-sync-certificate-name-fns";
import { PkiSync } from "@app/services/pki-sync/pki-sync-enums";
import { PemCertificateExtension, PkiSyncExportFormat } from "@app/services/pki-sync/pki-sync-export-fns";
-import { BaseHealthCheckTestSchema, HostCommandSchema, PkiSyncSchema } from "@app/services/pki-sync/pki-sync-schemas";
+import {
+ BaseHealthCheckTestSchema,
+ HostCommandSchema,
+ PkiSyncSchema,
+ PkiSyncTargetHostSchema,
+ PkiSyncTargetPortSchema
+} from "@app/services/pki-sync/pki-sync-schemas";
import { LINUX_SERVER_NAMING } from "./linux-server-pki-sync-constants";
@@ -23,7 +29,9 @@ export const LinuxServerPkiSyncConfigSchema = z.object({
.min(1, "Destination path is required")
.max(4096, "Destination path is too long")
.refine((p) => p.startsWith("/"), { message: "Destination path must be absolute (start with /)" })
- .refine((p) => !PATH_TRAVERSAL.test(p), { message: "Destination path must not contain '..'" })
+ .refine((p) => !PATH_TRAVERSAL.test(p), { message: "Destination path must not contain '..'" }),
+ host: PkiSyncTargetHostSchema,
+ port: PkiSyncTargetPortSchema
});
export const LinuxServerPkiSyncOptionsSchema = z.object({
@@ -127,6 +135,7 @@ export const UpdateLinuxServerPkiSyncSchema = z.object({
export const LinuxServerPkiSyncListItemSchema = z.object({
name: z.literal("Linux Server"),
connection: z.literal(AppConnection.SSH),
+ additionalConnections: z.literal(AppConnection.LDAP).array().optional(),
destination: z.literal(PkiSync.LinuxServer),
canImportCertificates: z.literal(false),
canRemoveCertificates: z.literal(true)
diff --git a/backend/src/services/pki-sync/pki-sync-fns.ts b/backend/src/services/pki-sync/pki-sync-fns.ts
index a81fbe8dda..3348544c79 100644
--- a/backend/src/services/pki-sync/pki-sync-fns.ts
+++ b/backend/src/services/pki-sync/pki-sync-fns.ts
@@ -4,6 +4,7 @@ import { z, ZodSchema } from "zod";
import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";
import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
+import { TKeyStoreFactory } from "@app/keystore/keystore";
import { BadRequestError } from "@app/lib/errors";
import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";
import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";
@@ -40,6 +41,7 @@ import {
import { PkiSync } from "./pki-sync-enums";
import { PkiSyncError } from "./pki-sync-errors";
import { THostCommandResult } from "./pki-sync-host-command-fns";
+import { getPkiSyncConnectionApps } from "./pki-sync-maps";
import { TCertificateMap, THealthCheckTarget, TPkiSyncSyncResult, TPkiSyncWithCredentials } from "./pki-sync-types";
import { WINDOWS_SERVER_PKI_SYNC_LIST_OPTION } from "./windows-server/windows-server-pki-sync-constants";
import { windowsServerPkiSyncFactory } from "./windows-server/windows-server-pki-sync-fns";
@@ -77,7 +79,14 @@ export const enterprisePkiSyncCheck = async (
};
export const listPkiSyncOptions = () => {
- return Object.values(PKI_SYNC_LIST_OPTIONS).sort((a, b) => a.name.localeCompare(b.name));
+ return Object.values(PKI_SYNC_LIST_OPTIONS)
+ .map((option) => {
+ const additionalConnections = getPkiSyncConnectionApps(option.destination).filter(
+ (app) => app !== option.connection
+ );
+ return additionalConnections.length ? { ...option, additionalConnections } : option;
+ })
+ .sort((a, b) => a.name.localeCompare(b.name));
};
export const getPkiSyncProviderCapabilities = (destination: PkiSync) => {
@@ -220,6 +229,7 @@ export const PkiSyncFns = {
certificateSyncDAL: TCertificateSyncDALFactory;
gatewayV2Service?: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
gatewayPoolService?: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;
+ keyStore: Pick<TKeyStoreFactory, "getItem" | "setItemWithExpiry">;
}
): Promise<TPkiSyncSyncResult> => {
switch (pkiSync.destination) {
@@ -314,7 +324,8 @@ export const PkiSyncFns = {
const linuxServerPkiSync = linuxServerPkiSyncFactory({
certificateSyncDAL: dependencies.certificateSyncDAL,
gatewayV2Service: dependencies.gatewayV2Service,
- gatewayPoolService: dependencies.gatewayPoolService
+ gatewayPoolService: dependencies.gatewayPoolService,
+ keyStore: dependencies.keyStore
});
return linuxServerPkiSync.syncCertificates(pkiSync, certificateMap);
}
@@ -326,7 +337,8 @@ export const PkiSyncFns = {
const windowsServerPkiSync = windowsServerPkiSyncFactory({
certificateSyncDAL: dependencies.certificateSyncDAL,
gatewayV2Service: dependencies.gatewayV2Service,
- gatewayPoolService: dependencies.gatewayPoolService
+ gatewayPoolService: dependencies.gatewayPoolService,
+ keyStore: dependencies.keyStore
});
return windowsServerPkiSync.syncCertificates(pkiSync, certificateMap);
}
@@ -352,6 +364,7 @@ export const PkiSyncFns = {
certificateSyncDAL: TCertificateSyncDALFactory;
gatewayV2Service?: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
gatewayPoolService?: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;
+ keyStore: Pick<TKeyStoreFactory, "getItem" | "setItemWithExpiry">;
}
): Promise<THostCommandResult | undefined> => {
switch (pkiSync.destination) {
@@ -359,7 +372,8 @@ export const PkiSyncFns = {
const linuxServerPkiSync = linuxServerPkiSyncFactory({
certificateSyncDAL: dependencies.certificateSyncDAL,
gatewayV2Service: dependencies.gatewayV2Service,
- gatewayPoolService: dependencies.gatewayPoolService
+ gatewayPoolService: dependencies.gatewayPoolService,
+ keyStore: dependencies.keyStore
});
return linuxServerPkiSync.runHealthCheck(pkiSync, certificateMap);
}
@@ -373,7 +387,8 @@ export const PkiSyncFns = {
const windowsServerPkiSync = windowsServerPkiSyncFactory({
certificateSyncDAL: dependencies.certificateSyncDAL,
gatewayV2Service: dependencies.gatewayV2Service,
- gatewayPoolService: dependencies.gatewayPoolService
+ gatewayPoolService: dependencies.gatewayPoolService,
+ keyStore: dependencies.keyStore
});
return windowsServerPkiSync.runHealthCheck(pkiSync, certificateMap);
}
@@ -393,6 +408,7 @@ export const PkiSyncFns = {
certificateMap: TCertificateMap;
gatewayV2Service?: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
gatewayPoolService?: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;
+ keyStore: Pick<TKeyStoreFactory, "getItem" | "setItemWithExpiry">;
}
): Promise<void> => {
switch (pkiSync.destination) {
@@ -520,7 +536,8 @@ export const PkiSyncFns = {
const linuxServerPkiSync = linuxServerPkiSyncFactory({
certificateSyncDAL: dependencies.certificateSyncDAL,
gatewayV2Service: dependencies.gatewayV2Service,
- gatewayPoolService: dependencies.gatewayPoolService
+ gatewayPoolService: dependencies.gatewayPoolService,
+ keyStore: dependencies.keyStore
});
await linuxServerPkiSync.removeCertificates(pkiSync, certificateNames, {
certificateSyncDAL: dependencies.certificateSyncDAL,
@@ -536,7 +553,8 @@ export const PkiSyncFns = {
const windowsServerPkiSync = windowsServerPkiSyncFactory({
certificateSyncDAL: dependencies.certificateSyncDAL,
gatewayV2Service: dependencies.gatewayV2Service,
- gatewayPoolService: dependencies.gatewayPoolService
+ gatewayPoolService: dependencies.gatewayPoolService,
+ keyStore: dependencies.keyStore
});
await windowsServerPkiSync.removeCertificates(pkiSync, certificateNames, {
certificateMap: dependencies.certificateMap
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 0fed805f31..304b3c3856 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
@@ -46,6 +46,7 @@ import {
THealthCheckCommandResult
} from "./pki-sync-health-check-command-fns";
import { commandNeedsCertificateData, HostCommandFailure } from "./pki-sync-host-command-fns";
+import { getPkiSyncTargetHost } from "./pki-sync-target-host-fns";
import { TCertificateMap, THealthCheckTarget, TPkiSyncRaw } from "./pki-sync-types";
const ENQUEUE_CHUNK_SIZE = 200;
@@ -71,7 +72,10 @@ type TPkiSyncHealthCheckQueueFactoryDep = {
| "recordHealthCheckOutcome"
| "findById"
>;
- keyStore: Pick<TKeyStoreFactory, "acquireLock" | "incrementByAndRefreshExpiryIfUnderLimit" | "decrementByOrDelete">;
+ keyStore: Pick<
+ TKeyStoreFactory,
+ "acquireLock" | "incrementByAndRefreshExpiryIfUnderLimit" | "decrementByOrDelete" | "getItem" | "setItemWithExpiry"
+ >;
appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">;
projectDAL: TProjectDALFactory;
kmsService: Pick<
@@ -140,23 +144,31 @@ export const pkiSyncHealthCheckQueueFactory = ({
observableResult.observe(lastDiscoveryCount);
});
- const $withConnectionHostAccess = async <T>(connectionId: string, run: () => Promise<T>): Promise<T> => {
+ const $withConnectionHostAccess = async <T>(
+ connectionId: string,
+ targetHost: string | undefined,
+ run: () => Promise<T>
+ ): Promise<T> => {
const connectionLock = await keyStore
.acquireLock(
- [KeyStorePrefixes.AppConnectionCommandLock(connectionId)],
+ [KeyStorePrefixes.AppConnectionCommandLock(connectionId, targetHost)],
HEALTH_CHECK_LOCK_TTL_MS,
PKI_SYNC_CONNECTION_LOCK_RETRY
)
.catch(() => null);
if (!connectionLock) {
- throw new HealthCheckBusyError("This connection is busy running another command.");
+ throw new HealthCheckBusyError(
+ targetHost
+ ? `The host ${targetHost} is busy running another command.`
+ : "This connection is busy running another command."
+ );
}
let admittedSlot = false;
try {
admittedSlot =
(await keyStore.incrementByAndRefreshExpiryIfUnderLimit(
- KeyStorePrefixes.AppConnectionConcurrentJobs(connectionId),
+ KeyStorePrefixes.AppConnectionConcurrentJobs(connectionId, targetHost),
PKI_SYNC_CONNECTION_CONCURRENCY_LIMIT,
PKI_SYNC_CONNECTION_CONCURRENCY_TTL_S
)) !== -1;
@@ -168,7 +180,7 @@ export const pkiSyncHealthCheckQueueFactory = ({
} finally {
await Promise.allSettled([
admittedSlot
- ? keyStore.decrementByOrDelete(KeyStorePrefixes.AppConnectionConcurrentJobs(connectionId))
+ ? keyStore.decrementByOrDelete(KeyStorePrefixes.AppConnectionConcurrentJobs(connectionId, targetHost))
: undefined,
connectionLock.release()
]);
@@ -312,33 +324,40 @@ export const pkiSyncHealthCheckQueueFactory = ({
const certificateMap = await $certificatesForCheck(pkiSync, command);
- const result = await $withConnectionHostAccess(pkiSync.connectionId, async () => {
- const lock = await keyStore
- .acquireLock([KeyStorePrefixes.PkiSyncLock(syncId)], HEALTH_CHECK_LOCK_TTL_MS)
- .catch(() => null);
- if (!lock) {
- logger.info(`cron[${CronJobName.PkiSyncHealthCheck}]: a sync is already running, skipping [syncId=${syncId}]`);
- return HealthCheckSkipReason.SyncInProgress;
- }
-
- try {
- const checkResult = await PkiSyncFns.runHealthCheck(pkiSyncWithCredentials, certificateMap, {
- certificateSyncDAL,
- gatewayV2Service,
- gatewayPoolService
- });
- if (!checkResult) {
- return commandNeedsCertificateData(command)
- ? HealthCheckSkipReason.NoCertificateData
- : HealthCheckSkipReason.NotSupported;
+ const result = await $withConnectionHostAccess(
+ pkiSync.connectionId,
+ getPkiSyncTargetHost(pkiSync.destinationConfig),
+ async () => {
+ const lock = await keyStore
+ .acquireLock([KeyStorePrefixes.PkiSyncLock(syncId)], HEALTH_CHECK_LOCK_TTL_MS)
+ .catch(() => null);
+ if (!lock) {
+ logger.info(
+ `cron[${CronJobName.PkiSyncHealthCheck}]: a sync is already running, skipping [syncId=${syncId}]`
+ );
+ return HealthCheckSkipReason.SyncInProgress;
}
- await $recordCheckResult(pkiSync, checkResult, isFinalAttempt, messageSubject);
- return checkResult;
- } finally {
- await lock.release();
+ try {
+ const checkResult = await PkiSyncFns.runHealthCheck(pkiSyncWithCredentials, certificateMap, {
+ certificateSyncDAL,
+ gatewayV2Service,
+ gatewayPoolService,
+ keyStore
+ });
+ if (!checkResult) {
+ return commandNeedsCertificateData(command)
+ ? HealthCheckSkipReason.NoCertificateData
+ : HealthCheckSkipReason.NotSupported;
+ }
+
+ await $recordCheckResult(pkiSync, checkResult, isFinalAttempt, messageSubject);
+ return checkResult;
+ } finally {
+ await lock.release();
+ }
}
- });
+ );
if (typeof result === "string") return { skipped: result };
@@ -425,11 +444,12 @@ export const pkiSyncHealthCheckQueueFactory = ({
}
};
- return $withConnectionHostAccess(connection.id, async () => {
+ return $withConnectionHostAccess(connection.id, getPkiSyncTargetHost(target.destinationConfig), async () => {
const result = await PkiSyncFns.runHealthCheck(target, linkedCertificates, {
certificateSyncDAL,
gatewayV2Service,
- gatewayPoolService
+ gatewayPoolService,
+ keyStore
}).catch((err) => {
if (err instanceof PkiSyncError) throw new BadRequestError({ message: err.message });
throw err;
diff --git a/backend/src/services/pki-sync/pki-sync-maps.ts b/backend/src/services/pki-sync/pki-sync-maps.ts
index 3aaa7f531f..9d42032537 100644
--- a/backend/src/services/pki-sync/pki-sync-maps.ts
+++ b/backend/src/services/pki-sync/pki-sync-maps.ts
@@ -31,3 +31,13 @@ export const PKI_SYNC_CONNECTION_MAP: Record<PkiSync, AppConnection> = {
[PkiSync.WindowsServer]: AppConnection.WinRM,
[PkiSync.NutanixPrismCentral]: AppConnection.NutanixPrismCentral
};
+
+const PKI_SYNC_ADDITIONAL_CONNECTION_MAP: Partial<Record<PkiSync, AppConnection[]>> = {
+ [PkiSync.LinuxServer]: [AppConnection.LDAP],
+ [PkiSync.WindowsServer]: [AppConnection.LDAP]
+};
+
+export const getPkiSyncConnectionApps = (destination: PkiSync): AppConnection[] => [
+ PKI_SYNC_CONNECTION_MAP[destination],
+ ...(PKI_SYNC_ADDITIONAL_CONNECTION_MAP[destination] ?? [])
+];
diff --git a/backend/src/services/pki-sync/pki-sync-queue.ts b/backend/src/services/pki-sync/pki-sync-queue.ts
index d5c0d5fffc..33ec0847f6 100644
--- a/backend/src/services/pki-sync/pki-sync-queue.ts
+++ b/backend/src/services/pki-sync/pki-sync-queue.ts
@@ -58,6 +58,7 @@ import {
getPostSyncCommand,
TPostSyncCommandResult
} from "./pki-sync-post-sync-command-fns";
+import { getPkiSyncTargetHost } from "./pki-sync-target-host-fns";
import {
TCertificateMap,
TPkiSyncImportCertificatesDTO,
@@ -78,7 +79,10 @@ type TPkiSyncQueueFactoryDep = {
"createCipherPairWithDataKey" | "decryptWithKmsKey" | "generateKmsKey" | "encryptWithKmsKey"
>;
appConnectionDAL: Pick<TAppConnectionDALFactory, "findById" | "update" | "updateById">;
- keyStore: Pick<TKeyStoreFactory, "acquireLock" | "incrementByAndRefreshExpiryIfUnderLimit" | "decrementByOrDelete">;
+ keyStore: Pick<
+ TKeyStoreFactory,
+ "acquireLock" | "incrementByAndRefreshExpiryIfUnderLimit" | "decrementByOrDelete" | "getItem" | "setItemWithExpiry"
+ >;
pkiSyncDAL: Pick<
TPkiSyncDALFactory,
"findById" | "find" | "updateById" | "deleteById" | "update" | "findFailureNotificationRecipients"
@@ -152,9 +156,9 @@ export const pkiSyncQueueFactory = ({
unit: "1"
});
- const $tryAdmitConnectionConcurrency = async (connectionId: string) => {
+ const $tryAdmitConnectionConcurrency = async (connectionId: string, targetHost?: string) => {
const count = await keyStore.incrementByAndRefreshExpiryIfUnderLimit(
- KeyStorePrefixes.AppConnectionConcurrentJobs(connectionId),
+ KeyStorePrefixes.AppConnectionConcurrentJobs(connectionId, targetHost),
PKI_SYNC_CONNECTION_CONCURRENCY_LIMIT,
PKI_SYNC_CONNECTION_CONCURRENCY_TTL_S
);
@@ -162,8 +166,8 @@ export const pkiSyncQueueFactory = ({
return count !== -1;
};
- const $releaseConnectionConcurrency = async (connectionId: string) => {
- await keyStore.decrementByOrDelete(KeyStorePrefixes.AppConnectionConcurrentJobs(connectionId));
+ const $releaseConnectionConcurrency = async (connectionId: string, targetHost?: string) => {
+ await keyStore.decrementByOrDelete(KeyStorePrefixes.AppConnectionConcurrentJobs(connectionId, targetHost));
};
const $certificatesForSync = (pkiSync: TPkiSyncRaw) =>
@@ -276,7 +280,8 @@ export const pkiSyncQueueFactory = ({
certificateDAL,
certificateSyncDAL,
gatewayV2Service,
- gatewayPoolService
+ gatewayPoolService,
+ keyStore
});
logger.info(
@@ -650,7 +655,8 @@ export const pkiSyncQueueFactory = ({
certificateDAL,
certificateMap,
gatewayV2Service,
- gatewayPoolService
+ gatewayPoolService,
+ keyStore
});
isSuccess = true;
@@ -781,11 +787,13 @@ export const pkiSyncQueueFactory = ({
const needsHostSerialisation =
needsConnectionSlot && getPkiSyncProviderCapabilities(pkiSync.destination).canRunHealthCheckCommand;
+ const targetHost = getPkiSyncTargetHost(pkiSync.destinationConfig);
+
let connectionLock: Awaited<ReturnType<typeof keyStore.acquireLock>> | null = null;
if (needsHostSerialisation) {
connectionLock = await keyStore
.acquireLock(
- [KeyStorePrefixes.AppConnectionCommandLock(connectionId)],
+ [KeyStorePrefixes.AppConnectionCommandLock(connectionId, targetHost)],
HOST_SERIALISATION_LOCK_TTL_MS,
PKI_SYNC_CONNECTION_LOCK_RETRY
)
@@ -798,7 +806,7 @@ export const pkiSyncQueueFactory = ({
}
}
- if (needsConnectionSlot && !(await $tryAdmitConnectionConcurrency(connectionId))) {
+ if (needsConnectionSlot && !(await $tryAdmitConnectionConcurrency(connectionId, targetHost))) {
await connectionLock?.release();
await $handleAcquireLockFailure(job as PkiSyncActionJob);
@@ -814,7 +822,7 @@ export const pkiSyncQueueFactory = ({
5 * 60 * 1000
);
} catch (e) {
- if (needsConnectionSlot) await $releaseConnectionConcurrency(connectionId);
+ if (needsConnectionSlot) await $releaseConnectionConcurrency(connectionId, targetHost);
await connectionLock?.release();
await $handleAcquireLockFailure(job as PkiSyncActionJob);
@@ -837,7 +845,7 @@ export const pkiSyncQueueFactory = ({
throw new Error(`Unhandled PKI Sync Job ${String(job.name)}`);
}
} finally {
- if (needsConnectionSlot) await $releaseConnectionConcurrency(connectionId);
+ if (needsConnectionSlot) await $releaseConnectionConcurrency(connectionId, targetHost);
await Promise.allSettled([lock.release(), connectionLock?.release()]);
}
diff --git a/backend/src/services/pki-sync/pki-sync-schemas.ts b/backend/src/services/pki-sync/pki-sync-schemas.ts
index 03c68e0593..4b4dd78ab6 100644
--- a/backend/src/services/pki-sync/pki-sync-schemas.ts
+++ b/backend/src/services/pki-sync/pki-sync-schemas.ts
@@ -1,6 +1,8 @@
import RE2 from "re2";
import { z } from "zod";
+import { HOSTNAME_MAX_LENGTH, isValidHostname } from "@app/lib/validator/validate-hostname";
+
import { buildCertificateNameSchemaTestName } from "./pki-sync-certificate-name-fns";
import { PkiSync, PkiSyncStatus } from "./pki-sync-enums";
import { HOST_COMMAND_MAX_LENGTH } from "./pki-sync-host-command-fns";
@@ -12,6 +14,24 @@ export const HostCommandSchema = z
.nullable()
.optional();
+export const PkiSyncTargetPortSchema = z.coerce
+ .number()
+ .int()
+ .min(1)
+ .max(65535)
+ .optional()
+ .describe("The port to reach the target host on. Defaults to the protocol's standard port.");
+
+export const PkiSyncTargetHostSchema = z
+ .string()
+ .trim()
+ .min(1, "Target host is required")
+ .max(HOSTNAME_MAX_LENGTH, "Target host is too long")
+ .refine(isValidHostname, {
+ message: "Target host must be a hostname or IP address (for example server01.corp.example.com or 10.0.0.5)"
+ })
+ .optional();
+
// Sync options shared by every destination. Destinations extend this with their own
// certificateNameSchema and any extra options.
export const BasePkiSyncOptionsSchema = z.object({
diff --git a/backend/src/services/pki-sync/pki-sync-service.ts b/backend/src/services/pki-sync/pki-sync-service.ts
index 9535f174e9..c48b5315a5 100644
--- a/backend/src/services/pki-sync/pki-sync-service.ts
+++ b/backend/src/services/pki-sync/pki-sync-service.ts
@@ -11,6 +11,7 @@ import {
} from "@app/ee/services/permission/resource-permission";
import { getProcessedPermissionRules } from "@app/lib/casl/permission-filter-utils";
import { BadRequestError, DatabaseError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
+import { deepEqual } from "@app/lib/fn/object";
import { OrgServiceActor } from "@app/lib/types";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
import { TAppConnectionServiceFactory } from "@app/services/app-connection/app-connection-service";
@@ -45,7 +46,7 @@ import {
formatHostCommandVariables,
HostCommandKind
} from "./pki-sync-host-command-fns";
-import { PKI_SYNC_CONNECTION_MAP, PKI_SYNC_NAME_MAP } from "./pki-sync-maps";
+import { getPkiSyncConnectionApps, PKI_SYNC_NAME_MAP } from "./pki-sync-maps";
import {
applyPostSyncCommandUpdate,
getPostSyncCommand,
@@ -53,6 +54,7 @@ import {
POST_SYNC_COMMAND_OPTION_KEY
} from "./pki-sync-post-sync-command-fns";
import { TPkiSyncQueueFactory } from "./pki-sync-queue";
+import { assertTargetHostMatchesConnection, TPkiSyncDeliveryTarget } from "./pki-sync-target-host-fns";
import {
TAddCertificatesToPkiSyncDTO,
TClearDefaultCertificateDTO,
@@ -71,16 +73,6 @@ import {
TUpdatePkiSyncDTO
} from "./pki-sync-types";
-const getDestinationAppType = (destination: PkiSync): AppConnection => {
- const appConnection = PKI_SYNC_CONNECTION_MAP[destination];
- if (!appConnection) {
- throw new BadRequestError({
- message: `Unsupported PKI sync destination: ${destination}`
- });
- }
- return appConnection;
-};
-
type TPkiSyncServiceFactoryDep = {
pkiSyncDAL: Pick<
TPkiSyncDALFactory,
@@ -233,6 +225,41 @@ export const pkiSyncServiceFactory = ({
await $assertSyncAction(actions.project, actions.resource, pkiSync, subscriberName, actor);
};
+ const $deliveryTarget = (destinationConfig: Record<string, unknown> | null | undefined) => {
+ const config = destinationConfig as TPkiSyncDeliveryTarget | undefined;
+ return JSON.stringify([
+ config?.host?.toLowerCase(),
+ config?.port,
+ config?.sslEnabled,
+ config?.sslRejectUnauthorized,
+ config?.sslCertificate
+ ]);
+ };
+
+ const $assertMaySetTargetHost = async ({
+ nextConfig,
+ currentConfig,
+ pkiSync,
+ subscriberName,
+ actor
+ }: {
+ nextConfig: Record<string, unknown> | null | undefined;
+ currentConfig: Record<string, unknown> | null | undefined;
+ pkiSync: { projectId: string; applicationId?: string | null; name: string };
+ subscriberName: string | undefined;
+ actor: OrgServiceActor;
+ }) => {
+ if ($deliveryTarget(nextConfig) === $deliveryTarget(currentConfig)) return;
+
+ await $assertSyncAction(
+ ProjectPermissionPkiSyncActions.SetTargetHost,
+ ResourcePermissionPkiSyncActions.SetTargetHost,
+ pkiSync,
+ subscriberName,
+ actor
+ );
+ };
+
const HOST_COMMAND_ACTIONS = {
[HEALTH_CHECK_COMMAND_OPTION_KEY]: {
project: ProjectPermissionPkiSyncActions.SetHealthCheckCommand,
@@ -417,11 +444,20 @@ export const pkiSyncServiceFactory = ({
throw new ForbiddenRequestError({ message: "User has insufficient privileges" });
}
- // Get the destination app type based on PKI sync destination
- const destinationApp = getDestinationAppType(destination);
+ const destinationApps = getPkiSyncConnectionApps(destination);
// Validates permission to connect and app is valid for sync destination
- const connection = await appConnectionService.connectAppConnectionById(destinationApp, connectionId, actor);
+ const connection = await appConnectionService.connectAppConnectionById(destinationApps, connectionId, actor);
+
+ assertTargetHostMatchesConnection({ destination, connection, destinationConfig });
+
+ await $assertMaySetTargetHost({
+ nextConfig: destinationConfig,
+ currentConfig: undefined,
+ pkiSync: { projectId, applicationId, name },
+ subscriberName: undefined,
+ actor
+ });
const providerCapabilities = getPkiSyncProviderCapabilities(destination);
const resolvedSyncOptions = normalizeNewHealthCheckCommand(
@@ -560,14 +596,42 @@ export const pkiSyncServiceFactory = ({
}
}
- let effectiveConnection: { gatewayId?: string | null; gatewayPoolId?: string | null } | undefined;
- if (connectionId && connectionId !== pkiSync.connectionId) {
- const destinationApp = getDestinationAppType(pkiSync.destination);
- effectiveConnection = await appConnectionService.connectAppConnectionById(destinationApp, connectionId, actor);
- }
+ let resolvedConnection: Awaited<ReturnType<typeof appConnectionService.connectAppConnectionById>> | undefined;
+ const resolveConnection = async () => {
+ resolvedConnection ??= await appConnectionService.connectAppConnectionById(
+ getPkiSyncConnectionApps(pkiSync.destination),
+ connectionId ?? pkiSync.connectionId,
+ actor
+ );
+ return resolvedConnection;
+ };
+
+ const isConnectionChanging = Boolean(connectionId && connectionId !== pkiSync.connectionId);
const isDestinationConfigChanging =
- Boolean(destinationConfig) && JSON.stringify(destinationConfig) !== JSON.stringify(pkiSync.destinationConfig);
+ Boolean(destinationConfig) && !deepEqual(destinationConfig, pkiSync.destinationConfig);
+
+ const nextDestinationConfig = (destinationConfig ?? pkiSync.destinationConfig) as
+ | (Record<string, unknown> & { host?: string })
+ | undefined;
+
+ if (isConnectionChanging || destinationConfig !== undefined) {
+ assertTargetHostMatchesConnection({
+ destination: pkiSync.destination,
+ connection: isConnectionChanging
+ ? await resolveConnection()
+ : { ...pkiSync.connection, app: pkiSync.connection.app as AppConnection },
+ destinationConfig: nextDestinationConfig
+ });
+ }
+
+ await $assertMaySetTargetHost({
+ nextConfig: nextDestinationConfig,
+ currentConfig: pkiSync.destinationConfig as Record<string, unknown> | undefined,
+ pkiSync,
+ subscriberName: currentSubscriber?.name,
+ actor
+ });
const storedSyncOptions = pkiSync.syncOptions as Record<string, unknown> | undefined;
let resolvedSyncOptions = syncOptions;
@@ -601,14 +665,8 @@ export const pkiSyncServiceFactory = ({
pkiSync,
subscriberName: currentSubscriber?.name,
actor,
- isExecutionTargetChanging: Boolean(effectiveConnection) || isDestinationConfigChanging,
- resolveConnection: async () =>
- effectiveConnection ??
- appConnectionService.connectAppConnectionById(
- getDestinationAppType(pkiSync.destination),
- pkiSync.connectionId,
- actor
- )
+ isExecutionTargetChanging: isConnectionChanging || isDestinationConfigChanging,
+ resolveConnection
});
if (certificateIds !== undefined) {
@@ -918,11 +976,17 @@ export const pkiSyncServiceFactory = ({
}
const connection = await appConnectionService.connectAppConnectionById(
- getDestinationAppType(args.destination),
+ getPkiSyncConnectionApps(args.destination),
args.connectionId,
actor
);
+ assertTargetHostMatchesConnection({
+ destination: args.destination,
+ connection,
+ destinationConfig: args.destinationConfig
+ });
+
$assertHostCommandsAreSupported(args.destination, args.syncOptions, connection);
const result = await pkiSyncHealthCheckQueue.testHealthCheckCommand({
diff --git a/backend/src/services/pki-sync/pki-sync-target-host-fns.test.ts b/backend/src/services/pki-sync/pki-sync-target-host-fns.test.ts
new file mode 100644
index 0000000000..1c697b3f65
--- /dev/null
+++ b/backend/src/services/pki-sync/pki-sync-target-host-fns.test.ts
@@ -0,0 +1,133 @@
+import { AppConnection } from "@app/services/app-connection/app-connection-enums";
+
+import { PkiSync } from "./pki-sync-enums";
+import { assertTargetHostMatchesConnection } from "./pki-sync-target-host-fns";
+
+const sshConnection = { app: AppConnection.SSH, name: "prod-web-01" };
+const winrmConnection = { app: AppConnection.WinRM, name: "prod-dc-01" };
+const ldapConnection = { app: AppConnection.LDAP, name: "corp-directory", gatewayId: "gateway-id" };
+const ldapConnectionWithoutGateway = { app: AppConnection.LDAP, name: "corp-directory" };
+
+describe("assertTargetHostMatchesConnection", () => {
+ test("accepts an SSH connection with no target host", () => {
+ expect(() =>
+ assertTargetHostMatchesConnection({
+ destination: PkiSync.LinuxServer,
+ connection: sshConnection,
+ destinationConfig: { destinationPath: "/etc/ssl/certs" }
+ })
+ ).not.toThrow();
+ });
+
+ test("rejects a target host on an SSH connection rather than ignoring it", () => {
+ expect(() =>
+ assertTargetHostMatchesConnection({
+ destination: PkiSync.LinuxServer,
+ connection: sshConnection,
+ destinationConfig: { destinationPath: "/etc/ssl/certs", host: "server01.corp.example.com" }
+ })
+ ).toThrow(/cannot be set when using the 'prod-web-01' connection/);
+ });
+
+ test("rejects a target host on a WinRM connection", () => {
+ expect(() =>
+ assertTargetHostMatchesConnection({
+ destination: PkiSync.WindowsServer,
+ connection: winrmConnection,
+ destinationConfig: { destinationPath: "C:\\certs", host: "server01.corp.example.com" }
+ })
+ ).toThrow(/cannot be set when using the 'prod-dc-01' connection/);
+ });
+
+ test("rejects an LDAP connection with no target host", () => {
+ expect(() =>
+ assertTargetHostMatchesConnection({
+ destination: PkiSync.LinuxServer,
+ connection: ldapConnection,
+ destinationConfig: { destinationPath: "/etc/ssl/certs" }
+ })
+ ).toThrow(/A target host is required when using the LDAP connection 'corp-directory'/);
+ });
+
+ test("rejects an empty-string host on an LDAP connection", () => {
+ expect(() =>
+ assertTargetHostMatchesConnection({
+ destination: PkiSync.LinuxServer,
+ connection: ldapConnection,
+ destinationConfig: { destinationPath: "/etc/ssl/certs", host: "" }
+ })
+ ).toThrow(/A target host is required/);
+ });
+
+ test("accepts an LDAP connection with a target host", () => {
+ expect(() =>
+ assertTargetHostMatchesConnection({
+ destination: PkiSync.LinuxServer,
+ connection: ldapConnection,
+ destinationConfig: { destinationPath: "/etc/ssl/certs", host: "server01.corp.example.com" }
+ })
+ ).not.toThrow();
+ });
+
+ test("accepts an LDAP-backed Linux sync with no Gateway, because SSH can be reached directly", () => {
+ expect(() =>
+ assertTargetHostMatchesConnection({
+ destination: PkiSync.LinuxServer,
+ connection: ldapConnectionWithoutGateway,
+ destinationConfig: { destinationPath: "/etc/ssl/certs", host: "server01.corp.example.com" }
+ })
+ ).not.toThrow();
+ });
+
+ test("rejects an LDAP-backed Windows sync when the connection has no Gateway", () => {
+ expect(() =>
+ assertTargetHostMatchesConnection({
+ destination: PkiSync.WindowsServer,
+ connection: ldapConnectionWithoutGateway,
+ destinationConfig: { destinationPath: "C:\\certs", host: "server01.corp.example.com" }
+ })
+ ).toThrow(/requires a Gateway/);
+ });
+
+ test("accepts an LDAP-backed Windows sync reached through a Gateway pool", () => {
+ expect(() =>
+ assertTargetHostMatchesConnection({
+ destination: PkiSync.WindowsServer,
+ connection: { ...ldapConnectionWithoutGateway, gatewayPoolId: "pool-id" },
+ destinationConfig: { destinationPath: "C:\\certs", host: "server01.corp.example.com" }
+ })
+ ).not.toThrow();
+ });
+
+ test("treats a missing destinationConfig as no target host", () => {
+ expect(() =>
+ assertTargetHostMatchesConnection({
+ destination: PkiSync.LinuxServer,
+ connection: sshConnection,
+ destinationConfig: undefined
+ })
+ ).not.toThrow();
+ });
+
+ test("rejects the transport fields on a non-LDAP connection, not only the host", () => {
+ for (const field of ["port", "sslEnabled", "sslRejectUnauthorized"] as const) {
+ expect(() =>
+ assertTargetHostMatchesConnection({
+ destination: PkiSync.WindowsServer,
+ connection: { app: AppConnection.WinRM, name: "prod-web-01" },
+ destinationConfig: { [field]: field === "port" ? 5986 : false }
+ })
+ ).toThrow(new RegExp(`${field} cannot be set when using the 'prod-web-01' connection`));
+ }
+ });
+
+ test("accepts a non-LDAP connection that sets none of them", () => {
+ expect(() =>
+ assertTargetHostMatchesConnection({
+ destination: PkiSync.WindowsServer,
+ connection: { app: AppConnection.WinRM, name: "prod-web-01" },
+ destinationConfig: { destinationPath: "C:\\certs" }
+ })
+ ).not.toThrow();
+ });
+});
diff --git a/backend/src/services/pki-sync/pki-sync-target-host-fns.ts b/backend/src/services/pki-sync/pki-sync-target-host-fns.ts
new file mode 100644
index 0000000000..3a0aed0643
--- /dev/null
+++ b/backend/src/services/pki-sync/pki-sync-target-host-fns.ts
@@ -0,0 +1,68 @@
+import { BadRequestError } from "@app/lib/errors";
+import { AppConnection } from "@app/services/app-connection/app-connection-enums";
+
+import { PkiSync } from "./pki-sync-enums";
+import { PKI_SYNC_NAME_MAP } from "./pki-sync-maps";
+
+type TTargetHostConnection = {
+ app: AppConnection;
+ name: string;
+ gatewayId?: string | null;
+ gatewayPoolId?: string | null;
+};
+
+export type TPkiSyncDeliveryTarget = {
+ host?: string;
+ port?: number;
+ sslEnabled?: boolean;
+ sslRejectUnauthorized?: boolean;
+ sslCertificate?: string;
+};
+
+const LDAP_ONLY_TARGET_FIELDS = [
+ "host",
+ "port",
+ "sslEnabled",
+ "sslRejectUnauthorized",
+ "sslCertificate"
+] as const satisfies readonly (keyof TPkiSyncDeliveryTarget)[];
+
+export const getPkiSyncTargetHost = (
+ destinationConfig: Record<string, unknown> | null | undefined
+): string | undefined => (destinationConfig as { host?: string } | undefined)?.host;
+
+export const assertTargetHostMatchesConnection = ({
+ destination,
+ connection,
+ destinationConfig
+}: {
+ destination: PkiSync;
+ connection: TTargetHostConnection;
+ destinationConfig: (Record<string, unknown> & { host?: string }) | undefined;
+}) => {
+ const host = getPkiSyncTargetHost(destinationConfig);
+
+ if (connection.app !== AppConnection.LDAP) {
+ const setFields = LDAP_ONLY_TARGET_FIELDS.filter((field) => destinationConfig?.[field] !== undefined);
+ if (setFields.length) {
+ throw new BadRequestError({
+ message: `${setFields.join(", ")} cannot be set when using the '${connection.name}' connection, because that connection already targets a single host and supplies these itself. Remove them, or select an LDAP connection to choose the host per sync.`
+ });
+ }
+ return;
+ }
+
+ const destinationName = PKI_SYNC_NAME_MAP[destination];
+
+ if (!host) {
+ throw new BadRequestError({
+ message: `A target host is required when using the LDAP connection '${connection.name}', because an LDAP connection can reach many machines. Set the target host to the machine this ${destinationName} sync should deliver to.`
+ });
+ }
+
+ if (destination === PkiSync.WindowsServer && !connection.gatewayId && !connection.gatewayPoolId) {
+ throw new BadRequestError({
+ message: `${destinationName} syncs reach the host over WinRM, which requires a Gateway. Assign a Gateway to the LDAP connection '${connection.name}' before using it for this sync.`
+ });
+ }
+};
diff --git a/backend/src/services/pki-sync/windows-server/windows-server-pki-sync-fns.ts b/backend/src/services/pki-sync/windows-server/windows-server-pki-sync-fns.ts
index 76b927125a..4feccc1fd4 100644
--- a/backend/src/services/pki-sync/windows-server/windows-server-pki-sync-fns.ts
+++ b/backend/src/services/pki-sync/windows-server/windows-server-pki-sync-fns.ts
@@ -3,12 +3,19 @@ import RE2 from "re2";
import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";
import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";
+import { TKeyStoreFactory } from "@app/keystore/keystore";
import { WinRmRpcEndpoint, WinRmRunCommandResult } from "@app/lib/gateway-v2/winrm-rpc";
import { logger } from "@app/lib/logger";
+import { AppConnection } from "@app/services/app-connection/app-connection-enums";
+import {
+ LdapTargetConfigurationError,
+ resolveLdapBackedHostCredentials
+} from "@app/services/app-connection/ldap/ldap-directory-fns";
import { executeWinRMGatewayOperation, TWinRMConnection, TWinRMCredentials } from "@app/services/app-connection/winrm";
import { TCertificateSyncDALFactory } from "@app/services/certificate-sync/certificate-sync-dal";
import { TSyncMetadata } from "@app/services/certificate-sync/certificate-sync-schemas";
+import { PkiSyncError } from "../pki-sync-errors";
import { exportCertificateForSync, PemCertificateExtension, PkiSyncExportFormat } from "../pki-sync-export-fns";
import {
buildHealthCheckCommandFailureMessage,
@@ -37,6 +44,7 @@ type TWindowsServerPkiSyncFactoryDeps = {
>;
gatewayV2Service: Pick<TGatewayV2ServiceFactory, "getPlatformConnectionDetailsByGatewayId">;
gatewayPoolService?: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;
+ keyStore: Pick<TKeyStoreFactory, "getItem" | "setItemWithExpiry">;
};
type TWindowsServerSyncOptions = {
@@ -61,13 +69,72 @@ const resolveWindowsExportOptions = (options: TWindowsServerSyncOptions) => ({
const TRAILING_BACKSLASH = new RE2("\\\\+$");
const joinWindowsPath = (dir: string, name: string): string => `${dir.replace(TRAILING_BACKSLASH, "")}\\${name}`;
-const buildWinRMTarget = (pkiSync: THealthCheckTarget) => {
+type TWinRMSyncTarget = {
+ credentials: TWinRMCredentials;
+ gatewayId?: string;
+ gatewayPoolId?: string | null;
+};
+
+type TGatewayServices = Pick<TWindowsServerPkiSyncFactoryDeps, "gatewayV2Service" | "gatewayPoolService" | "keyStore">;
+
+const DEFAULT_WINRM_PORT = 5985;
+const DEFAULT_WINRM_HTTPS_PORT = 5986;
+
+const buildLdapBackedWinRMTarget = async (
+ pkiSync: THealthCheckTarget,
+ gatewayServices: TGatewayServices
+): Promise<TWinRMSyncTarget> => {
const { connection } = pkiSync;
+ const { host, port, sslEnabled, sslRejectUnauthorized, sslCertificate } =
+ pkiSync.destinationConfig as TWindowsServerPkiSyncConfig;
+
+ const credentials = await resolveLdapBackedHostCredentials(
+ { connection, host },
+ {
+ gatewayV2Service: gatewayServices.gatewayV2Service,
+ gatewayPoolService: gatewayServices.gatewayPoolService,
+ keyStore: gatewayServices.keyStore
+ }
+ ).catch((err: unknown) => {
+ if (err instanceof LdapTargetConfigurationError) {
+ throw new PkiSyncError({ shouldRetry: false, message: err.message });
+ }
+ throw err;
+ });
+
+ return {
+ credentials: {
+ ...credentials,
+ port: port ?? (sslEnabled ? DEFAULT_WINRM_HTTPS_PORT : DEFAULT_WINRM_PORT),
+ sslEnabled,
+ sslRejectUnauthorized,
+ sslCertificate
+ },
+ gatewayId: connection.gatewayId,
+ gatewayPoolId: connection.gatewayPoolId
+ };
+};
+
+const buildWinRMTarget = async (
+ pkiSync: THealthCheckTarget,
+ gatewayServices: TGatewayServices
+): Promise<TWinRMSyncTarget> => {
+ const { connection } = pkiSync;
+
+ if (connection.app === AppConnection.LDAP) return buildLdapBackedWinRMTarget(pkiSync, gatewayServices);
+
+ if (connection.app !== AppConnection.WinRM) {
+ throw new PkiSyncError({
+ shouldRetry: false,
+ message: `A ${connection.app} connection cannot deliver to a Windows Server sync.`
+ });
+ }
+
const credentials = connection.credentials as TWinRMConnection["credentials"];
const winrmCredentials: TWinRMCredentials = {
host: credentials.host,
- port: credentials.port ?? 5985,
+ port: credentials.port ?? DEFAULT_WINRM_PORT,
username: credentials.username,
password: credentials.password,
sslEnabled: credentials.sslEnabled,
@@ -89,7 +156,7 @@ const reconcileWindowsServerRemovals = async (args: {
pkiSync: TPkiSyncWithCredentials;
certificateMap: TCertificateMap;
deliveredPaths: Set<string>;
- target: ReturnType<typeof buildWinRMTarget>;
+ target: TWinRMSyncTarget;
certificateSyncDAL: Pick<TCertificateSyncDALFactory, "findByPkiSyncId" | "removeCertificates">;
gatewayDeps: Parameters<typeof executeWinRMGatewayOperation>[1];
}): Promise<{ removed: number; failedRemovals: Array<{ name: string; error: string }> }> => {
@@ -140,7 +207,7 @@ const reconcileWindowsServerRemovals = async (args: {
const executeWindowsServerHostCommand = async (
kind: HostCommandKind,
plan: { command: string; context: THostCommandContext },
- target: ReturnType<typeof buildWinRMTarget>,
+ target: TWinRMSyncTarget,
gatewayDeps: Parameters<typeof executeWinRMGatewayOperation>[1]
): Promise<THostCommandExecutionResult> => {
const result = await executeWinRMGatewayOperation<WinRmRunCommandResult>(
@@ -157,17 +224,17 @@ const executeWindowsServerHostCommand = async (
return { stdout: result.stdout, stderr: result.stderr, exitCode: result.exitCode };
};
-const runWindowsServerHealthCheckCommand = ({
+const runWindowsServerHealthCheckCommand = async ({
pkiSync,
certificateMap,
- target,
+ resolveTarget,
gatewayDeps
}: {
pkiSync: THealthCheckTarget;
certificateMap: TCertificateMap;
- target: ReturnType<typeof buildWinRMTarget>;
+ resolveTarget: () => Promise<TWinRMSyncTarget>;
gatewayDeps: Parameters<typeof executeWinRMGatewayOperation>[1];
-}): Promise<THealthCheckCommandResult> | undefined => {
+}): Promise<THealthCheckCommandResult | undefined> => {
const options = (pkiSync.syncOptions ?? {}) as TWindowsServerSyncOptions;
const config = pkiSync.destinationConfig as TWindowsServerPkiSyncConfig;
const exportOptions = resolveWindowsExportOptions(options);
@@ -183,10 +250,15 @@ const runWindowsServerHealthCheckCommand = ({
});
if (!plan) return undefined;
+ const target = await resolveTarget().catch((err: unknown) => err as Error);
+
return runHealthCheckCommand({
syncId: pkiSync.id,
secretsToRedact: [plan.context.pkcs12Password],
- execute: () => executeWindowsServerHostCommand(HostCommandKind.HealthCheck, plan, target, gatewayDeps)
+ execute: async () => {
+ if (target instanceof Error) throw target;
+ return executeWindowsServerHostCommand(HostCommandKind.HealthCheck, plan, target, gatewayDeps);
+ }
});
};
@@ -198,7 +270,7 @@ const runWindowsServerPostSyncCommand = ({
}: {
syncId: string;
plan: TPostSyncCommandPlan;
- target: ReturnType<typeof buildWinRMTarget>;
+ target: TWinRMSyncTarget;
gatewayDeps: Parameters<typeof executeWinRMGatewayOperation>[1];
}) =>
runPostSyncCommand({
@@ -210,9 +282,10 @@ const runWindowsServerPostSyncCommand = ({
export const windowsServerPkiSyncFactory = ({
certificateSyncDAL,
gatewayV2Service,
- gatewayPoolService
+ gatewayPoolService,
+ keyStore
}: TWindowsServerPkiSyncFactoryDeps) => {
- const gatewayDeps = { gatewayV2Service, gatewayPoolService };
+ const gatewayDeps = { gatewayV2Service, gatewayPoolService, keyStore };
const syncCertificates = async (
pkiSync: TPkiSyncWithCredentials,
@@ -232,11 +305,16 @@ export const windowsServerPkiSyncFactory = ({
// just rewrote under the same name, and tells the post-sync command what landed.
const deliveredPaths = new Set<string>();
const deliveredCertificates: Array<{ paths: string[]; commonName?: string }> = [];
- const target = buildWinRMTarget(pkiSync);
+ const target = await buildWinRMTarget(pkiSync, gatewayDeps);
let uploaded = 0;
let removed = 0;
- const healthCheck = await runWindowsServerHealthCheckCommand({ pkiSync, certificateMap, target, gatewayDeps });
+ const healthCheck = await runWindowsServerHealthCheckCommand({
+ pkiSync,
+ certificateMap,
+ resolveTarget: async () => target,
+ gatewayDeps
+ });
if (healthCheck && didHealthCheckFail(healthCheck)) {
logger.info(
`Windows Server PKI sync [syncId=${pkiSync.id}]: health check failed, delivered nothing (${buildHealthCheckCommandFailureMessage(healthCheck)})`
@@ -394,7 +472,7 @@ export const windowsServerPkiSyncFactory = ({
}
if (pathsToRemove.size > 0) {
- const target = buildWinRMTarget(pkiSync);
+ const target = await buildWinRMTarget(pkiSync, gatewayDeps);
await executeWinRMGatewayOperation(
{ ...target, endpoint: WinRmRpcEndpoint.RemoveFiles, params: { paths: Array.from(pathsToRemove) } },
gatewayDeps
@@ -411,7 +489,7 @@ export const windowsServerPkiSyncFactory = ({
runWindowsServerHealthCheckCommand({
pkiSync,
certificateMap,
- target: buildWinRMTarget(pkiSync),
+ resolveTarget: () => buildWinRMTarget(pkiSync, gatewayDeps),
gatewayDeps
});
diff --git a/backend/src/services/pki-sync/windows-server/windows-server-pki-sync-schemas.ts b/backend/src/services/pki-sync/windows-server/windows-server-pki-sync-schemas.ts
index a4ba74a144..942bff7da1 100644
--- a/backend/src/services/pki-sync/windows-server/windows-server-pki-sync-schemas.ts
+++ b/backend/src/services/pki-sync/windows-server/windows-server-pki-sync-schemas.ts
@@ -6,7 +6,13 @@ import { pkiDescriptionSchema } from "@app/services/certificate-common/certifica
import { buildCertificateNameSchemaTestName } from "@app/services/pki-sync/pki-sync-certificate-name-fns";
import { PkiSync } from "@app/services/pki-sync/pki-sync-enums";
import { PemCertificateExtension, PkiSyncExportFormat } from "@app/services/pki-sync/pki-sync-export-fns";
-import { BaseHealthCheckTestSchema, HostCommandSchema, PkiSyncSchema } from "@app/services/pki-sync/pki-sync-schemas";
+import {
+ BaseHealthCheckTestSchema,
+ HostCommandSchema,
+ PkiSyncSchema,
+ PkiSyncTargetHostSchema,
+ PkiSyncTargetPortSchema
+} from "@app/services/pki-sync/pki-sync-schemas";
import { WINDOWS_SERVER_NAMING } from "./windows-server-pki-sync-constants";
@@ -50,7 +56,20 @@ export const WindowsServerPkiSyncConfigSchema = z.object({
.refine((p) => !WINDOWS_PATH_TRAVERSAL.test(p), { message: "Destination path must not contain '..'" })
.refine((p) => !WINDOWS_DOUBLE_SEPARATOR.test(p), {
message: "Destination path must not contain consecutive path separators"
- })
+ }),
+ host: PkiSyncTargetHostSchema,
+ port: PkiSyncTargetPortSchema,
+ sslEnabled: z
+ .boolean()
+ .optional()
+ .describe("Reach the host over HTTPS WinRM instead of HTTP with NTLM message encryption."),
+ sslRejectUnauthorized: z.boolean().optional().describe("Verify the host's WinRM certificate when using HTTPS."),
+ sslCertificate: z
+ .string()
+ .trim()
+ .max(8192)
+ .optional()
+ .describe("CA certificate (PEM) used to verify a self-signed WinRM HTTPS listener (HTTPS only).")
});
export const WindowsServerPkiSyncOptionsSchema = z.object({
@@ -146,6 +165,7 @@ export const UpdateWindowsServerPkiSyncSchema = z.object({
export const WindowsServerPkiSyncListItemSchema = z.object({
name: z.literal("Windows Server"),
connection: z.literal(AppConnection.WinRM),
+ additionalConnections: z.literal(AppConnection.LDAP).array().optional(),
destination: z.literal(PkiSync.WindowsServer),
canImportCertificates: z.literal(false),
canRemoveCertificates: z.literal(true)
diff --git a/docs/documentation/platform/pki/applications/certificate-syncs/linux-server.mdx b/docs/documentation/platform/pki/applications/certificate-syncs/linux-server.mdx
index 885bceeb42..d86ae3897b 100644
--- a/docs/documentation/platform/pki/applications/certificate-syncs/linux-server.mdx
+++ b/docs/documentation/platform/pki/applications/certificate-syncs/linux-server.mdx
@@ -17,7 +17,8 @@ Deploy certificates from Infisical to a directory on a Linux server over SSH. Fi
## Prerequisites
-- An [SSH Connection](/integrations/app-connections/ssh) with access to the target server
+- An [SSH Connection](/integrations/app-connections/ssh) with access to the target server, or an [LDAP Connection](/integrations/app-connections/ldap) to the domain the server is joined to. See [using an LDAP connection for many servers](#using-an-ldap-connection-for-many-servers).
+- For an LDAP Connection: the connection URL must use LDAPS on port 636, because a hardened domain controller rejects a plaintext simple bind on port 389 with `strongerAuthRequired`. The domain controller must be reachable as well as the target server, since every run reads the directory to derive the login.
- The destination directory must already exist on the server and the connection user must be able to write to it
- The server must be reachable from Infisical, either directly or through an [Infisical Gateway](/documentation/platform/gateways/overview)
- A Gateway is required to use a [health check](#health-checks) or a [post-sync command](#post-sync-commands), because the Gateway is what executes them. It must be running Infisical CLI v0.43.120 or later
@@ -31,10 +32,14 @@ Deploy certificates from Infisical to a directory on a Linux server over SSH. Fi
2. Select the **Linux Server** option.
3. Configure the **Destination**:
- - **SSH Connection**: The SSH Connection used to reach the server.
+ - **Connection**: The SSH Connection used to reach the server, or an LDAP Connection to the domain the server is joined to.
- **Destination Directory**: The absolute path to the directory where certificate files are written, for example `/etc/ssl/certs`.
- 4. Configure the **Sync Options**:
+ 4. Configure the **Target Host**. This step appears only when the connection is an LDAP Connection, because that connection reaches a whole domain rather than one machine:
+ - **Target Host**: The machine this sync delivers to. Servers found in the directory are offered as suggestions, and you can enter a host that is not listed. Enter a host name or an IPv4 address. Underscores, ports and IPv6 literals are not accepted.
+ - **Port**: Leave empty to use 22. Set a value only if the SSH listener is on a non-standard port.
+
+ 5. Configure the **Sync Options**:
- **Export Format**: Choose **PEM** to write separate certificate, chain, and key files, or **PKCS#12** to write a single password-protected `.pfx` bundle.
- **Certificate File Extension**: For PEM, choose `.pem` (default) or `.crt` for the certificate and chain files. Both hold the same PEM-encoded content, so pick the one the consuming service expects.
- **Combine Certificate and Chain**: For PEM, write the leaf certificate followed by the chain in a single file (a full-chain file, as nginx expects) and skip the separate chain file.
@@ -47,21 +52,23 @@ Deploy certificates from Infisical to a directory on a Linux server over SSH. Fi
- **Certificate Name Schema**: The base file name, using placeholders such as `{{commonName}}`, `{{certificateId}}`, or `{{shortCertificateId}}`. The export format adds the extension. A schema with no placeholder can be linked to only one certificate.
- **Auto-Sync Enabled**: Automatically sync certificates when changes occur.
- 5. Configure the **Commands**, or leave them empty:
+ 6. Configure the **Commands**, or leave them empty:
- **Health check**: A command run on the server before any certificate is written, to confirm the host is ready, for example `test -w /etc/ssl/certs`. A non-zero exit stops the sync, so nothing is delivered. See [health checks](#health-checks).
- **Post-sync command**: A command run on the server after the sync delivers a certificate, so the service that uses it picks up the new file, for example `sudo systemctl reload nginx`. See [Post-Sync Commands](#post-sync-commands).
- 6. Configure the **Details**:
+ 7. Configure the **Details**:
- **Name**: The name of your sync.
- **Description**: Optional description.
- 7. Select which certificates should be synced.
+ 8. Select which certificates should be synced.
- 8. Review and click **Create Sync**.
+ 9. Review and click **Create Sync**.
</Tab>
<Tab title="API">
To create a **Linux Server Certificate Sync**, make an API request to the [Create Linux Server PKI Sync](/api-reference/endpoints/pki/syncs/linux-server/create) endpoint.
+ `destinationConfig.host` is required when `connectionId` refers to an LDAP Connection, and an optional `port` sits alongside it, defaulting to 22. Both are rejected when `connectionId` refers to an SSH Connection, because that connection carries its own host and port.
+
### Sample request
```bash Request
@@ -84,13 +91,43 @@ Deploy certificates from Infisical to a directory on a Linux server over SSH. Fi
"postSyncCommand": "sudo systemctl reload nginx"
},
"destinationConfig": {
- "destinationPath": "/etc/ssl/certs"
+ "destinationPath": "/etc/ssl/certs",
+ "host": "server01.corp.example.com"
}
}'
```
</Tab>
</Tabs>
+## Using an LDAP connection for many servers
+
+An SSH Connection stores the target machine's address alongside its credential, so it reaches exactly one server. Pushing one certificate to fifty servers means fifty connections holding the same credential, and fifty objects to update when that credential is rotated.
+
+An LDAP Connection removes that duplication. It is both the credential and the directory, so one connection serves as many syncs as you have servers. Each sync names its own **Target Host**, and every sync shares the one credential. When you rotate the service account's password on the connection, every sync that uses it picks up the new password on its next run with no further action.
+
+This works because an Active Directory service account is a single identity. On a domain-joined Linux host, the same username and password that performs the LDAP bind performs the SSH logon, so no second credential is needed. The host must accept domain credentials over SSH, which is what a directory client such as SSSD provides.
+
+The **Target Host** field offers machines read from the directory. The list is not closed, because the name a domain controller advertises is not always the address you can reach, so you can enter a host that is not listed. The value must be a host name or an IPv4 address.
+
+### The host must accept the `DOMAIN\user` login form
+
+Infisical logs in to the server as `DOMAIN\user`, for example `CORP\svc-certs`. Whether a Linux host
+accepts that form depends on how its directory client is configured.
+
+A host joined to the domain with `realm join` uses the SSSD `ad` provider, which understands
+`DOMAIN\user` out of the box. A host configured against the directory over LDAP instead uses the
+`ldap` provider, whose default name parsing only understands `user@domain`, so the login is rejected
+before the password is ever checked. Add the domain-qualified form to that host's `sssd.conf`:
+
+```ini
+[domain/CORP]
+re_expression = (((?P<domain>[^\\]+)\\(?P<name>.+$))|((?P<name>[^@]+)@(?P<domain>.+$))|(^(?P<name>[^@\\]+)$))
+use_fully_qualified_names = False
+```
+
+Confirm it with `getent passwd 'CORP\svc-certs'` on the server before creating the sync. If that
+returns nothing, the sync will fail to authenticate no matter what the connection holds.
+
## Export formats
The file extension is set by the export format, not by the name schema. The name schema only provides the base file name.
@@ -126,7 +163,7 @@ The same check also runs on its own once a day, so a host that stops being ready
Write a check that answers a question rather than one that changes something. `test -w /etc/ssl/certs` and `systemctl is-active nginx` are good checks. Creating the directory or starting the service is work for the post-sync command.
<Note>
- Your [Infisical Gateway](/documentation/platform/gateways/overview) runs the check, never Infisical. The sync's SSH Connection must therefore use a gateway, otherwise the check is rejected when you save the sync.
+ Your [Infisical Gateway](/documentation/platform/gateways/overview) runs the check, never Infisical. The sync's App Connection must therefore use a gateway, otherwise the check is rejected when you save the sync.
</Note>
<HealthCheckFlow />
@@ -193,7 +230,7 @@ Set one command on the sync. It runs on the target server, in that server's own
The field accepts a whole script, so several steps can run in one go: put each on its own line, or chain them with `&&`.
<Note>
- Your [Infisical Gateway](/documentation/platform/gateways/overview) runs the command, never Infisical. The sync's SSH Connection must therefore use a gateway, otherwise the command is rejected when you save the sync.
+ Your [Infisical Gateway](/documentation/platform/gateways/overview) runs the command, never Infisical. The sync's App Connection must therefore use a gateway, otherwise the command is rejected when you save the sync.
The Gateway must be running Infisical CLI **v0.43.120 or later**. Earlier Gateways either cannot run the command at all or cannot unlock an SSH Connection's passphrase-protected private key, so the command fails. Run `infisical --version` on the Gateway host to check, and see [Gateway deployment](/documentation/platform/gateways/gateway-deployment) for how to upgrade.
</Note>
diff --git a/docs/documentation/platform/pki/applications/certificate-syncs/windows-server.mdx b/docs/documentation/platform/pki/applications/certificate-syncs/windows-server.mdx
index 3cdbf81f0a..13dfb877a6 100644
--- a/docs/documentation/platform/pki/applications/certificate-syncs/windows-server.mdx
+++ b/docs/documentation/platform/pki/applications/certificate-syncs/windows-server.mdx
@@ -17,12 +17,13 @@ Deploy certificates from Infisical to a directory on a Windows server over WinRM
## Prerequisites
-- A [Windows (WinRM) Connection](/integrations/app-connections/winrm) with access to the target server
+- A [Windows (WinRM) Connection](/integrations/app-connections/winrm) with access to the target server, or an [LDAP Connection](/integrations/app-connections/ldap) to the domain the server belongs to. See [using an LDAP connection for many servers](#using-an-ldap-connection-for-many-servers).
+- For an LDAP Connection: the connection URL must use LDAPS on port 636, because a hardened domain controller rejects a plaintext simple bind on port 389 with `strongerAuthRequired`. A Gateway must be assigned to the LDAP Connection itself, and that Gateway must reach both the domain controller and the target server.
- An [Infisical Gateway](/documentation/platform/gateways/overview) that can reach the server. Windows delivery always runs through the Gateway. A [post-sync command](#post-sync-commands) additionally needs the Gateway to be running Infisical CLI v0.43.120 or later.
- The connection user must be able to write to the destination directory
<Note>
- Windows delivery runs on the Gateway, which reaches the host inside your network and runs the WinRM session on Infisical's behalf. By default it uses HTTP with NTLM message encryption, which lets a certificate travel confidentially over the default WinRM listener without a server certificate. This is the same zero-configuration posture most Windows hosts already ship with. HTTPS is also supported.
+ Windows delivery runs on the Gateway, which reaches the host inside your network and runs the WinRM session on Infisical's behalf. By default it uses HTTP with NTLM message encryption, which lets a certificate travel confidentially over the default WinRM listener without a server certificate. This is the same zero-configuration posture most Windows hosts already ship with. HTTPS is also supported: on a Windows (WinRM) Connection it is a property of the connection, and on an LDAP Connection the sync itself carries **Enable SSL**.
</Note>
## Create a Windows Server sync
@@ -34,10 +35,21 @@ Deploy certificates from Infisical to a directory on a Windows server over WinRM
2. Select the **Windows Server** option.
3. Configure the **Destination**:
- - **Windows (WinRM) Connection**: The WinRM Connection used to reach the server.
+ - **Connection**: The WinRM Connection used to reach the server, or an LDAP Connection to the server's domain.
- **Destination Directory**: The absolute Windows drive path where certificate files are written, for example `C:\certs`. It is created if it does not exist. The path cannot contain `..` segments or consecutive separators.
- 4. Configure the **Sync Options**:
+ 4. Configure the **Target Host**. This step appears only when the connection is an LDAP Connection, because that connection reaches a whole domain rather than one machine. A Windows (WinRM) Connection carries all of these itself:
+ - **Target Host**: The machine this sync delivers to. Servers found in the directory are offered as suggestions, and you can enter a host that is not listed. Enter a host name or an IPv4 address. Underscores, ports and IPv6 literals are not accepted.
+ - **Port**: Leave empty to use 5985, or 5986 when **Enable SSL** is on. Set a value only if the WinRM listener is on a non-standard port.
+ - **Enable SSL**: Connect over HTTPS. When off, HTTP with NTLM message encryption is used and no server certificate is required.
+ - **SSL Certificate**: Leave empty to verify against the system trust store, or paste the listener's certificate to verify a self-signed WinRM HTTPS listener.
+ - **Reject Unauthorized**: When on, Infisical only connects if the listener presents a valid, trusted certificate.
+
+ <Note>
+ With **Reject Unauthorized** on, the **Target Host** must match the name on the listener's certificate. A WinRM HTTPS listener created by `winrm quickconfig -transport:https` carries the machine name, so target `server01.corp.example.com` rather than its IP address, otherwise the connection fails on a name mismatch even when the certificate is trusted.
+ </Note>
+
+ 5. Configure the **Sync Options**:
- **Export Format**: Choose **PKCS#12** to write a single password-protected `.pfx` bundle, or **PEM** to write separate certificate, chain, and key files.
- **Certificate File Extension**: For PEM, choose `.pem` (default) or `.crt` for the certificate and chain files. Both hold the same PEM-encoded content, so pick the one the consuming service expects.
- **Combine Certificate and Chain**: For PEM, write the leaf certificate followed by the chain in a single file (a full-chain file) and skip the separate chain file.
@@ -49,21 +61,23 @@ Deploy certificates from Infisical to a directory on a Windows server over WinRM
- **Certificate Name Schema**: The base file name, using placeholders such as `{{commonName}}`, `{{certificateId}}`, or `{{shortCertificateId}}`. The export format adds the extension. A schema with no placeholder can be linked to only one certificate.
- **Auto-Sync Enabled**: Automatically sync certificates when changes occur.
- 5. Configure the **Commands**, or leave them empty:
+ 6. Configure the **Commands**, or leave them empty:
- **Health check**: A PowerShell command run on the server before any certificate is written, to confirm the host is ready, for example `Get-Service W3SVC | Where-Object Status -ne 'Running' | ForEach-Object { throw "W3SVC is not running" }`. A failure stops the sync, so nothing is delivered. See [health checks](#health-checks).
- **Post-sync command**: A PowerShell command run on the server after the sync delivers a certificate, so the service that uses it picks up the new file, for example `Restart-Service -Name "W3SVC"`. See [Post-Sync Commands](#post-sync-commands).
- 6. Configure the **Details**:
+ 7. Configure the **Details**:
- **Name**: The name of your sync.
- **Description**: Optional description.
- 7. Select which certificates should be synced.
+ 8. Select which certificates should be synced.
- 8. Review and click **Create Sync**.
+ 9. Review and click **Create Sync**.
</Tab>
<Tab title="API">
To create a **Windows Server Certificate Sync**, make an API request to the [Create Windows Server PKI Sync](/api-reference/endpoints/pki/syncs/windows-server/create) endpoint.
+ `destinationConfig.host` is required when `connectionId` refers to an LDAP Connection, and optional `port`, `sslEnabled`, `sslRejectUnauthorized` and `sslCertificate` sit alongside it. All five are rejected when `connectionId` refers to a Windows (WinRM) Connection, because that connection carries them itself.
+
### Sample request
```bash Request
@@ -88,13 +102,42 @@ Deploy certificates from Infisical to a directory on a Windows server over WinRM
"postSyncCommand": "Restart-Service -Name W3SVC"
},
"destinationConfig": {
- "destinationPath": "C:\\certs"
+ "destinationPath": "C:\\certs",
+ "host": "server01.corp.example.com"
}
}'
```
</Tab>
</Tabs>
+## Using an LDAP connection for many servers
+
+A Windows (WinRM) Connection stores the target machine's address alongside its credential, so it reaches exactly one server. Pushing one certificate to fifty servers means fifty connections holding the same credential, and fifty objects to update when that credential is rotated.
+
+An LDAP Connection removes that duplication. It is both the credential and the directory, so one connection serves as many syncs as you have servers. Each sync names its own **Target Host**, and every sync shares the one credential. When you rotate the service account's password on the connection, every sync that uses it picks up the new password on its next run with no further action.
+
+This works because an Active Directory service account is a single identity. The same username and password that performs the LDAP bind performs the WinRM logon, so no second credential is needed.
+
+Infisical derives that logon name rather than asking for it twice. It reads the domain's NetBIOS name from the directory and signs in as `NETBIOS\account`, for example `CORP\svc-certs`. The account part comes from the connection's bind identity: from the name before the `@` when the bind is a user principal name, and read from the directory as the account's `sAMAccountName` when the bind is a distinguished name. Grant WinRM rights to that account, not to the connection's bind string.
+
+The **Target Host** field offers servers read from the directory. The list is not closed, because the name a domain controller advertises is not always the address you can reach, so you can enter a host that is not listed. The value must be a host name or an IPv4 address.
+
+### Preparing the service account
+
+The service account needs permission to open a WinRM session on each target server. Add it to the **Remote Management Users** group on the server:
+
+```powershell
+Add-LocalGroupMember -Group "Remote Management Users" -Member "CORP\svc-certs"
+```
+
+<Warning>
+ On a domain controller, use `Add-ADGroupMember` instead. A domain controller has no local groups, and `Add-LocalGroupMember` reports success while doing nothing, which surfaces later as a 401 at the WinRM handshake.
+
+ ```powershell
+ Add-ADGroupMember -Identity "Remote Management Users" -Members "svc-certs"
+ ```
+</Warning>
+
## Export formats
The file extension is set by the export format, not by the name schema. The name schema only provides the base file name.
diff --git a/docs/integrations/app-connections/ldap.mdx b/docs/integrations/app-connections/ldap.mdx
index 8314542f98..ae5c12a832 100644
--- a/docs/integrations/app-connections/ldap.mdx
+++ b/docs/integrations/app-connections/ldap.mdx
@@ -26,6 +26,14 @@ Depending on how you intend to use your LDAP connection, there may be additional
- Permission to update their own password if rotating their personal password
</Note>
</Tab>
+ <Tab title="Certificate Syncs">
+ <Note>
+ To back a [Linux Server](/documentation/platform/pki/applications/certificate-syncs/linux-server) or [Windows Server](/documentation/platform/pki/applications/certificate-syncs/windows-server) certificate sync, the following requirements must additionally be met:
+ - You must use an LDAPS connection, because a hardened domain controller rejects a plaintext simple bind on port 389
+ - Windows Server syncs must have a Gateway assigned to this connection, and that Gateway must reach both the domain controller and the target servers
+ - Each target host must accept the binding account in `DOMAIN\user` form, which Infisical derives from the directory
+ </Note>
+ </Tab>
</Tabs>
diff --git a/frontend/src/components/app-connections/AppConnectionOption.tsx b/frontend/src/components/app-connections/AppConnectionOption.tsx
index 87132c9e45..a87f17226c 100644
--- a/frontend/src/components/app-connections/AppConnectionOption.tsx
+++ b/frontend/src/components/app-connections/AppConnectionOption.tsx
@@ -19,7 +19,8 @@ export const AppConnectionOption = ({
children,
...props
}: OptionProps<TAvailableAppConnection>) => {
- const isCreateOption = props.data.id === "_create";
+ const isCreateOption = props.data.id === "_create" || props.data.id.startsWith("_create:");
+ const isPerAppCreateOption = isCreateOption && props.data.id !== "_create";
const isOnlyOption = isCreateOption && props.selectProps.options.length === 1;
const { isSubOrganization } = useOrganization();
@@ -32,7 +33,9 @@ export const AppConnectionOption = ({
className={`flex items-center gap-x-1 ${isOnlyOption ? "text-foreground" : "text-accent"}`}
>
<FontAwesomeIcon icon={faPlus} size="sm" />
- <span className="mr-auto">Create New Connection</span>
+ <span className="mr-auto">
+ {isPerAppCreateOption ? children : "Create New Connection"}
+ </span>
</div>
) : (
<>
diff --git a/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsx b/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsx
index a8cfda38dc..bdf2ccefdd 100644
--- a/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsx
+++ b/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsx
@@ -27,6 +27,7 @@ import {
} from "@app/components/v3";
import { useProject } from "@app/context";
import { PKI_SYNC_MAP } from "@app/helpers/pkiSyncs";
+import { AppConnection } from "@app/hooks/api/appConnections/enums";
import {
PkiSync,
PkiSyncExportFormat,
@@ -47,6 +48,7 @@ import { PkiSyncHealthCheckCommandFields } from "./PkiSyncHealthCheckCommandFiel
import { PkiSyncOptionsFields } from "./PkiSyncOptionsFields";
import { PkiSyncPostSyncCommandFields } from "./PkiSyncPostSyncCommandFields";
import { PkiSyncReviewFields } from "./PkiSyncReviewFields";
+import { PkiSyncTargetHostField } from "./PkiSyncTargetHostField";
type Props = {
onComplete: (pkiSync: TPkiSync) => void;
@@ -67,6 +69,13 @@ const STEP_META: Record<
rightDescription:
"Choose the connection and the destination where certificates will be pushed. The available fields depend on the selected service."
},
+ targetHost: {
+ short: "Which machine to reach",
+ subtitle: "Name the machine this sync delivers to and how to reach it.",
+ rightLabel: "TARGET HOST",
+ rightDescription:
+ "An LDAP Connection supplies the credential for a whole domain rather than one machine, so each sync names its own host.\n\nMachines found in the directory are offered as suggestions, and you can enter one that is not listed."
+ },
options: {
short: "Sync behavior",
subtitle: "Control how certificates are written and whether they sync automatically.",
@@ -113,21 +122,31 @@ const STEP_META: Record<
const getFormTabs = (
destination: PkiSync,
- canRunHostCommands: boolean
+ canRunHostCommands: boolean,
+ needsTargetHost: boolean
): { name: string; key: string; fields: FieldPath<TPkiSyncForm>[] }[] => {
const baseTabs = [
{
name: "Destination",
key: "destination",
fields: ["connection", "destinationConfig"] as FieldPath<TPkiSyncForm>[]
- },
- {
- name: "Sync Options",
- key: "options",
- fields: ["syncOptions", "credentials"] as FieldPath<TPkiSyncForm>[]
}
];
+ if (needsTargetHost) {
+ baseTabs.push({
+ name: "Target Host",
+ key: "targetHost",
+ fields: ["destinationConfig"] as FieldPath<TPkiSyncForm>[]
+ });
+ }
+
+ baseTabs.push({
+ name: "Sync Options",
+ key: "options",
+ fields: ["syncOptions", "credentials"] as FieldPath<TPkiSyncForm>[]
+ });
+
if (destination === PkiSync.Chef || destination === PkiSync.AwsSecretsManager) {
baseTabs.push({
name: "Mappings",
@@ -182,12 +201,6 @@ export const CreatePkiSyncForm = ({
const { syncOption } = usePkiSyncOption(destination);
const canSetPostSyncCommand = useCanSetPostSyncCommand(applicationId);
const canSetHealthCheckCommand = useCanSetHealthCheckCommand(applicationId);
- const FORM_TABS = getFormTabs(
- destination,
- (Boolean(syncOption?.canRunHealthCheckCommand) && canSetHealthCheckCommand) ||
- (Boolean(syncOption?.canRunPostSyncCommand) && canSetPostSyncCommand)
- );
-
const formMethods = useForm<TPkiSyncForm>({
resolver: zodResolver(PkiSyncFormSchema),
defaultValues: {
@@ -227,6 +240,14 @@ export const CreatePkiSyncForm = ({
reValidateMode: "onChange"
});
+ const selectedConnectionApp = formMethods.watch("connection")?.app;
+ const FORM_TABS = getFormTabs(
+ destination,
+ (Boolean(syncOption?.canRunHealthCheckCommand) && canSetHealthCheckCommand) ||
+ (Boolean(syncOption?.canRunPostSyncCommand) && canSetPostSyncCommand),
+ selectedConnectionApp === AppConnection.LDAP
+ );
+
const onSubmit = async ({
connection,
destinationConfig,
@@ -265,6 +286,19 @@ export const CreatePkiSyncForm = ({
const isValid = await trigger(FORM_TABS[index].fields);
if (!isValid) return false;
+ // The union member is still incomplete at this point (name is unset), so the schema's cross-field
+ // rule does not surface here. Same reason the PKCS#12 rule below is checked by hand.
+ if (FORM_TABS[index].key === "targetHost") {
+ const { destinationConfig } = getValues() as { destinationConfig?: { host?: string } };
+ if (!destinationConfig?.host) {
+ setError("destinationConfig.host" as FieldPath<TPkiSyncForm>, {
+ type: "manual",
+ message: "A target host is required when using an LDAP connection"
+ });
+ return false;
+ }
+ }
+
if (FORM_TABS[index].key === "options") {
const values = getValues() as {
destination?: PkiSync;
@@ -353,6 +387,9 @@ export const CreatePkiSyncForm = ({
<p className="mt-1 text-sm text-muted">{currentDetail.subtitle}</p>
</div>
{currentKey === "destination" && <PkiSyncDestinationFields />}
+ {currentKey === "targetHost" && (
+ <PkiSyncTargetHostField applicationId={applicationId} />
+ )}
{currentKey === "options" && (
<>
<PkiSyncOptionsFields destination={destination} />
diff --git a/frontend/src/components/pki-syncs/forms/EditPkiSyncForm.tsx b/frontend/src/components/pki-syncs/forms/EditPkiSyncForm.tsx
index 0349d31952..1b09ae9f5e 100644
--- a/frontend/src/components/pki-syncs/forms/EditPkiSyncForm.tsx
+++ b/frontend/src/components/pki-syncs/forms/EditPkiSyncForm.tsx
@@ -16,6 +16,7 @@ import {
Switch
} from "@app/components/v3";
import { PKI_SYNC_MAP } from "@app/helpers/pkiSyncs";
+import { AppConnection } from "@app/hooks/api/appConnections/enums";
import {
PkiSync,
TPkiSync,
@@ -32,6 +33,7 @@ import { PkiSyncFieldMappingsFields } from "./PkiSyncFieldMappingsFields";
import { PkiSyncHealthCheckCommandFields } from "./PkiSyncHealthCheckCommandFields";
import { PkiSyncOptionsFields } from "./PkiSyncOptionsFields";
import { PkiSyncPostSyncCommandFields } from "./PkiSyncPostSyncCommandFields";
+import { PkiSyncTargetHostField } from "./PkiSyncTargetHostField";
type Props = {
onComplete: (pkiSync: TPkiSync) => void;
@@ -50,7 +52,11 @@ type FormStep = {
rightDescription: string;
};
-const getFormSteps = (destination: PkiSync, canRunHostCommands: boolean): FormStep[] => {
+const getFormSteps = (
+ destination: PkiSync,
+ canRunHostCommands: boolean,
+ needsTargetHost: boolean
+): FormStep[] => {
const steps: FormStep[] = [
{
key: "destination",
@@ -62,6 +68,20 @@ const getFormSteps = (destination: PkiSync, canRunHostCommands: boolean): FormSt
rightDescription:
"Choose the connection and the destination where certificates will be pushed. The available fields depend on the selected service."
},
+ ...(needsTargetHost
+ ? [
+ {
+ key: "targetHost",
+ name: "Target Host",
+ description: "Which machine to reach",
+ title: "Target Host",
+ subtitle: "Name the machine this sync delivers to and how to reach it.",
+ rightLabel: "TARGET HOST",
+ rightDescription:
+ "An LDAP Connection supplies the credential for a whole domain rather than one machine, so each sync names its own host.\n\nMachines found in the directory are offered as suggestions, and you can enter one that is not listed."
+ }
+ ]
+ : []),
{
key: "options",
name: "Sync Options",
@@ -114,17 +134,20 @@ const getFormSteps = (destination: PkiSync, canRunHostCommands: boolean): FormSt
return steps;
};
+const LDAP_TARGET_DEFAULTS = {
+ host: undefined,
+ port: undefined,
+ sslEnabled: undefined,
+ sslRejectUnauthorized: undefined,
+ sslCertificate: undefined
+};
+
export const EditPkiSyncForm = ({ pkiSync, onComplete, onDirtyChange, onCancel }: Props) => {
const updatePkiSync = useUpdatePkiSync();
const { name: destinationName } = PKI_SYNC_MAP[pkiSync.destination];
const { syncOption } = usePkiSyncOption(pkiSync.destination);
const canSetPostSyncCommand = useCanSetPostSyncCommand(pkiSync.applicationId);
const canSetHealthCheckCommand = useCanSetHealthCheckCommand(pkiSync.applicationId);
- const steps = getFormSteps(
- pkiSync.destination,
- Boolean(syncOption?.canRunHealthCheckCommand || syncOption?.canRunPostSyncCommand)
- );
-
const [selectedStepIndex, setSelectedStepIndex] = useState(0);
const formMethods = useForm<TUpdatePkiSyncForm>({
@@ -135,15 +158,25 @@ export const EditPkiSyncForm = ({ pkiSync, onComplete, onDirtyChange, onCancel }
description: pkiSync.description ?? "",
connection: {
id: pkiSync.connectionId,
- name: pkiSync.appConnectionName
+ name: pkiSync.appConnectionName,
+ app: pkiSync.connection.app
},
syncOptions: pkiSync.syncOptions,
- destinationConfig: pkiSync.destinationConfig,
+ destinationConfig: { ...LDAP_TARGET_DEFAULTS, ...pkiSync.destinationConfig },
isAutoSyncEnabled: pkiSync.isAutoSyncEnabled
} as Partial<TUpdatePkiSyncForm>,
reValidateMode: "onChange"
});
+ const selectedConnectionApp = (
+ formMethods.watch("connection") as { app?: AppConnection } | undefined
+ )?.app;
+ const steps = getFormSteps(
+ pkiSync.destination,
+ Boolean(syncOption?.canRunHealthCheckCommand || syncOption?.canRunPostSyncCommand),
+ selectedConnectionApp === AppConnection.LDAP
+ );
+
const {
handleSubmit,
control,
@@ -180,6 +213,8 @@ export const EditPkiSyncForm = ({ pkiSync, onComplete, onDirtyChange, onCancel }
switch (currentStep.key) {
case "destination":
return <PkiSyncDestinationFields />;
+ case "targetHost":
+ return <PkiSyncTargetHostField applicationId={pkiSync.applicationId} />;
case "options":
return (
<>
diff --git a/frontend/src/components/pki-syncs/forms/PkiSyncConnectionField.tsx b/frontend/src/components/pki-syncs/forms/PkiSyncConnectionField.tsx
index 142ff0cd71..62442db86d 100644
--- a/frontend/src/components/pki-syncs/forms/PkiSyncConnectionField.tsx
+++ b/frontend/src/components/pki-syncs/forms/PkiSyncConnectionField.tsx
@@ -1,3 +1,4 @@
+import { useState } from "react";
import { Controller, useFormContext } from "react-hook-form";
import { SingleValue } from "react-select";
import { useRouterState } from "@tanstack/react-router";
@@ -17,9 +18,10 @@ import {
import { ProjectPermissionSub, useProject, useProjectPermission } from "@app/context";
import { ProjectPermissionAppConnectionActions } from "@app/context/ProjectPermissionContext/types";
import { APP_CONNECTION_MAP } from "@app/helpers/appConnections";
-import { PKI_SYNC_CONNECTION_MAP } from "@app/helpers/pkiSyncs";
+import { getPkiSyncConnectionApps, PKI_SYNC_CONNECTION_MAP } from "@app/helpers/pkiSyncs";
import { usePopUp } from "@app/hooks";
-import { useListAvailableAppConnections } from "@app/hooks/api/appConnections";
+import { useListAvailableAppConnectionsForApps } from "@app/hooks/api/appConnections";
+import { AppConnection } from "@app/hooks/api/appConnections/enums";
import { AddAppConnectionModal } from "@app/pages/organization/AppConnections/AppConnectionsPage/components";
import { TPkiSyncForm } from "./schemas/pki-sync-schema";
@@ -28,14 +30,31 @@ type Props = {
onChange?: VoidFunction;
};
+const LDAP_TARGET_FIELDS = [
+ "host",
+ "port",
+ "sslEnabled",
+ "sslRejectUnauthorized",
+ "sslCertificate"
+] as const;
+
export const PkiSyncConnectionField = ({ onChange: callback }: Props) => {
const { permission } = useProjectPermission();
const { control, watch, setValue } = useFormContext<TPkiSyncForm>();
const { popUp, handlePopUpToggle, handlePopUpOpen } = usePopUp(["addConnection"] as const);
+ const [appToCreate, setAppToCreate] = useState<AppConnection | null>(null);
const destination = watch("destination");
const app = PKI_SYNC_CONNECTION_MAP[destination];
+ const apps = getPkiSyncConnectionApps(destination);
+
+ const clearLdapTargetFields = (nextApp?: AppConnection) => {
+ if (nextApp === AppConnection.LDAP) return;
+ LDAP_TARGET_FIELDS.forEach((field) =>
+ setValue(`destinationConfig.${field}` as never, undefined as never, { shouldDirty: true })
+ );
+ };
const { currentProject } = useProject();
@@ -54,19 +73,20 @@ export const PkiSyncConnectionField = ({ onChange: callback }: Props) => {
return pathname;
};
- const { data: availableConnections, isPending } = useListAvailableAppConnections(
- app,
+ const { connections: availableConnections, isPending } = useListAvailableAppConnectionsForApps(
+ apps,
currentProject.id
);
- const connectionName = APP_CONNECTION_MAP[app].name;
+ const connectionLabel =
+ apps.length > 1 ? "Connection" : `${APP_CONNECTION_MAP[app].name} Connection`;
const canCreateConnection = permission.can(
ProjectPermissionAppConnectionActions.Create,
ProjectPermissionSub.AppConnections
);
- const appName = APP_CONNECTION_MAP[PKI_SYNC_CONNECTION_MAP[destination]].name;
+ const appNames = apps.map((accepted) => APP_CONNECTION_MAP[accepted].name).join(" or ");
return (
<>
@@ -76,7 +96,7 @@ export const PkiSyncConnectionField = ({ onChange: callback }: Props) => {
render={({ field: { value, onChange }, fieldState: { error } }) => (
<Field className="mb-4">
<FieldLabel>
- {connectionName} Connection
+ {connectionLabel}
<Tooltip>
<TooltipTrigger asChild>
<Info />
@@ -89,7 +109,13 @@ export const PkiSyncConnectionField = ({ onChange: callback }: Props) => {
<FilterableSelect
value={value}
onChange={(newValue) => {
- if ((newValue as SingleValue<{ id: string; name: string }>)?.id === "_create") {
+ const selected = newValue as SingleValue<{
+ id: string;
+ name: string;
+ app?: AppConnection;
+ }>;
+ if (selected?.id?.startsWith("_create")) {
+ setAppToCreate(selected.app ?? app);
handlePopUpOpen("addConnection");
onChange(null);
const formData = { ...watch(), returnUrl: getPkiSyncReturnUrl() };
@@ -99,22 +125,32 @@ export const PkiSyncConnectionField = ({ onChange: callback }: Props) => {
}
onChange(newValue);
+ clearLdapTargetFields((newValue as SingleValue<{ app?: AppConnection }>)?.app);
if (callback) callback();
}}
isLoading={isPending}
options={[
- ...(canCreateConnection ? [{ id: "_create", name: "Create Connection" }] : []),
- ...(availableConnections ?? [])
+ ...(canCreateConnection
+ ? apps.map((creatable) => ({
+ id: `_create:${creatable}`,
+ name: `Create ${APP_CONNECTION_MAP[creatable].name} Connection`,
+ app: creatable
+ }))
+ : []),
+ ...availableConnections
]}
+ groupBy={apps.length > 1 ? "app" : null}
+ getGroupHeaderLabel={(groupApp: AppConnection) => APP_CONNECTION_MAP[groupApp].name}
placeholder="Select connection..."
getOptionLabel={(option) => option.name}
getOptionValue={(option) => option.id}
components={{ Option: AppConnectionOption }}
isError={Boolean(error)}
/>
- {!isPending && !availableConnections?.length && !canCreateConnection ? (
+ {!isPending && !availableConnections.length && !canCreateConnection ? (
<FieldDescription className="text-warning">
- You do not have access to any {appName} Connections. Contact an admin to create one.
+ You do not have access to any {appNames} Connections. Contact an admin to create
+ one.
</FieldDescription>
) : (
<FieldError errors={[error]} />
@@ -130,10 +166,11 @@ export const PkiSyncConnectionField = ({ onChange: callback }: Props) => {
}}
projectType={currentProject.type}
projectId={currentProject.id}
- app={app}
+ app={appToCreate ?? app}
onComplete={(connection) => {
if (connection) {
setValue("connection", connection);
+ clearLdapTargetFields(connection.app);
}
}}
/>
diff --git a/frontend/src/components/pki-syncs/forms/PkiSyncReviewFields.tsx b/frontend/src/components/pki-syncs/forms/PkiSyncReviewFields.tsx
index 6ca36220fa..ee291b1712 100644
--- a/frontend/src/components/pki-syncs/forms/PkiSyncReviewFields.tsx
+++ b/frontend/src/components/pki-syncs/forms/PkiSyncReviewFields.tsx
@@ -146,6 +146,19 @@ export const PkiSyncReviewFields = () => {
{destinationConfig && "vaultBaseUrl" in destinationConfig && (
<ReviewFieldLabel label="Vault URL">{destinationConfig.vaultBaseUrl}</ReviewFieldLabel>
)}
+ {destinationConfig && "host" in destinationConfig && destinationConfig.host && (
+ <ReviewFieldLabel label="Target Host">
+ {destinationConfig.host}
+ {"port" in destinationConfig && destinationConfig.port
+ ? `:${destinationConfig.port}`
+ : ""}
+ </ReviewFieldLabel>
+ )}
+ {destinationConfig &&
+ "sslEnabled" in destinationConfig &&
+ destinationConfig.sslEnabled && (
+ <ReviewFieldLabel label="WinRM Transport">HTTPS</ReviewFieldLabel>
+ )}
</div>
</div>
<div className="flex flex-col gap-3">
diff --git a/frontend/src/components/pki-syncs/forms/PkiSyncTargetHostField.tsx b/frontend/src/components/pki-syncs/forms/PkiSyncTargetHostField.tsx
new file mode 100644
index 0000000000..dcee519df7
--- /dev/null
+++ b/frontend/src/components/pki-syncs/forms/PkiSyncTargetHostField.tsx
@@ -0,0 +1,223 @@
+import { useState } from "react";
+import { Controller, useFormContext } from "react-hook-form";
+import { Info } from "lucide-react";
+
+import {
+ CreatableSelect,
+ Field,
+ FieldContent,
+ FieldDescription,
+ FieldError,
+ FieldLabel,
+ FieldTitle,
+ Input,
+ Switch,
+ TextArea,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger
+} from "@app/components/v3";
+import { useDebounce } from "@app/hooks";
+import { AppConnection } from "@app/hooks/api/appConnections/enums";
+import { useLdapConnectionListMachines } from "@app/hooks/api/appConnections/ldap";
+import { PkiSync } from "@app/hooks/api/pkiSyncs";
+import { useCanSetTargetHost } from "@app/hooks/api/pkiSyncs/usePkiSyncPermissions";
+
+import { TPkiSyncForm } from "./schemas/pki-sync-schema";
+
+type Props = {
+ applicationId?: string | null;
+};
+
+export const PkiSyncTargetHostField = ({ applicationId }: Props) => {
+ const { control, watch } = useFormContext<
+ TPkiSyncForm & { destination: PkiSync.LinuxServer | PkiSync.WindowsServer }
+ >();
+
+ const connection = watch("connection");
+ const destination = watch("destination");
+ const canSetTargetHost = useCanSetTargetHost(applicationId);
+ const [search, setSearch] = useState("");
+ const [debouncedSearch] = useDebounce(search, 300);
+
+ const isLdapConnection = connection?.app === AppConnection.LDAP;
+ const { sslEnabled } = (watch("destinationConfig") ?? {}) as { sslEnabled?: boolean };
+
+ const {
+ data: machines,
+ isPending,
+ isError
+ } = useLdapConnectionListMachines(connection?.id ?? "", debouncedSearch || undefined, {
+ enabled: isLdapConnection && Boolean(connection?.id)
+ });
+
+ if (!isLdapConnection) return null;
+
+ const windowsPortHint = sslEnabled ? "5986" : "5985";
+ const defaultPortHint = destination === PkiSync.WindowsServer ? windowsPortHint : "22";
+
+ const options = (machines ?? []).map((machine) => ({
+ value: machine.hostname,
+ label: machine.hostname
+ }));
+
+ const hostField = (
+ <Controller
+ name="destinationConfig.host"
+ control={control}
+ render={({ field: { value, onChange }, fieldState: { error } }) => (
+ <Field className="mb-4">
+ <FieldLabel>
+ Target Host
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Info />
+ </TooltipTrigger>
+ <TooltipContent className="max-w-sm">
+ The machine this sync delivers to. The LDAP connection supplies the credential, so
+ one connection can serve many hosts.
+ </TooltipContent>
+ </Tooltip>
+ </FieldLabel>
+ {isError ? (
+ <Input
+ value={value ?? ""}
+ onChange={(event) => onChange(event.target.value)}
+ placeholder="server01.corp.example.com"
+ disabled={!canSetTargetHost}
+ isError={Boolean(error)}
+ />
+ ) : (
+ <CreatableSelect
+ value={value ? { value, label: value } : null}
+ onChange={(newValue) => onChange((newValue as { value: string } | null)?.value ?? "")}
+ onCreateOption={(inputValue) => onChange(inputValue.trim())}
+ onInputChange={(inputValue) => setSearch(inputValue)}
+ options={options}
+ isLoading={isPending}
+ isClearable
+ noOptionsMessage={() => "No machines match search"}
+ placeholder="Select or enter a host..."
+ isDisabled={!canSetTargetHost}
+ isError={Boolean(error)}
+ />
+ )}
+ <FieldError errors={[error]} />
+ {!error && (
+ <FieldDescription>
+ {isError
+ ? "The directory could not be listed, so enter the host name."
+ : "Choose a machine from the directory, or enter a host this sync should reach."}
+ </FieldDescription>
+ )}
+ </Field>
+ )}
+ />
+ );
+
+ return (
+ <>
+ {hostField}
+ <Controller
+ name="destinationConfig.port"
+ control={control}
+ render={({ field: { value, onChange }, fieldState: { error } }) => (
+ <Field className="mb-4">
+ <FieldLabel>Port</FieldLabel>
+ <Input
+ type="number"
+ value={value ?? ""}
+ onChange={(event) =>
+ onChange(event.target.value === "" ? undefined : event.target.value)
+ }
+ placeholder={defaultPortHint}
+ disabled={!canSetTargetHost}
+ isError={Boolean(error)}
+ />
+ <FieldError errors={[error]} />
+ {!error && (
+ <FieldDescription>
+ Leave empty to use {defaultPortHint}. Set a value only if the listener is on a
+ non-standard port.
+ </FieldDescription>
+ )}
+ </Field>
+ )}
+ />
+ {destination === PkiSync.WindowsServer && (
+ <>
+ <Controller
+ name="destinationConfig.sslEnabled"
+ control={control}
+ render={({ field: { value, onChange } }) => (
+ <Field orientation="horizontal" className="mb-4">
+ <FieldContent>
+ <FieldTitle>Enable SSL</FieldTitle>
+ <FieldDescription>
+ Connect over HTTPS. When disabled, HTTP with NTLM message encryption is used and
+ no server certificate is required.
+ </FieldDescription>
+ </FieldContent>
+ <Switch
+ id="target-ssl-enabled"
+ checked={Boolean(value)}
+ onCheckedChange={onChange}
+ disabled={!canSetTargetHost}
+ />
+ </Field>
+ )}
+ />
+ {sslEnabled && (
+ <Controller
+ name="destinationConfig.sslCertificate"
+ control={control}
+ render={({ field: { value, onChange }, fieldState: { error } }) => (
+ <Field className="mb-4">
+ <FieldLabel>SSL Certificate</FieldLabel>
+ <TextArea
+ value={(value as string) ?? ""}
+ onChange={(event) => onChange(event.target.value || undefined)}
+ placeholder={"-----BEGIN CERTIFICATE-----\n...\n-----END CERTIFICATE-----"}
+ disabled={!canSetTargetHost}
+ isError={Boolean(error)}
+ className="min-h-32"
+ />
+ <FieldError errors={[error]} />
+ {!error && (
+ <FieldDescription>
+ Leave empty to verify against the system trust store, or paste the
+ listener&apos;s certificate to verify a self-signed WinRM HTTPS listener.
+ </FieldDescription>
+ )}
+ </Field>
+ )}
+ />
+ )}
+ {sslEnabled && (
+ <Controller
+ name="destinationConfig.sslRejectUnauthorized"
+ control={control}
+ render={({ field: { value, onChange } }) => (
+ <Field orientation="horizontal" className="mb-4">
+ <FieldContent>
+ <FieldTitle>Reject Unauthorized</FieldTitle>
+ <FieldDescription>
+ If enabled, Infisical only connects when the listener presents a valid,
+ trusted certificate.
+ </FieldDescription>
+ </FieldContent>
+ <Switch
+ disabled={!canSetTargetHost}
+ id="target-ssl-reject-unauthorized"
+ checked={value !== false}
+ onCheckedChange={onChange}
+ />
+ </Field>
+ )}
+ />
+ )}
+ </>
+ )}
+ </>
+ );
+};
diff --git a/frontend/src/components/pki-syncs/forms/schemas/base-pki-sync-schema.ts b/frontend/src/components/pki-syncs/forms/schemas/base-pki-sync-schema.ts
index da8f07ddea..e99a1472d7 100644
--- a/frontend/src/components/pki-syncs/forms/schemas/base-pki-sync-schema.ts
+++ b/frontend/src/components/pki-syncs/forms/schemas/base-pki-sync-schema.ts
@@ -1,5 +1,7 @@
import { AnyZodObject, z } from "zod";
+import { AppConnection } from "@app/hooks/api/appConnections/enums";
+
export const HOST_COMMAND_MAX_LENGTH = 8192;
export const HostCommandSchema = z
@@ -9,6 +11,37 @@ export const HostCommandSchema = z
.nullish()
.transform((command) => command || null);
+export const PkiSyncConnectionSchema = z.object({
+ id: z.string().uuid("Invalid connection ID format"),
+ name: z.string().max(255, "Connection name must be less than 255 characters"),
+ app: z.nativeEnum(AppConnection).optional()
+});
+
+export const PkiSyncTargetPortSchema = z.coerce
+ .number()
+ .int()
+ .min(1, "Port must be between 1 and 65535")
+ .max(65535, "Port must be between 1 and 65535")
+ .optional();
+
+export const PkiSyncTargetHostSchema = z
+ .string()
+ .trim()
+ .max(253, "Target host is too long")
+ .refine(
+ (value) =>
+ !value ||
+ /^[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(
+ value
+ ),
+ {
+ message:
+ "Target host must be a hostname or IP address (for example server01.corp.example.com or 10.0.0.5)"
+ }
+ )
+ .transform((value) => value || undefined)
+ .optional();
+
export const BasePkiSyncSchema = <T extends AnyZodObject | undefined = undefined>(
additionalSyncOptions?: T
) => {
@@ -69,10 +102,7 @@ export const BasePkiSyncSchema = <T extends AnyZodObject | undefined = undefined
isAutoSyncEnabled: z.boolean().default(true),
subscriberId: z.string().nullable().optional(),
certificateIds: z.array(z.string()).optional(),
- connection: z.object({
- id: z.string().uuid("Invalid connection ID format"),
- name: z.string().max(255, "Connection name must be less than 255 characters")
- }),
+ connection: PkiSyncConnectionSchema,
syncOptions: syncOptionsSchema
});
};
diff --git a/frontend/src/components/pki-syncs/forms/schemas/linux-server-pki-sync-destination-schema.ts b/frontend/src/components/pki-syncs/forms/schemas/linux-server-pki-sync-destination-schema.ts
index aa0618ed79..b10900232a 100644
--- a/frontend/src/components/pki-syncs/forms/schemas/linux-server-pki-sync-destination-schema.ts
+++ b/frontend/src/components/pki-syncs/forms/schemas/linux-server-pki-sync-destination-schema.ts
@@ -2,7 +2,13 @@ import { z } from "zod";
import { PemCertificateExtension, PkiSync, PkiSyncExportFormat } from "@app/hooks/api/pkiSyncs";
-import { BasePkiSyncSchema, HostCommandSchema } from "./base-pki-sync-schema";
+import {
+ BasePkiSyncSchema,
+ HostCommandSchema,
+ PkiSyncConnectionSchema,
+ PkiSyncTargetHostSchema,
+ PkiSyncTargetPortSchema
+} from "./base-pki-sync-schema";
const compileNameSchema = (val: string) =>
val
@@ -88,7 +94,9 @@ export const LinuxServerPkiSyncDestinationSchema = BasePkiSyncSchema(
z.object({
destination: z.literal(PkiSync.LinuxServer),
destinationConfig: z.object({
- destinationPath: DestinationPathSchema
+ destinationPath: DestinationPathSchema,
+ host: PkiSyncTargetHostSchema,
+ port: PkiSyncTargetPortSchema
}),
credentials: z
.object({
@@ -107,12 +115,6 @@ export const UpdateLinuxServerPkiSyncDestinationSchema =
.min(1, "Name is required")
.max(255, "Name must be less than 255 characters"),
destination: z.literal(PkiSync.LinuxServer),
- connection: z.object({
- id: z.string().uuid("Invalid connection ID format"),
- name: z
- .string()
- .min(1, "Connection name is required")
- .max(255, "Connection name must be less than 255 characters")
- })
+ connection: PkiSyncConnectionSchema
})
);
diff --git a/frontend/src/components/pki-syncs/forms/schemas/pki-sync-schema.ts b/frontend/src/components/pki-syncs/forms/schemas/pki-sync-schema.ts
index b81ec13014..5dc810bab6 100644
--- a/frontend/src/components/pki-syncs/forms/schemas/pki-sync-schema.ts
+++ b/frontend/src/components/pki-syncs/forms/schemas/pki-sync-schema.ts
@@ -1,5 +1,6 @@
import { z } from "zod";
+import { AppConnection } from "@app/hooks/api/appConnections/enums";
import { PkiSync, PkiSyncExportFormat } from "@app/hooks/api/pkiSyncs";
import {
@@ -81,6 +82,32 @@ const UpdatePkiSyncUnionSchema = z.discriminatedUnion("destination", [
UpdateNutanixPrismCentralPkiSyncDestinationSchema
]);
+const refineTargetHost = (data: unknown, ctx: z.RefinementCtx) => {
+ const { connection, destinationConfig } = data as {
+ connection?: { app?: AppConnection };
+ destinationConfig?: { host?: string };
+ };
+
+ if (!connection?.app) return;
+
+ if (connection.app === AppConnection.LDAP && !destinationConfig?.host) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ["destinationConfig", "host"],
+ message: "A target host is required when using an LDAP connection"
+ });
+ return;
+ }
+
+ if (connection.app !== AppConnection.LDAP && destinationConfig?.host) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ path: ["destinationConfig", "host"],
+ message: "A target host cannot be set when the connection already targets a single host"
+ });
+ }
+};
+
export const PkiSyncFormSchema = PkiSyncUnionSchema.superRefine((data, ctx) => {
if (
(data.destination === PkiSync.WindowsServer || data.destination === PkiSync.LinuxServer) &&
@@ -93,9 +120,11 @@ export const PkiSyncFormSchema = PkiSyncUnionSchema.superRefine((data, ctx) => {
message: "A password is required for PKCS#12 exports"
});
}
+
+ refineTargetHost(data, ctx);
});
-export const UpdatePkiSyncFormSchema = UpdatePkiSyncUnionSchema;
+export const UpdatePkiSyncFormSchema = UpdatePkiSyncUnionSchema.superRefine(refineTargetHost);
export type TPkiSyncForm = z.infer<typeof PkiSyncFormSchema>;
diff --git a/frontend/src/components/pki-syncs/forms/schemas/windows-server-pki-sync-destination-schema.ts b/frontend/src/components/pki-syncs/forms/schemas/windows-server-pki-sync-destination-schema.ts
index 5037766d08..4ad3083464 100644
--- a/frontend/src/components/pki-syncs/forms/schemas/windows-server-pki-sync-destination-schema.ts
+++ b/frontend/src/components/pki-syncs/forms/schemas/windows-server-pki-sync-destination-schema.ts
@@ -7,7 +7,13 @@ import {
WindowsFileAccess
} from "@app/hooks/api/pkiSyncs";
-import { BasePkiSyncSchema, HostCommandSchema } from "./base-pki-sync-schema";
+import {
+ BasePkiSyncSchema,
+ HostCommandSchema,
+ PkiSyncConnectionSchema,
+ PkiSyncTargetHostSchema,
+ PkiSyncTargetPortSchema
+} from "./base-pki-sync-schema";
const compileNameSchema = (val: string) =>
val
@@ -74,7 +80,12 @@ export const WindowsServerPkiSyncDestinationSchema = BasePkiSyncSchema(
z.object({
destination: z.literal(PkiSync.WindowsServer),
destinationConfig: z.object({
- destinationPath: WindowsDestinationPathSchema
+ destinationPath: WindowsDestinationPathSchema,
+ host: PkiSyncTargetHostSchema,
+ port: PkiSyncTargetPortSchema,
+ sslEnabled: z.boolean().optional(),
+ sslRejectUnauthorized: z.boolean().optional(),
+ sslCertificate: z.string().trim().max(8192).optional()
}),
credentials: z
.object({
@@ -93,12 +104,6 @@ export const UpdateWindowsServerPkiSyncDestinationSchema =
.min(1, "Name is required")
.max(255, "Name must be less than 255 characters"),
destination: z.literal(PkiSync.WindowsServer),
- connection: z.object({
- id: z.string().uuid("Invalid connection ID format"),
- name: z
- .string()
- .min(1, "Connection name is required")
- .max(255, "Connection name must be less than 255 characters")
- })
+ connection: PkiSyncConnectionSchema
})
);
diff --git a/frontend/src/context/ProjectPermissionContext/types.ts b/frontend/src/context/ProjectPermissionContext/types.ts
index f77ff58ea8..7d900de424 100644
--- a/frontend/src/context/ProjectPermissionContext/types.ts
+++ b/frontend/src/context/ProjectPermissionContext/types.ts
@@ -78,6 +78,7 @@ export enum ProjectPermissionPkiSyncActions {
ImportCertificates = "import-certificates",
RemoveCertificates = "remove-certificates",
SetPostSyncCommand = "set-post-sync-command",
+ SetTargetHost = "set-target-host",
SetHealthCheckCommand = "set-health-check-command"
}
diff --git a/frontend/src/helpers/pkiSyncs.ts b/frontend/src/helpers/pkiSyncs.ts
index a593cdce2b..3d94bd288c 100644
--- a/frontend/src/helpers/pkiSyncs.ts
+++ b/frontend/src/helpers/pkiSyncs.ts
@@ -126,6 +126,16 @@ export const PKI_SYNC_CONNECTION_MAP: Record<PkiSync, AppConnection> = {
[PkiSync.NutanixPrismCentral]: AppConnection.NutanixPrismCentral
};
+const PKI_SYNC_ADDITIONAL_CONNECTION_MAP: Partial<Record<PkiSync, AppConnection[]>> = {
+ [PkiSync.LinuxServer]: [AppConnection.LDAP],
+ [PkiSync.WindowsServer]: [AppConnection.LDAP]
+};
+
+export const getPkiSyncConnectionApps = (destination: PkiSync): AppConnection[] => [
+ PKI_SYNC_CONNECTION_MAP[destination],
+ ...(PKI_SYNC_ADDITIONAL_CONNECTION_MAP[destination] ?? [])
+];
+
export const BOOLEAN_SYNC_OPTION_FIELDS = [
{ key: "canRemoveCertificates", label: "Remove Expired/Revoked Certificates" },
{ key: "canImportCertificates", label: "Import Certificates" },
diff --git a/frontend/src/hooks/api/appConnections/ldap/index.ts b/frontend/src/hooks/api/appConnections/ldap/index.ts
new file mode 100644
index 0000000000..b69c251208
--- /dev/null
+++ b/frontend/src/hooks/api/appConnections/ldap/index.ts
@@ -0,0 +1 @@
+export * from "./queries";
diff --git a/frontend/src/hooks/api/appConnections/ldap/queries.tsx b/frontend/src/hooks/api/appConnections/ldap/queries.tsx
new file mode 100644
index 0000000000..ab25c3e764
--- /dev/null
+++ b/frontend/src/hooks/api/appConnections/ldap/queries.tsx
@@ -0,0 +1,43 @@
+import { useQuery, UseQueryOptions } from "@tanstack/react-query";
+
+import { apiRequest } from "@app/config/request";
+
+import { appConnectionKeys } from "../queries";
+
+export type TLdapDirectoryMachine = {
+ hostname: string;
+};
+
+const ldapConnectionKeys = {
+ all: [...appConnectionKeys.all, "ldap"] as const,
+ listMachines: (connectionId: string, search?: string) =>
+ [...ldapConnectionKeys.all, "machines", connectionId, ...(search ? [search] : [])] as const
+};
+
+export const useLdapConnectionListMachines = (
+ connectionId: string,
+ search?: string,
+ options?: Omit<
+ UseQueryOptions<
+ TLdapDirectoryMachine[],
+ unknown,
+ TLdapDirectoryMachine[],
+ ReturnType<typeof ldapConnectionKeys.listMachines>
+ >,
+ "queryKey" | "queryFn"
+ >
+) => {
+ return useQuery({
+ placeholderData: (previous) => previous,
+ queryKey: ldapConnectionKeys.listMachines(connectionId, search),
+ queryFn: async () => {
+ const { data } = await apiRequest.get<{ machines: TLdapDirectoryMachine[] }>(
+ `/api/v1/app-connections/ldap/${connectionId}/machines`,
+ { params: { ...(search ? { search } : {}) } }
+ );
+
+ return data.machines;
+ },
+ ...options
+ });
+};
diff --git a/frontend/src/hooks/api/appConnections/queries.tsx b/frontend/src/hooks/api/appConnections/queries.tsx
index a27ffdc107..96354b01ec 100644
--- a/frontend/src/hooks/api/appConnections/queries.tsx
+++ b/frontend/src/hooks/api/appConnections/queries.tsx
@@ -1,5 +1,5 @@
import { useMemo } from "react";
-import { useQuery, UseQueryOptions } from "@tanstack/react-query";
+import { useQueries, useQuery, UseQueryOptions } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request";
import { AppConnection } from "@app/hooks/api/appConnections/enums";
@@ -97,6 +97,31 @@ export const useListAppConnections = (
});
};
+const fetchAvailableAppConnections = async (app: AppConnection, projectId: string) => {
+ const { data } = await apiRequest.get<TAvailableAppConnectionsResponse>(
+ `/api/v1/app-connections/${app}/available`,
+ { params: { projectId } }
+ );
+
+ return data.appConnections;
+};
+
+export const useListAvailableAppConnectionsForApps = (apps: AppConnection[], projectId: string) => {
+ const results = useQueries({
+ queries: apps.map((app) => ({
+ queryKey: appConnectionKeys.listAvailable(app, projectId),
+ queryFn: () => fetchAvailableAppConnections(app, projectId)
+ }))
+ });
+
+ return {
+ connections: apps.flatMap((app, index) =>
+ (results[index].data ?? []).map((connection) => ({ ...connection, app }))
+ ),
+ isPending: results.some((result) => result.isPending)
+ };
+};
+
export const useListAvailableAppConnections = (
app: AppConnection,
projectId: string,
@@ -112,14 +137,7 @@ export const useListAvailableAppConnections = (
) => {
return useQuery({
queryKey: appConnectionKeys.listAvailable(app, projectId),
- queryFn: async () => {
- const { data } = await apiRequest.get<TAvailableAppConnectionsResponse>(
- `/api/v1/app-connections/${app}/available`,
- { params: { projectId } }
- );
-
- return data.appConnections;
- },
+ queryFn: () => fetchAvailableAppConnections(app, projectId),
...options
});
};
diff --git a/frontend/src/hooks/api/pkiApplications/types.ts b/frontend/src/hooks/api/pkiApplications/types.ts
index c1696aec8f..a4ab915fe6 100644
--- a/frontend/src/hooks/api/pkiApplications/types.ts
+++ b/frontend/src/hooks/api/pkiApplications/types.ts
@@ -32,6 +32,7 @@ export enum PkiApplicationResourceActions {
ImportCertificates = "import-certificates",
RemoveCertificates = "remove-certificates",
SetPostSyncCommand = "set-post-sync-command",
+ SetTargetHost = "set-target-host",
SetHealthCheckCommand = "set-health-check-command",
RevealAcmeEabSecret = "reveal-acme-eab-secret",
RotateAcmeEabSecret = "rotate-acme-eab-secret",
diff --git a/frontend/src/hooks/api/pkiSyncs/types/linux-server-sync.ts b/frontend/src/hooks/api/pkiSyncs/types/linux-server-sync.ts
index 8f8d6f13c6..4fe6fef859 100644
--- a/frontend/src/hooks/api/pkiSyncs/types/linux-server-sync.ts
+++ b/frontend/src/hooks/api/pkiSyncs/types/linux-server-sync.ts
@@ -7,6 +7,8 @@ export type TLinuxServerPkiSync = TRootPkiSync & {
destination: PkiSync.LinuxServer;
destinationConfig: {
destinationPath: string;
+ host?: string;
+ port?: number;
};
syncOptions: TRootPkiSync["syncOptions"] & {
exportFormat?: PkiSyncExportFormat;
@@ -21,7 +23,7 @@ export type TLinuxServerPkiSync = TRootPkiSync & {
postSyncCommand?: string | null;
};
connection: {
- app: AppConnection.SSH;
+ app: AppConnection;
name: string;
id: string;
};
diff --git a/frontend/src/hooks/api/pkiSyncs/types/windows-server-sync.ts b/frontend/src/hooks/api/pkiSyncs/types/windows-server-sync.ts
index e6ea11ea7e..9ae7189340 100644
--- a/frontend/src/hooks/api/pkiSyncs/types/windows-server-sync.ts
+++ b/frontend/src/hooks/api/pkiSyncs/types/windows-server-sync.ts
@@ -7,6 +7,11 @@ export type TWindowsServerPkiSync = TRootPkiSync & {
destination: PkiSync.WindowsServer;
destinationConfig: {
destinationPath: string;
+ host?: string;
+ port?: number;
+ sslEnabled?: boolean;
+ sslRejectUnauthorized?: boolean;
+ sslCertificate?: string;
};
syncOptions: TRootPkiSync["syncOptions"] & {
exportFormat?: PkiSyncExportFormat;
@@ -18,7 +23,7 @@ export type TWindowsServerPkiSync = TRootPkiSync & {
postSyncCommand?: string | null;
};
connection: {
- app: AppConnection.WinRM;
+ app: AppConnection;
name: string;
id: string;
};
diff --git a/frontend/src/hooks/api/pkiSyncs/usePkiSyncPermissions.ts b/frontend/src/hooks/api/pkiSyncs/usePkiSyncPermissions.ts
index 3b0f92b050..a8be04c580 100644
--- a/frontend/src/hooks/api/pkiSyncs/usePkiSyncPermissions.ts
+++ b/frontend/src/hooks/api/pkiSyncs/usePkiSyncPermissions.ts
@@ -8,7 +8,7 @@ import {
} from "../pkiApplications";
import { TPkiSync } from "./types";
-const useCanSetHostCommand = (
+const useCanPerformSyncAction = (
action: PkiApplicationResourceActions,
projectAction: ProjectPermissionPkiSyncActions,
applicationId?: string | null
@@ -24,14 +24,21 @@ const useCanSetHostCommand = (
};
export const useCanSetPostSyncCommand = (applicationId?: string | null) =>
- useCanSetHostCommand(
+ useCanPerformSyncAction(
PkiApplicationResourceActions.SetPostSyncCommand,
ProjectPermissionPkiSyncActions.SetPostSyncCommand,
applicationId
);
+export const useCanSetTargetHost = (applicationId?: string | null) =>
+ useCanPerformSyncAction(
+ PkiApplicationResourceActions.SetTargetHost,
+ ProjectPermissionPkiSyncActions.SetTargetHost,
+ applicationId
+ );
+
export const useCanSetHealthCheckCommand = (applicationId?: string | null) =>
- useCanSetHostCommand(
+ useCanPerformSyncAction(
PkiApplicationResourceActions.SetHealthCheckCommand,
ProjectPermissionPkiSyncActions.SetHealthCheckCommand,
applicationId
diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection/LinuxServerPkiSyncDestinationSection.tsx b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection/LinuxServerPkiSyncDestinationSection.tsx
index 873572c6cd..eca2d02729 100644
--- a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection/LinuxServerPkiSyncDestinationSection.tsx
+++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection/LinuxServerPkiSyncDestinationSection.tsx
@@ -11,6 +11,15 @@ export const LinuxServerPkiSyncDestinationSection = ({ pkiSync }: Props) => {
return (
<>
+ {pkiSync.destinationConfig.host && (
+ <Detail>
+ <DetailLabel>Target Host</DetailLabel>
+ <DetailValue>
+ {pkiSync.destinationConfig.host}
+ {pkiSync.destinationConfig.port ? `:${pkiSync.destinationConfig.port}` : ""}
+ </DetailValue>
+ </Detail>
+ )}
<Detail>
<DetailLabel>Destination Directory</DetailLabel>
<DetailValue>{pkiSync.destinationConfig.destinationPath}</DetailValue>
diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection/WindowsServerPkiSyncDestinationSection.tsx b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection/WindowsServerPkiSyncDestinationSection.tsx
index d44175bfb9..dd104d2372 100644
--- a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection/WindowsServerPkiSyncDestinationSection.tsx
+++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncDestinationSection/WindowsServerPkiSyncDestinationSection.tsx
@@ -11,6 +11,21 @@ export const WindowsServerPkiSyncDestinationSection = ({ pkiSync }: Props) => {
return (
<>
+ {pkiSync.destinationConfig.host && (
+ <Detail>
+ <DetailLabel>Target Host</DetailLabel>
+ <DetailValue>
+ {pkiSync.destinationConfig.host}
+ {pkiSync.destinationConfig.port ? `:${pkiSync.destinationConfig.port}` : ""}
+ </DetailValue>
+ </Detail>
+ )}
+ {pkiSync.destinationConfig.sslEnabled && (
+ <Detail>
+ <DetailLabel>WinRM Transport</DetailLabel>
+ <DetailValue>HTTPS</DetailValue>
+ </Detail>
+ )}
<Detail>
<DetailLabel>Destination Directory</DetailLabel>
<DetailValue>{pkiSync.destinationConfig.destinationPath}</DetailValue>
diff --git a/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx b/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx
index e55cc6035f..f5ef3a8af5 100644
--- a/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx
+++ b/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx
@@ -169,6 +169,7 @@ const PkiSyncPolicyActionSchema = z.object({
[ProjectPermissionPkiSyncActions.ImportCertificates]: z.boolean().optional(),
[ProjectPermissionPkiSyncActions.RemoveCertificates]: z.boolean().optional(),
[ProjectPermissionPkiSyncActions.SetPostSyncCommand]: z.boolean().optional(),
+ [ProjectPermissionPkiSyncActions.SetTargetHost]: z.boolean().optional(),
[ProjectPermissionPkiSyncActions.SetHealthCheckCommand]: z.boolean().optional()
});
@@ -1114,6 +1115,7 @@ export const rolePermission2Form = (permissions: TProjectPermission[] = []) => {
const canSetHealthCheckCommand = action.includes(
ProjectPermissionPkiSyncActions.SetHealthCheckCommand
);
+ const canSetTargetHost = action.includes(ProjectPermissionPkiSyncActions.SetTargetHost);
if (!formVal[subject]) formVal[subject] = [{ conditions: [], inverted: false }];
@@ -1128,6 +1130,7 @@ export const rolePermission2Form = (permissions: TProjectPermission[] = []) => {
[ProjectPermissionPkiSyncActions.RemoveCertificates]: canRemoveCertificates,
[ProjectPermissionPkiSyncActions.SetPostSyncCommand]: canSetPostSyncCommand,
[ProjectPermissionPkiSyncActions.SetHealthCheckCommand]: canSetHealthCheckCommand,
+ [ProjectPermissionPkiSyncActions.SetTargetHost]: canSetTargetHost,
conditions: conditions ? convertCaslConditionToFormOperator(conditions) : [],
inverted
});
@@ -2914,6 +2917,11 @@ export const PROJECT_PERMISSION_OBJECT: TProjectPermissionObject = {
label: "Set Post-Sync Command",
value: ProjectPermissionPkiSyncActions.SetPostSyncCommand,
description: "Set the command a sync runs on the destination host after delivering"
+ },
+ {
+ label: "Set Target Host",
+ value: ProjectPermissionPkiSyncActions.SetTargetHost,
+ description: "Choose which host a sync delivers to when using an LDAP connection"
}
]
},