Skip to content

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

improvements: add validations to ssh dynamic secret creation

adilson43020ebdc842
diff --git a/backend/src/ee/services/dynamic-secret/dynamic-secret-service.ts b/backend/src/ee/services/dynamic-secret/dynamic-secret-service.ts
index f9c5195e69..3230435373 100644
--- a/backend/src/ee/services/dynamic-secret/dynamic-secret-service.ts
+++ b/backend/src/ee/services/dynamic-secret/dynamic-secret-service.ts
@@ -369,7 +369,10 @@ export const dynamicSecretServiceFactory = ({
throw error;
}
}
- const updatedInput = await selectedProvider.validateProviderInputs(newInput, { projectId });
+ const updatedInput = await selectedProvider.validateProviderInputs(newInput, {
+ projectId,
+ previousInputs: decryptedStoredInput
+ });
const updatedFields = getUpdatedFieldPaths(
{
diff --git a/backend/src/ee/services/dynamic-secret/providers/models.test.ts b/backend/src/ee/services/dynamic-secret/providers/models.test.ts
index 7d4681b091..a1094a4f60 100644
--- a/backend/src/ee/services/dynamic-secret/providers/models.test.ts
+++ b/backend/src/ee/services/dynamic-secret/providers/models.test.ts
@@ -2,14 +2,20 @@ import { describe, expect, test } from "vitest";
import { SshCertKeyAlgorithm } from "@app/lib/ssh";
-import { DYNAMIC_SECRET_SECRET_FIELDS, DynamicSecretProviders, redactStoredInputs } from "./models";
+import {
+ DYNAMIC_SECRET_SECRET_FIELDS,
+ DynamicSecretProviders,
+ DynamicSecretSshSchema,
+ redactStoredInputs
+} from "./models";
describe("redactStoredInputs", () => {
const sshStoredInputs = {
caPrivateKey: "-----BEGIN OPENSSH PRIVATE KEY-----\nca-key-material\n-----END OPENSSH PRIVATE KEY-----",
caPublicKey: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5 ca@infisical",
principals: ["ubuntu"],
- keyAlgorithm: SshCertKeyAlgorithm.ED25519
+ keyAlgorithm: SshCertKeyAlgorithm.ED25519,
+ caKeyAlgorithm: SshCertKeyAlgorithm.ED25519
};
test("withholds the SSH CA private key and keeps the rest of the configuration", () => {
@@ -18,7 +24,8 @@ describe("redactStoredInputs", () => {
expect(redacted).toStrictEqual({
caPublicKey: sshStoredInputs.caPublicKey,
principals: sshStoredInputs.principals,
- keyAlgorithm: SshCertKeyAlgorithm.ED25519
+ keyAlgorithm: SshCertKeyAlgorithm.ED25519,
+ caKeyAlgorithm: SshCertKeyAlgorithm.ED25519
});
expect(JSON.stringify(redacted)).not.toContain("ca-key-material");
});
@@ -40,3 +47,38 @@ describe("redactStoredInputs", () => {
expect(declared).toStrictEqual(Object.values(DynamicSecretProviders).sort());
});
});
+
+describe("DynamicSecretSshSchema", () => {
+ test("accepts a supported cert algorithm value", () => {
+ expect(
+ DynamicSecretSshSchema.parse({
+ principals: ["ubuntu"],
+ keyAlgorithm: SshCertKeyAlgorithm.ECDSA_P256,
+ caKeyAlgorithm: SshCertKeyAlgorithm.RSA_2048
+ })
+ ).toMatchObject({
+ keyAlgorithm: SshCertKeyAlgorithm.ECDSA_P256,
+ caKeyAlgorithm: SshCertKeyAlgorithm.RSA_2048
+ });
+ });
+
+ test("rejects a TypeScript enum key that is not an algorithm value", () => {
+ expect(() =>
+ DynamicSecretSshSchema.parse({
+ principals: ["ubuntu"],
+ keyAlgorithm: "ECDSA_P256",
+ caKeyAlgorithm: SshCertKeyAlgorithm.ED25519
+ })
+ ).toThrow();
+ });
+
+ test("rejects an OpenSSH public key type in place of a cert algorithm", () => {
+ expect(() =>
+ DynamicSecretSshSchema.parse({
+ principals: ["ubuntu"],
+ keyAlgorithm: "ssh-ed25519",
+ caKeyAlgorithm: SshCertKeyAlgorithm.ED25519
+ })
+ ).toThrow();
+ });
+});
diff --git a/backend/src/ee/services/dynamic-secret/providers/models.ts b/backend/src/ee/services/dynamic-secret/providers/models.ts
index b73c92f258..4b3385d0e7 100644
--- a/backend/src/ee/services/dynamic-secret/providers/models.ts
+++ b/backend/src/ee/services/dynamic-secret/providers/models.ts
@@ -2,7 +2,7 @@ import RE2 from "re2";
import { z } from "zod";
import { TDynamicSecrets } from "@app/db/schemas";
-import { SshCertKeyAlgorithm } from "@app/lib/ssh";
+import { SSH_CERT_KEY_ALGORITHMS, SshCertKeyAlgorithm } from "@app/lib/ssh";
import { CharacterType, characterValidator } from "@app/lib/validator/validate-string";
import { ResourceMetadataNonEncryptionSchema } from "@app/services/resource-metadata/resource-metadata-schema";
import { TConstraints } from "@app/services/secret-validation-rule/secret-validation-rule-types";
@@ -975,14 +975,16 @@ export const DynamicSecretTailscaleSchema = z
export const DynamicSecretSshSchema = z.object({
principals: z.array(z.string().trim().min(1)).min(1),
- keyAlgorithm: z.nativeEnum(SshCertKeyAlgorithm).default(SshCertKeyAlgorithm.ED25519)
+ keyAlgorithm: z.enum(SSH_CERT_KEY_ALGORITHMS).default(SshCertKeyAlgorithm.ED25519),
+ caKeyAlgorithm: z.enum(SSH_CERT_KEY_ALGORITHMS).default(SshCertKeyAlgorithm.ED25519)
});
export const SshStoredSchema = z.object({
caPrivateKey: z.string(),
caPublicKey: z.string(),
principals: z.array(z.string().trim().min(1)).min(1),
- keyAlgorithm: z.nativeEnum(SshCertKeyAlgorithm)
+ keyAlgorithm: z.enum(SSH_CERT_KEY_ALGORITHMS),
+ caKeyAlgorithm: z.enum(SSH_CERT_KEY_ALGORITHMS).default(SshCertKeyAlgorithm.ED25519)
});
export const DYNAMIC_SECRET_SECRET_FIELDS: Record<DynamicSecretProviders, readonly string[]> = {
@@ -1068,6 +1070,11 @@ export type TDynamicProviderCreateMetadata = {
};
};
+export type TDynamicProviderValidateMetadata = {
+ projectId: string;
+ previousInputs?: object;
+};
+
export type TDynamicProviderFns = {
create: (arg: {
inputs: unknown;
@@ -1079,7 +1086,7 @@ export type TDynamicProviderFns = {
config?: TDynamicSecretLeaseConfig;
}) => Promise<{ entityId: string; data: unknown }>;
validateConnection: (inputs: unknown, metadata: { projectId: string }) => Promise<boolean>;
- validateProviderInputs: (inputs: object, metadata: { projectId: string }) => Promise<unknown>;
+ validateProviderInputs: (inputs: object, metadata: TDynamicProviderValidateMetadata) => Promise<unknown>;
revoke: (
inputs: unknown,
entityId: string,
diff --git a/backend/src/ee/services/dynamic-secret/providers/ssh.test.ts b/backend/src/ee/services/dynamic-secret/providers/ssh.test.ts
new file mode 100644
index 0000000000..7ba068cc0c
--- /dev/null
+++ b/backend/src/ee/services/dynamic-secret/providers/ssh.test.ts
@@ -0,0 +1,200 @@
+import { beforeEach, describe, expect, test, vi } from "vitest";
+
+import { TDynamicSecrets } from "@app/db/schemas";
+import { BadRequestError } from "@app/lib/errors";
+import { ms } from "@app/lib/ms";
+import { createSshKeyPair, SshCertKeyAlgorithm } from "@app/lib/ssh";
+
+import { SshProvider } from "./ssh";
+
+vi.mock("@app/lib/ssh", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@app/lib/ssh")>()),
+ createSshKeyPair: vi.fn()
+}));
+
+const mockedCreateSshKeyPair = vi.mocked(createSshKeyPair);
+
+const metadata = { projectId: "proj-1" };
+
+const existingCa = {
+ caPrivateKey: "-----BEGIN OPENSSH PRIVATE KEY-----\nstored-ca\n-----END OPENSSH PRIVATE KEY-----",
+ caPublicKey: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5 stored-ca"
+};
+
+const rsaCa = {
+ caPrivateKey: "-----BEGIN OPENSSH PRIVATE KEY-----\nrsa-2048\n-----END OPENSSH PRIVATE KEY-----",
+ caPublicKey: "ssh-rsa AAAAB3NzaC1yc2E stored-ca"
+};
+
+describe("SshProvider.validateProviderInputs", () => {
+ beforeEach(() => {
+ mockedCreateSshKeyPair.mockReset();
+ mockedCreateSshKeyPair.mockResolvedValue({
+ privateKey: "-----BEGIN OPENSSH PRIVATE KEY-----\nnew-ca\n-----END OPENSSH PRIVATE KEY-----",
+ publicKey: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5 new-ca"
+ });
+ });
+
+ test("generates a CA with the requested algorithm on first create", async () => {
+ const provider = SshProvider();
+
+ const result = await provider.validateProviderInputs(
+ {
+ principals: ["ubuntu"],
+ keyAlgorithm: SshCertKeyAlgorithm.ED25519,
+ caKeyAlgorithm: SshCertKeyAlgorithm.RSA_2048
+ },
+ metadata
+ );
+
+ expect(mockedCreateSshKeyPair).toHaveBeenCalledOnce();
+ expect(mockedCreateSshKeyPair).toHaveBeenCalledWith(SshCertKeyAlgorithm.RSA_2048);
+ expect(result).toMatchObject({
+ caPrivateKey: "-----BEGIN OPENSSH PRIVATE KEY-----\nnew-ca\n-----END OPENSSH PRIVATE KEY-----",
+ caPublicKey: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5 new-ca",
+ principals: ["ubuntu"],
+ keyAlgorithm: SshCertKeyAlgorithm.ED25519,
+ caKeyAlgorithm: SshCertKeyAlgorithm.RSA_2048
+ });
+ });
+
+ test("reuses the stored CA when the algorithm is unchanged", async () => {
+ const provider = SshProvider();
+
+ const result = await provider.validateProviderInputs(
+ {
+ ...existingCa,
+ principals: ["ubuntu"],
+ keyAlgorithm: SshCertKeyAlgorithm.ED25519,
+ caKeyAlgorithm: SshCertKeyAlgorithm.ED25519
+ },
+ metadata
+ );
+
+ expect(mockedCreateSshKeyPair).not.toHaveBeenCalled();
+ expect(result).toMatchObject({
+ caPrivateKey: existingCa.caPrivateKey,
+ caPublicKey: existingCa.caPublicKey,
+ caKeyAlgorithm: SshCertKeyAlgorithm.ED25519
+ });
+ });
+
+ test("regenerates the CA when the algorithm changes", async () => {
+ const provider = SshProvider();
+
+ const result = await provider.validateProviderInputs(
+ {
+ ...existingCa,
+ principals: ["ubuntu"],
+ keyAlgorithm: SshCertKeyAlgorithm.ED25519,
+ caKeyAlgorithm: SshCertKeyAlgorithm.RSA_4096
+ },
+ { ...metadata, previousInputs: { ...existingCa, caKeyAlgorithm: SshCertKeyAlgorithm.ED25519 } }
+ );
+
+ expect(mockedCreateSshKeyPair).toHaveBeenCalledOnce();
+ expect(mockedCreateSshKeyPair).toHaveBeenCalledWith(SshCertKeyAlgorithm.RSA_4096);
+ expect(result).toMatchObject({
+ caPrivateKey: "-----BEGIN OPENSSH PRIVATE KEY-----\nnew-ca\n-----END OPENSSH PRIVATE KEY-----",
+ caPublicKey: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5 new-ca",
+ caKeyAlgorithm: SshCertKeyAlgorithm.RSA_4096
+ });
+ });
+
+ test("treats a legacy stored secret without caKeyAlgorithm as ED25519 and does not regenerate", async () => {
+ const provider = SshProvider();
+
+ const result = await provider.validateProviderInputs(
+ {
+ ...existingCa,
+ principals: ["ubuntu"],
+ keyAlgorithm: SshCertKeyAlgorithm.ED25519
+ },
+ { ...metadata, previousInputs: existingCa }
+ );
+
+ expect(mockedCreateSshKeyPair).not.toHaveBeenCalled();
+ expect(result).toMatchObject({
+ caPrivateKey: existingCa.caPrivateKey,
+ caPublicKey: existingCa.caPublicKey,
+ caKeyAlgorithm: SshCertKeyAlgorithm.ED25519
+ });
+ });
+
+ test("regenerates the CA when the RSA key size changes", async () => {
+ const provider = SshProvider();
+
+ const result = await provider.validateProviderInputs(
+ {
+ ...rsaCa,
+ principals: ["ubuntu"],
+ keyAlgorithm: SshCertKeyAlgorithm.ED25519,
+ caKeyAlgorithm: SshCertKeyAlgorithm.RSA_4096
+ },
+ { ...metadata, previousInputs: { ...rsaCa, caKeyAlgorithm: SshCertKeyAlgorithm.RSA_2048 } }
+ );
+
+ expect(mockedCreateSshKeyPair).toHaveBeenCalledOnce();
+ expect(mockedCreateSshKeyPair).toHaveBeenCalledWith(SshCertKeyAlgorithm.RSA_4096);
+ expect(result).toMatchObject({
+ caPrivateKey: "-----BEGIN OPENSSH PRIVATE KEY-----\nnew-ca\n-----END OPENSSH PRIVATE KEY-----",
+ caPublicKey: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5 new-ca",
+ caKeyAlgorithm: SshCertKeyAlgorithm.RSA_4096
+ });
+ });
+
+ test("reuses an RSA CA when the requested size matches the stored key", async () => {
+ const provider = SshProvider();
+
+ const result = await provider.validateProviderInputs(
+ {
+ ...rsaCa,
+ principals: ["ubuntu"],
+ keyAlgorithm: SshCertKeyAlgorithm.ED25519,
+ caKeyAlgorithm: SshCertKeyAlgorithm.RSA_2048
+ },
+ { ...metadata, previousInputs: { ...rsaCa, caKeyAlgorithm: SshCertKeyAlgorithm.RSA_2048 } }
+ );
+
+ expect(mockedCreateSshKeyPair).not.toHaveBeenCalled();
+ expect(result).toMatchObject({
+ caPrivateKey: rsaCa.caPrivateKey,
+ caPublicKey: rsaCa.caPublicKey,
+ caKeyAlgorithm: SshCertKeyAlgorithm.RSA_2048
+ });
+ });
+
+ test("rejects a stored CA with an unsupported key type instead of regenerating", async () => {
+ const provider = SshProvider();
+
+ await expect(
+ provider.validateProviderInputs(
+ {
+ ...existingCa,
+ caPublicKey: "ssh-dss AAAA unsupported",
+ principals: ["ubuntu"],
+ keyAlgorithm: SshCertKeyAlgorithm.ED25519,
+ caKeyAlgorithm: SshCertKeyAlgorithm.ED25519
+ },
+ metadata
+ )
+ ).rejects.toThrow(BadRequestError);
+ expect(mockedCreateSshKeyPair).not.toHaveBeenCalled();
+ });
+});
+
+describe("SshProvider.create", () => {
+ test("rejects a lease TTL above 7 days", async () => {
+ const provider = SshProvider();
+
+ await expect(
+ provider.create({
+ inputs: {},
+ expireAt: Date.now() + ms("7d") + 1000,
+ identity: { name: "alice" },
+ dynamicSecret: {} as TDynamicSecrets,
+ metadata
+ })
+ ).rejects.toThrow("SSH lease TTL must be 7 days or less");
+ });
+});
diff --git a/backend/src/ee/services/dynamic-secret/providers/ssh.ts b/backend/src/ee/services/dynamic-secret/providers/ssh.ts
index d535138531..85fa946dab 100644
--- a/backend/src/ee/services/dynamic-secret/providers/ssh.ts
+++ b/backend/src/ee/services/dynamic-secret/providers/ssh.ts
@@ -2,29 +2,52 @@ import slugify from "@sindresorhus/slugify";
import RE2 from "re2";
import { BadRequestError } from "@app/lib/errors";
-import { createSshCert, createSshKeyPair, getSshPublicKey, SshCertKeyAlgorithm, SshCertType } from "@app/lib/ssh";
+import { ms } from "@app/lib/ms";
+import { createSshCert, createSshKeyPair, getSshPublicKey, inferSshCertKeyAlgorithm, SshCertType } from "@app/lib/ssh";
import { TDynamicSecretLeaseConfig } from "../../dynamic-secret-lease/dynamic-secret-lease-types";
-import { DynamicSecretSshSchema, SshStoredSchema, TDynamicProviderFns } from "./models";
+import {
+ DynamicSecretSshSchema,
+ SshStoredSchema,
+ TDynamicProviderFns,
+ TDynamicProviderValidateMetadata
+} from "./models";
+
+const SSH_LEASE_MAX_TTL_MS = ms("7d");
export const SshProvider = (): TDynamicProviderFns => {
- const validateProviderInputs = async (inputs: object) => {
+ const validateProviderInputs = async (inputs: object, { previousInputs }: TDynamicProviderValidateMetadata) => {
const parsed = DynamicSecretSshSchema.parse(inputs);
- // Check if CA fields already exist (update case)
const raw = inputs as Record<string, unknown>;
- if (raw.caPrivateKey && raw.caPublicKey) {
- return SshStoredSchema.parse(inputs);
+ const hasCa = Boolean(raw.caPrivateKey && raw.caPublicKey);
+
+ if (hasCa && typeof raw.caPublicKey === "string") {
+ inferSshCertKeyAlgorithm(raw.caPublicKey);
+ }
+
+ const storedCaKeyAlgorithm = previousInputs
+ ? DynamicSecretSshSchema.pick({ caKeyAlgorithm: true }).parse(previousInputs).caKeyAlgorithm
+ : parsed.caKeyAlgorithm;
+
+ if (hasCa && storedCaKeyAlgorithm === parsed.caKeyAlgorithm) {
+ return SshStoredSchema.parse({
+ caPrivateKey: raw.caPrivateKey,
+ caPublicKey: raw.caPublicKey,
+ principals: parsed.principals,
+ keyAlgorithm: parsed.keyAlgorithm,
+ caKeyAlgorithm: parsed.caKeyAlgorithm
+ });
}
- // First creation: generate CA key pair (always ED25519 for the CA)
- const caKeyPair = await createSshKeyPair(SshCertKeyAlgorithm.ED25519);
+ const caKeyPair = await createSshKeyPair(parsed.caKeyAlgorithm);
return {
caPrivateKey: caKeyPair.privateKey,
caPublicKey: caKeyPair.publicKey,
principals: parsed.principals,
- keyAlgorithm: parsed.keyAlgorithm
+ keyAlgorithm: parsed.keyAlgorithm,
+ caKeyAlgorithm: parsed.caKeyAlgorithm
};
};
@@ -66,6 +89,12 @@ export const SshProvider = (): TDynamicProviderFns => {
identity: { name: string };
config?: TDynamicSecretLeaseConfig;
}) => {
+ if (expireAt > Date.now() + SSH_LEASE_MAX_TTL_MS) {
+ throw new BadRequestError({
+ message: "SSH lease TTL must be 7 days or less"
+ });
+ }
+
const parsed = SshStoredSchema.parse(inputs);
// Validate principals from lease config
diff --git a/backend/src/lib/ssh/index.test.ts b/backend/src/lib/ssh/index.test.ts
new file mode 100644
index 0000000000..cee7a28a71
--- /dev/null
+++ b/backend/src/lib/ssh/index.test.ts
@@ -0,0 +1,18 @@
+import { describe, expect, test } from "vitest";
+
+import { BadRequestError } from "@app/lib/errors";
+import { inferSshCertKeyAlgorithm, SshPublicKeyType } from "@app/lib/ssh";
+
+describe("inferSshCertKeyAlgorithm", () => {
+ test("accepts each supported OpenSSH public key type", () => {
+ expect(inferSshCertKeyAlgorithm(`${SshPublicKeyType.ED25519} AAAA`)).toBe(SshPublicKeyType.ED25519);
+ expect(inferSshCertKeyAlgorithm(`${SshPublicKeyType.ECDSA_P256} AAAA`)).toBe(SshPublicKeyType.ECDSA_P256);
+ expect(inferSshCertKeyAlgorithm(`${SshPublicKeyType.ECDSA_P384} AAAA`)).toBe(SshPublicKeyType.ECDSA_P384);
+ expect(inferSshCertKeyAlgorithm(`${SshPublicKeyType.RSA} AAAA`)).toBe(SshPublicKeyType.RSA);
+ });
+
+ test("rejects an unknown OpenSSH public key type", () => {
+ expect(() => inferSshCertKeyAlgorithm("ssh-dss AAAA")).toThrow(BadRequestError);
+ expect(() => inferSshCertKeyAlgorithm("ssh-dss AAAA")).toThrow("Unsupported SSH key type 'ssh-dss'");
+ });
+});
diff --git a/backend/src/lib/ssh/index.ts b/backend/src/lib/ssh/index.ts
index b37dc93fa6..4d15609d05 100644
--- a/backend/src/lib/ssh/index.ts
+++ b/backend/src/lib/ssh/index.ts
@@ -24,6 +24,20 @@ export enum SshCertKeyAlgorithm {
ED25519 = "ED25519"
}
+export const SSH_CERT_KEY_ALGORITHMS = Object.values(SshCertKeyAlgorithm) as [
+ SshCertKeyAlgorithm,
+ ...SshCertKeyAlgorithm[]
+];
+
+export enum SshPublicKeyType {
+ RSA = "ssh-rsa",
+ ED25519 = "ssh-ed25519",
+ ECDSA_P256 = "ecdsa-sha2-nistp256",
+ ECDSA_P384 = "ecdsa-sha2-nistp384"
+}
+
+const SUPPORTED_SSH_PUBLIC_KEY_TYPES = new Set<string>(Object.values(SshPublicKeyType));
+
export enum SshCertType {
USER = "user",
HOST = "host"
@@ -116,6 +130,18 @@ export const createSshKeyPair = async (keyAlgorithm: SshCertKeyAlgorithm) => {
}
};
+export const inferSshCertKeyAlgorithm = (publicKey: string): SshPublicKeyType => {
+ const space = publicKey.indexOf(" ");
+ const type = space === -1 ? publicKey : publicKey.slice(0, space);
+ if (!SUPPORTED_SSH_PUBLIC_KEY_TYPES.has(type)) {
+ throw new BadRequestError({
+ message: `Unsupported SSH key type '${type}'. Allowed types are RSA 2048, RSA 4096, ECDSA P256, ECDSA P384, and ED25519.`
+ });
+ }
+
+ return type as SshPublicKeyType;
+};
+
/**
* Return the SSH public key for the given SSH private key.
*/
@@ -166,11 +192,7 @@ const validateSshCertificateKeyId = (keyId: string) => {
* Validate the format of the SSH public key
*/
const validateSshPublicKey = async (publicKey: string) => {
- const validPrefixes = ["ssh-rsa", "ssh-ed25519", "ecdsa-sha2-nistp256", "ecdsa-sha2-nistp384"];
- const startsWithValidPrefix = validPrefixes.some((prefix) => publicKey.startsWith(`${prefix} `));
- if (!startsWithValidPrefix) {
- throw new BadRequestError({ message: "Failed to validate SSH public key format: unsupported key type." });
- }
+ inferSshCertKeyAlgorithm(publicKey);
// write the key to a temp file and run `ssh-keygen -l -f`
// check to see if OpenSSH can read/interpret the public key
diff --git a/docs/documentation/platform/dynamic-secrets/ssh.mdx b/docs/documentation/platform/dynamic-secrets/ssh.mdx
index a7b9ad96e9..1aa08e4908 100644
--- a/docs/documentation/platform/dynamic-secrets/ssh.mdx
+++ b/docs/documentation/platform/dynamic-secrets/ssh.mdx
@@ -7,7 +7,7 @@ The Infisical SSH dynamic secret allows you to generate ephemeral SSH certificat
## How it works
-When you create an SSH dynamic secret, Infisical generates an internal CA key pair. Target hosts are configured to trust this CA. When a lease is requested, Infisical generates an ephemeral key pair, signs the public key with the CA, and returns the private key and signed certificate. The certificate expires when the lease TTL ends — no manual key rotation or revocation needed.
+When you create an SSH dynamic secret, Infisical generates an internal CA key pair. Target hosts are configured to trust this CA. When a lease is requested, Infisical generates an ephemeral key pair, signs the public key with the CA, and returns the private key and signed certificate. The certificate expires when the lease TTL ends so no manual key rotation or revocation is required.
## Set up dynamic secrets with SSH
@@ -15,7 +15,8 @@ When you create an SSH dynamic secret, Infisical generates an internal CA key pa
<Step title="Open Secret Overview Dashboard">
Open the Secret Overview dashboard and select the environment in which you would like to add a dynamic secret.
- ![Add Dynamic Secret Overview](/images/platform/dynamic-secrets/ssh/secret-overview-dashboard.png)
+ ![Add Dynamic Secret Overview](/images/platform/dynamic-secrets/ssh/secret-overview-dashboard.png)
+
</Step>
<Step title="Click on the 'Add Dynamic Secret' button">
![Add Dynamic Secret Button](/images/platform/dynamic-secrets/ssh/add-dynamic-secret-button.png)
@@ -23,114 +24,120 @@ When you create an SSH dynamic secret, Infisical generates an internal CA key pa
<Step title="Select 'SSH'">
Select **SSH** from the dynamic secret type list.
- ![Select SSH](/images/platform/dynamic-secrets/ssh/select-ssh-provider.png)
+ ![Select SSH](/images/platform/dynamic-secrets/ssh/select-ssh-provider.png)
+
</Step>
<Step title="Provide the inputs for dynamic secret parameters">
<ParamField path="Secret Name" type="string" required>
Name by which you want the secret to be referenced
</ParamField>
- <ParamField path="Default TTL" type="string" required>
- Default time-to-live for a generated certificate (e.g. `1h`, `8h`)
- </ParamField>
+ <ParamField path="Default TTL" type="string" required>
+ Default time-to-live for a generated certificate (e.g. `1h`, `8h`, up to `7d`)
+ </ParamField>
- <ParamField path="Max TTL" type="string" required>
- Maximum time-to-live for a generated certificate
- </ParamField>
+ <ParamField path="Max TTL" type="string" required>
+ Maximum time-to-live for a generated certificate (e.g. `24h`, up to `7d`)
+ </ParamField>
- <ParamField path="Allowed Principals" type="list" required>
- The usernames this dynamic secret can issue certificates for (e.g. `ubuntu`, `deploy`, `root`). When creating a lease, the requester selects a subset of these principals.
- </ParamField>
+ <ParamField path="Allowed Principals" type="list" required>
+ The usernames this dynamic secret can issue certificates for (e.g. `ubuntu`, `deploy`, `root`). When creating a lease, the requester selects a subset of these principals.
+ </ParamField>
- <ParamField path="Key Algorithm" type="string" required>
- Algorithm for the ephemeral key pairs generated per lease. Supported options: **ED25519** (default, recommended), **RSA 2048**, **RSA 4096**, **ECDSA P-256**, **ECDSA P-384**.
- </ParamField>
+ <ParamField path="Key Algorithm" type="string" required>
+ Algorithm for the ephemeral key pairs generated per lease. Supported options: **ED25519** (default, recommended), **RSA 2048**, **RSA 4096**, **ECDSA P-256**, **ECDSA P-384**.
+ </ParamField>
+
+ ![SSH Form](/images/platform/dynamic-secrets/ssh/ssh-configuration-form.png)
- ![SSH Form](/images/platform/dynamic-secrets/ssh/ssh-configuration-form.png)
</Step>
<Step title="Click 'Submit'">
After submitting the form, a **Certificate Authentication Setup** modal will appear with two options for configuring target hosts to trust the CA:
- - **Automated setup**: A `curl | sudo bash` command that installs the CA certificate, configures `TrustedUserCAKeys` in `sshd_config`, and restarts the SSH service.
- - **Manual setup**: The raw CA public key, which you can reveal and copy to install manually on target hosts.
+ - **Automated setup**: A `curl | sudo bash` command that installs the CA certificate, configures `TrustedUserCAKeys` in `sshd_config`, and restarts the SSH service.
+ - **Manual setup**: The raw CA public key, which you can reveal and copy to install manually on target hosts.
- ![CA Setup Modal](/images/platform/dynamic-secrets/ssh/ca-setup-modal.png)
+ ![CA Setup Modal](/images/platform/dynamic-secrets/ssh/ca-setup-modal.png)
+
+ <Note>
+ You must configure your target SSH servers to trust the CA before certificate-based authentication will work. This only needs to be done once per host.
+ </Note>
- <Note>
- You must configure your target SSH servers to trust the CA before certificate-based authentication will work. This only needs to be done once per host.
- </Note>
</Step>
<Step title="Configure target hosts">
**Option A — Automated setup**
- Run the provided command on each target host:
- ```bash
- curl -H "Authorization: Bearer <your-token>" "https://<your-infisical-url>/api/v1/dynamic-secrets/ssh-ca-setup/<dynamic-secret-id>" | sudo bash
- ```
-
- This script will:
- - Write the CA public key to `/etc/ssh/infisical_ca.pub`
- - Add `TrustedUserCAKeys /etc/ssh/infisical_ca.pub` to `/etc/ssh/sshd_config`
- - Validate the SSH configuration and restart the SSH service
-
- **Option B — Manual setup**
-
- 1. Copy the CA public key (available via the eye icon in the setup modal or the edit form)
- 2. Save it to `/etc/ssh/infisical_ca.pub` on the target host
- 3. Add the following line to `/etc/ssh/sshd_config`:
- ```
- TrustedUserCAKeys /etc/ssh/infisical_ca.pub
- ```
- 4. Restart the SSH service
-
- You can also retrieve the CA public key programmatically:
- ```bash
- curl -H "Authorization: Bearer <your-token>" "https://<your-infisical-url>/api/v1/dynamic-secrets/ssh-ca-public-key/<dynamic-secret-id>"
- ```
- This returns a JSON response: `{ "caPublicKey": "ssh-ed25519 AAAA..." }`
+ Run the provided command on each target host:
+ ```bash
+ curl -H "Authorization: Bearer <your-token>" "https://<your-infisical-url>/api/v1/dynamic-secrets/ssh-ca-setup/<dynamic-secret-id>" | sudo bash
+ ```
+
+ This script will:
+ - Write the CA public key to `/etc/ssh/infisical_ca.pub`
+ - Add `TrustedUserCAKeys /etc/ssh/infisical_ca.pub` to `/etc/ssh/sshd_config`
+ - Validate the SSH configuration and restart the SSH service
+
+ **Option B — Manual setup**
+
+ 1. Copy the CA public key (available via the eye icon in the setup modal or the edit form)
+ 2. Save it to `/etc/ssh/infisical_ca.pub` on the target host
+ 3. Add the following line to `/etc/ssh/sshd_config`:
+ ```
+ TrustedUserCAKeys /etc/ssh/infisical_ca.pub
+ ```
+ 4. Restart the SSH service
+
+ You can also retrieve the CA public key programmatically:
+ ```bash
+ curl -H "Authorization: Bearer <your-token>" "https://<your-infisical-url>/api/v1/dynamic-secrets/ssh-ca-public-key/<dynamic-secret-id>"
+ ```
+ This returns a JSON response: `{ "caPublicKey": "ssh-ed25519 AAAA..." }`
+
</Step>
<Step title="Generate dynamic secrets">
Once you've configured the dynamic secret and set up target hosts, you're ready to generate on-demand credentials.
To do this, simply select the **Generate** button which appears when hovering over the dynamic secret item.
- ![Hover Generate Lease](/images/platform/dynamic-secrets/ssh/hover-generate-lease.png)
+ ![Hover Generate Lease](/images/platform/dynamic-secrets/ssh/hover-generate-lease.png)
- When generating a lease, you will need to provide:
+ When generating a lease, you will need to provide:
- <ParamField path="TTL" type="string" required>
- How long the certificate should be valid for. Must be within the Max TTL configured on the dynamic secret.
- </ParamField>
+ <ParamField path="TTL" type="string" required>
+ How long the certificate should be valid for. Must be within the Max TTL configured on the dynamic secret.
+ </ParamField>
- <ParamField path="Principals" type="list" required>
- One or more usernames (from the allowed principals) that the certificate should be valid for.
- </ParamField>
+ <ParamField path="Principals" type="list" required>
+ One or more usernames (from the allowed principals) that the certificate should be valid for.
+ </ParamField>
- ![Generate Lease Form](/images/platform/dynamic-secrets/ssh/generate-lease-form.png)
+ ![Generate Lease Form](/images/platform/dynamic-secrets/ssh/generate-lease-form.png)
- Once you click **Submit**, a new lease will be generated containing:
- - **Private Key** — the ephemeral SSH private key (downloadable as `key.pem`)
- - **Signed Certificate** — the SSH certificate signed by the CA (downloadable as `cert.pub`)
+ Once you click **Submit**, a new lease will be generated containing:
+ - **Private Key** — the ephemeral SSH private key (downloadable as `key.pem`)
+ - **Signed Certificate** — the SSH certificate signed by the CA (downloadable as `cert.pub`)
- Both can be downloaded or copied directly from the UI.
+ Both can be downloaded or copied directly from the UI.
- ![Lease Output](/images/platform/dynamic-secrets/ssh/lease-credentials.png)
+ ![Lease Output](/images/platform/dynamic-secrets/ssh/lease-credentials.png)
+
+ <Warning>
+ Copy or download these credentials immediately. You will not be able to see them again after closing the modal.
+ </Warning>
- <Warning>
- Copy or download these credentials immediately. You will not be able to see them again after closing the modal.
- </Warning>
</Step>
<Step title="Use the certificate to connect">
After downloading `key.pem` (private key) and `cert.pub` (signed certificate), set the correct permissions and connect:
- ```bash
- # Set private key permissions
- chmod 600 key.pem
+ ```bash
+ # Set private key permissions
+ chmod 600 key.pem
+
+ # Connect to the target host
+ ssh -i key.pem -o CertificateFile=cert.pub <principal>@<hostname>
+ ```
- # Connect to the target host
- ssh -i key.pem -o CertificateFile=cert.pub <principal>@<hostname>
- ```
+ Replace `<principal>` with one of the principals included in the certificate and `<hostname>` with the target host address.
- Replace `<principal>` with one of the principals included in the certificate and `<hostname>` with the target host address.
</Step>
</Steps>
@@ -160,7 +167,9 @@ This will allow you to see the expiration time of the lease or delete the lease
![View Leases Expiry](/images/platform/dynamic-secrets/ssh/lease-expiry.png)
<Note>
- SSH certificates are time-bound and expire automatically. Revoking a lease in Infisical removes the record, but the certificate remains valid until its TTL expires.
+ SSH certificates are time-bound and expire automatically. Revoking a lease in
+ Infisical removes the record, but the certificate remains valid until its TTL
+ expires.
</Note>
## Edit dynamic secret
@@ -172,5 +181,6 @@ To update the configuration of an existing SSH dynamic secret (principals, key a
## Renew leases
<Note>
- SSH certificate leases cannot be renewed because the certificate validity is baked in at signing time. To get a new certificate, create a new lease.
+ SSH certificate leases cannot be renewed because the certificate validity is
+ baked in at signing time. To get a new certificate, create a new lease.
</Note>
diff --git a/frontend/src/components/dynamic-secrets/DynamicSecretProviderForm/identity-access-contract.test.ts b/frontend/src/components/dynamic-secrets/DynamicSecretProviderForm/identity-access-contract.test.ts
index 1c5b59306d..884ca97ee9 100644
--- a/frontend/src/components/dynamic-secrets/DynamicSecretProviderForm/identity-access-contract.test.ts
+++ b/frontend/src/components/dynamic-secrets/DynamicSecretProviderForm/identity-access-contract.test.ts
@@ -940,14 +940,19 @@ const sshCreateDefaults = {
defaultTTL: "1h",
maxTTL: "24h",
environment,
- inputs: { principals: [], keyAlgorithm: SshCertKeyAlgorithm.ED25519 }
+ inputs: {
+ principals: [],
+ keyAlgorithm: SshCertKeyAlgorithm.ED25519,
+ caKeyAlgorithm: SshCertKeyAlgorithm.ED25519
+ }
};
const sshCreateValues = {
...sshCreateDefaults,
name: "ssh-secret",
inputs: {
principals: ["deploy", "root"],
- keyAlgorithm: SshCertKeyAlgorithm.ED25519
+ keyAlgorithm: SshCertKeyAlgorithm.ED25519,
+ caKeyAlgorithm: SshCertKeyAlgorithm.ED25519
}
};
const sshEditContext = getEditContext({
@@ -955,7 +960,8 @@ const sshEditContext = getEditContext({
inputs: {
caPublicKey: "ignored",
principals: ["deploy"],
- keyAlgorithm: SshCertKeyAlgorithm.ED25519
+ keyAlgorithm: SshCertKeyAlgorithm.ED25519,
+ caKeyAlgorithm: SshCertKeyAlgorithm.ED25519
}
});
const sshEditValues = {
@@ -964,7 +970,8 @@ const sshEditValues = {
maxTTL: "24h",
inputs: {
principals: ["deploy"],
- keyAlgorithm: SshCertKeyAlgorithm.ED25519
+ keyAlgorithm: SshCertKeyAlgorithm.ED25519,
+ caKeyAlgorithm: SshCertKeyAlgorithm.ED25519
}
};
@@ -992,6 +999,21 @@ testDynamicSecretProviderContract({
name: "no principals",
values: { ...sshCreateValues, inputs: { ...sshCreateValues.inputs, principals: [] } },
issuePaths: [["inputs", "principals"]]
+ },
+ {
+ name: "max TTL is missing",
+ values: { ...sshCreateValues, maxTTL: "" },
+ issuePaths: [["maxTTL"]]
+ },
+ {
+ name: "max TTL exceeds 7 days",
+ values: { ...sshCreateValues, maxTTL: "8d" },
+ issuePaths: [["maxTTL"]]
+ },
+ {
+ name: "default TTL exceeds 7 days",
+ values: { ...sshCreateValues, defaultTTL: "8d", maxTTL: "8d" },
+ issuePaths: [["defaultTTL"], ["maxTTL"]]
}
]
},
@@ -1003,10 +1025,23 @@ testDynamicSecretProviderContract({
maxTTL: "24h",
inputs: {
principals: ["deploy"],
- keyAlgorithm: SshCertKeyAlgorithm.ED25519
+ keyAlgorithm: SshCertKeyAlgorithm.ED25519,
+ caKeyAlgorithm: SshCertKeyAlgorithm.ED25519
}
},
validValues: sshEditValues,
+ invalidValues: [
+ {
+ name: "max TTL is missing",
+ values: { ...sshEditValues, maxTTL: "" },
+ issuePaths: [["maxTTL"]]
+ },
+ {
+ name: "max TTL exceeds 7 days",
+ values: { ...sshEditValues, maxTTL: "8d" },
+ issuePaths: [["maxTTL"]]
+ }
+ ],
payload: {
name: "existing-secret",
path: "/folder",
diff --git a/frontend/src/components/dynamic-secrets/DynamicSecretProviderForm/providerDefinitions/ssh.tsx b/frontend/src/components/dynamic-secrets/DynamicSecretProviderForm/providerDefinitions/ssh.tsx
index 8134f031fe..903ca39133 100644
--- a/frontend/src/components/dynamic-secrets/DynamicSecretProviderForm/providerDefinitions/ssh.tsx
+++ b/frontend/src/components/dynamic-secrets/DynamicSecretProviderForm/providerDefinitions/ssh.tsx
@@ -160,6 +160,44 @@ const SshFields = ({ context, mode }: TDynamicSecretProviderRendererProps) => {
</Field>
)}
/>
+ <Controller
+ control={control}
+ name="inputs.caKeyAlgorithm"
+ render={({ field, fieldState: { error } }) => (
+ <Field data-invalid={Boolean(error)}>
+ <FieldLabel htmlFor="ssh-ca-key-algorithm">CA Key Algorithm</FieldLabel>
+ <Select
+ value={field.value}
+ onValueChange={(value) => {
+ if (!value || value === field.value) return;
+ field.onChange(value);
+ }}
+ >
+ <SelectTrigger
+ ref={field.ref}
+ id="ssh-ca-key-algorithm"
+ onBlur={field.onBlur}
+ isError={Boolean(error)}
+ aria-describedby="ssh-ca-key-algorithm-feedback"
+ >
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {sshCertKeyAlgorithms.map((algorithm) => (
+ <SelectItem key={algorithm.value} value={algorithm.value}>
+ {algorithm.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <FieldFeedback
+ id="ssh-ca-key-algorithm-feedback"
+ description="Algorithm for the CA that signs lease certificates. Changing this generates a new CA, and hosts that trust the previous CA must be set up again."
+ error={error?.message}
+ />
+ </Field>
+ )}
+ />
</DynamicSecretProviderGroup>
{mode === "edit" && (
@@ -190,6 +228,11 @@ const SshFields = ({ context, mode }: TDynamicSecretProviderRendererProps) => {
);
};
+const sshTtlFields = {
+ defaultTTL: { description: "Must be 7 days or less" },
+ maxTTL: { description: "Must be 7 days or less" }
+} as const;
+
export const sshDynamicSecretProvider = defineDynamicSecretProvider({
provider: DynamicSecretProviders.Ssh,
label: "SSH",
@@ -198,12 +241,14 @@ export const sshDynamicSecretProvider = defineDynamicSecretProvider({
schema: sshCreateFormSchema,
getDefaultValues: getSshCreateDefaultValues,
toPayload: getSshCreatePayload,
+ commonFields: sshTtlFields,
submitLabel: "Submit"
},
edit: {
schema: sshEditFormSchema,
getDefaultValues: getSshEditDefaultValues,
toPayload: getSshEditPayload,
+ commonFields: sshTtlFields,
submitLabel: "Submit",
successMessage: "Successfully updated dynamic secret"
}
diff --git a/frontend/src/components/dynamic-secrets/DynamicSecretProviderForm/providerDefinitions/sshContract.ts b/frontend/src/components/dynamic-secrets/DynamicSecretProviderForm/providerDefinitions/sshContract.ts
index bc0bdcba4d..30869bd76e 100644
--- a/frontend/src/components/dynamic-secrets/DynamicSecretProviderForm/providerDefinitions/sshContract.ts
+++ b/frontend/src/components/dynamic-secrets/DynamicSecretProviderForm/providerDefinitions/sshContract.ts
@@ -20,26 +20,60 @@ import {
export const SSH_CUSTOM_RENDERER_REASONS = ["repeatable-fields"] as const;
export const SSH_CREATE_WORKFLOW_BOUNDARY_REASONS = ["post-create-workflow"] as const;
+export const SSH_DYNAMIC_SECRET_MAX_TTL = "7d";
const algorithmValues = sshCertKeyAlgorithms.map(({ value }) => value);
const sshInputsSchema = z.object({
principals: z.array(z.string().trim().min(1)).min(1, "At least one principal is required"),
- keyAlgorithm: z.enum(algorithmValues as [string, ...string[]])
+ keyAlgorithm: z.enum(algorithmValues as [string, ...string[]]),
+ caKeyAlgorithm: z.enum(algorithmValues as [string, ...string[]])
});
export type TSshFormValues = TDynamicSecretProviderFormValues<z.infer<typeof sshInputsSchema>>;
+const sshTtlSchema = z
+ .string()
+ .min(1, "TTL is required")
+ .superRefine((value, context) => {
+ if (!value) return;
+ const valueMs = ms(value);
+ if (valueMs < 60 * 1000) {
+ context.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "TTL must be a greater than 1min"
+ });
+ }
+ if (valueMs > ms(SSH_DYNAMIC_SECRET_MAX_TTL)) {
+ context.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: "TTL must be 7 days or less"
+ });
+ }
+ });
+
+const withSshTtls = <T extends z.ZodRawShape>(schema: z.ZodObject<T>) =>
+ schema.extend({
+ defaultTTL: sshTtlSchema,
+ maxTTL: sshTtlSchema
+ });
+
const withTtlOrder = <T extends z.ZodType<TSshFormValues>>(schema: T) =>
- schema.refine((data) => !data.maxTTL || ms(data.maxTTL)! >= ms(data.defaultTTL)!, {
- path: ["maxTTL"],
- message: "Max TTL must be greater than or equal to Default TTL"
- }) as z.ZodType<TSshFormValues>;
+ schema.refine(
+ (data) => {
+ if (!data.maxTTL || !data.defaultTTL) return true;
+ return ms(data.maxTTL)! >= ms(data.defaultTTL)!;
+ },
+ {
+ path: ["maxTTL"],
+ message: "Max TTL must be greater than or equal to Default TTL"
+ }
+ ) as z.ZodType<TSshFormValues>;
export const sshCreateFormSchema = withTtlOrder(
- createDynamicSecretProviderFormSchema(sshInputsSchema) as z.ZodType<TSshFormValues>
+ withSshTtls(createDynamicSecretProviderFormSchema(sshInputsSchema)) as z.ZodType<TSshFormValues>
);
export const sshEditFormSchema = withTtlOrder(
- editDynamicSecretProviderFormSchema(sshInputsSchema) as z.ZodType<TSshFormValues>
+ withSshTtls(editDynamicSecretProviderFormSchema(sshInputsSchema)) as z.ZodType<TSshFormValues>
);
export const getSshCreateDefaultValues = (
@@ -49,7 +83,11 @@ export const getSshCreateDefaultValues = (
defaultTTL: "1h",
maxTTL: "24h",
environment: context.isSingleEnvironmentMode ? context.environments[0] : undefined,
- inputs: { principals: [], keyAlgorithm: SshCertKeyAlgorithm.ED25519 }
+ inputs: {
+ principals: [],
+ keyAlgorithm: SshCertKeyAlgorithm.ED25519,
+ caKeyAlgorithm: SshCertKeyAlgorithm.ED25519
+ }
});
export const getSshEditDefaultValues = (
@@ -62,7 +100,8 @@ export const getSshEditDefaultValues = (
maxTTL: context.dynamicSecret.maxTTL,
inputs: {
principals: inputs.principals ?? [],
- keyAlgorithm: inputs.keyAlgorithm ?? SshCertKeyAlgorithm.ED25519
+ keyAlgorithm: inputs.keyAlgorithm ?? SshCertKeyAlgorithm.ED25519,
+ caKeyAlgorithm: inputs.caKeyAlgorithm ?? SshCertKeyAlgorithm.ED25519
}
};
};
@@ -73,7 +112,7 @@ export const getSshCreatePayload = (
): TCreateDynamicSecretProviderDTO<DynamicSecretProviders.Ssh> => ({
provider: { type: DynamicSecretProviders.Ssh, inputs: sshInputsSchema.parse(values.inputs) },
defaultTTL: values.defaultTTL,
- maxTTL: values.maxTTL || undefined,
+ maxTTL: values.maxTTL ?? undefined,
name: values.name,
path: context.secretPath,
projectSlug: context.projectSlug,
@@ -92,6 +131,6 @@ export const getSshEditPayload = (
inputs: sshInputsSchema.parse(values.inputs),
newName: values.name === context.dynamicSecret.name ? undefined : values.name,
defaultTTL: values.defaultTTL,
- maxTTL: values.maxTTL || undefined
+ maxTTL: values.maxTTL
}
});
diff --git a/frontend/src/hooks/api/dynamicSecret/types.ts b/frontend/src/hooks/api/dynamicSecret/types.ts
index 96860cb4cc..cab9ba1679 100644
--- a/frontend/src/hooks/api/dynamicSecret/types.ts
+++ b/frontend/src/hooks/api/dynamicSecret/types.ts
@@ -522,6 +522,7 @@ export type TDynamicSecretProvider =
caPublicKey?: string;
principals: string[];
keyAlgorithm: string;
+ caKeyAlgorithm?: string;
};
}
| {