Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat(dynamic-secrets): add SSH certificate provider (#5914)
Saif Ur Rahman5821541fa794
diff --git a/backend/src/ee/routes/v1/dynamic-secret-router.ts b/backend/src/ee/routes/v1/dynamic-secret-router.tsindex d1c5690079..df57997e0a 100644--- a/backend/src/ee/routes/v1/dynamic-secret-router.ts+++ b/backend/src/ee/routes/v1/dynamic-secret-router.ts@@ -473,6 +473,105 @@ export const registerDynamicSecretRouter = async (server: FastifyZodProvider) =>}});+ server.route({+ method: "GET",+ url: "/ssh-ca-setup/:dynamicSecretId",+ config: {+ rateLimit: readLimit+ },+ schema: {+ operationId: "getSshDynamicSecretCaSetup",+ description: "Get SSH dynamic secret CA setup script for configuring the target server to trust the CA",+ params: z.object({+ dynamicSecretId: z.string().uuid()+ }),+ response: {+ 200: z.string()+ }+ },+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),+ handler: async (req, reply) => {+ const { caPublicKey } = await server.services.dynamicSecret.getSshCaPublicKey({+ dynamicSecretId: req.params.dynamicSecretId,+ actor: req.permission.type,+ actorId: req.permission.id,+ actorAuthMethod: req.permission.authMethod,+ actorOrgId: req.permission.orgId+ });++ const setupScript = `#!/bin/bash+set -e++CA_PUBLIC_KEY="${caPublicKey}"+CA_FILE="/etc/ssh/infisical_ca.pub"+SSHD_CONFIG="/etc/ssh/sshd_config"++echo "==> Infisical SSH CA Setup"+echo ""++if [ "$(id -u)" -ne 0 ]; then+ echo "Error: This script must be run as root (use sudo)"+ exit 1+fi++echo "==> Writing CA public key to \${CA_FILE}..."+echo "\${CA_PUBLIC_KEY}" > "\${CA_FILE}"+chmod 644 "\${CA_FILE}"+echo " Done."++if grep -q "^TrustedUserCAKeys" "\${SSHD_CONFIG}"; then+ EXISTING_CA_FILE=$(grep "^TrustedUserCAKeys" "\${SSHD_CONFIG}" | awk '{print $2}')+ if [ "\${EXISTING_CA_FILE}" = "\${CA_FILE}" ]; then+ echo "==> TrustedUserCAKeys already configured for \${CA_FILE}"+ else+ echo "Warning: TrustedUserCAKeys is already set to \${EXISTING_CA_FILE}"+ echo " You may need to manually update sshd_config to use \${CA_FILE}"+ echo " or combine multiple CA keys into a single file."+ fi+else+ echo "==> Adding TrustedUserCAKeys to \${SSHD_CONFIG}..."+ echo "" >> "\${SSHD_CONFIG}"+ echo "# Infisical SSH CA - Added by setup script" >> "\${SSHD_CONFIG}"+ echo "TrustedUserCAKeys \${CA_FILE}" >> "\${SSHD_CONFIG}"+ echo " Done."+fi++echo "==> Validating SSH configuration..."+if sshd -t; then+ echo " Configuration is valid."+else+ echo "Error: SSH configuration is invalid. Please check \${SSHD_CONFIG}"+ exit 1+fi++echo "==> Restarting SSH service..."+if command -v systemctl &> /dev/null; then+ if systemctl cat sshd.service &>/dev/null; then+ systemctl restart sshd+ elif systemctl cat ssh.service &>/dev/null; then+ systemctl restart ssh+ else+ echo "Warning: Could not find SSH service. Please restart it manually."+ fi+elif command -v service &> /dev/null; then+ service sshd restart 2>/dev/null || service ssh restart+else+ echo "Warning: Could not detect init system. Please restart sshd manually."+fi+echo " Done."++echo ""+echo "==> Setup complete!"+echo ""+echo "Your SSH server is now configured to trust certificates signed by the Infisical CA."+echo ""+`;++ void reply.header("Content-Type", "text/plain; charset=utf-8");+ return setupScript;+ }+ });+server.route({method: "POST",url: "/entra-id/users",diff --git a/backend/src/ee/services/dynamic-secret-lease/dynamic-secret-lease-types.ts b/backend/src/ee/services/dynamic-secret-lease/dynamic-secret-lease-types.tsindex e175f25c7e..9799ade252 100644--- a/backend/src/ee/services/dynamic-secret-lease/dynamic-secret-lease-types.ts+++ b/backend/src/ee/services/dynamic-secret-lease/dynamic-secret-lease-types.ts@@ -52,7 +52,11 @@ export type TDynamicSecretKubernetesLeaseConfig = {namespace?: string;};-export type TDynamicSecretLeaseConfig = TDynamicSecretKubernetesLeaseConfig;+export type TDynamicSecretSshLeaseConfig = {+ principals?: string[];+};++export type TDynamicSecretLeaseConfig = TDynamicSecretKubernetesLeaseConfig & TDynamicSecretSshLeaseConfig;export type TDynamicSecretLeaseServiceFactory = {create: (arg: TCreateDynamicSecretLeaseDTO) => Promise<{diff --git a/backend/src/ee/services/dynamic-secret/dynamic-secret-service.ts b/backend/src/ee/services/dynamic-secret/dynamic-secret-service.tsindex 4da278c090..b5c82fd624 100644--- a/backend/src/ee/services/dynamic-secret/dynamic-secret-service.ts+++ b/backend/src/ee/services/dynamic-secret/dynamic-secret-service.ts@@ -25,7 +25,7 @@ import { OrgPermissionGatewayActions, OrgPermissionSubjects } from "../permissioimport { TDynamicSecretDALFactory } from "./dynamic-secret-dal";import { DynamicSecretStatus, TDynamicSecretServiceFactory } from "./dynamic-secret-types";import { AzureEntraIDProvider } from "./providers/azure-entra-id";-import { DynamicSecretProviders, TDynamicProviderFns } from "./providers/models";+import { DynamicSecretProviders, SshStoredSchema, TDynamicProviderFns } from "./providers/models";type TDynamicSecretServiceFactoryDep = {dynamicSecretDAL: TDynamicSecretDALFactory;@@ -36,7 +36,10 @@ type TDynamicSecretServiceFactoryDep = {"pruneDynamicSecret" | "unsetLeaseRevocation">;licenseService: Pick<TLicenseServiceFactory, "getPlan">;- folderDAL: Pick<TSecretFolderDALFactory, "findBySecretPath" | "findBySecretPathMultiEnv">;+ folderDAL: Pick<+ TSecretFolderDALFactory,+ "findBySecretPath" | "findBySecretPathMultiEnv" | "findById" | "findSecretPathByFolderIds"+ >;projectDAL: Pick<TProjectDALFactory, "findProjectBySlug">;permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getOrgPermission">;kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;@@ -800,6 +803,62 @@ export const dynamicSecretServiceFactory = ({});};+ const getSshCaPublicKey: TDynamicSecretServiceFactory["getSshCaPublicKey"] = async ({+ dynamicSecretId,+ actor,+ actorId,+ actorAuthMethod,+ actorOrgId+ }) => {+ const dynamicSecretCfg = await dynamicSecretDAL.findOne({ id: dynamicSecretId });+ if (!dynamicSecretCfg) {+ throw new NotFoundError({ message: `Dynamic secret with ID '${dynamicSecretId}' not found` });+ }++ if (dynamicSecretCfg.type !== DynamicSecretProviders.Ssh) {+ throw new BadRequestError({ message: "Dynamic secret is not an SSH type" });+ }++ // Find the folder to get environment and path for permission check+ const folder = await folderDAL.findById(dynamicSecretCfg.folderId);+ if (!folder) {+ throw new NotFoundError({ message: "Dynamic secret folder not found" });+ }++ // Get the full secret path for the permission check+ const folderPaths = await folderDAL.findSecretPathByFolderIds(folder.projectId, [dynamicSecretCfg.folderId]);+ const secretPath = folderPaths?.[0]?.path || "/";++ const { permission } = await permissionService.getProjectPermission({+ actor,+ actorId,+ projectId: folder.projectId,+ actorAuthMethod,+ actorOrgId,+ actionProjectType: ActionProjectType.SecretManager+ });++ ForbiddenError.from(permission).throwUnlessCan(+ ProjectPermissionDynamicSecretActions.EditRootCredential,+ subject(ProjectPermissionSub.DynamicSecrets, {+ environment: folder.environment.envSlug,+ secretPath,+ metadata: dynamicSecretCfg.metadata+ })+ );++ const { decryptor: secretManagerDecryptor } = await kmsService.createCipherPairWithDataKey({+ type: KmsDataKey.SecretManager,+ projectId: folder.projectId+ });++ const decryptedStoredInput = SshStoredSchema.pick({ caPublicKey: true }).parse(+ JSON.parse(secretManagerDecryptor({ cipherTextBlob: dynamicSecretCfg.encryptedInput }).toString())+ );++ return { caPublicKey: decryptedStoredInput.caPublicKey };+ };+const fetchAzureEntraIdUsers: TDynamicSecretServiceFactory["fetchAzureEntraIdUsers"] = async ({tenantId,applicationId,@@ -823,6 +882,7 @@ export const dynamicSecretServiceFactory = ({getDynamicSecretCount,getCountMultiEnv,fetchAzureEntraIdUsers,- listDynamicSecretsByFolderIds+ listDynamicSecretsByFolderIds,+ getSshCaPublicKey};};diff --git a/backend/src/ee/services/dynamic-secret/dynamic-secret-types.ts b/backend/src/ee/services/dynamic-secret/dynamic-secret-types.tsindex d5fa291b5a..a501752406 100644--- a/backend/src/ee/services/dynamic-secret/dynamic-secret-types.ts+++ b/backend/src/ee/services/dynamic-secret/dynamic-secret-types.ts@@ -54,6 +54,10 @@ export type TDetailsDynamicSecretDTO = {projectSlug: string;} & Omit<TProjectPermission, "projectId">;+export type TGetSshCaPublicKeyDTO = {+ dynamicSecretId: string;+} & Omit<TProjectPermission, "projectId">;+export type ListDynamicSecretsFilters = {offset?: number;limit?: number;@@ -124,4 +128,5 @@ export type TDynamicSecretServiceFactory = {arg: TListDynamicSecretsByFolderMappingsDTO,actor: OrgServiceActor) => Promise<Array<TDynamicSecretWithMetadata & { environment: string; path: string }>>;+ getSshCaPublicKey: (arg: TGetSshCaPublicKeyDTO) => Promise<{ caPublicKey: string }>;};diff --git a/backend/src/ee/services/dynamic-secret/providers/index.ts b/backend/src/ee/services/dynamic-secret/providers/index.tsindex b2c329a6f2..10573e1cad 100644--- a/backend/src/ee/services/dynamic-secret/providers/index.ts+++ b/backend/src/ee/services/dynamic-secret/providers/index.ts@@ -22,6 +22,7 @@ import { RedisDatabaseProvider } from "./redis";import { SapAseProvider } from "./sap-ase";import { SapHanaProvider } from "./sap-hana";import { SqlDatabaseProvider } from "./sql-database";+import { SshProvider } from "./ssh";import { TotpProvider } from "./totp";import { VerticaProvider } from "./vertica";@@ -55,5 +56,6 @@ export const buildDynamicSecretProviders = ({[DynamicSecretProviders.Vertica]: VerticaProvider({ gatewayService }),[DynamicSecretProviders.GcpIam]: GcpIamProvider(),[DynamicSecretProviders.Github]: GithubProvider(),- [DynamicSecretProviders.Couchbase]: CouchbaseProvider()+ [DynamicSecretProviders.Couchbase]: CouchbaseProvider(),+ [DynamicSecretProviders.Ssh]: SshProvider()});diff --git a/backend/src/ee/services/dynamic-secret/providers/models.ts b/backend/src/ee/services/dynamic-secret/providers/models.tsindex 38703ae7bb..e2e156e2e6 100644--- a/backend/src/ee/services/dynamic-secret/providers/models.ts+++ b/backend/src/ee/services/dynamic-secret/providers/models.ts@@ -2,6 +2,7 @@ import RE2 from "re2";import { z } from "zod";import { TDynamicSecrets } from "@app/db/schemas";+import { SshCertKeyAlgorithm } from "@app/ee/services/ssh-certificate/ssh-certificate-types";import { CharacterType, characterValidator } from "@app/lib/validator/validate-string";import { ResourceMetadataNonEncryptionSchema } from "@app/services/resource-metadata/resource-metadata-schema";@@ -698,9 +699,22 @@ export enum DynamicSecretProviders {Vertica = "vertica",GcpIam = "gcp-iam",Github = "github",- Couchbase = "couchbase"+ Couchbase = "couchbase",+ Ssh = "ssh"}+export const DynamicSecretSshSchema = z.object({+ principals: z.array(z.string().trim().min(1)).min(1),+ keyAlgorithm: z.nativeEnum(SshCertKeyAlgorithm).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)+});+export const DynamicSecretProviderSchema = z.discriminatedUnion("type", [z.object({ type: z.literal(DynamicSecretProviders.SqlDatabase), inputs: DynamicSecretSqlDBSchema }),z.object({ type: z.literal(DynamicSecretProviders.Clickhouse), inputs: DynamicSecretClickhouseSchema }),@@ -723,7 +737,8 @@ export const DynamicSecretProviderSchema = z.discriminatedUnion("type", [z.object({ type: z.literal(DynamicSecretProviders.Vertica), inputs: DynamicSecretVerticaSchema }),z.object({ type: z.literal(DynamicSecretProviders.GcpIam), inputs: DynamicSecretGcpIamSchema }),z.object({ type: z.literal(DynamicSecretProviders.Github), inputs: DynamicSecretGithubSchema }),- z.object({ type: z.literal(DynamicSecretProviders.Couchbase), inputs: DynamicSecretCouchbaseSchema })+ z.object({ type: z.literal(DynamicSecretProviders.Couchbase), inputs: DynamicSecretCouchbaseSchema }),+ z.object({ type: z.literal(DynamicSecretProviders.Ssh), inputs: DynamicSecretSshSchema })]);export type TDynamicProviderFns = {diff --git a/backend/src/ee/services/dynamic-secret/providers/ssh.ts b/backend/src/ee/services/dynamic-secret/providers/ssh.tsnew file mode 100644index 0000000000..02abf56368--- /dev/null+++ b/backend/src/ee/services/dynamic-secret/providers/ssh.ts@@ -0,0 +1,135 @@+import slugify from "@sindresorhus/slugify";+import RE2 from "re2";++import { BadRequestError } from "@app/lib/errors";++import { TDynamicSecretLeaseConfig } from "../../dynamic-secret-lease/dynamic-secret-lease-types";+import { createSshCert, createSshKeyPair, getSshPublicKey } from "../../ssh/ssh-certificate-authority-fns";+import { SshCertType } from "../../ssh/ssh-certificate-authority-types";+import { SshCertKeyAlgorithm } from "../../ssh-certificate/ssh-certificate-types";+import { DynamicSecretSshSchema, SshStoredSchema, TDynamicProviderFns } from "./models";++export const SshProvider = (): TDynamicProviderFns => {+ const validateProviderInputs = async (inputs: object) => {+ 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);+ }++ // First creation: generate CA key pair (always ED25519 for the CA)+ const caKeyPair = await createSshKeyPair(SshCertKeyAlgorithm.ED25519);++ return {+ caPrivateKey: caKeyPair.privateKey,+ caPublicKey: caKeyPair.publicKey,+ principals: parsed.principals,+ keyAlgorithm: parsed.keyAlgorithm+ };+ };++ // No remote connection to test for SSH — this validates the CA key pair consistency instead.+ // Required by the TDynamicProviderFns interface that all providers implement.+ const validateConnection = async (inputs: unknown) => {+ // On create, the service passes the raw user inputs (no CA keys — those are generated+ // in validateProviderInputs). On update, it passes the merged stored + new inputs.+ const storedResult = SshStoredSchema.safeParse(inputs);++ if (!storedResult.success) {+ // Initial creation — CA keys not present yet. Validate the user-facing fields.+ DynamicSecretSshSchema.parse(inputs);+ return true;+ }++ // Update path — CA keys are present. Verify the key pair is consistent.+ const parsed = storedResult.data;+ const derivedPublicKey = await getSshPublicKey(parsed.caPrivateKey);++ const normalize = (key: string) => key.trim().split(new RE2(/\s+/)).slice(0, 2).join(" ");+ if (normalize(derivedPublicKey) !== normalize(parsed.caPublicKey)) {+ throw new BadRequestError({+ message: "SSH CA key pair validation failed: derived public key does not match stored public key"+ });+ }++ return true;+ };++ const create = async ({+ inputs,+ expireAt,+ identity,+ config+ }: {+ inputs: unknown;+ expireAt: number;+ identity: { name: string };+ config?: TDynamicSecretLeaseConfig;+ }) => {+ const parsed = SshStoredSchema.parse(inputs);++ // Validate principals from lease config+ const requestedPrincipals = config?.principals;+ if (!requestedPrincipals || requestedPrincipals.length === 0) {+ throw new BadRequestError({+ message: "SSH lease requires at least one principal in config.principals"+ });+ }++ // Validate each requested principal is in the allowed list+ const allowedSet = new Set(parsed.principals);+ const invalidPrincipals = requestedPrincipals.filter((p: string) => !allowedSet.has(p));+ if (invalidPrincipals.length > 0) {+ throw new BadRequestError({+ message: `Requested principals not in allowed list: ${invalidPrincipals.join(", ")}`+ });+ }++ const keyId = `infisical-${slugify(identity.name)}`;++ // Generate ephemeral key pair with configured algorithm+ const ephemeralKeyPair = await createSshKeyPair(parsed.keyAlgorithm);++ // Calculate TTL string for createSshCert (expects ms-lib format)+ const ttlSeconds = Math.ceil((expireAt - Date.now()) / 1000);+ const requestedTtl = `${ttlSeconds}s`;++ // Sign the ephemeral public key with the CA+ const { serialNumber, signedPublicKey } = await createSshCert({+ caPrivateKey: parsed.caPrivateKey,+ clientPublicKey: ephemeralKeyPair.publicKey,+ keyId,+ principals: requestedPrincipals,+ requestedTtl,+ certType: SshCertType.USER+ });++ return {+ entityId: serialNumber,+ data: {+ PRIVATE_KEY: ephemeralKeyPair.privateKey,+ SIGNED_KEY: signedPublicKey+ }+ };+ };++ const revoke = async (_inputs: unknown, entityId: string) => {+ // SSH certs are time-bound — revocation is a no-op+ return { entityId };+ };++ const renew = async (_inputs: unknown, entityId: string) => {+ // SSH cert validity is baked in at signing time — renewal is not supported+ return { entityId };+ };++ return {+ validateProviderInputs,+ validateConnection,+ create,+ revoke,+ renew+ };+};diff --git a/frontend/src/hooks/api/dynamicSecret/types.ts b/frontend/src/hooks/api/dynamicSecret/types.tsindex 97a4b37c1b..52c19f37fd 100644--- a/frontend/src/hooks/api/dynamicSecret/types.ts+++ b/frontend/src/hooks/api/dynamicSecret/types.ts@@ -40,7 +40,8 @@ export enum DynamicSecretProviders {GcpIam = "gcp-iam",Github = "github",Couchbase = "couchbase",- Clickhouse = "clickhouse"+ Clickhouse = "clickhouse",+ Ssh = "ssh"}export enum KubernetesDynamicSecretCredentialType {@@ -449,6 +450,14 @@ export type TDynamicSecretProvider =allowedSymbols?: string;};};+ }+ | {+ type: DynamicSecretProviders.Ssh;+ inputs: {+ caPublicKey?: string;+ principals: string[];+ keyAlgorithm: string;+ };};export type TCreateDynamicSecretDTO = {diff --git a/frontend/src/hooks/api/dynamicSecretLease/types.ts b/frontend/src/hooks/api/dynamicSecretLease/types.tsindex 51ee64c4bb..7f3d2acf26 100644--- a/frontend/src/hooks/api/dynamicSecretLease/types.ts+++ b/frontend/src/hooks/api/dynamicSecretLease/types.ts@@ -19,7 +19,12 @@ export type TDynamicSecretKubernetesLeaseConfig = {namespace?: string;};-export type TDynamicSecretLeaseConfig = TDynamicSecretKubernetesLeaseConfig;+export type TDynamicSecretSshLeaseConfig = {+ principals?: string[];+};++export type TDynamicSecretLeaseConfig = TDynamicSecretKubernetesLeaseConfig &+ TDynamicSecretSshLeaseConfig;export type TCreateDynamicSecretLeaseDTO = {dynamicSecretName: string;diff --git a/frontend/src/pages/secret-manager/OverviewPage/components/DynamicSecretTableRow/DynamicSecretTableRow.tsx b/frontend/src/pages/secret-manager/OverviewPage/components/DynamicSecretTableRow/DynamicSecretTableRow.tsxindex 3cff1b1b63..78007e4f95 100644--- a/frontend/src/pages/secret-manager/OverviewPage/components/DynamicSecretTableRow/DynamicSecretTableRow.tsx+++ b/frontend/src/pages/secret-manager/OverviewPage/components/DynamicSecretTableRow/DynamicSecretTableRow.tsx@@ -57,7 +57,8 @@ const DYNAMIC_SECRET_PROVIDER_NAMES: Record<DynamicSecretProviders, string> = {[DynamicSecretProviders.GcpIam]: "GCP IAM",[DynamicSecretProviders.Github]: "GitHub",[DynamicSecretProviders.Clickhouse]: "ClickHouse",- [DynamicSecretProviders.Couchbase]: "Couchbase"+ [DynamicSecretProviders.Couchbase]: "Couchbase",+ [DynamicSecretProviders.Ssh]: "SSH"};type DynamicSecretWithEnv = TDynamicSecret & { environment: string };diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/CreateDynamicSecretForm.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/CreateDynamicSecretForm.tsxindex 23b0688062..f610151aa3 100644--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/CreateDynamicSecretForm.tsx+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/CreateDynamicSecretForm.tsx@@ -14,7 +14,7 @@ import {} from "react-icons/si";import { VscAzure } from "react-icons/vsc";import { faAws, faGithub, faGoogle } from "@fortawesome/free-brands-svg-icons";-import { faClock, faDatabase } from "@fortawesome/free-solid-svg-icons";+import { faClock, faDatabase, faTerminal } from "@fortawesome/free-solid-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";import { AnimatePresence, motion } from "framer-motion";@@ -43,6 +43,7 @@ import { SapAseInputForm } from "./SapAseInputForm";import { SapHanaInputForm } from "./SapHanaInputForm";import { SnowflakeInputForm } from "./SnowflakeInputForm";import { SqlDatabaseInputForm } from "./SqlDatabaseInputForm";+import { SshInputForm } from "./SshInputForm";import { TotpInputForm } from "./TotpInputForm";import { VerticaInputForm } from "./VerticaInputForm";@@ -170,6 +171,11 @@ const DYNAMIC_SECRET_LIST = [icon: <SiClickhouse size="1.5rem" />,provider: DynamicSecretProviders.Clickhouse,title: "ClickHouse"+ },+ {+ icon: <FontAwesomeIcon icon={faTerminal} size="lg" />,+ provider: DynamicSecretProviders.Ssh,+ title: "SSH"}];@@ -669,6 +675,25 @@ export const CreateDynamicSecretForm = ({/></motion.div>)}+ {wizardStep === WizardSteps.ProviderInputs &&+ selectedProvider === DynamicSecretProviders.Ssh && (+ <motion.div+ key="dynamic-ssh-step"+ transition={{ duration: 0.1 }}+ initial={{ opacity: 0, translateX: 30 }}+ animate={{ opacity: 1, translateX: 0 }}+ exit={{ opacity: 0, translateX: -30 }}+ >+ <SshInputForm+ onCompleted={handleFormReset}+ onCancel={handleFormReset}+ projectSlug={projectSlug}+ secretPath={secretPath}+ environments={environments}+ isSingleEnvironmentMode={isSingleEnvironmentMode}+ />+ </motion.div>+ )}</AnimatePresence></ModalContent></Modal>diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/SshInputForm.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/SshInputForm.tsxnew file mode 100644index 0000000000..80cb8080b8--- /dev/null+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/SshInputForm.tsx@@ -0,0 +1,388 @@+import { useState } from "react";+import { Controller, useForm } from "react-hook-form";+import { faCopy } from "@fortawesome/free-regular-svg-icons";+import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";+import { zodResolver } from "@hookform/resolvers/zod";+import ms from "ms";+import { z } from "zod";++import { TtlFormLabel } from "@app/components/features";+import { createNotification } from "@app/components/notifications";+import {+ Button,+ FilterableSelect,+ FormControl,+ IconButton,+ Input,+ Modal,+ ModalContent,+ Select,+ SelectItem,+ Tag+} from "@app/components/v2";+import { useCreateDynamicSecret } from "@app/hooks/api";+import { DynamicSecretProviders } from "@app/hooks/api/dynamicSecret/types";+import { getAuthToken } from "@app/hooks/api/reactQuery";+import { SshCertKeyAlgorithm, sshCertKeyAlgorithms } from "@app/hooks/api/sshCa/constants";+import { ProjectEnv } from "@app/hooks/api/types";+import { slugSchema } from "@app/lib/schemas";++const sshCertKeyAlgorithmsArray = sshCertKeyAlgorithms.map((a) => a.value);++const formSchema = z+ .object({+ provider: z.object({+ principals: z.array(z.string().trim().min(1)).min(1, "At least one principal is required"),+ keyAlgorithm: z.enum(sshCertKeyAlgorithmsArray as [string, ...string[]])+ }),+ defaultTTL: z.string().superRefine((val, ctx) => {+ const valMs = ms(val);+ if (valMs < 60 * 1000)+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: "TTL must be a greater than 1min" });+ if (valMs > ms("10y"))+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: "TTL must be less than 10 years" });+ }),+ maxTTL: z+ .string()+ .optional()+ .superRefine((val, ctx) => {+ if (!val) return;+ const valMs = ms(val);+ if (valMs < 60 * 1000)+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: "TTL must be a greater than 1min" });+ if (valMs > ms("10y"))+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: "TTL must be less than 10 years" });+ })+ .nullable(),+ name: slugSchema({ field: "Name" }),+ environment: z.object({ name: z.string(), slug: z.string() })+ })+ .refine((d) => !d.maxTTL || ms(d.maxTTL)! >= ms(d.defaultTTL)!, {+ path: ["maxTTL"],+ message: "Max TTL must be greater than or equal to Default TTL"+ });+type TForm = z.infer<typeof formSchema>;++type Props = {+ onCompleted: () => void;+ onCancel: () => void;+ secretPath: string;+ projectSlug: string;+ environments: ProjectEnv[];+ isSingleEnvironmentMode?: boolean;+};++export const SshInputForm = ({+ onCompleted,+ onCancel,+ environments,+ secretPath,+ projectSlug,+ isSingleEnvironmentMode+}: Props) => {+ const {+ control,+ formState: { isSubmitting },+ handleSubmit,+ setValue,+ watch+ } = useForm<TForm>({+ resolver: zodResolver(formSchema),+ defaultValues: {+ provider: {+ principals: [],+ keyAlgorithm: SshCertKeyAlgorithm.ED25519+ },+ defaultTTL: "1h",+ maxTTL: "24h",+ environment: isSingleEnvironmentMode && environments.length > 0 ? environments[0] : undefined+ }+ });++ const [showSetupModal, setShowSetupModal] = useState(false);+ const [createdDynamicSecretId, setCreatedDynamicSecretId] = useState<string | null>(null);+ const [principalInput, setPrincipalInput] = useState("");++ const createDynamicSecret = useCreateDynamicSecret();++ const principals = watch("provider.principals");++ const handleCreateDynamicSecret = async ({+ name,+ provider,+ defaultTTL,+ maxTTL,+ environment+ }: TForm) => {+ if (createDynamicSecret.isPending) return;+ const result = await createDynamicSecret.mutateAsync({+ provider: {+ type: DynamicSecretProviders.Ssh,+ inputs: {+ principals: provider.principals,+ keyAlgorithm: provider.keyAlgorithm+ }+ },+ defaultTTL,+ maxTTL: maxTTL || undefined,+ name,+ path: secretPath,+ projectSlug,+ environmentSlug: environment.slug+ });++ const dynamicSecret = result as { id: string };+ setCreatedDynamicSecretId(dynamicSecret.id);+ setShowSetupModal(true);+ };++ const handleAddPrincipal = () => {+ const trimmed = principalInput.trim();+ if (trimmed && !principals.includes(trimmed)) {+ setValue("provider.principals", [...principals, trimmed], { shouldValidate: true });+ }+ setPrincipalInput("");+ };++ const handleRemovePrincipal = (idx: number) => {+ setValue(+ "provider.principals",+ principals.filter((_, i) => i !== idx),+ { shouldValidate: true }+ );+ };++ const { protocol, hostname, port } = window.location;+ const portSuffix = port && port !== "80" ? `:${port}` : "";+ const siteURL = `${protocol}//${hostname}${portSuffix}`;++ const setupCommand = createdDynamicSecretId+ ? `curl -H "Authorization: Bearer ${getAuthToken()}" "${siteURL}/api/v1/dynamic-secrets/ssh-ca-setup/${createdDynamicSecretId}" | sudo bash`+ : "";++ return (+ <div>+ <form onSubmit={handleSubmit(handleCreateDynamicSecret)} autoComplete="off">+ <div>+ <div className="flex items-center space-x-2">+ <div className="grow">+ <Controller+ control={control}+ defaultValue=""+ name="name"+ render={({ field, fieldState: { error } }) => (+ <FormControl+ label="Secret Name"+ isError={Boolean(error)}+ errorText={error?.message}+ >+ <Input {...field} placeholder="dynamic-secret" />+ </FormControl>+ )}+ />+ </div>+ <div className="w-32">+ <Controller+ control={control}+ name="defaultTTL"+ render={({ field, fieldState: { error } }) => (+ <FormControl+ label={<TtlFormLabel label="Default TTL" />}+ isError={Boolean(error?.message)}+ errorText={error?.message}+ >+ <Input {...field} />+ </FormControl>+ )}+ />+ </div>+ <div className="w-32">+ <Controller+ control={control}+ name="maxTTL"+ render={({ field, fieldState: { error } }) => (+ <FormControl+ label={<TtlFormLabel label="Max TTL" />}+ isError={Boolean(error?.message)}+ errorText={error?.message}+ >+ <Input {...field} value={field.value || ""} />+ </FormControl>+ )}+ />+ </div>+ </div>+ <div>+ <div className="mt-4 mb-4 border-b border-border pb-2 pl-1 font-medium text-label">+ Configuration+ </div>++ <div className="flex flex-col">+ <Controller+ control={control}+ name="provider.principals"+ render={({ fieldState: { error } }) => (+ <FormControl+ label="Allowed Principals"+ isError={Boolean(error?.message)}+ errorText={error?.message}+ helperText="The usernames this dynamic secret can issue certificates for (e.g., deploy, ubuntu, root)"+ isRequired+ >+ <div className="flex flex-col gap-2">+ <div className="flex items-center gap-2">+ <Input+ value={principalInput}+ onChange={(e) => setPrincipalInput(e.target.value)}+ placeholder="Enter principal name..."+ onKeyDown={(e) => {+ if (e.key === "Enter") {+ e.preventDefault();+ handleAddPrincipal();+ }+ }}+ />+ <Button+ type="button"+ variant="outline_bg"+ size="sm"+ onClick={handleAddPrincipal}+ isDisabled={!principalInput.trim()}+ >+ Add+ </Button>+ </div>+ {principals.length > 0 && (+ <div className="flex flex-wrap gap-1">+ {principals.map((principal, idx) => (+ <Tag+ className="bg-neutral/15 text-neutral"+ key={principal}+ onClose={() => handleRemovePrincipal(idx)}+ >+ {principal}+ </Tag>+ ))}+ </div>+ )}+ </div>+ </FormControl>+ )}+ />++ <Controller+ control={control}+ name="provider.keyAlgorithm"+ render={({ field: { value, onChange }, fieldState: { error } }) => (+ <FormControl+ label="Key Algorithm"+ isError={Boolean(error?.message)}+ errorText={error?.message}+ helperText="Algorithm for ephemeral key pairs generated per lease"+ >+ <Select value={value} onValueChange={onChange} className="w-full">+ {sshCertKeyAlgorithms.map((alg) => (+ <SelectItem key={alg.value} value={alg.value}>+ {alg.label}+ </SelectItem>+ ))}+ </Select>+ </FormControl>+ )}+ />+ </div>++ {!isSingleEnvironmentMode && (+ <Controller+ control={control}+ name="environment"+ render={({ field: { value, onChange }, fieldState: { error } }) => (+ <FormControl+ label="Environment"+ isError={Boolean(error)}+ errorText={error?.message}+ >+ <FilterableSelect+ options={environments}+ value={value}+ onChange={onChange}+ placeholder="Select the environment to create secret in..."+ getOptionLabel={(option) => option.name}+ getOptionValue={(option) => option.slug}+ menuPlacement="top"+ />+ </FormControl>+ )}+ />+ )}+ </div>+ </div>++ <div className="mt-4 flex items-center space-x-4">+ <Button type="submit" isLoading={isSubmitting}>+ Submit+ </Button>+ <Button variant="outline_bg" onClick={onCancel}>+ Cancel+ </Button>+ </div>+ </form>++ <Modal+ isOpen={showSetupModal}+ onOpenChange={(open) => {+ if (!open) {+ setShowSetupModal(false);+ onCompleted();+ }+ }}+ >+ <ModalContent+ className="max-w-2xl"+ title="Certificate Authentication Setup"+ subTitle="Configure the target host to trust certificates issued by this dynamic secret."+ >+ <div className="flex flex-col">+ <span className="text-sm text-muted">Run this command on the target host:</span>+ <div className="mt-2 flex items-center gap-1">+ <Input value={setupCommand} isDisabled />+ <IconButton+ ariaLabel="copy"+ variant="plain"+ colorSchema="secondary"+ size="sm"+ onClick={() => {+ navigator.clipboard.writeText(setupCommand);+ createNotification({+ text: "Command copied to clipboard",+ type: "info"+ });+ }}+ className="size-8 shrink-0"+ >+ <FontAwesomeIcon icon={faCopy} className="text-label" />+ </IconButton>+ </div>+ <div className="mt-4 flex flex-col gap-1 text-sm text-muted">+ <span>This command will:</span>+ <span>- Install the CA certificate on the target host</span>+ <span>- Configure SSH to trust certificate-based authentication</span>+ <span>- Restart the SSH service</span>+ </div>+ </div>+ <div className="mt-6 flex justify-end">+ <Button+ colorSchema="secondary"+ onClick={() => {+ setShowSetupModal(false);+ onCompleted();+ }}+ >+ Close+ </Button>+ </div>+ </ModalContent>+ </Modal>+ </div>+ );+};diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/CreateDynamicSecretLease.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/CreateDynamicSecretLease.tsxindex 247063142c..830bec608a 100644--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/CreateDynamicSecretLease.tsx+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/CreateDynamicSecretLease.tsx@@ -1,8 +1,9 @@import { ReactNode, useEffect, useState } from "react";import { Controller, useForm } from "react-hook-form";-import { faCheck, faClock, faCopy } from "@fortawesome/free-solid-svg-icons";+import { faCheck, faClock, faCopy, faDownload } from "@fortawesome/free-solid-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";import { zodResolver } from "@hookform/resolvers/zod";+import FileSaver from "file-saver";import { AnimatePresence, motion } from "framer-motion";import ms from "ms";import { z } from "zod";@@ -12,10 +13,12 @@ import { createNotification } from "@app/components/notifications";import {Button,FormControl,+ FormLabel,IconButton,Input,SecretInput,Spinner,+ Tag,Tooltip} from "@app/components/v2";import { useTimedReset, useToggle } from "@app/hooks";@@ -537,6 +540,321 @@ export const CreateKubernetesDynamicSecretLease = ({);};+const sshFormSchema = z.object({+ ttl: z+ .string()+ .refine((val) => ms(val) > 0, "TTL must be a positive number")+ .optional(),+ principals: z.array(z.string().trim().min(1)).min(1, "At least one principal is required")+});++type TSshForm = z.infer<typeof sshFormSchema>;++const SshLeaseOutput = ({+ data,+ firstPrincipal+}: {+ data: { PRIVATE_KEY: string; SIGNED_KEY: string };+ firstPrincipal: string;+}) => {+ const [copyTextPrivateKey, isCopyingPrivateKey, setCopyTextPrivateKey] = useTimedReset<string>({+ initialState: "Copy to clipboard"+ });+ const [copyTextSignedKey, isCopyingSignedKey, setCopyTextSignedKey] = useTimedReset<string>({+ initialState: "Copy to clipboard"+ });++ const downloadTxtFile = (filename: string, content: string) => {+ const blob = new Blob([content], { type: "text/plain;charset=utf-8" });+ FileSaver.saveAs(blob, filename);+ };++ const chmodCommand = "chmod 600 key.pem";+ const sshCommand = `ssh -i key.pem -o CertificateFile=cert.pub ${firstPrincipal}@<hostname>`;++ const copyCommand = (cmd: string) => {+ navigator.clipboard.writeText(cmd);+ createNotification({ text: "Command copied to clipboard", type: "info" });+ };++ return (+ <div>+ <div className="mb-4 flex items-center justify-between">+ <h2 className="text-sm font-medium">Private Key</h2>+ <div className="flex">+ <Tooltip content={copyTextPrivateKey}>+ <IconButton+ ariaLabel="copy icon"+ colorSchema="secondary"+ className="group relative"+ onClick={() => {+ navigator.clipboard.writeText(data.PRIVATE_KEY);+ setCopyTextPrivateKey("Copied");+ }}+ >+ <FontAwesomeIcon icon={isCopyingPrivateKey ? faCheck : faCopy} />+ </IconButton>+ </Tooltip>+ <Tooltip content="Download key.pem">+ <IconButton+ ariaLabel="download icon"+ colorSchema="secondary"+ className="group relative ml-2"+ onClick={() => downloadTxtFile("key.pem", data.PRIVATE_KEY)}+ >+ <FontAwesomeIcon icon={faDownload} />+ </IconButton>+ </Tooltip>+ </div>+ </div>+ <div className="mb-6 max-h-32 thin-scrollbar overflow-auto rounded-md bg-foreground/10 p-2 text-base text-label">+ <p className="mr-4 break-all whitespace-pre-wrap">{data.PRIVATE_KEY}</p>+ </div>+ <div className="mb-4 flex items-center justify-between">+ <h2 className="text-sm font-medium">Signed Certificate</h2>+ <div className="flex">+ <Tooltip content={copyTextSignedKey}>+ <IconButton+ ariaLabel="copy icon"+ colorSchema="secondary"+ className="group relative"+ onClick={() => {+ navigator.clipboard.writeText(data.SIGNED_KEY);+ setCopyTextSignedKey("Copied");+ }}+ >+ <FontAwesomeIcon icon={isCopyingSignedKey ? faCheck : faCopy} />+ </IconButton>+ </Tooltip>+ <Tooltip content="Download cert.pub">+ <IconButton+ ariaLabel="download icon"+ colorSchema="secondary"+ className="group relative ml-2"+ onClick={() => downloadTxtFile("cert.pub", data.SIGNED_KEY)}+ >+ <FontAwesomeIcon icon={faDownload} />+ </IconButton>+ </Tooltip>+ </div>+ </div>+ <div className="mb-6 max-h-32 thin-scrollbar overflow-auto rounded-md bg-foreground/10 p-2 text-base text-label">+ <p className="mr-4 break-all whitespace-pre-wrap">{data.SIGNED_KEY}</p>+ </div>+ <div className="flex flex-col gap-4">+ <div>+ <FormLabel label="Set private key permissions" />+ <div className="flex gap-2">+ <Input value={chmodCommand} isDisabled />+ <IconButton+ ariaLabel="copy"+ variant="outline_bg"+ colorSchema="secondary"+ onClick={() => copyCommand(chmodCommand)}+ className="w-10"+ >+ <FontAwesomeIcon icon={faCopy} />+ </IconButton>+ </div>+ </div>+ <div>+ <FormLabel label="Connect to the target host" />+ <div className="flex gap-2">+ <Input value={sshCommand} isDisabled />+ <IconButton+ ariaLabel="copy"+ variant="outline_bg"+ colorSchema="secondary"+ onClick={() => copyCommand(sshCommand)}+ className="w-10"+ >+ <FontAwesomeIcon icon={faCopy} />+ </IconButton>+ </div>+ </div>+ </div>+ <p className="mt-4 text-xs text-muted">+ Important: Copy or download these credentials now. You will not be able to see them again+ after you close the modal.+ </p>+ </div>+ );+};++export const CreateSshDynamicSecretLease = ({+ onClose,+ projectSlug,+ dynamicSecretName,+ provider,+ secretPath,+ environment+}: Props) => {+ const {+ control,+ formState: { isSubmitting },+ handleSubmit,+ setValue,+ watch+ } = useForm<TSshForm>({+ resolver: zodResolver(sshFormSchema),+ defaultValues: {+ ttl: "1h",+ principals: []+ }+ });++ const [principalInput, setPrincipalInput] = useState("");+ const createDynamicSecretLease = useCreateDynamicSecretLease();+ const principals = watch("principals");++ const handleAddPrincipal = () => {+ const trimmed = principalInput.trim();+ if (trimmed && !principals.includes(trimmed)) {+ setValue("principals", [...principals, trimmed], { shouldValidate: true });+ }+ setPrincipalInput("");+ };++ const handleRemovePrincipal = (idx: number) => {+ setValue(+ "principals",+ principals.filter((_: string, i: number) => i !== idx),+ { shouldValidate: true }+ );+ };++ const handleDynamicSecretLeaseCreate = async ({ ttl, principals: reqPrincipals }: TSshForm) => {+ if (createDynamicSecretLease.isPending) return;+ await createDynamicSecretLease.mutateAsync({+ environmentSlug: environment,+ projectSlug,+ path: secretPath,+ ttl,+ dynamicSecretName,+ config: {+ principals: reqPrincipals+ },+ provider+ });++ createNotification({+ type: "success",+ text: "Successfully leased dynamic secret"+ });+ };++ const isOutputMode = Boolean(createDynamicSecretLease?.data);++ return (+ <div>+ <AnimatePresence>+ {!isOutputMode && (+ <motion.div+ key="lease-input"+ transition={{ duration: 0.1 }}+ initial={{ opacity: 0, translateX: 30 }}+ animate={{ opacity: 1, translateX: 0 }}+ exit={{ opacity: 0, translateX: 30 }}+ >+ <form onSubmit={handleSubmit(handleDynamicSecretLeaseCreate)}>+ <Controller+ control={control}+ name="principals"+ render={({ fieldState: { error } }) => (+ <FormControl+ label="Principals"+ isError={Boolean(error?.message)}+ errorText={error?.message}+ helperText="The usernames to embed in the certificate (must be from the allowed list)"+ >+ <div className="flex flex-col gap-2">+ <div className="flex items-center gap-2">+ <Input+ value={principalInput}+ onChange={(e: React.ChangeEvent<HTMLInputElement>) =>+ setPrincipalInput(e.target.value)+ }+ placeholder="Enter principal name..."+ onKeyDown={(e: React.KeyboardEvent<HTMLInputElement>) => {+ if (e.key === "Enter") {+ e.preventDefault();+ handleAddPrincipal();+ }+ }}+ />+ <Button+ type="button"+ variant="outline_bg"+ size="sm"+ onClick={handleAddPrincipal}+ isDisabled={!principalInput.trim()}+ >+ Add+ </Button>+ </div>+ {principals.length > 0 && (+ <div className="flex flex-wrap gap-1">+ {principals.map((principal: string, idx: number) => (+ <Tag+ className="bg-neutral/15 text-neutral"+ key={principal}+ onClose={() => handleRemovePrincipal(idx)}+ >+ {principal}+ </Tag>+ ))}+ </div>+ )}+ </div>+ </FormControl>+ )}+ />+ <Controller+ control={control}+ name="ttl"+ defaultValue="1h"+ render={({ field, fieldState: { error } }) => (+ <FormControl+ label={<TtlFormLabel label="Default TTL" />}+ isError={Boolean(error?.message)}+ errorText={error?.message}+ >+ <Input {...field} />+ </FormControl>+ )}+ />+ <div className="mt-4 flex items-center space-x-4">+ <Button type="submit" isLoading={isSubmitting}>+ Submit+ </Button>+ <Button variant="outline_bg" onClick={onClose}>+ Cancel+ </Button>+ </div>+ </form>+ </motion.div>+ )}+ {isOutputMode && (+ <motion.div+ key="lease-output"+ transition={{ duration: 0.1 }}+ initial={{ opacity: 0, translateX: 30 }}+ animate={{ opacity: 1, translateX: 0 }}+ exit={{ opacity: 0, translateX: 30 }}+ >+ <SshLeaseOutput+ data={+ createDynamicSecretLease.data?.data as { PRIVATE_KEY: string; SIGNED_KEY: string }+ }+ firstPrincipal={principals[0]}+ />+ </motion.div>+ )}+ </AnimatePresence>+ </div>+ );+};+const formSchema = z.object({ttl: z.string()@@ -624,6 +942,19 @@ export const CreateDynamicSecretLease = ({);}+ if (provider === DynamicSecretProviders.Ssh) {+ return (+ <CreateSshDynamicSecretLease+ onClose={onClose}+ projectSlug={projectSlug}+ dynamicSecretName={dynamicSecretName}+ provider={provider}+ secretPath={secretPath}+ environment={environment}+ />+ );+ }+const isOutputMode = Boolean(createDynamicSecretLease?.data);if (isPreloading) {diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/DynamicSecretLease.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/DynamicSecretLease.tsxindex 1f734de32d..9130bfe973 100644--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/DynamicSecretLease.tsx+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/DynamicSecretLease.tsx@@ -44,7 +44,7 @@ type Props = {onClose: () => void;};-const DYNAMIC_SECRETS_WITHOUT_RENEWAL = [DynamicSecretProviders.Github];+const DYNAMIC_SECRETS_WITHOUT_RENEWAL = [DynamicSecretProviders.Github, DynamicSecretProviders.Ssh];export const DynamicSecretLease = ({projectSlug,diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/EditDynamicSecretForm/EditDynamicSecretForm.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/EditDynamicSecretForm/EditDynamicSecretForm.tsxindex dfaaf68bf0..ee7d61f0be 100644--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/EditDynamicSecretForm/EditDynamicSecretForm.tsx+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/EditDynamicSecretForm/EditDynamicSecretForm.tsx@@ -24,6 +24,7 @@ import { EditDynamicSecretSapAseForm } from "./EditDynamicSecretSapAseForm";import { EditDynamicSecretSapHanaForm } from "./EditDynamicSecretSapHanaForm";import { EditDynamicSecretSnowflakeForm } from "./EditDynamicSecretSnowflakeForm";import { EditDynamicSecretSqlProviderForm } from "./EditDynamicSecretSqlProviderForm";+import { EditDynamicSecretSshForm } from "./EditDynamicSecretSshForm";import { EditDynamicSecretTotpForm } from "./EditDynamicSecretTotpForm";import { EditDynamicSecretVerticaForm } from "./EditDynamicSecretVertica";@@ -439,6 +440,23 @@ export const EditDynamicSecretForm = ({/></motion.div>)}+ {dynamicSecretDetails?.type === DynamicSecretProviders.Ssh && (+ <motion.div+ key="ssh-edit"+ transition={{ duration: 0.1 }}+ initial={{ opacity: 0, translateX: 30 }}+ animate={{ opacity: 1, translateX: 0 }}+ exit={{ opacity: 0, translateX: -30 }}+ >+ <EditDynamicSecretSshForm+ onClose={onClose}+ projectSlug={projectSlug}+ secretPath={secretPath}+ dynamicSecret={dynamicSecretDetails}+ environment={environment}+ />+ </motion.div>+ )}</AnimatePresence>);};diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/EditDynamicSecretForm/EditDynamicSecretSshForm.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/EditDynamicSecretForm/EditDynamicSecretSshForm.tsxnew file mode 100644index 0000000000..fd49d976b6--- /dev/null+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/DynamicSecretListView/EditDynamicSecretForm/EditDynamicSecretSshForm.tsx@@ -0,0 +1,366 @@+import { useState } from "react";+import { Controller, useForm } from "react-hook-form";+import { faCopy } from "@fortawesome/free-regular-svg-icons";+import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";+import { zodResolver } from "@hookform/resolvers/zod";+import { ChevronDownIcon, ShieldIcon } from "lucide-react";+import ms from "ms";+import { twMerge } from "tailwind-merge";+import { z } from "zod";++import { TtlFormLabel } from "@app/components/features";+import { createNotification } from "@app/components/notifications";+import {+ Button,+ FormControl,+ IconButton,+ Input,+ Select,+ SelectItem,+ Tag+} from "@app/components/v2";+import { useUpdateDynamicSecret } from "@app/hooks/api";+import { TDynamicSecret } from "@app/hooks/api/dynamicSecret/types";+import { getAuthToken } from "@app/hooks/api/reactQuery";+import { SshCertKeyAlgorithm, sshCertKeyAlgorithms } from "@app/hooks/api/sshCa/constants";+import { slugSchema } from "@app/lib/schemas";++const sshCertKeyAlgorithmsArray = sshCertKeyAlgorithms.map((a) => a.value);++const formSchema = z+ .object({+ inputs: z.object({+ principals: z.array(z.string().trim().min(1)).min(1, "At least one principal is required"),+ keyAlgorithm: z.enum(sshCertKeyAlgorithmsArray as [string, ...string[]])+ }),+ defaultTTL: z.string().superRefine((val, ctx) => {+ const valMs = ms(val);+ if (valMs < 60 * 1000)+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: "TTL must be a greater than 1min" });+ if (valMs > ms("10y"))+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: "TTL must be less than 10 years" });+ }),+ maxTTL: z+ .string()+ .optional()+ .superRefine((val, ctx) => {+ if (!val) return;+ const valMs = ms(val);+ if (valMs < 60 * 1000)+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: "TTL must be a greater than 1min" });+ if (valMs > ms("10y"))+ ctx.addIssue({ code: z.ZodIssueCode.custom, message: "TTL must be less than 10 years" });+ })+ .nullable(),+ newName: slugSchema({ field: "Name" }).optional()+ })+ .refine((d) => !d.maxTTL || ms(d.maxTTL)! >= ms(d.defaultTTL)!, {+ path: ["maxTTL"],+ message: "Max TTL must be greater than or equal to Default TTL"+ });+type TForm = z.infer<typeof formSchema>;++type Props = {+ onClose: () => void;+ dynamicSecret: TDynamicSecret & { inputs: unknown };+ secretPath: string;+ environment: string;+ projectSlug: string;+};++export const EditDynamicSecretSshForm = ({+ onClose,+ dynamicSecret,+ secretPath,+ environment,+ projectSlug+}: Props) => {+ const sshInputs = dynamicSecret.inputs as {+ caPublicKey?: string;+ principals: string[];+ keyAlgorithm: string;+ };++ const {+ control,+ formState: { isSubmitting },+ handleSubmit,+ setValue,+ watch+ } = useForm<TForm>({+ resolver: zodResolver(formSchema),+ values: {+ newName: dynamicSecret.name,+ defaultTTL: dynamicSecret.defaultTTL,+ maxTTL: dynamicSecret.maxTTL,+ inputs: {+ principals: sshInputs.principals || [],+ keyAlgorithm: sshInputs.keyAlgorithm || SshCertKeyAlgorithm.ED25519+ }+ }+ });++ const [principalInput, setPrincipalInput] = useState("");+ const [cmdOpen, setCmdOpen] = useState(false);++ const updateDynamicSecret = useUpdateDynamicSecret();++ const principals = watch("inputs.principals");++ const handleUpdateDynamicSecret = async ({ inputs, newName, defaultTTL, maxTTL }: TForm) => {+ if (updateDynamicSecret.isPending) return;+ await updateDynamicSecret.mutateAsync({+ name: dynamicSecret.name,+ path: secretPath,+ projectSlug,+ environmentSlug: environment,+ data: {+ inputs: {+ principals: inputs.principals,+ keyAlgorithm: inputs.keyAlgorithm+ },+ newName: newName === dynamicSecret.name ? undefined : newName,+ defaultTTL,+ maxTTL: maxTTL || undefined+ }+ });+ onClose();+ createNotification({+ type: "success",+ text: "Successfully updated dynamic secret"+ });+ };++ const handleAddPrincipal = () => {+ const trimmed = principalInput.trim();+ if (trimmed && !principals.includes(trimmed)) {+ setValue("inputs.principals", [...principals, trimmed], { shouldValidate: true });+ }+ setPrincipalInput("");+ };++ const handleRemovePrincipal = (idx: number) => {+ setValue(+ "inputs.principals",+ principals.filter((_, i) => i !== idx),+ { shouldValidate: true }+ );+ };++ const { protocol, hostname, port } = window.location;+ const portSuffix = port && port !== "80" ? `:${port}` : "";+ const siteURL = `${protocol}//${hostname}${portSuffix}`;++ const setupSshCaCommand = `curl -H "Authorization: Bearer ${getAuthToken()}" "${siteURL}/api/v1/dynamic-secrets/ssh-ca-setup/${dynamicSecret.id}" | sudo bash`;++ return (+ <div>+ <form onSubmit={handleSubmit(handleUpdateDynamicSecret)} autoComplete="off">+ <div>+ <div className="flex items-center space-x-2">+ <div className="grow">+ <Controller+ control={control}+ name="newName"+ render={({ field, fieldState: { error } }) => (+ <FormControl+ label="Secret Name"+ isError={Boolean(error)}+ errorText={error?.message}+ >+ <Input {...field} placeholder="dynamic-secret" />+ </FormControl>+ )}+ />+ </div>+ <div className="w-32">+ <Controller+ control={control}+ name="defaultTTL"+ render={({ field, fieldState: { error } }) => (+ <FormControl+ label={<TtlFormLabel label="Default TTL" />}+ isError={Boolean(error?.message)}+ errorText={error?.message}+ >+ <Input {...field} />+ </FormControl>+ )}+ />+ </div>+ <div className="w-32">+ <Controller+ control={control}+ name="maxTTL"+ render={({ field, fieldState: { error } }) => (+ <FormControl+ label={<TtlFormLabel label="Max TTL" />}+ isError={Boolean(error?.message)}+ errorText={error?.message}+ >+ <Input {...field} value={field.value || ""} />+ </FormControl>+ )}+ />+ </div>+ </div>+ <div>+ <div className="mt-4 mb-4 border-b border-border pb-2 pl-1 font-medium text-label">+ Configuration+ </div>++ <div className="flex flex-col">+ <Controller+ control={control}+ name="inputs.principals"+ render={({ fieldState: { error } }) => (+ <FormControl+ label="Allowed Principals"+ isError={Boolean(error?.message)}+ errorText={error?.message}+ helperText="The usernames this dynamic secret can issue certificates for"+ isRequired+ >+ <div className="flex flex-col gap-2">+ <div className="flex items-center gap-2">+ <Input+ value={principalInput}+ onChange={(e) => setPrincipalInput(e.target.value)}+ placeholder="Enter principal name..."+ onKeyDown={(e) => {+ if (e.key === "Enter") {+ e.preventDefault();+ handleAddPrincipal();+ }+ }}+ />+ <Button+ type="button"+ variant="outline_bg"+ size="sm"+ onClick={handleAddPrincipal}+ isDisabled={!principalInput.trim()}+ >+ Add+ </Button>+ </div>+ {principals.length > 0 && (+ <div className="flex flex-wrap gap-1">+ {principals.map((principal, idx) => (+ <Tag+ className="bg-neutral/15 text-neutral"+ key={principal}+ onClose={() => handleRemovePrincipal(idx)}+ >+ {principal}+ </Tag>+ ))}+ </div>+ )}+ </div>+ </FormControl>+ )}+ />++ <Controller+ control={control}+ name="inputs.keyAlgorithm"+ render={({ field: { value, onChange }, fieldState: { error } }) => (+ <FormControl+ label="Key Algorithm"+ isError={Boolean(error?.message)}+ errorText={error?.message}+ helperText="Algorithm for ephemeral key pairs generated per lease"+ >+ <Select value={value} onValueChange={onChange} className="w-full">+ {sshCertKeyAlgorithms.map((alg) => (+ <SelectItem key={alg.value} value={alg.value}>+ {alg.label}+ </SelectItem>+ ))}+ </Select>+ </FormControl>+ )}+ />+ </div>++ <button+ type="button"+ onClick={() => setCmdOpen(!cmdOpen)}+ className="flex w-full cursor-pointer flex-col rounded-md border border-border bg-container p-3 text-sm hover:bg-container-hover"+ >+ <div className="flex gap-2.5">+ <ShieldIcon className="mt-0.5 size-6 shrink-0 text-info" />+ <div className="flex w-full flex-col">+ <div className="flex justify-between gap-2 pr-1">+ <div className="flex flex-col text-left">+ <span className="text-base">Certificate-Based Authentication</span>+ <span className="text-sm text-muted">+ Run this command on target hosts to trust certificates from this dynamic+ secret+ </span>+ </div>+ <ChevronDownIcon+ className={twMerge(+ "shrink-0 text-muted transition-transform duration-200 ease-in-out",+ cmdOpen && "rotate-180"+ )}+ />+ </div>+ <div+ className={twMerge(+ "grid transition-all duration-200 ease-in-out",+ cmdOpen ? "mt-2 grid-rows-[1fr]" : "mt-0 grid-rows-[0fr]"+ )}+ >+ <div className="overflow-hidden">+ <div className="flex flex-col text-left">+ <span className="mt-2 text-sm text-muted">+ Run this command on the target host:+ </span>+ <div className="mt-1 flex items-center gap-1">+ <Input value={setupSshCaCommand} isDisabled />+ <IconButton+ ariaLabel="copy"+ variant="plain"+ colorSchema="secondary"+ size="sm"+ onClick={(e) => {+ e.stopPropagation();+ navigator.clipboard.writeText(setupSshCaCommand);+ createNotification({+ text: "Command copied to clipboard",+ type: "info"+ });+ }}+ className="size-8 shrink-0"+ >+ <FontAwesomeIcon icon={faCopy} className="text-label" />+ </IconButton>+ </div>+ <div className="mt-4 flex flex-col gap-1 text-xs text-muted">+ <span>This command will:</span>+ <span>- Install the CA certificate on the target host</span>+ <span>- Configure SSH to trust certificate-based authentication</span>+ <span>- Restart the SSH service</span>+ </div>+ </div>+ </div>+ </div>+ </div>+ </div>+ </button>+ </div>+ </div>+ <div className="mt-4 flex items-center space-x-4">+ <Button type="submit" isLoading={isSubmitting}>+ Submit+ </Button>+ <Button variant="outline_bg" onClick={onClose}>+ Cancel+ </Button>+ </div>+ </form>+ </div>+ );+};