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
fix: address review findings on approval request webhook events
InfisiCalvin8a1b52e2c056
diff --git a/backend/src/ee/services/access-approval-request/access-approval-request-service.ts b/backend/src/ee/services/access-approval-request/access-approval-request-service.tsindex 9b0a9605c5..e2527131f2 100644--- a/backend/src/ee/services/access-approval-request/access-approval-request-service.ts+++ b/backend/src/ee/services/access-approval-request/access-approval-request-service.ts@@ -160,6 +160,12 @@ export const accessApprovalRequestServiceFactory = ({return;}+ if (!environment) {+ logger.warn(+ `Access request webhook payload has no environment name, environment not found [projectId=${projectId}] [environmentSlug=${envSlug}] [requestId=${accessApprovalRequest.id}] [action=${action}]`+ );+ }+const cfg = getConfig();// Taking every mutable field from one source keeps a caller-supplied null from being read as// "not provided" and silently replaced by the replica's value.diff --git a/backend/src/ee/services/secret-approval-request/secret-approval-request-service.ts b/backend/src/ee/services/secret-approval-request/secret-approval-request-service.tsindex d6aa86c021..34d83dbcc5 100644--- a/backend/src/ee/services/secret-approval-request/secret-approval-request-service.ts+++ b/backend/src/ee/services/secret-approval-request/secret-approval-request-service.ts@@ -9,6 +9,7 @@ import {SecretKeyEncoding,SecretType,TableName,+ TSecretApprovalRequests,TSecretApprovalRequestsSecretsInsert,TSecretApprovalRequestsSecretsV2Insert} from "@app/db/schemas";@@ -169,6 +170,10 @@ type TSecretApprovalRequestServiceFactoryDep = {export type TSecretApprovalRequestServiceFactory = ReturnType<typeof secretApprovalRequestServiceFactory>;+// findById reads from a replica, which can lag the write that triggered a webhook event. Callers+// holding the primary-side row pass it so the payload's mutable fields cannot go stale.+type TChangeRequestPrimaryRow = Pick<TSecretApprovalRequests, "status" | "hasMerged" | "updatedAt">;+export const secretApprovalRequestServiceFactory = ({secretApprovalRequestDAL,secretDAL,@@ -484,9 +489,7 @@ export const secretApprovalRequestServiceFactory = ({environment,environmentName,secretPath,- status,- hasMerged,- updatedAt,+ primaryRow,isBypassed,tx}: {@@ -496,11 +499,7 @@ export const secretApprovalRequestServiceFactory = ({environment: string;environmentName?: string;secretPath: string;- // findById reads from a replica, which can lag the write that triggered the event. Callers- // holding the primary-side row pass its volatile fields here so the payload cannot go stale.- status?: string;- hasMerged?: boolean;- updatedAt?: Date;+ primaryRow?: TChangeRequestPrimaryRow;isBypassed?: boolean;tx?: Knex;}) => {@@ -513,6 +512,9 @@ export const secretApprovalRequestServiceFactory = ({}const cfg = getConfig();+ // Taking every mutable field from one source keeps a caller-supplied null from being read as+ // "not provided" and silently replaced by the replica's value.+ const currentState = primaryRow ?? secretApprovalRequest;const { committerUser } = secretApprovalRequest;const requestedBy: TWebhookActor | null = secretApprovalRequest.committerUserId? {@@ -542,8 +544,8 @@ export const secretApprovalRequestServiceFactory = ({id: secretApprovalRequest.id,slug: secretApprovalRequest.slug,url: `${cfg.SITE_URL}/organizations/${project.orgId}/projects/secret-management/${projectId}/approval?requestId=${secretApprovalRequest.id}`,- status: status ?? secretApprovalRequest.status,- hasMerged: hasMerged ?? secretApprovalRequest.hasMerged,+ status: currentState.status,+ hasMerged: currentState.hasMerged,isBypassed: isBypassed ?? Boolean(secretApprovalRequest.bypassReason),policy: {id: secretApprovalRequest.policy.id,@@ -552,7 +554,7 @@ export const secretApprovalRequestServiceFactory = ({},requestedBy,createdAt: secretApprovalRequest.createdAt.toISOString(),- updatedAt: (updatedAt ?? secretApprovalRequest.updatedAt).toISOString()+ updatedAt: currentState.updatedAt.toISOString()}}},@@ -745,9 +747,7 @@ export const secretApprovalRequestServiceFactory = ({environment: statusFolder.environmentSlug,environmentName: statusFolder.environmentName,secretPath: statusFolder.path,- status: updatedRequest.status,- hasMerged: updatedRequest.hasMerged,- updatedAt: updatedRequest.updatedAt+ primaryRow: updatedRequest});} else {logger.warn(@@ -1384,9 +1384,7 @@ export const secretApprovalRequestServiceFactory = ({environment: folder.environmentSlug,environmentName: folder.environmentName,secretPath: folder.path,- status: mergeStatus.approval.status,- hasMerged: mergeStatus.approval.hasMerged,- updatedAt: mergeStatus.approval.updatedAt,+ primaryRow: mergeStatus.approval,isBypassed: isMergedViaBypass});} else {@@ -2433,6 +2431,12 @@ export const secretApprovalRequestServiceFactory = ({);}} catch (error) {+ // A failed read on the caller's transaction has already aborted it. Swallowing here would+ // let the caller commit, which Postgres turns into a silent rollback, so the caller would+ // see success with nothing written. Elsewhere the webhook is genuinely best-effort because+ // the user's action has already committed.+ if (providedTx) throw error;+logger.error(error,`Failed to queue change request webhook [requestId=${secretApprovalRequest.id}] [action=${ChangeRequestWebhookAction.Created}]`diff --git a/backend/src/services/webhook/webhook-fns.test.ts b/backend/src/services/webhook/webhook-fns.test.tsindex cfa5ae40c4..ab6cda7f90 100644--- a/backend/src/services/webhook/webhook-fns.test.ts+++ b/backend/src/services/webhook/webhook-fns.test.ts@@ -209,6 +209,35 @@ describe("getWebhookPayload: secrets.change-request.modified", () => {expect(result.attachments[0].content.body.map((b) => b.type)).toEqual(["TextBlock", "FactSet"]);});++ test.each([+ [WebhookType.SLACK, "Merged", { hasMerged: true, status: "close" }],+ [WebhookType.SLACK, "Closed", { hasMerged: false, status: "close" }],+ [WebhookType.SLACK, "Open", { hasMerged: false, status: "open" }],+ [WebhookType.MICROSOFT_TEAMS, "Merged", { hasMerged: true, status: "close" }],+ [WebhookType.MICROSOFT_TEAMS, "Closed", { hasMerged: false, status: "close" }],+ [WebhookType.MICROSOFT_TEAMS, "Open", { hasMerged: false, status: "open" }]+ ] as const)("%s payload renders status %s rather than the raw column value", (channel, label, state) => {+ const result = getWebhookPayload({+ type: WebhookEvents.ChangeRequestModified,+ payload: {+ ...changeRequestPayload,+ type: channel,+ request: { ...changeRequestPayload.request, ...state }+ }+ });++ const facts =+ channel === WebhookType.SLACK+ ? (result as { attachments: { fields: { title: string; value: string }[] }[] }).attachments[0].fields+ : (+ result as {+ attachments: { content: { body: { facts?: { title: string; value: string }[] }[] } }[];+ }+ ).attachments[0].content.body[1].facts!;++ expect(facts.find((f) => f.title === "Status")?.value).toBe(label);+ });});const accessRequestPayload = {diff --git a/backend/src/services/webhook/webhook-fns.ts b/backend/src/services/webhook/webhook-fns.tsindex 954fae5689..35507e6ed2 100644--- a/backend/src/services/webhook/webhook-fns.ts+++ b/backend/src/services/webhook/webhook-fns.ts@@ -2,6 +2,7 @@ import picomatch from "picomatch";import { TWebhooks } from "@app/db/schemas";import { EventType, TAuditLogServiceFactory, WebhookTriggeredEvent } from "@app/ee/services/audit-log/audit-log-types";+import { RequestState } from "@app/ee/services/secret-approval-request/secret-approval-request-types";import { haveDisjointLiteralPrefixes } from "@app/lib/casl/glob-subset";import { crypto } from "@app/lib/crypto/cryptography";import { NotFoundError } from "@app/lib/errors";@@ -18,6 +19,16 @@ import { TWebhookPayloads, WebhookEvents, WebhookType } from "./webhook-types";const WEBHOOK_TRIGGER_TIMEOUT = 15 * 1000;+const CHANGE_REQUEST_STATUS_LABEL: Record<string, string> = {+ [RequestState.Open]: "Open",+ [RequestState.Closed]: "Closed"+};++// The stored status is a database enum, not copy. Slack and Teams render it into a channel a+// whole team reads, so it is mapped here; the general payload keeps the raw column value.+const formatChangeRequestStatus = (request: { hasMerged: boolean; status: string }) =>+ request.hasMerged ? "Merged" : (CHANGE_REQUEST_STATUS_LABEL[request.status] ?? request.status);+export const decryptWebhookDetails = (webhook: TWebhooks, decryptor: (value: Buffer) => string) => {const { encryptedPassKey, encryptedUrl } = webhook;@@ -407,7 +418,7 @@ export const getWebhookPayload = (event: TWebhookPayloads) => {{ title: "Environment", value: environmentName || environment, short: false },{ title: "Secret Path", value: secretPath, short: false },{ title: "Policy", value: request.policy.name, short: false },- { title: "Status", value: request.hasMerged ? "Merged" : request.status, short: false },+ { title: "Status", value: formatChangeRequestStatus(request), short: false },{ title: "Requested By", value: request.requestedBy?.name || "Unknown", short: false },{ title: "Bypassed", value: request.isBypassed ? "Yes" : "No", short: false }]@@ -437,7 +448,7 @@ export const getWebhookPayload = (event: TWebhookPayloads) => {{ title: "Environment", value: environmentName || environment },{ title: "Secret Path", value: secretPath || "" },{ title: "Policy", value: request.policy.name },- { title: "Status", value: request.hasMerged ? "Merged" : request.status },+ { title: "Status", value: formatChangeRequestStatus(request) },{ title: "Requested By", value: request.requestedBy?.name || "Unknown" },{ title: "Bypassed", value: request.isBypassed ? "Yes" : "No" }]diff --git a/docs/documentation/platform/webhooks.mdx b/docs/documentation/platform/webhooks.mdxindex bd8a361789..72eabcb830 100644--- a/docs/documentation/platform/webhooks.mdx+++ b/docs/documentation/platform/webhooks.mdx@@ -33,10 +33,12 @@ Supported events:- **Secret Rotation Failed** (`secrets.rotation-failed`): triggered when a secret rotation in the configured scope fails.- **Honey Token Triggered** (`honey-token.triggered`): triggered when a honey token is activated.- **Change Request Modified** (`secrets.change-request.modified`): triggered when a secret change request in the configured scope is created, reviewed, closed, reopened, or merged.-- **Access Request Modified** (`secrets.access-request.modified`): triggered when an access request is created, edited, reviewed, or revoked. This event matches on environment and on overlapping secret paths, so a webhook receives a request whenever the requested path could include the path the webhook watches. An access request's path is a pattern rather than a single folder, which is why the matching rule differs from the other events.+- **Access Request Modified** (`secrets.access-request.modified`): triggered when an access request is created, edited, reviewed, or revoked. This event matches the environment and the secret path, and the path test is deliberately conservative: Infisical delivers the event unless the requested path and the watched path provably cannot overlap. An access request's path is a pattern rather than a single folder, which is why the matching rule differs from the other events.### Webhook Payload Format+Every payload has a top-level `timestamp` field, in epoch milliseconds, set to when Infisical sent the webhook.+```json{"event": "secrets.modified",@@ -85,11 +87,12 @@ Supported events:"eventName": "the AWS event that triggered the honey token","sourceIp": "IP address of the caller","awsRegion": "AWS region where the event occurred"- }+ },+ "timestamp": ""}```-The change request and access request payloads below carry no secret values, no diff of the proposed change, and no free text a user typed, such as a commit message, a bypass reason, or a review note. Each also has a top-level `timestamp` field, in epoch milliseconds, set to when Infisical sent the webhook.+The change request and access request payloads below carry no secret values, no diff of the proposed change, and no free text a user typed, such as a commit message, a bypass reason, or a review note.```json{@@ -101,7 +104,7 @@ The change request and access request payloads below carry no secret values, no},"request": {"id": "2a7c9e10-4b3d-4f5a-8c6b-1d2e3f4a5b6c",- "slug": "quiet-falcon",+ "slug": "k3Bq7ZxP1r","url": "https://app.infisical.com/organizations/<org-id>/projects/secret-management/<project-id>/approval?requestId=<request-id>","target": {"environment": {@@ -133,6 +136,8 @@ The change request and access request payloads below carry no secret values, no`requestedBy` is `null` when the person who created the change request has since deleted their account.+Reviewing a change request writes only the review, never the request row, so two `reviewed` deliveries for the same request carry an identical `request.updatedAt`. Order and deduplicate deliveries by the top-level `timestamp` rather than by `request.updatedAt`.+```json{"event": "secrets.access-request.modified",