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
Address PR comments
Carlos Monastyrski72fa50b5823a
diff --git a/backend/src/db/migrations/20260824173418_add-certificate-order-id.ts b/backend/src/db/migrations/20260824173418_add-certificate-order-id.tsindex bffecda690..4ff885209a 100644--- a/backend/src/db/migrations/20260824173418_add-certificate-order-id.ts+++ b/backend/src/db/migrations/20260824173418_add-certificate-order-id.ts@@ -2,36 +2,86 @@ import { Knex } from "knex";import { TableName } from "../schemas";+const ORDER_ID_INDEX = "certificates_orderid_index";+const MIGRATION_TIMEOUT = 60 * 60 * 1000; // 60 minutes+const MIGRATION_LOCK_TIMEOUT = 30 * 1000; // 30 seconds+export async function up(knex: Knex): Promise<void> {- if (await knex.schema.hasColumn(TableName.Certificate, "orderId")) return;-- await knex.schema.alterTable(TableName.Certificate, (t) => {- t.uuid("orderId").notNullable().defaultTo(knex.raw("gen_random_uuid()"));- t.index("orderId");- });-- await knex.raw(`- WITH RECURSIVE chain AS (- SELECT id, "orderId"- FROM "${TableName.Certificate}"- WHERE "renewedFromCertificateId" IS NULL- UNION ALL- SELECT c.id, chain."orderId"- FROM "${TableName.Certificate}" c- INNER JOIN chain ON c."renewedFromCertificateId" = chain.id- )- UPDATE "${TableName.Certificate}" AS target- SET "orderId" = chain."orderId"- FROM chain- WHERE target.id = chain.id- AND target."orderId" <> chain."orderId"- `);+ const connection = await knex.client.acquireConnection();+ const raw = (sql: string) => knex.raw(sql).connection(connection);++ try {+ const stmtResult = await raw("SHOW statement_timeout");+ const originalStatementTimeout = stmtResult.rows[0].statement_timeout;+ const lockResult = await raw("SHOW lock_timeout");+ const originalLockTimeout = lockResult.rows[0].lock_timeout;++ try {+ await raw(`SET statement_timeout = ${MIGRATION_TIMEOUT}`);+ await raw(`SET lock_timeout = ${MIGRATION_LOCK_TIMEOUT}`);++ if (!(await knex.schema.hasColumn(TableName.Certificate, "orderId"))) {+ await raw(`ALTER TABLE "${TableName.Certificate}" ADD COLUMN "orderId" uuid`);+ }++ await raw(`ALTER TABLE "${TableName.Certificate}" ALTER COLUMN "orderId" SET DEFAULT gen_random_uuid()`);++ await raw(`+ WITH RECURSIVE ranked AS (+ SELECT id, "renewedFromCertificateId",+ ROW_NUMBER() OVER (PARTITION BY "renewedFromCertificateId" ORDER BY "createdAt", id) AS sibling_rank+ FROM "${TableName.Certificate}"+ ),+ chain AS (+ SELECT c.id, COALESCE(c."orderId", gen_random_uuid()) AS "orderId"+ FROM "${TableName.Certificate}" c+ INNER JOIN ranked r ON r.id = c.id+ WHERE c."renewedFromCertificateId" IS NULL OR r.sibling_rank > 1+ UNION ALL+ SELECT c.id, chain."orderId"+ FROM "${TableName.Certificate}" c+ INNER JOIN ranked r ON r.id = c.id+ INNER JOIN chain ON c."renewedFromCertificateId" = chain.id+ WHERE r.sibling_rank = 1+ )+ UPDATE "${TableName.Certificate}" AS target+ SET "orderId" = chain."orderId"+ FROM chain+ WHERE target.id = chain.id+ AND target."orderId" IS DISTINCT FROM chain."orderId"+ `);++ await raw(`UPDATE "${TableName.Certificate}" SET "orderId" = gen_random_uuid() WHERE "orderId" IS NULL`);++ const invalid = await raw(+ `SELECT 1 FROM pg_class c JOIN pg_index i ON i.indexrelid = c.oid WHERE c.relname = '${ORDER_ID_INDEX}' AND NOT i.indisvalid`+ );+ if (invalid.rows.length > 0) {+ await raw(`DROP INDEX CONCURRENTLY IF EXISTS "${ORDER_ID_INDEX}"`);+ }++ await raw(`+ CREATE INDEX CONCURRENTLY IF NOT EXISTS "${ORDER_ID_INDEX}"+ ON "${TableName.Certificate}" ("orderId")+ `);++ await raw(`ALTER TABLE "${TableName.Certificate}" ALTER COLUMN "orderId" SET NOT NULL`);+ } finally {+ await raw(`SET statement_timeout = '${originalStatementTimeout}'`);+ await raw(`SET lock_timeout = '${originalLockTimeout}'`);+ }+ } finally {+ await knex.client.releaseConnection(connection);+ }}export async function down(knex: Knex): Promise<void> {- if (!(await knex.schema.hasColumn(TableName.Certificate, "orderId"))) return;+ await knex.raw(`DROP INDEX CONCURRENTLY IF EXISTS "${ORDER_ID_INDEX}"`);- await knex.schema.alterTable(TableName.Certificate, (t) => {- t.dropColumn("orderId");- });+ if (await knex.schema.hasColumn(TableName.Certificate, "orderId")) {+ await knex.raw(`ALTER TABLE "${TableName.Certificate}" DROP COLUMN "orderId"`);+ }}++const config = { transaction: false };+export { config };diff --git a/backend/src/services/certificate/certificate-dal.ts b/backend/src/services/certificate/certificate-dal.tsindex 28c88ca271..41b95d1ea4 100644--- a/backend/src/services/certificate/certificate-dal.ts+++ b/backend/src/services/certificate/certificate-dal.ts@@ -45,8 +45,6 @@ const toLegacyExtendedKeyUsageForQuery = (usage: string): string => {}};-const MAX_RENEWAL_CHAIN_DEPTH = 1000;-export const certificateDALFactory = (db: TDbClient) => {const certificateOrm = ormify(db, TableName.Certificate);@@ -746,38 +744,22 @@ export const certificateDALFactory = (db: TDbClient) => {const findLatestRenewalOf = async (anchor: { id: string; orderId: string }, tx?: Knex): Promise<string | null> => {try {- // Walks the anchor's own descendants rather than the whole order. A certificate renewed twice- // leaves two branches sharing one orderId, and the sibling branch never replaced this anchor,- // so picking the newest row in the order can hand back a certificate for a different name.- const result = await (tx || db.replicaNode()).raw<{ rows: { id: string }[] }>(- `- WITH RECURSIVE descendants AS (- SELECT id, "createdAt", status, "notAfter", 1 AS depth- FROM ??- WHERE "renewedFromCertificateId" = ? AND "orderId" = ?- UNION ALL- SELECT c.id, c."createdAt", c.status, c."notAfter", d.depth + 1- FROM ?? c- INNER JOIN descendants d ON c."renewedFromCertificateId" = d.id- WHERE c."orderId" = ? AND d.depth < ?- )- SELECT id FROM descendants- WHERE status <> ? AND "notAfter" > NOW()- ORDER BY "createdAt" DESC, id DESC- LIMIT 1- `,- [- TableName.Certificate,- anchor.id,- anchor.orderId,+ const newer = await (tx || db.replicaNode())(TableName.Certificate)+ .where("orderId", anchor.orderId)+ .whereNot("status", CertStatus.REVOKED)+ .where("notAfter", ">", db.raw("NOW()"))+ .whereRaw(`("createdAt", "id") > (SELECT "createdAt", "id" FROM ?? WHERE "id" = ?)`, [TableName.Certificate,- anchor.orderId,- MAX_RENEWAL_CHAIN_DEPTH,- CertStatus.REVOKED- ]- );+ anchor.id+ ])+ .orderBy([+ { column: "createdAt", order: "desc" },+ { column: "id", order: "desc" }+ ])+ .select("id")+ .first();- return result.rows[0]?.id ?? null;+ return newer?.id ?? null;} catch (error) {throw new DatabaseError({ error, name: "Find latest renewal of certificate" });}diff --git a/docs/documentation/platform/pki/reference/infisical-agent.mdx b/docs/documentation/platform/pki/reference/infisical-agent.mdxindex c71be0c286..afe5bbb699 100644--- a/docs/documentation/platform/pki/reference/infisical-agent.mdx+++ b/docs/documentation/platform/pki/reference/infisical-agent.mdx@@ -155,7 +155,7 @@ Each entry in the `certificates` list accepts the following parameters:| --------- | -------- | ----------- || `application-name` | Yes | The name of the [Application](/documentation/platform/pki/applications/overview) to request a certificate from || `profile-name` | Yes | The slug of the [certificate profile](/documentation/platform/pki/settings/profiles) to request a certificate against. The profile must be attached to the Application |-| `certificate-id` | Conditional | The ID of an existing certificate to fetch and track instead of issuing a new one. Cannot be combined with the parameters above, `csr`/`csr-path`, or `attributes`. See [Tracking an existing certificate](#tracking-an-existing-certificate) |+| `certificate-id` | Conditional | The ID of an existing certificate to fetch and track instead of issuing a new one. Cannot be combined with the parameters above, `csr`/`csr-path`, or `attributes`. See [Tracking an existing certificate](#tracking-an-existing-certificate) and [Following renewals](#following-renewals) || `attributes.common-name` | Optional | The common name for the certificate (e.g. `www.example.com`) || `attributes.alt-names` | Optional | The list of DNS subject alternative names for the certificate (e.g. `["www.example.com", "api.example.com"]`) || `attributes.ttl` | Optional (uses profile default if not specified) | The time-to-live duration for the certificate (e.g. `72h`, `90d`). Cannot be combined with `not-before`/`not-after` |@@ -174,6 +174,7 @@ Each entry in the `certificates` list accepts the following parameters:| `file-output.chain.permission` | Optional (defaults to `0600`) | The octal file permissions for the chain file (e.g. `0644`) || `file-output.chain.omit-root` | Optional (defaults to `true`) | Whether to exclude the root CA certificate from the written chain || `lifecycle.renew-before-expiry` | Optional (auto-renewal is disabled if not set) | How long before expiration the agent should renew the certificate (e.g. `14d`). Must be shorter than the certificate's TTL |+| `lifecycle.replace-on-renewals` | Optional (defaults to `false`) | Only valid with `certificate-id`. Whether the agent should deliver the most recent renewal of that certificate instead of the certificate itself || `lifecycle.status-check-interval` | Optional (defaults to `10s`) | How frequently the agent checks certificate status and renewal needs || `lifecycle.failure-retry-interval` | Optional (defaults to the status check interval) | How long the agent waits before retrying after a failed operation || `lifecycle.max-failure-retries` | Optional (defaults to `10`) | How many consecutive failures the agent tolerates before it stops retrying an operation |@@ -357,6 +358,14 @@ Instead of issuing a new certificate, the agent can fetch an existing one by setUse this when the certificate's lifecycle is managed in Infisical (for example, through [server-driven auto-renewal](/documentation/platform/pki/applications/enrollment-methods/api#server-driven-auto-renewal)) and the agent's job is only to deliver it to the machine.+This is also how several machines share one certificate. Ten web servers terminating TLS for `*.example.com` can point at the same `certificate-id` and serve the same wildcard certificate, instead of each issuing its own. Nothing reaches the certificate authority, and your inventory does not grow with the fleet.++`certificate-id` replaces the fields that describe a new certificate. Combining it with `application-name`, `profile-name`, `attributes`, `csr` or `csr-path` is rejected when the agent starts, rather than silently ignored.++<Note>+ The machine identity the agent authenticates as needs permission to read the certificate you point it at. Without it, the agent reports the authorization failure and leaves any files it has already written untouched.+</Note>+```yamlversion: v2@@ -388,3 +397,44 @@ certificates:command: "logger 'Tracked certificate was revoked or expired'"timeout: 30```++### Following renewals++[Renewing a certificate](/documentation/platform/pki/applications/certificate-renewal) produces a new certificate with its own ID, and the one it replaced stays valid until its own expiry. An agent pinned to the original ID therefore keeps serving the original.++Set `lifecycle.replace-on-renewals` to `true` and the agent delivers the most recent renewal instead:++```yaml+certificates:+ - certificate-id: "d2f4c1a0-0000-0000-0000-000000000000"+ lifecycle:+ status-check-interval: "6h"+ replace-on-renewals: true+ post-hooks:+ on-renewal:+ command: "systemctl reload nginx"+ timeout: 30+ file-output:+ certificate:+ path: "/etc/ssl/certs/wildcard.crt"+ permission: "0644"+ private-key:+ path: "/etc/ssl/private/wildcard.key"+ permission: "0600"+```++Renewing the certificate once in Infisical then reaches every machine running the agent, with no configuration change and no manual step on the machines. Leave `certificate-id` pointing at the certificate you started from: Infisical resolves the most recent renewal for you, however many times it has been renewed.++The agent rewrites the files only when the certificate it resolves to changes, and runs the `on-renewal` hook when that happens. When nothing has changed it writes nothing and runs no hooks, including across a restart, because it compares what it resolves against the certificate already on disk.++<Warning>+ `lifecycle.renew-before-expiry` has no effect alongside `certificate-id`. The agent delivers a certificate, it does not renew one. The agent logs a warning and carries on. Use `lifecycle.replace-on-renewals` instead.+</Warning>++**What to expect in less common cases:**++- A revoked or expired certificate is reported and runs the `on-failure` hook, but the agent does not overwrite what is already on disk. The machine keeps serving the last certificate known to be good.+- A certificate that Infisical does not hold a private key for, such as one issued from a certificate signing request or through ACME, is written along with its chain. The agent logs a warning and skips the private key file. If such a certificate would *replace* one already delivered, the agent refuses the write instead, because that would leave a non-matching certificate and key on disk.+- `status-check-interval` sets how often the agent checks, and so how quickly a renewal reaches the machine.+- Keep the certificate named in `certificate-id`, even after it has been renewed. The agent starts from it. Certificates that replaced it can be deleted safely.+- `replace-on-renewals` requires an Infisical server that supports it. Against an older self-hosted instance the agent cannot tell that a renewal exists, so it logs a warning and stays on the certificate it already delivered.diff --git a/docs/integrations/platforms/certificate-agent.mdx b/docs/integrations/platforms/certificate-agent.mdxdeleted file mode 100644index 964db0f814..0000000000--- a/docs/integrations/platforms/certificate-agent.mdx+++ /dev/null@@ -1,695 +0,0 @@-----title: "Infisical Agent"-sidebarTitle: "Infisical Agent"-description: "Learn how to use Infisical CLI Agent to manage certificates automatically."------<Tip>- Looking for a step-by-step setup guide? See [Automate Certificates with Infisical Agent](/documentation/platform/pki/guides/applications/infisical-agent).-</Tip>--## Concept--The Infisical Agent is a client daemon that is packaged into the [Infisical CLI](/cli/overview).-It can be used to request a certificate from Infisical using the [API enrollment method](/documentation/platform/pki/enrollment-methods/api) configured on a [certificate profile](/documentation/platform/pki/certificates/profiles), persist it to a specified path on the filesystem, and automatically monitor and renew it before expiration.--It can also run in distribution mode, where it fetches a certificate that already exists in Infisical by ID instead of requesting a new one. This lets many machines share a single centrally managed certificate, such as a wildcard certificate, without each of them triggering an issuance against the certificate authority.--The Infisical Agent is notable:--- Automating certificate management: The agent can request, persist, monitor, and renew certificates from Infisical automatically without manual intervention. It also supports post-event hooks to execute custom commands after certificate issuance, renewal, or failure events.-- Distributing a shared certificate: The agent can deliver an existing certificate to many machines and pick up server-side renewals of it automatically.-- Leveraging workload identity: The agent can authenticate with Infisical as a [machine identity](/documentation/platform/identities/machine-identities) using an infrastructure-native authentication method such as [AWS Auth](/documentation/platform/identities/aws-auth), [Azure Auth](/documentation/platform/identities/azure-auth), [GCP Auth](/documentation/platform/identities/gcp-auth), [Kubernetes Auth](/documentation/platform/identities/kubernetes-auth), etc.--The typical workflow for using the agent involves installing the Infisical CLI on the target machine, creating a configuration file defining the certificate to request and how it should be managed, and then starting the agent with that configuration so it can request, persist, monitor, and renew the certificate before it expires.-This follows a [client-driven approach](/documentation/platform/pki/certificates/certificates#client-driven-certificate-renewal) to certificate renewal.--## Workflow--A typical workflow for using the Infisical Agent to request certificates from Infisical consists of the following steps:--1. Create a [certificate profile](/documentation/platform/pki/certificates/profiles) in Infisical with the [API enrollment method](/documentation/platform/pki/enrollment-methods/api) configured on it.-2. Install the [Infisical CLI](/cli/overview) on the target machine.-3. Create an agent [configuration file](/integrations/platforms/certificate-agent#agent-configuration) containing details about the certificate to request and how it should be managed such as renewal thresholds, post-event hooks, etc.-4. Start the agent with that configuration so it can request, persist, monitor, and going forward automatically renew the certificate before it expires on the target machine.--## Operating the agent--This section describes how to use the Infisical Agent to request certificates from Infisical. It covers how the agent authenticates with Infisical,-and how to configure it to start requesting certificates from Infisical.--### Authentication--The Infisical Agent can authenticate with Infisical as a [machine identity](/documentation/platform/identities/machine-identities) using one of its supported authentication methods.--Upon successful authentication, the agent receives a short-lived access token that it uses to make subsequent authenticated requests to obtain and renew certificates from Infisical;-the agent automatically handles token renewal as documented [here](/integrations/platforms/infisical-agent#token-renewal).--<AccordionGroup>-<Accordion title="Universal Auth">- The Universal Auth method uses a client ID and secret for authentication.-- <Steps>- <Step title="Create a universal auth machine identity">- To create a universal auth machine identity, follow the step by step guide outlined [here](/documentation/platform/identities/universal-auth).- </Step>- <Step title="Configure the agent">- Update the agent configuration file with the auth method and credentials:-- ```yaml- auth:- type: "universal-auth"- config:- client-id: "./client-id" # Path to file containing client ID- client-secret: "./client-secret" # Path to file containing client secret- remove-client-secret-on-read: false # Optional: remove secret file after reading- ```-- You can also provide credentials directly:-- ```yaml- auth:- type: "universal-auth"- config:- client-id: "your-client-id"- client-secret: "your-client-secret"- ```- </Step>-- </Steps>-</Accordion>-<Accordion title="Kubernetes Auth">- The Kubernetes Auth method is used when running the agent in a Kubernetes environment.-- <Steps>- <Step title="Create a Kubernetes machine identity">- To create a Kubernetes machine identity, follow the step by step guide outlined [here](/documentation/platform/identities/kubernetes-auth).- </Step>- <Step title="Configure the agent">- Configure the agent to use Kubernetes service account authentication:-- ```yaml- auth:- type: "kubernetes-auth"- config:- identity-id: "your-kubernetes-identity-id"- service-account-token-path: "/var/run/secrets/kubernetes.io/serviceaccount/token"- ```- </Step>-- </Steps>-</Accordion>- <Accordion title="Azure Auth">- The Azure Auth method is used when running the agent in an Azure environment.-- <Steps>- <Step title="Create an Azure machine identity">- To create an Azure machine identity, follow the step by step guide outlined [here](/documentation/platform/identities/azure-auth).- </Step>- <Step title="Configure the agent">- Configure the agent to use Azure managed identity authentication:-- ```yaml- auth:- type: "azure-auth"- config:- identity-id: "your-azure-identity-id"- ```- </Step>- </Steps>-- </Accordion>- <Accordion title="Native GCP ID Token">- The Native GCP ID Token method is used to authenticate with Infisical when running in a GCP environment.-- <Steps>- <Step title="Create a GCP machine identity">- To create a GCP machine identity, follow the step by step guide outlined [here](/documentation/platform/identities/gcp-auth).- </Step>- <Step title="Configure the agent">- Update the agent configuration file with the specified auth method and identity ID:-- ```yaml- auth:- type: "gcp-id-token"- config:- identity-id: "your-gcp-identity-id"- ```- </Step>- </Steps>-- </Accordion>- <Accordion title="GCP IAM">- The GCP IAM method is used to authenticate with Infisical with a GCP service account key.-- <Steps>- <Step title="Create a GCP machine identity">- To create a GCP machine identity, follow the step by step guide outlined [here](/documentation/platform/identities/gcp-auth).- </Step>- <Step title="Configure the agent">- Update the agent configuration file with the specified auth method, identity ID, and service account key:-- ```yaml- auth:- type: "gcp-iam"- config:- identity-id: "your-gcp-identity-id"- service-account-key: "/path/to/service-account-key.json"- ```- </Step>- </Steps>-- </Accordion>- <Accordion title="Native AWS IAM">- The AWS IAM method is used to authenticate with Infisical with an AWS IAM role while running in an AWS environment.-- <Steps>- <Step title="Create an AWS machine identity">- To create an AWS machine identity, follow the step by step guide outlined [here](/documentation/platform/identities/aws-auth).- </Step>- <Step title="Configure the agent">- Update the agent configuration file with the specified auth method and identity ID:-- ```yaml- auth:- type: "aws-iam"- config:- identity-id: "your-aws-identity-id"- ```- </Step>- </Steps>-- </Accordion>-</AccordionGroup>--### Agent configuration--The Infisical Agent relies on a YAML configuration file to define its behavior, including how it should authenticate with Infisical, the certificate it should request, and how that certificate should be managed including auto-renewal.--The code snippet below shows an example configuration file that instructs the agent to request and continuously renew a certificate from Infisical.--Note that not all configuration options in this file are required but this example includes all of the available options.--```yaml example-cert-agent-config.yaml-version: v1--# Infisical server configuration-infisical:- address: "https://app.infisical.com" # The URL of the Infisical instance (e.g. https://app.infisical.com, https://eu.infisical.com, https://your-self-hosted-instance.com)- retry-strategy:- max-retries: 3- max-delay: "5s"- base-delay: "200ms"--# Infisical authentication configuration-auth:- type: "universal-auth" # The authentication method to use (e.g. universal-auth, kubernetes-auth, azure-auth, gcp-id-token, gcp-iam, aws-iam)- config:- client-id: "your-client-id"- client-secret: "your-client-secret"--# Certificate configuration-certificates:- - profile-name: "prof-web-server-12345"- project-slug: "my-project-slug"- attributes:- common-name: "api.example.com"- alt-names: ["api.example.com", "api-v2.example.com"]- ttl: "90d"- key-algorithm: "RSA_2048"- signature-algorithm: "RSA-SHA256"- key-usages:- - "digital_signature"- - "key_encipherment"- extended-key-usages:- - "server_auth"-- # Enable automatic certificate renewal- lifecycle:- renew-before-expiry: "30d"- status-check-interval: "6h"-- # Configure where to store the issued certificate and its associated private key and certificate chain- file-output:- private-key:- path: "/etc/ssl/private/web.key"- permission: "0600" # Read/write for owner only- certificate:- path: "/etc/ssl/certs/web.crt"- permission: "0644" # Read for all, write for owner- chain:- path: "/etc/ssl/certs/web-chain.crt"- permission: "0644" # Read for all, write for owner- omit-root: true # Exclude the root CA certificate in chain-- # Configure custom commands to execute after certificate issuance, renewal, or failure events- post-hooks:- on-issuance:- command: |- echo "Certificate issued for ${CERT_COMMON_NAME}"- systemctl reload nginx- timeout: 30-- on-renewal:- command: |- echo "Certificate renewed for ${CERT_COMMON_NAME}"- systemctl reload nginx- timeout: 30-- on-failure:- command: |- echo "Certificate operation failed: ${ERROR_MESSAGE}"- mail -s "Certificate Alert" [email protected] < /dev/null- timeout: 30-```--To be more specific, the configuration file instructs the agent to:--- Authenticate with Infisical using the [Universal Auth](/integrations/platforms/certificate-agent#universal-auth) authentication method.-- Request a 90-day certificate against the [certificate profile](/documentation/platform/pki/certificates/profiles) named `prof-web-server-12345` with the common name `web.company.com` and the subject alternative names `web.company.com` and `www.company.com`.-- Automatically renew the certificate 30 days before expiration by checking the certificate status every 6 hours and retrying up to 3 times with a base delay of 200ms and a maximum delay of 5s if the certificate status check fails.-- Store the certificate and its associated private key and certificate chain (excluding the root CA certificate) in the filesystem at the specified paths with the specified permissions.-- Execute custom commands after certificate issuance, renewal, or failure events such as reloading an `nginx` service or sending an email notification.--### Agent execution--After creating the configuration file, you can run the command below with the `--config` flag pointing to the path where the agent configuration file is located.--```bash-infisical cert-manager agent --config /path/to/your/agent-config.yaml-```--This will start the agent as a daemon process, continuously monitoring and managing certificates according to your configuration. You can also run it in the foreground for debugging:--```bash-infisical cert-manager agent --config /path/to/your/agent-config.yaml --verbose-```--For production deployments, you may consider running the agent as a system service to ensure it starts automatically and runs continuously.--### Agent certificate configuration parameters--The table below provides a complete list of parameters that can be configured in the **certificate configuration** section of the agent configuration file:--| Parameter | Required | Description |-| ------------------------------------ | ------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `certificate-id` | Conditional | The ID of an existing certificate in Infisical to deliver instead of requesting a new one. See [Distributing an existing certificate](/integrations/platforms/certificate-agent#distributing-an-existing-certificate). Cannot be combined with `profile-name`, `project-slug`, `application-name`, `attributes`, or a CSR. |-| `profile-name` | Conditional | The name of the [certificate profile](/documentation/platform/pki/certificates/profiles) to request a certificate against (e.g., `web-server-12345`). Not used when `certificate-id` is set. |-| `project-slug` | Conditional | The slug of the project to request a certificate against (e.g., `my-project-slug`). Not used when `certificate-id` is set. |-| `common-name` | Optional | The common name for the certificate (e.g. `www.example.com`) |-| `alt-names` | Optional | The list of subject alternative names for the certificate (e.g., `["www.example.com", "api.example.com"]`) |-| `ttl` | Optional (uses profile default if not specified) | The time-to-live duration for the certificate, specified as a duration string (e.g. `72h`, `90d`, `1y`, etc.) |-| `key-algorithm` | Optional | The algorithm for the certificate key pair. One of: `RSA_2048`, `RSA_3072`, `RSA_4096`, `EC_prime256v1`, `EC_secp384r1`, `EC_secp521r1`. |-| `signature-algorithm` | Optional | The algorithm used to sign the certificate. One of: `RSA-SHA256`, `RSA-SHA384`, `RSA-SHA512`, `ECDSA-SHA256`, `ECDSA-SHA384`, `ECDSA-SHA512`. |-| `key-usages` | Optional | The list of key usage values for the certificate. One or more of: `digital_signature`, `key_encipherment`, `non_repudiation`, `data_encipherment`, `key_agreement`, `key_cert_sign`, `crl_sign`, `encipher_only`, `decipher_only`. |-| `extended-key-usages` | Optional | The list of extended key usage values for the certificate. One or more of: `server_auth`, `client_auth`, `code_signing`, `email_protection`, `timestamping`, `ocsp_signing`. |-| `csr-path` | Conditional | The path to a certificate signing request (CSR) file (e.g., `./csr/webserver.csr`, `/etc/ssl/csr.pem`). This is required if using a pre-generated CSR. |-| `file-output.private-key.path` | Optional (required if the `csr-path` is not specified) | The path to store the private key (required if not using a CSR) |-| `file-output.private-key.permission` | Optional (defaults to `0600`) | The octal file permissions for the private key file (e.g. `0600`) |-| `file-output.certificate.path` | Yes | The path to store the issued certificate in the filesystem |-| `file-output.certificate.permission` | Optional (defaults to `0600`) | The octal file permissions for the certificate file (e.g. `0644`) |-| `file-output.chain.path` | Optional | The path to store the certificate chain in the filesystem. |-| `file-output.chain.permission` | Optional (defaults to `0600`) | The octal permissions for the chain file (e.g. `0644`) |-| `file-output.chain.omit-root` | Optional (defaults to `true`) | Whether to exclude the root CA certificate from the returned certificate chain |-| `lifecycle.renew-before-expiry` | Optional (auto-renewal is disabled if not set) | Duration before certificate expiration when renewal checks should begin, specified as a duration string (e.g. `72h`, `90d`, `1y`, etc.). Ignored when `certificate-id` is set, because the agent delivers a certificate rather than renewing one. |-| `lifecycle.status-check-interval` | Optional (defaults to `10s`) | How frequently the agent checks certificate status and renewal needs, specified as a duration string (e.g. `10s`, `30m`, `1d`, etc.) |-| `lifecycle.use-latest` | Optional (defaults to `false`) | Whether the agent should deliver the most recent renewal of the certificate named by `certificate-id` instead of that certificate itself. Only valid together with `certificate-id`. |-| `post-hooks.on-issuance.command` | Optional | The shell command to execute after a certificate is successfully issued for the first time (e.g., `systemctl reload nginx`, `/usr/local/bin/reload-service.sh`) |-| `post-hooks.on-issuance.timeout` | Optional (defaults to `30`) | Maximum execution time in seconds for the on-issuance post-hook command before it is terminated (e.g., `30`, `60`, `120`) |-| `post-hooks.on-renewal.command` | Optional | The shell command to execute after a certificate is successfully renewed (e.g., `systemctl reload nginx`, `docker restart web-server`) |-| `post-hooks.on-renewal.timeout` | Optional (defaults to `30`) | Maximum execution time in seconds for the on-renewal post-hook command before it is terminated (e.g., `30`, `60`, `120`) |-| `post-hooks.on-failure.command` | Optional | The shell command to execute when certificate issuance or renewal fails (e.g., `logger 'Certificate renewal failed'`, `/usr/local/bin/alert.sh`) |-| `post-hooks.on-failure.timeout` | Optional (defaults to `30`) | Maximum execution time in seconds for the on-failure post-hook command before it is terminated (e.g., `10`, `30`, `60`) |--### Distributing an existing certificate--By default, the agent requests a new certificate from a certificate profile each time it starts on a new machine. That suits machines that each need their own identity. It does not suit machines meant to serve the same certificate: ten web servers behind a load balancer terminating TLS for `*.example.com` should share one wildcard certificate, not hold ten.--Set `certificate-id` to the ID of a certificate that already exists in Infisical and the agent delivers that certificate instead of issuing one. Nothing reaches the certificate authority, and your certificate inventory does not grow with your fleet.--Copy the ID from the certificate's page in Infisical, or take it from the response of the [issue certificate](/api-reference/endpoints/certificates/create-certificate) endpoint.--```yaml distribution-agent-config.yaml-version: v2--infisical:- address: "https://app.infisical.com"--auth:- type: "universal-auth"- config:- client-id: "your-client-id"- client-secret: "your-client-secret"--certificates:- - certificate-id: "8f2a1c40-5f3b-4e7a-9c21-b3d4e5f60718"- lifecycle:- status-check-interval: "6h"- file-output:- certificate:- path: "/etc/ssl/certs/wildcard.crt"- permission: "0644"- chain:- path: "/etc/ssl/certs/wildcard-chain.crt"- permission: "0644"- private-key:- path: "/etc/ssl/private/wildcard.key"- permission: "0600"-```--`certificate-id` replaces the fields that describe a new certificate. Combining it with `profile-name`, `project-slug`, `application-name`, `attributes`, `csr`, or `csr-path` is rejected when the agent starts, rather than silently ignored.--<Warning>- `lifecycle.renew-before-expiry` has no effect in distribution mode. The agent delivers a certificate, it does not renew one, so a renewal threshold has nothing to act on. The agent logs a warning and carries on. To have it deliver renewals made in Infisical, use [`lifecycle.use-latest`](/integrations/platforms/certificate-agent#keeping-up-with-renewals) instead.-</Warning>--<Note>- The machine identity the agent authenticates as needs permission to read the certificate you point it at. Without it, the agent reports the authorization failure and leaves any files it has already written untouched.-</Note>--#### Keeping up with renewals--[Renewing a certificate](/documentation/platform/pki/applications/certificate-renewal) produces a new certificate with its own ID, and the certificate it replaced stays valid until its own expiry. An agent pinned to the original ID therefore keeps serving the original until it expires.--Set `lifecycle.use-latest` to `true` and the agent delivers the most recent renewal instead:--```yaml-certificates:- - certificate-id: "8f2a1c40-5f3b-4e7a-9c21-b3d4e5f60718"- lifecycle:- status-check-interval: "6h"- use-latest: true- post-hooks:- on-renewal:- command: "systemctl reload nginx"- timeout: 30- file-output:- certificate:- path: "/etc/ssl/certs/wildcard.crt"- permission: "0644"- private-key:- path: "/etc/ssl/private/wildcard.key"- permission: "0600"-```--Renewing the certificate once in Infisical then reaches every machine running the agent, with no configuration change and no manual step on the machines. Leave `certificate-id` pointing at the certificate you started from. You never need to update it, and Infisical resolves the most recent renewal for you however many times the certificate has been renewed.--The agent rewrites the files only when the certificate it resolves to changes, and runs the `on-renewal` hook when that happens. Use that hook to reload whatever service consumes the certificate. When nothing has changed, the agent writes nothing and runs no hooks, including across a restart: it compares what it resolves against the certificate already on disk, not just against what it delivered earlier in the same run.--<Note>- Leaving `use-latest` unset keeps the agent on exactly the certificate you named. Choose that when you want a deliberate step before a new certificate reaches production.-</Note>--**What to expect in less common cases:**--- A revoked or expired certificate is reported and runs the `on-failure` hook, but the agent does not overwrite what is already on disk. The machine keeps serving the last certificate known to be good.-- A certificate that Infisical does not hold a private key for, such as one issued from a certificate signing request or through ACME, is written along with its chain. The agent logs a warning and skips the private key file. If such a certificate would *replace* one already delivered, the agent refuses the write instead, because overwriting the certificate while leaving the previous key in place would put a non-matching pair on disk and the `on-renewal` hook would reload a service onto it.-- `status-check-interval` sets how often the agent checks, and so how quickly a renewal reaches the machine.-- Keep the certificate named in `certificate-id`, even after it has been renewed. The agent starts from it, so deleting it leaves a restarted agent unable to resolve. Certificates that replaced it can be deleted safely, including the one directly after it.-- `use-latest` requires an Infisical server that supports it. Against an older self-hosted instance the agent cannot tell that a renewal exists, so it logs a warning and stays on the certificate it already delivered. Upgrade the server, or leave `use-latest` unset and point `certificate-id` at the current certificate.--### Post-event hooks--The Infisical Agent supports running custom commands in response to certificate lifecycle events such as issuance, renewal, and failure through the `post-hooks` configuration-in the agent configuration file.--<Tabs>- <Tab title="Issuance Hook">- Runs when a new certificate is successfully issued:-- ```yaml- post-hooks:- on-issuance:- command: |- echo "New certificate issued for ${CERT_COMMON_NAME}"- chown nginx:nginx ${CERT_FILE_PATH}- chmod 644 ${CERT_FILE_PATH}- systemctl reload nginx- timeout: 30- ```-- </Tab>-- <Tab title="Renewal Hook">- Runs when a certificate is successfully renewed:-- ```yaml- post-hooks:- on-renewal:- command: |- echo "Certificate renewed for ${CERT_COMMON_NAME}"- # Reload services that use the certificate- systemctl reload nginx- systemctl reload haproxy-- # Send notification- curl -X POST https://hooks.slack.com/... \- -d "{'text': 'Certificate for ${CERT_COMMON_NAME} renewed successfully'}"- timeout: 60- ```-- </Tab>-- <Tab title="Failure Hook">- Runs when certificate operations fail:-- ```yaml- post-hooks:- on-failure:- command: |- echo "Certificate operation failed for ${CERT_COMMON_NAME}: ${ERROR_MESSAGE}"- # Send alert- mail -s "Certificate Failure Alert" [email protected] < /dev/null- # Log to syslog- logger -p daemon.error "Certificate agent failure: ${ERROR_MESSAGE}"- timeout: 30- ```-- </Tab>-</Tabs>--### Retrying mechanism--The Infisical Agent will automatically attempt to retry any failed API requests including authentication, certificate issuance, and renewal operations.-By default, the agent will retry up to 3 times with a base delay of 200ms and a maximum delay of 5s.--You can configure the retrying mechanism through the agent configuration file:--```yaml-infisical:- address: "https://app.infisical.com"- retry-strategy:- max-retries: 3- max-delay: "5s"- base-delay: "200ms"-# ... rest of the agent configuration file-```--## Example agent configuration files--Since there are several ways you might want to use the Infisical Agent to request certificates from Infisical,-we provide a few example configuration files for common use cases below to help you get started.--### One-time certificate issuance--The code snippet below shows a configuration file that instructs the agent to request a certificate from Infisical-once without performing any subsequent auto-renewal.--```yaml-version: v1--# Infisical server configuration-infisical:- address: "https://app.infisical.com" # The URL of the Infisical instance (e.g. https://app.infisical.com, https://eu.infisical.com, https://your-self-hosted-instance.com)- retry-strategy:- max-retries: 3- max-delay: "5s"- base-delay: "200ms"--# Infisical authentication configuration-auth:- type: "universal-auth" # The authentication method to use (e.g. universal-auth, kubernetes-auth, azure-auth, gcp-id-token, gcp-iam, aws-iam)- config:- client-id: "your-client-id"- client-secret: "your-client-secret"--# Certificate configuration-certificates:- - profile-name: "prof-web-server-12345"- project-slug: "my-project-slug"- attributes:- common-name: "api.example.com"- alt-names:- - "api.example.com"- - "api-v2.example.com"- key-algorithm: "RSA_2048"- signature-algorithm: "RSA-SHA256"- key-usages:- - "digital_signature"- - "key_encipherment"- extended-key-usages:- - "server_auth"- ttl: "30d"- file-output:- private-key:- path: "/etc/ssl/private/api.example.com.key"- permission: "0600"- certificate:- path: "/etc/ssl/certs/api.example.com.crt"- permission: "0644"- chain:- path: "/etc/ssl/certs/api.example.com.chain.crt"- permission: "0644"- omit-root: true-```--### One-time certificate issuance using a pre-generated CSR--The code snippet below shows a configuration file that instructs the agent to request a certificate from Infisical-once using a pre-generated CSR.--Note that when `csr-path` is specified:--- The `private-key` is omitted from the configuration file because we assume that it is pre-generated and managed externally, with only the CSR being submitted to Infisical for signing.-- The agent will not be able to perform any auto-renewal operations, as it is assumed to not have access to the private key required to generate a new CSR.--```yaml-version: v1--# Infisical server configuration-infisical:- address: "https://app.infisical.com" # The URL of the Infisical instance (e.g. https://app.infisical.com, https://eu.infisical.com, https://your-self-hosted-instance.com)- retry-strategy:- max-retries: 3- max-delay: "5s"- base-delay: "200ms"--# Infisical authentication configuration-auth:- type: "universal-auth" # The authentication method to use (e.g. universal-auth, kubernetes-auth, azure-auth, gcp-id-token, gcp-iam, aws-iam)- config:- client-id: "your-client-id"- client-secret: "your-client-secret"--# Certificate configuration-certificates:- - profile-name: "prof-web-server-12345"- project-slug: "my-project-slug"- csr-path: "/etc/ssl/requests/api.csr"- file-output:- certificate:- path: "/etc/ssl/certs/api.example.com.crt"- permission: "0644"- chain:- path: "/etc/ssl/certs/api.example.com.chain.crt"- permission: "0644"- omit-root: true-```--### Certificate issuance with automatic renewal--The code snippet below shows a configuration file that instructs the agent to request a certificate from Infisical and continuously renew it 14 days before expiration, checking the certificate status every 6 hours.--```yaml-version: v1--# Infisical server configuration-infisical:- address: "https://app.infisical.com" # The URL of the Infisical instance (e.g. https://app.infisical.com, https://eu.infisical.com, https://your-self-hosted-instance.com)- retry-strategy:- max-retries: 3- max-delay: "5s"- base-delay: "200ms"--# Infisical authentication configuration-auth:- type: "universal-auth" # The authentication method to use (e.g. universal-auth, kubernetes-auth, azure-auth, gcp-id-token, gcp-iam, aws-iam)- config:- client-id: "your-client-id"- client-secret: "your-client-secret"--# Certificate configuration-certificates:- - profile-name: "prof-web-server-12345"- project-slug: "my-project-slug"- attributes:- common-name: "api.example.com"- alt-names:- - "api.example.com"- - "api-v2.example.com"- key-algorithm: "RSA_2048"- signature-algorithm: "RSA-SHA256"- key-usages:- - "digital_signature"- - "key_encipherment"- extended-key-usages:- - "server_auth"- ttl: "30d"- lifecycle:- renew-before-expiry: "14d" # Renew 14 days before expiration- status-check-interval: "6h" # Check certificate status every 6 hours- file-output:- private-key:- path: "/etc/ssl/private/api.example.com.key"- permission: "0600"- certificate:- path: "/etc/ssl/certs/api.example.com.crt"- permission: "0644"- chain:- path: "/etc/ssl/certs/api.example.com.chain.crt"- permission: "0644"- post-hooks:- on-issuance:- command: "systemctl reload nginx"- timeout: 30- on-renewal:- command: "systemctl reload nginx && logger 'Certificate renewed'"- timeout: 30-```--### Distributing a shared wildcard certificate--The configuration below instructs the agent to fetch an existing wildcard certificate by ID rather than issue a new one, and to keep it current as the certificate is renewed in Infisical. The same file can be deployed unchanged to every machine that terminates TLS for the domain.--```yaml-version: v2--# Infisical server configuration-infisical:- address: "https://app.infisical.com"- retry-strategy:- max-retries: 3- max-delay: "5s"- base-delay: "200ms"--# Infisical authentication configuration-auth:- type: "universal-auth"- config:- client-id: "your-client-id"- client-secret: "your-client-secret"--# Certificate configuration-certificates:- - certificate-id: "8f2a1c40-5f3b-4e7a-9c21-b3d4e5f60718"- lifecycle:- status-check-interval: "6h" # How often to check certificate status and renewal needs- use-latest: true # Deliver the most recent renewal of the certificate above- file-output:- private-key:- path: "/etc/ssl/private/wildcard.example.com.key"- permission: "0600"- certificate:- path: "/etc/ssl/certs/wildcard.example.com.crt"- permission: "0644"- chain:- path: "/etc/ssl/certs/wildcard.example.com.chain.crt"- permission: "0644"- post-hooks:- on-renewal:- command: "systemctl reload nginx"- timeout: 30- on-failure:- command: "logger 'Shared certificate could not be refreshed'"- timeout: 10-```