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
PKI sync post-sync command UI improvements
Carlos Monastyrski5f512896b946
diff --git a/backend/src/services/pki-sync/pki-sync-post-sync-command-fns.ts b/backend/src/services/pki-sync/pki-sync-post-sync-command-fns.tsindex e48830525b..5f15b41401 100644--- a/backend/src/services/pki-sync/pki-sync-post-sync-command-fns.ts+++ b/backend/src/services/pki-sync/pki-sync-post-sync-command-fns.ts@@ -13,8 +13,8 @@ export enum PostSyncCommandVariable {Pkcs12Password = "pkcs12Password"}-// Matches a {{name}} placeholder.-const PLACEHOLDER_PATTERN = new RE2("\\{\\{\\s*([a-zA-Z0-9_]+)\\s*\\}\\}", "g");+// Matches a {{name}} variable.+const VARIABLE_PATTERN = new RE2("\\{\\{\\s*([a-zA-Z0-9_]+)\\s*\\}\\}", "g");const isPostSyncCommandVariable = (name: string): name is PostSyncCommandVariable =>(Object.values(PostSyncCommandVariable) as string[]).includes(name);@@ -31,7 +31,7 @@ export const findSingleCertificatePostSyncCommandVariables = (command?: string):if (!command) return [];const used = new Set<string>();- command.replace(PLACEHOLDER_PATTERN, (match: string, name: string) => {+ command.replace(VARIABLE_PATTERN, (match: string, name: string) => {used.add(name);return match;});@@ -116,7 +116,7 @@ export const buildPostSyncCommandPlan = (args: {throw new PkiSyncError({message: `Post-sync command uses ${formatPostSyncCommandVariables(singleCertificateVariables- )}. A placeholder that names one certificate cannot be resolved for a run that delivered ${+ )}. A variable that names one certificate cannot be resolved for a run that delivered ${deliveredCertificates.length} certificates. Unlink all but one certificate, or use {{certificateFiles}} instead.`,shouldRetry: false@@ -165,7 +165,7 @@ export const renderPostSyncCommand = ([PostSyncCommandVariable.Pkcs12Password, context.pkcs12Password]]);- return command.replace(PLACEHOLDER_PATTERN, (match: string, name: string) =>+ return command.replace(VARIABLE_PATTERN, (match: string, name: string) =>isPostSyncCommandVariable(name) ? toShellLiteral(values.get(name) ?? "") : match);};diff --git a/backend/src/services/pki-sync/pki-sync-service.ts b/backend/src/services/pki-sync/pki-sync-service.tsindex 0ab0edb442..a57f5954ad 100644--- a/backend/src/services/pki-sync/pki-sync-service.ts+++ b/backend/src/services/pki-sync/pki-sync-service.ts@@ -287,7 +287,7 @@ export const pkiSyncServiceFactory = ({throw new BadRequestError({message: `This sync's post-sync command uses ${formatPostSyncCommandVariables(singleCertificateVariables- )}. A placeholder that names one certificate can only be used on a sync with a single certificate linked. Use {{certificateFiles}} or {{certificateDirectory}} to write a command that covers every certificate in the run.`+ )}. A variable that names one certificate can only be used on a sync with a single certificate linked. Use {{certificateFiles}} or {{certificateDirectory}} to write a command that covers every certificate in the run.`});}};diff --git a/docs/documentation/platform/pki/applications/certificate-syncs/linux-server.mdx b/docs/documentation/platform/pki/applications/certificate-syncs/linux-server.mdxindex 96360f9cd2..a5e7ea7820 100644--- a/docs/documentation/platform/pki/applications/certificate-syncs/linux-server.mdx+++ b/docs/documentation/platform/pki/applications/certificate-syncs/linux-server.mdx@@ -4,7 +4,8 @@ sidebarTitle: "Linux Server"description: "Deploy certificates to Linux servers over SSH."----import PostSyncCommandPlaceholders from "/snippets/documentation/platform/pki/applications/certificate-syncs/post-sync-command-placeholders.mdx";+import PostSyncCommandVariables from "/snippets/documentation/platform/pki/applications/certificate-syncs/post-sync-command-variables.mdx";+import PostSyncCommandFlow from "/snippets/documentation/platform/pki/applications/certificate-syncs/post-sync-command-flow.mdx";Deploy certificates from Infisical to a directory on a Linux server over SSH. Files are written atomically over SFTP so a reader never sees a partially written certificate or key.@@ -17,7 +18,7 @@ Deploy certificates from Infisical to a directory on a Linux server over SSH. Fi- An [SSH Connection](/integrations/app-connections/ssh) with access to the target server- The destination directory must already exist on the server and the connection user must be able to write to it- The server must be reachable from Infisical, either directly or through an [Infisical Gateway](/documentation/platform/gateways/overview)-- A Gateway is required to use a [post-sync command](#post-sync-commands), because the Gateway is what executes it+- A Gateway is required to use a [post-sync command](#post-sync-commands), because the Gateway is what executes it. It must be running Infisical CLI v0.43.117 or later## Create a Linux Server Sync@@ -45,7 +46,7 @@ Deploy certificates from Infisical to a directory on a Linux server over SSH. Fi- **Auto-Sync Enabled**: Automatically sync certificates when changes occur.5. Configure the **Post-Sync Command**, or leave it empty:- - **Command**: A command run on the server after the sync delivers a certificate, so the service that uses it picks up the new file, for example `sudo systemctl reload nginx`. [Post-Sync Commands](#post-sync-commands) covers the available placeholders and what happens when the command fails.+ - **Command**: A command run on the server after the sync delivers a certificate, so the service that uses it picks up the new file, for example `sudo systemctl reload nginx`. [Post-Sync Commands](#post-sync-commands) covers the available variables and what happens when the command fails.6. Configure the **Details**:- **Name**: The name of your sync.@@ -120,24 +121,11 @@ The field accepts a whole script, so several steps can run in one go: put each o<Note>Your [Infisical Gateway](/documentation/platform/gateways/overview) runs the command, never Infisical. The sync's SSH Connection must therefore use a gateway, otherwise the command is rejected when you save the sync.++ The Gateway must be running Infisical CLI **v0.43.117 or later**, the release that shipped Gateway-side support for post-sync commands. On an older Gateway the command fails whenever the SSH Connection authenticates with a passphrase-protected private key, because that Gateway cannot unlock the key. Run `infisical --version` on the Gateway host to check, and see [Gateway deployment](/documentation/platform/gateways/gateway-deployment) for how to upgrade.</Note>-The command runs on the target server, not on Infisical, and only after the whole delivery has finished:--```mermaid-sequenceDiagram- participant I as Infisical- participant G as Gateway- participant S as Target server- I->>G: Deliver certificate files- G->>S: Write files- G->>S: Remove files for certificates no longer synced- Note over G,S: Only once the server is in its final state- I->>G: Run the post-sync command- G->>S: Execute as the connection's account- S-->>G: Output and outcome- G-->>I: Success, or the reason it failed-```+<PostSyncCommandFlow />### Setting a Command@@ -146,7 +134,7 @@ sequenceDiagramEdit the sync and select **Post-Sync Command**.</Step><Step title="Write the command">- Use a placeholder wherever you need a value from the run:+ Use a variable wherever you need a value from the run. Typing `{{` in the command field lists the ones available for this sync, so you can pick one instead of remembering the name:```bashcp {{certificatePath}} /etc/nginx/ssl/live.pem && systemctl reload nginx@@ -157,13 +145,13 @@ sequenceDiagram</Step></Steps>-### Available Placeholders+### Available Variables-<PostSyncCommandPlaceholders />+<PostSyncCommandVariables />### Length Limit-A command is limited to 2048 characters, counted after the placeholders are substituted. For anything longer, put the logic in a script on the server and call that script.+A command is limited to 2048 characters, counted after the variables are substituted. For anything longer, put the logic in a script on the server and call that script.### Post-Sync Command FAQdiff --git a/docs/documentation/platform/pki/applications/certificate-syncs/windows-server.mdx b/docs/documentation/platform/pki/applications/certificate-syncs/windows-server.mdxindex ba043cad8c..f73220ff06 100644--- a/docs/documentation/platform/pki/applications/certificate-syncs/windows-server.mdx+++ b/docs/documentation/platform/pki/applications/certificate-syncs/windows-server.mdx@@ -4,7 +4,8 @@ sidebarTitle: "Windows Server"description: "Deploy certificates to Windows servers over WinRM."----import PostSyncCommandPlaceholders from "/snippets/documentation/platform/pki/applications/certificate-syncs/post-sync-command-placeholders.mdx";+import PostSyncCommandVariables from "/snippets/documentation/platform/pki/applications/certificate-syncs/post-sync-command-variables.mdx";+import PostSyncCommandFlow from "/snippets/documentation/platform/pki/applications/certificate-syncs/post-sync-command-flow.mdx";Deploy certificates from Infisical to a directory on a Windows server over WinRM. Files are written atomically so a reader never sees a partially written certificate or key.@@ -15,7 +16,7 @@ Deploy certificates from Infisical to a directory on a Windows server over WinRM## Prerequisites- A [Windows (WinRM) Connection](/integrations/app-connections/winrm) with access to the target server-- An [Infisical Gateway](/documentation/platform/gateways/overview) that can reach the server. Windows delivery always runs through the Gateway.+- An [Infisical Gateway](/documentation/platform/gateways/overview) that can reach the server. Windows delivery always runs through the Gateway. A [post-sync command](#post-sync-commands) additionally needs the Gateway to be running Infisical CLI v0.43.117 or later.- The connection user must be able to write to the destination directory<Note>@@ -47,7 +48,7 @@ Deploy certificates from Infisical to a directory on a Windows server over WinRM- **Auto-Sync Enabled**: Automatically sync certificates when changes occur.5. Configure the **Post-Sync Command**, or leave it empty:- - **Command**: A PowerShell command run on the server after the sync delivers a certificate, so the service that uses it picks up the new file, for example `Restart-Service -Name "W3SVC"`. [Post-Sync Commands](#post-sync-commands) covers the available placeholders and what happens when the command fails.+ - **Command**: A PowerShell command run on the server after the sync delivers a certificate, so the service that uses it picks up the new file, for example `Restart-Service -Name "W3SVC"`. [Post-Sync Commands](#post-sync-commands) covers the available variables and what happens when the command fails.6. Configure the **Details**:- **Name**: The name of your sync.@@ -128,22 +129,11 @@ The field accepts a whole script, so several steps can run in one go: put each oYour Gateway runs the command, never Infisical. A WinRM Connection already requires a gateway, so nothing extra is needed here.-The command runs on the target server, not on Infisical, and only after the whole delivery has finished:--```mermaid-sequenceDiagram- participant I as Infisical- participant G as Gateway- participant S as Target server- I->>G: Deliver certificate files- G->>S: Write files- G->>S: Remove files for certificates no longer synced- Note over G,S: Only once the server is in its final state- I->>G: Run the post-sync command- G->>S: Execute as the connection's account- S-->>G: Output and outcome- G-->>I: Success, or the reason it failed-```+<Note>+ The Gateway must be running Infisical CLI **v0.43.117 or later**, the release that shipped Gateway-side support for post-sync commands. An older Gateway has no PowerShell run-command endpoint and rejects the request. Run `infisical --version` on the Gateway host to check, and see [Gateway deployment](/documentation/platform/gateways/gateway-deployment) for how to upgrade.+</Note>++<PostSyncCommandFlow />### Setting a Command@@ -152,7 +142,7 @@ sequenceDiagramEdit the sync and select **Post-Sync Command**.</Step><Step title="Write the command">- Use a placeholder wherever you need a value from the run:+ Use a variable wherever you need a value from the run. Typing `{{` in the command field lists the ones available for this sync, so you can pick one instead of remembering the name:```powershellImport-PfxCertificate -FilePath {{certificatePath}} -CertStoreLocation Cert:\LocalMachine\My -Password (ConvertTo-SecureString {{pkcs12Password}} -AsPlainText -Force)@@ -163,9 +153,9 @@ sequenceDiagram</Step></Steps>-### Available Placeholders+### Available Variables-<PostSyncCommandPlaceholders />+<PostSyncCommandVariables />### Length Limitdiff --git a/docs/snippets/documentation/platform/pki/applications/certificate-syncs/post-sync-command-flow.mdx b/docs/snippets/documentation/platform/pki/applications/certificate-syncs/post-sync-command-flow.mdxnew file mode 100644index 0000000000..6ab26a88b6--- /dev/null+++ b/docs/snippets/documentation/platform/pki/applications/certificate-syncs/post-sync-command-flow.mdx@@ -0,0 +1,16 @@+The command runs on the target server, not on Infisical, and only after the whole delivery has finished:++```mermaid+sequenceDiagram+ participant I as Infisical+ participant G as Gateway+ participant S as Target server+ I->>G: Deliver certificate files+ G->>S: Write files+ G->>S: Remove files for certificates no longer synced+ Note over G,S: Only once the server is in its final state+ I->>G: Run the post-sync command+ G->>S: Execute as the connection's account+ S-->>G: Output and outcome+ G-->>I: Success, or the reason it failed+```diff --git a/docs/snippets/documentation/platform/pki/applications/certificate-syncs/post-sync-command-placeholders.mdx b/docs/snippets/documentation/platform/pki/applications/certificate-syncs/post-sync-command-variables.mdxsimilarity index 63%rename from docs/snippets/documentation/platform/pki/applications/certificate-syncs/post-sync-command-placeholders.mdxrename to docs/snippets/documentation/platform/pki/applications/certificate-syncs/post-sync-command-variables.mdxindex 0c7edaf6f1..5aba170711 100644--- a/docs/snippets/documentation/platform/pki/applications/certificate-syncs/post-sync-command-placeholders.mdx+++ b/docs/snippets/documentation/platform/pki/applications/certificate-syncs/post-sync-command-variables.mdx@@ -1,6 +1,6 @@-Write a placeholder where you want this run's value. Infisical replaces it before the command is sent to the server, so the command keeps working when the name schema or export format changes.+Write a variable where you want this run's value. Infisical replaces it before the command is sent to the server, so the command keeps working when the name schema or export format changes.-| Placeholder | Value |+| Variable | Value || --- | --- || `{{certificatePath}}` | Full path of the certificate file delivered this run. Single-certificate syncs only || `{{certificateDirectory}}` | The destination directory |@@ -8,12 +8,12 @@ Write a placeholder where you want this run's value. Infisical replaces it befor| `{{commonName}}` | The certificate's common name. Single-certificate syncs only || `{{pkcs12Password}}` | The PKCS#12 export password, set only when the export format is PKCS#12 |-Each value is inserted already quoted for the target's shell, so write `{{certificatePath}}` rather than `"{{certificatePath}}"`. A placeholder that has no value for the run becomes an empty string.+Each value is inserted already quoted for the target's shell, so write `{{certificatePath}}` rather than `"{{certificatePath}}"`. A variable that has no value for the run becomes an empty string.-Only the names in this table are substituted. Anything else in double braces is left in the command exactly as you wrote it, so a command that calls a tool with its own braces (helm, jq, a Go template) keeps working, and a misspelled placeholder reaches the server as literal text rather than silently turning into nothing.+Only the names in this table are substituted. Anything else in double braces is left in the command exactly as you wrote it, so a command that calls a tool with its own braces (helm, jq, a Go template) keeps working, and a misspelled variable reaches the server as literal text rather than silently turning into nothing.<Note>- `{{certificatePath}}` and `{{commonName}}` name one specific certificate, so a command that uses either can only be saved on a sync with a single certificate linked. Linking a second certificate to such a sync is rejected, as is adding one of these placeholders to a sync that already has several. To act on every certificate in the run, use `{{certificateFiles}}`, which lists one path per line:+ `{{certificatePath}}` and `{{commonName}}` name one specific certificate, so a command that uses either can only be saved on a sync with a single certificate linked. Linking a second certificate to such a sync is rejected, as is adding one of these variables to a sync that already has several. To act on every certificate in the run, use `{{certificateFiles}}`, which lists one path per line:```bashecho {{certificateFiles}} | while read -r file; do echo "delivered $file"; donediff --git a/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsx b/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsxindex 97415fe311..c9e8380b5d 100644--- a/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsx+++ b/frontend/src/components/pki-syncs/forms/CreatePkiSyncForm.tsx@@ -84,7 +84,7 @@ const STEP_META: Record<subtitle: "Optionally run a command on the host after certificates are written.",rightLabel: "POST-SYNC COMMAND",rightDescription:- "Run a command on the destination host after certificates are written, for example to reload a service so it picks up the new certificate."+ "The gateway runs your command on the destination host once the run's files are in place, so a service can reload and pick up the new certificate. It only runs when the sync delivers a file, and a failure marks the sync failed."},details: {short: "Name and description",diff --git a/frontend/src/components/pki-syncs/forms/EditPkiSyncForm.tsx b/frontend/src/components/pki-syncs/forms/EditPkiSyncForm.tsxindex 6a2356fe69..3cb794cbee 100644--- a/frontend/src/components/pki-syncs/forms/EditPkiSyncForm.tsx+++ b/frontend/src/components/pki-syncs/forms/EditPkiSyncForm.tsx@@ -94,7 +94,7 @@ const getFormSteps = (destination: PkiSync, canRunPostSyncCommand: boolean): Forsubtitle: "Optionally run a command on the host after certificates are written.",rightLabel: "POST-SYNC COMMAND",rightDescription:- "Run a command on the destination host after certificates are written, for example to reload a service so it picks up the new certificate."+ "The gateway runs your command on the destination host once the run's files are in place, so a service can reload and pick up the new certificate. It only runs when the sync delivers a file, and a failure marks the sync failed."});}diff --git a/frontend/src/components/pki-syncs/forms/PkiSyncPostSyncCommandFields.tsx b/frontend/src/components/pki-syncs/forms/PkiSyncPostSyncCommandFields.tsxindex ae8b0cbf78..49e4076bf9 100644--- a/frontend/src/components/pki-syncs/forms/PkiSyncPostSyncCommandFields.tsx+++ b/frontend/src/components/pki-syncs/forms/PkiSyncPostSyncCommandFields.tsx@@ -1,4 +1,6 @@+import { Fragment } from "react";import { Controller, useFormContext } from "react-hook-form";+import { Info } from "lucide-react";import {Badge,@@ -6,10 +8,17 @@ import {FieldDescription,FieldError,FieldLabel,- TextArea+ Tooltip,+ TooltipContent,+ TooltipTrigger} from "@app/components/v3";+import {+ POST_SYNC_COMMAND_VARIABLE_DESCRIPTIONS,+ SINGLE_CERTIFICATE_POST_SYNC_COMMAND_VARIABLES+} from "@app/helpers/pkiSyncs";import { PkiSync, PkiSyncExportFormat, PostSyncCommandVariable } from "@app/hooks/api/pkiSyncs";+import { PostSyncCommandInput } from "./PostSyncCommandInput";import { TPkiSyncForm } from "./schemas/pki-sync-schema";const COMMAND_PLACEHOLDERS: Partial<Record<PkiSync, string>> = {@@ -17,18 +26,42 @@ const COMMAND_PLACEHOLDERS: Partial<Record<PkiSync, string>> = {[PkiSync.WindowsServer]: 'Restart-Service -Name "W3SVC"'};-const VARIABLE_DESCRIPTIONS: Record<PostSyncCommandVariable, string> = {- [PostSyncCommandVariable.CertificatePath]: "Full path of the certificate file delivered this run",- [PostSyncCommandVariable.CertificateDirectory]: "The destination directory",- [PostSyncCommandVariable.CertificateFiles]: "Every path written this run, one per line",- [PostSyncCommandVariable.CommonName]: "The certificate's common name",- [PostSyncCommandVariable.Pkcs12Password]: "The PKCS#12 export password"-};--const SINGLE_CERTIFICATE_VARIABLES = [- PostSyncCommandVariable.CertificatePath,- PostSyncCommandVariable.CommonName-];+// Anchored to one side with a gap: a tall tooltip left to collision-flip lands under the cursor for+// a frame, and Radix sets pointer-events:auto inline on the content inside a modal, so it steals the+// hover and the tooltip flickers open/closed.+const PostSyncCommandVariablesTooltip = ({+ variables+}: {+ variables: PostSyncCommandVariable[];+}) => (+ <Tooltip>+ <TooltipTrigger asChild>+ <Info />+ </TooltipTrigger>+ <TooltipContent side="right" sideOffset={8} collisionPadding={16} className="max-w-md">+ <p className="mb-2 font-medium">Available variables</p>+ <div className="grid grid-cols-[auto_1fr] items-center gap-x-3 gap-y-1.5">+ {variables.map((variable) => (+ <Fragment key={variable}>+ <Badge variant="neutral" className="font-mono">+ {`{{${variable}}}`}+ </Badge>+ <span>+ {POST_SYNC_COMMAND_VARIABLE_DESCRIPTIONS[variable]}+ {SINGLE_CERTIFICATE_POST_SYNC_COMMAND_VARIABLES.includes(variable) &&+ ". Single-certificate syncs only"}+ </span>+ </Fragment>+ ))}+ </div>+ <p className="mt-2">+ Type <span className="font-mono">{"{{"}</span> in the command to pick one. Each variable is+ replaced with its value before the command is sent to the host, and is inserted already+ quoted, so do not wrap one in quotes yourself. Do not paste secrets into the command.+ </p>+ </TooltipContent>+ </Tooltip>+);type Props = {destination?: PkiSync;@@ -45,59 +78,32 @@ export const PkiSyncPostSyncCommandFields = ({ destination, canEditCommand = tru);return (- <>- <p className="mb-4 text-sm text-bunker-300">- Run a command on the target server after a certificate is delivered, for example restarting- the service that uses it. Reference this run's values with the placeholders below.- Leave it empty to run nothing.- </p>- <Controller- control={control}- name="syncOptions.postSyncCommand"- render={({ field: { value, onChange }, fieldState: { error } }) => (- <Field data-invalid={Boolean(error)} data-disabled={!canEditCommand}>- <FieldLabel htmlFor="post-sync-command">Command</FieldLabel>- <TextArea- id="post-sync-command"- className="min-h-24 font-mono text-xs"- value={value ?? ""}- onChange={onChange}- isError={Boolean(error)}- readOnly={!canEditCommand}- disabled={!canEditCommand}- placeholder={canEditCommand ? COMMAND_PLACEHOLDERS[currentDestination] : undefined}- />- <FieldDescription>- {canEditCommand- ? "Runs once per sync run that delivers a file, as the sync's account, so keep that account least-privilege. If it fails, the sync is marked failed. The command is executed by the gateway, so the sync's connection must use one."- : "You do not have permission to set a post-sync command on this sync. Ask an administrator to change it."}- </FieldDescription>- <FieldError>{error?.message}</FieldError>- </Field>- )}- />- <div className="flex flex-col gap-2">- <p className="text-xs text-mineshaft-300">Available placeholders</p>- <ul className="flex flex-col gap-1.5">- {variables.map((variable) => (- <li key={variable} className="flex items-center gap-2">- <Badge variant="neutral" className="font-mono">- {`{{${variable}}}`}- </Badge>- <span className="text-xs text-mineshaft-400">- {VARIABLE_DESCRIPTIONS[variable]}- {SINGLE_CERTIFICATE_VARIABLES.includes(variable) &&- ". Single-certificate syncs only"}- </span>- </li>- ))}- </ul>- <p className="text-xs text-mineshaft-400">- Each placeholder is replaced with its value before the command is sent to the host, and is- inserted already quoted, so do not wrap one in quotes yourself. Do not paste secrets into- the command.- </p>- </div>- </>+ <Controller+ control={control}+ name="syncOptions.postSyncCommand"+ render={({ field: { value, onChange }, fieldState: { error } }) => (+ <Field data-invalid={Boolean(error)} data-disabled={!canEditCommand}>+ <FieldLabel htmlFor="post-sync-command">+ Command+ <PostSyncCommandVariablesTooltip variables={variables} />+ </FieldLabel>+ <PostSyncCommandInput+ id="post-sync-command"+ value={value ?? ""}+ onChange={onChange}+ variables={variables}+ isError={Boolean(error)}+ isDisabled={!canEditCommand}+ placeholder={canEditCommand ? COMMAND_PLACEHOLDERS[currentDestination] : undefined}+ />+ <FieldDescription>+ {canEditCommand+ ? "Runs once per sync run that delivers a file, as the sync's account, so keep that account least-privilege. If it fails, the sync is marked failed. The command is executed by the gateway, so the sync's connection must use one."+ : "You do not have permission to set a post-sync command on this sync. Ask an administrator to change it."}+ </FieldDescription>+ <FieldError>{error?.message}</FieldError>+ </Field>+ )}+ />);};diff --git a/frontend/src/components/pki-syncs/forms/PkiSyncReviewFields.tsx b/frontend/src/components/pki-syncs/forms/PkiSyncReviewFields.tsxindex a56c87d09c..b9c2716450 100644--- a/frontend/src/components/pki-syncs/forms/PkiSyncReviewFields.tsx+++ b/frontend/src/components/pki-syncs/forms/PkiSyncReviewFields.tsx@@ -3,6 +3,7 @@ import { useFormContext } from "react-hook-form";import {Badge,+ CodeBlock,Table,TableBody,TableCell,@@ -180,12 +181,10 @@ export const PkiSyncReviewFields = () => {</div>{postSyncCommand && (<div className="flex flex-col gap-3">- <div className="w-full border-b border-mineshaft-600">- <span className="text-sm text-mineshaft-300">Post-Sync Command</span>+ <div className="w-full border-b border-border">+ <span className="text-sm text-muted">Post-Sync Command</span></div>- <pre className="thin-scrollbar overflow-x-auto rounded-sm bg-mineshaft-600 p-2 font-mono text-xs whitespace-pre-wrap text-mineshaft-200">- {postSyncCommand}- </pre>+ <CodeBlock value={postSyncCommand} className="max-h-48 whitespace-pre-wrap" /></div>)}<div className="flex flex-col gap-3">diff --git a/frontend/src/components/pki-syncs/forms/PostSyncCommandInput.tsx b/frontend/src/components/pki-syncs/forms/PostSyncCommandInput.tsxnew file mode 100644index 0000000000..7397a2d7f5--- /dev/null+++ b/frontend/src/components/pki-syncs/forms/PostSyncCommandInput.tsx@@ -0,0 +1,171 @@+import { useEffect, useRef, useState } from "react";+import * as PopoverPrimitive from "@radix-ui/react-popover";++import { TextArea } from "@app/components/v3";+import { cn } from "@app/components/v3/utils";+import { POST_SYNC_COMMAND_VARIABLE_DESCRIPTIONS } from "@app/helpers/pkiSyncs";+import { PostSyncCommandVariable } from "@app/hooks/api/pkiSyncs";++const OPEN_VARIABLE_PATTERN = /\{\{([a-zA-Z0-9_]*)$/;++type Props = {+ id: string;+ value: string;+ onChange: (value: string) => void;+ variables: PostSyncCommandVariable[];+ placeholder?: string;+ isError?: boolean;+ isDisabled?: boolean;+};++export const PostSyncCommandInput = ({+ id,+ value,+ onChange,+ variables,+ placeholder,+ isError,+ isDisabled+}: Props) => {+ const inputRef = useRef<HTMLTextAreaElement>(null);+ const contentRef = useRef<HTMLDivElement>(null);+ const [cursor, setCursor] = useState(0);+ const [isFocused, setIsFocused] = useState(false);+ const [isDismissed, setIsDismissed] = useState(false);+ const [highlightedIndex, setHighlightedIndex] = useState(0);++ const query = OPEN_VARIABLE_PATTERN.exec(value.slice(0, cursor))?.[1] ?? null;+ const variableStart = query === null ? -1 : cursor - query.length;++ const matches =+ query === null+ ? []+ : variables.filter((variable) => variable.toLowerCase().startsWith(query.toLowerCase()));++ const isOpen = isFocused && !isDismissed && !isDisabled && matches.length > 0;+ const highlightedVariable = matches[highlightedIndex];++ useEffect(() => {+ contentRef.current+ ?.querySelector(`[data-nav-index="${highlightedIndex}"]`)+ ?.scrollIntoView({ block: "nearest" });+ }, [highlightedIndex]);++ const syncCursor = (element: HTMLTextAreaElement) => {+ setCursor(element.selectionStart ?? 0);+ setIsDismissed(false);+ setHighlightedIndex(0);+ };++ const insertVariable = (variable: PostSyncCommandVariable) => {+ if (variableStart === -1) return;++ const hasClosingBraces = value.slice(cursor, cursor + 2) === "}}";+ const before = value.slice(0, variableStart);+ const after = value.slice(hasClosingBraces ? cursor + 2 : cursor);+ const caret = before.length + variable.length + 2;++ onChange(`${before}${variable}}}${after}`);+ setIsDismissed(true);++ setTimeout(() => {+ const element = inputRef.current;+ if (!element) return;+ element.focus();+ element.setSelectionRange(caret, caret);+ setCursor(caret);+ }, 0);+ };++ const handleKeyDown = (event: React.KeyboardEvent<HTMLTextAreaElement>) => {+ if (!isOpen) return;++ if (event.key === "ArrowDown" || event.key === "ArrowUp") {+ event.preventDefault();+ setHighlightedIndex((prev) => {+ const next = event.key === "ArrowDown" ? prev + 1 : prev - 1;+ return (next + matches.length) % matches.length;+ });+ return;+ }+ if (event.key === "Enter" || event.key === "Tab") {+ event.preventDefault();+ if (highlightedVariable) insertVariable(highlightedVariable);+ return;+ }+ if (event.key === "Escape") {+ event.preventDefault();+ setIsDismissed(true);+ }+ };++ return (+ <PopoverPrimitive.Root open={isOpen}>+ <PopoverPrimitive.Trigger asChild>+ <TextArea+ id={id}+ ref={inputRef}+ className="min-h-24 font-mono text-xs"+ value={value}+ placeholder={placeholder}+ isError={isError}+ readOnly={isDisabled}+ disabled={isDisabled}+ onChange={(event) => {+ onChange(event.target.value);+ syncCursor(event.currentTarget);+ }}+ onKeyDown={handleKeyDown}+ onSelect={(event) => setCursor(event.currentTarget.selectionStart ?? 0)}+ onClick={(event) => syncCursor(event.currentTarget)}+ onFocus={(event) => {+ setIsFocused(true);+ setCursor(event.currentTarget.selectionStart ?? 0);+ }}+ onBlur={(event) => {+ if (event.relatedTarget?.getAttribute("aria-label") !== "suggestion-item")+ setIsFocused(false);+ }}+ />+ </PopoverPrimitive.Trigger>+ <PopoverPrimitive.Portal>+ <PopoverPrimitive.Content+ ref={contentRef}+ align="start"+ onOpenAutoFocus={(event) => event.preventDefault()}+ onMouseDown={(event) => event.preventDefault()}+ className="relative top-2 z-[100] max-h-80 thin-scrollbar overflow-auto rounded-md border border-border bg-popover text-foreground shadow-md"+ style={{ width: "var(--radix-popover-trigger-width)", minWidth: "320px" }}+ >+ <div className="px-2 py-1.5 text-[10px] font-semibold tracking-wider text-muted uppercase">+ Available variables+ </div>+ {matches.map((variable, index) => (+ <button+ key={variable}+ type="button"+ aria-label="suggestion-item"+ data-nav-index={index}+ onClick={() => insertVariable(variable)}+ onMouseEnter={() => setHighlightedIndex(index)}+ className={cn(+ "group flex w-full cursor-pointer items-center justify-between gap-4 px-2 py-2 text-left text-sm transition-colors hover:bg-foreground/10",+ highlightedIndex === index && "bg-foreground/10"+ )}+ >+ <div className="flex min-w-0 items-center gap-2">+ <span className="shrink-0">{variable}</span>+ <span className="truncate text-xs text-muted">+ {POST_SYNC_COMMAND_VARIABLE_DESCRIPTIONS[variable]}+ </span>+ </div>+ <span className="shrink-0 text-xs text-muted opacity-0 transition-opacity group-hover:opacity-100">+ insert+ </span>+ </button>+ ))}+ </PopoverPrimitive.Content>+ </PopoverPrimitive.Portal>+ </PopoverPrimitive.Root>+ );+};diff --git a/frontend/src/helpers/pkiSyncs.ts b/frontend/src/helpers/pkiSyncs.tsindex 17fff2c6ea..376b6a46a5 100644--- a/frontend/src/helpers/pkiSyncs.ts+++ b/frontend/src/helpers/pkiSyncs.ts@@ -1,5 +1,5 @@import { AppConnection } from "@app/hooks/api/appConnections";-import { PkiSync } from "@app/hooks/api/pkiSyncs";+import { PkiSync, PostSyncCommandVariable } from "@app/hooks/api/pkiSyncs";export const PKI_SYNC_MAP: Record<PkiSync,@@ -149,3 +149,16 @@ export const VALUE_SYNC_OPTION_FIELDS = [{ key: "owner", label: "Owner" },{ key: "group", label: "Group" }] as const;++export const POST_SYNC_COMMAND_VARIABLE_DESCRIPTIONS: Record<PostSyncCommandVariable, string> = {+ [PostSyncCommandVariable.CertificatePath]: "Full path of the certificate file delivered this run",+ [PostSyncCommandVariable.CertificateDirectory]: "The destination directory",+ [PostSyncCommandVariable.CertificateFiles]: "Every path written this run, one per line",+ [PostSyncCommandVariable.CommonName]: "The certificate's common name",+ [PostSyncCommandVariable.Pkcs12Password]: "The PKCS#12 export password"+};++export const SINGLE_CERTIFICATE_POST_SYNC_COMMAND_VARIABLES = [+ PostSyncCommandVariable.CertificatePath,+ PostSyncCommandVariable.CommonName+];diff --git a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncPostSyncCommandSection.tsx b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncPostSyncCommandSection.tsxindex 008205a40d..c6cc1352ba 100644--- a/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncPostSyncCommandSection.tsx+++ b/frontend/src/pages/cert-manager/PkiSyncDetailsByIDPage/components/PkiSyncPostSyncCommandSection.tsx@@ -1,4 +1,20 @@-import { Detail, DetailLabel, DetailValue } from "@app/components/v3";+import { useState } from "react";++import {+ Badge,+ CodeBlock,+ Detail,+ DetailLabel,+ DetailValue,+ Dialog,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle,+ Tooltip,+ TooltipContent,+ TooltipTrigger+} from "@app/components/v3";import { TPkiSync, usePkiSyncOption } from "@app/hooks/api/pkiSyncs";type Props = {@@ -8,6 +24,7 @@ type Props = {export const PkiSyncPostSyncCommandSection = ({ pkiSync }: Props) => {const { syncOption } = usePkiSyncOption(pkiSync.destination);const { postSyncCommand } = pkiSync.syncOptions as { postSyncCommand?: string };+ const [isCommandOpen, setIsCommandOpen] = useState(false);if (!syncOption?.canRunPostSyncCommand) return null;@@ -16,13 +33,31 @@ export const PkiSyncPostSyncCommandSection = ({ pkiSync }: Props) => {<DetailLabel>Post-Sync Command</DetailLabel><DetailValue>{postSyncCommand ? (- <pre className="max-h-32 thin-scrollbar overflow-auto rounded-sm bg-mineshaft-600 p-2 font-mono text-xs whitespace-pre-wrap text-foreground">- {postSyncCommand}- </pre>+ <Tooltip>+ <TooltipTrigger asChild>+ <Badge asChild variant="neutral">+ <button type="button" onClick={() => setIsCommandOpen(true)}>+ Configured+ </button>+ </Badge>+ </TooltipTrigger>+ <TooltipContent side="right">Show command</TooltipContent>+ </Tooltip>) : (<span className="text-muted/50 italic">None</span>)}</DetailValue>+ <Dialog open={isCommandOpen} onOpenChange={setIsCommandOpen}>+ <DialogContent className="max-w-2xl">+ <DialogHeader>+ <DialogTitle>Post-Sync Command</DialogTitle>+ <DialogDescription>+ Runs on the destination host after this sync delivers a certificate.+ </DialogDescription>+ </DialogHeader>+ <CodeBlock value={postSyncCommand ?? ""} className="max-h-96 whitespace-pre-wrap" />+ </DialogContent>+ </Dialog></Detail>);};