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
Merge branch 'feat/adilsitos/eng-4966-stack-2' into feat/adilsitos/eng-4966-stack-3
adilson360a995c4466
diff --cc CLAUDE.mdindex dd5fb0b40b,3d174126bb..3d704bd58c--- a/CLAUDE.md+++ b/CLAUDE.md@@@ -178,51 -182,28 +184,61 @@@ no Infisical approvers, so `POST /api/vone from Infisical: the requester, or anyone who can edit the policy, sets it `cancelled`, which is also how apolicy blocked by pending requests is freed for editing. Every provider implements `TDelegatedApprovalProvider` against the same`TDelegatedApprovalDispatchInput` and registers in `DELEGATED_APPROVAL_PROVIDER_MAP`-(`dispatch/providers/<name>/`); a new policy type adds an arm to `TDelegatedApprovalDispatchDetails` and a+(`delegated-approval/providers/<name>/`); a new policy type adds an arm to `TDelegatedApprovalDispatchDetails` and abuilder in `DELEGATED_APPROVAL_DISPATCH_DETAILS_BUILDER_MAP` rather than branching in a provider. The consumerreads from the primary, never checks the license, and treats bullmq's `UnrecoverableError` as the terminal failure- signal, returning `Failed` for it and `Retry` for anything else. The callback contract (token issuance now, the inbound route and approve / reject later) is its own+ signal, returning `Failed` for it and `Retry` for anything else until the last attempt. The callback contract (token issuance now, the inbound route and approve / reject later) is its ownmodule, `backend/src/services/delegated-approval-callback/`, so the delegated approval module never grows a-callback branch. A request gets exactly one callback token for its whole life: it is random, issued on the first-dispatch attempt, and stored in `encryptedCallbackToken` under the SecretManager KMS key of the request's project-(`getOrIssueCallbackToken` resolves the project from the delegated request itself, since the inbound route knows-only that row) so every retry resends the same value; the inbound side finds the row by the provider's record id-and compares the decrypted token with the presented one. Never send a provider a token that differs from the one-stored for the request; the provider keeps the first token it was given and cannot be told another, so a mismatch-is unrecoverable.+callback branch. A request gets exactly one callback token for its whole life: it is random, prefixed `inf_ext_`,- issued on the first dispatch attempt, and stored encrypted under the org KMS key in `encryptedCallbackToken` so- every retry resends the same value. Never send a provider a token that differs from the one stored for the- request; the provider keeps the first token it was given and cannot be told another, so a mismatch is- unrecoverable. The provider calls `POST /api/v1/delegated-approvals/callback` (unauthenticated, IP rate limited)++issued on the first dispatch attempt, and stored in `encryptedCallbackToken` under the SecretManager KMS key of++the request's project (`getOrIssueCallbackToken` resolves the project from the delegated request itself, since++the inbound route knows only that row) so every retry resends the same value. Never send a provider a token that++differs from the one stored for the request; the provider keeps the first token it was given and cannot be told++another, so a mismatch is unrecoverable. The provider calls `POST /api/v1/delegated-approvals/callback` (unauthenticated, IP rate limited)+with the token in the `Infisical-Approval-Token` header and a body naming the event and the provider's record id;+the body carries no decision, which a later worker reads back from the provider. The route finds the row by+`providerRequestId` (404 when none), checks the token, and only then counts the callback in `callbackAttempts`; on+the sixth callback with a valid token it sets the row `failed` with a readable `statusReason` and cancels the+attached approval request in the same transaction, so the policy is freed and the UI stops offering Cancel. A+refused callback is never counted: the limit closes the request, so counting it would let anyone who knows the+record id cancel the request, and the token is 256 random bits, so there is nothing to brute force. Every other+refusal (bad or missing token, request not `waiting_approval`)+gets one neutral 403 while the reason goes to the log. An accepted callback only emits an outbox event, and+only when it wins `claimDecisionRead`: a conditional update of `decisionReadRequestedAt`, in the emit's+transaction, that one of any number of concurrent callbacks wins. A repeat while a read-back is still in+flight gets the same 200 and emits nothing; a claim older than `DELEGATED_APPROVAL_DECISION_READ_CLAIM_TTL_MS`+(70 minutes, past the outbox's last retry) has expired, so a fresh notification after an earlier read-back+ran out of retries still starts one. `eventType` is the+body's event and `idempotencyKey` is the delegated request id plus the attempt count. The+`delegated-approval-decision` consumer (`backend/src/services/delegated-approval-decision/`, a thin outbox+adapter over `delegatedApprovalDecisionService.applyDecision`) then reads the decision back through the+policy's app connection: `TDelegatedApprovalProvider.fetchDecision` returns `pending` or a decision with+the permissions the provider holds, and the consumer answers `Retry` for `pending`, compares the approved+permissions with the ones it dispatched after both go through `normalizeDelegatedApprovalPermissions` (set+comparison: padding, order, duplicates and case never count as a change), and finalizes in one transaction+that locks the approval request, moves the delegated row `waiting_approval` → `approved` / `rejected`, and+runs the policy type's `postApprovalTxRoutine` from `approvalResources`. A mismatch, a record for another+request, or any other `UnrecoverableError` goes through `failDelegatedApprovalRequest`: the delegated row+becomes `failed` with a readable `statusReason`, the approval request is cancelled, and nothing can retry+it. A request whose requester was deleted (`requesterId` is set null) or is no longer a member of the+project, directly or through a group (`membershipDAL.isUserProjectMember`), takes the same path before the+decision is read back. The secret access `postApprovalTxRoutine` refuses a non-member too, on both approval+paths: removing a member reaps only the privileges that already exist, so one written afterwards would take+effect if the user were ever added back. Every outcome is audited as+`ACCESS_APPROVAL_REQUEST_DELEGATED_DECISION` with the `PLATFORM` actor, and+product notifications (the access request webhook) go through `decisionNotifiers`, never through the+consumer itself. ServiceNow stamps an immutable `decision` on its record before it posts the callback, so+the provider reads that field alone and ignores `state`.+ ### Object Storage++ New product files go to S3 through `backend/src/services/object-storage/`, not a product's own S3 client (PAM+ recordings predate it and haven't moved). A product+ registers a namespace (record-first path like `sessions/{sessionId}/logs/{file}`, checked for naming collisions at+ boot) and the layer builds org-first keys, signs links, and applies the retention tag and, for default storage on Infisical Cloud, a daily upload cap. Storage is+ `default` (the instance's bucket, `OBJECT_STORAGE_S3_*`) or `external` (the customer's, through an AWS connection);+ use those two words everywhere.+### API Layer (Frontend)React Query + Axios with query key factories per domain. Each API domain in `frontend/src/hooks/api/` has `queries.tsx`, `mutations.tsx`, and `types.tsx` — see `frontend/CLAUDE.md` for conventions.diff --cc backend/src/services/delegated-approval-callback/delegated-approval-callback-service.test.tsindex 23897fff85,3e20ed8d5e..68ff989e51--- a/backend/src/services/delegated-approval-callback/delegated-approval-callback-service.test.ts+++ b/backend/src/services/delegated-approval-callback/delegated-approval-callback-service.test.ts@@@ -39,31 -23,25 +39,37 @@@ const PRIMARY = { isPrimary: true }const makeService = ({stored = true,- currentRow = null- }: { stored?: boolean; currentRow?: { encryptedCallbackToken: Buffer | null } | null } = {}) => {+ currentRow = null,+ approvalRequest = { id: "req-1", projectId: "project-1" }+ }: {+ stored?: boolean;+ currentRow?: { encryptedCallbackToken: Buffer | null } | null;+ approvalRequest?: { id: string; projectId: string } | null;+ } = {}) => {const delegatedApprovalRequestDAL = {- update: vi.fn(async () => (stored ? [{ id: "delegated-1" }] : [])),+ update: vi.fn(async (_filter: unknown, patch: object) => (stored ? [{ id: "delegated-1", ...patch }] : [])),+ updateWithDetails: vi.fn(async (_filter: unknown, patch: object) =>+ stored ? [{ id: "delegated-1", ...patch }] : []+ ),+ transaction: vi.fn(async (cb: (tx: unknown) => Promise<unknown>) => cb(TX)),primaryNode: vi.fn(() => PRIMARY),- findById: vi.fn(async () => currentRow)+ findById: vi.fn(async (): Promise<unknown> => currentRow),+ findByProviderRequestId: vi.fn(async (): Promise<unknown> => null),+ claimDecisionRead: vi.fn(async (): Promise<unknown> => ({ id: "delegated-1" }))};- const approvalRequestDAL = { findById: vi.fn(async () => approvalRequest) };const kmsService = {createCipherPairWithDataKey: vi.fn(async () => ({encryptor: ({ plainText }: { plainText: Buffer }) => ({ cipherTextBlob: encrypt(plainText) }),decryptor: ({ cipherTextBlob }: { cipherTextBlob: Buffer }) => decrypt(cipherTextBlob)}))};+ const approvalRequestDAL = {++ findById: vi.fn(async () => approvalRequest),+ transaction: vi.fn(async (cb: (tx: unknown) => Promise<unknown>) => cb(TX)),+ findByIdForUpdate: vi.fn(async (): Promise<unknown> => null),+ updateById: vi.fn(async () => null)+ };+ const eventEmitter = { emit: vi.fn(async () => {}) };const service = delegatedApprovalCallbackServiceFactory({delegatedApprovalRequestDAL: delegatedApprovalRequestDAL as never,@@@ -84,18 -61,16 +90,18 @@@ describe("getCallbackUrl", () =>});describe("getOrIssueCallbackToken", () => {- test("issues a token once and stores it encrypted under the org key", async () => {- const { service, delegatedApprovalRequestDAL, kmsService } = makeService();++ const delegatedRequest = { id: "delegated-1", requestId: "req-1", encryptedCallbackToken: null };+- const token = await service.getOrIssueCallbackToken({- delegatedRequest: { id: "delegated-1", encryptedCallbackToken: null },- orgId: "org-1"- });+ test("issues a token once and stores it encrypted under the project key", async () => {+ const { service, delegatedApprovalRequestDAL, approvalRequestDAL, kmsService } = makeService();++ const token = await service.getOrIssueCallbackToken({ delegatedRequest });expect(token).toBeTruthy();+ expect(approvalRequestDAL.findById).toHaveBeenCalledWith("req-1", PRIMARY);expect(kmsService.createCipherPairWithDataKey).toHaveBeenCalledWith({- type: KmsDataKey.Organization,- orgId: "org-1"+ type: KmsDataKey.SecretManager,+ projectId: "project-1"});expect(delegatedApprovalRequestDAL.update).toHaveBeenCalledWith({ id: "delegated-1", encryptedCallbackToken: null },@@@ -121,13 -95,9 +126,10 @@@currentRow: { encryptedCallbackToken: encrypt(Buffer.from("winner-token")) }});- const token = await service.getOrIssueCallbackToken({- delegatedRequest: { id: "delegated-1", encryptedCallbackToken: null },- orgId: "org-1"- });+ const token = await service.getOrIssueCallbackToken({ delegatedRequest });expect(token).toBe("winner-token");+ expect(delegatedApprovalRequestDAL.findById).toHaveBeenCalledWith("delegated-1", PRIMARY);});test("returns null when the request vanished before a token could be stored", async () => {@@@ -140,203 -107,14 +139,214 @@@expect(token).toBeNull();});++ test("returns null without issuing a token when the approval request is gone", async () => {+ const { service, delegatedApprovalRequestDAL, kmsService } = makeService({ approvalRequest: null });++ const token = await service.getOrIssueCallbackToken({ delegatedRequest });++ expect(token).toBeNull();+ expect(kmsService.createCipherPairWithDataKey).not.toHaveBeenCalled();+ expect(delegatedApprovalRequestDAL.update).not.toHaveBeenCalled();+ });});++describe("handleCallback", () => {+ const TOKEN = "inf_ext_stored-token";+ const EXTERNAL_ID = "9d41f2a7c3b24e1088f6a05e7b1d4c93";+ const EVENT = DelegatedApprovalCallbackEvent.SecretsManagementAccessRequest;++ const makeDelegatedRequest = (overrides?: Record<string, unknown>) => ({+ id: "delegated-1",+ requestId: "request-1",+ status: DelegatedApprovalRequestStatus.WaitingApproval,+ encryptedCallbackToken: encrypt(Buffer.from(TOKEN)),+ providerRequestId: EXTERNAL_ID,+ callbackAttempts: 0,+ approvalRequestOrganizationId: "org-1",++ approvalRequestProjectId: "project-1",+ ...overrides+ });++ const makeCallbackService = ({+ delegatedRequest = makeDelegatedRequest(),+ attemptsAfterIncrement = 1,+ lockedApprovalRequest = { id: "request-1", status: ApprovalRequestStatus.Pending }+ }: {+ delegatedRequest?: ReturnType<typeof makeDelegatedRequest> | null;+ attemptsAfterIncrement?: number;+ lockedApprovalRequest?: { id: string; status: ApprovalRequestStatus } | null;+ } = {}) => {+ const built = makeService();+ built.delegatedApprovalRequestDAL.findByProviderRequestId.mockResolvedValue(delegatedRequest);+ built.delegatedApprovalRequestDAL.update.mockResolvedValue([+ { ...delegatedRequest, callbackAttempts: attemptsAfterIncrement }+ ] as never);+ built.approvalRequestDAL.findByIdForUpdate.mockResolvedValue(lockedApprovalRequest);+ return built;+ };++ const callback = (overrides?: Partial<{ token: string | undefined; event: typeof EVENT; externalId: string }>) => ({+ token: TOKEN,+ event: EVENT,+ externalId: EXTERNAL_ID,+ ...overrides+ });++ test("returns 404 when no request has the external ID", async () => {+ const { service, delegatedApprovalRequestDAL, eventEmitter } = makeCallbackService({ delegatedRequest: null });++ await expect(service.handleCallback(callback())).rejects.toBeInstanceOf(NotFoundError);+ expect(delegatedApprovalRequestDAL.findByProviderRequestId).toHaveBeenCalledWith(EXTERNAL_ID);+ expect(delegatedApprovalRequestDAL.update).not.toHaveBeenCalled();+ expect(eventEmitter.emit).not.toHaveBeenCalled();+ });++ test.each([+ ["missing", undefined],+ ["unprefixed", "stored-token"],+ ["mismatched", "inf_ext_other-token"]+ ])("rejects a %s token without counting it, even when it would pass the limit", async (_label, token) => {+ const { service, delegatedApprovalRequestDAL, approvalRequestDAL, eventEmitter } = makeCallbackService({+ delegatedRequest: makeDelegatedRequest({ callbackAttempts: DELEGATED_APPROVAL_CALLBACK_MAX_ATTEMPTS }),+ attemptsAfterIncrement: DELEGATED_APPROVAL_CALLBACK_MAX_ATTEMPTS + 1+ });++ await expect(service.handleCallback(callback({ token }))).rejects.toBeInstanceOf(ForbiddenRequestError);+ expect(delegatedApprovalRequestDAL.update).not.toHaveBeenCalled();+ expect(delegatedApprovalRequestDAL.updateWithDetails).not.toHaveBeenCalled();+ expect(approvalRequestDAL.updateById).not.toHaveBeenCalled();+ expect(eventEmitter.emit).not.toHaveBeenCalled();+ });++ test("counts a callback once its token matches", async () => {+ const { service, delegatedApprovalRequestDAL } = makeCallbackService();++ await service.handleCallback(callback());++ expect(delegatedApprovalRequestDAL.update).toHaveBeenCalledWith(+ { id: "delegated-1" },+ { $incr: { callbackAttempts: 1 } }+ );+ });++ test("rejects a request that is not awaiting a decision", async () => {+ const { service, eventEmitter } = makeCallbackService({+ delegatedRequest: makeDelegatedRequest({ status: DelegatedApprovalRequestStatus.Approved })+ });++ await expect(service.handleCallback(callback())).rejects.toBeInstanceOf(ForbiddenRequestError);+ expect(eventEmitter.emit).not.toHaveBeenCalled();+ });++ test("fails the request and cancels its approval request on the callback past the limit", async () => {+ const { service, delegatedApprovalRequestDAL, approvalRequestDAL, eventEmitter } = makeCallbackService({+ attemptsAfterIncrement: DELEGATED_APPROVAL_CALLBACK_MAX_ATTEMPTS + 1+ });++ await expect(service.handleCallback(callback())).rejects.toBeInstanceOf(ForbiddenRequestError);++ expect(approvalRequestDAL.findByIdForUpdate).toHaveBeenCalledWith("request-1", TX);+ expect(approvalRequestDAL.updateById).toHaveBeenCalledWith(+ "request-1",+ { status: ApprovalRequestStatus.Cancelled },+ TX+ );+ const [filter, patch, tx] = delegatedApprovalRequestDAL.updateWithDetails.mock.lastCall as unknown as [+ unknown,+ { status: string; details: { statusReason: string } },+ unknown+ ];+ expect(filter).toEqual({ id: "delegated-1", status: DelegatedApprovalRequestStatus.WaitingApproval });+ expect(patch.status).toBe(DelegatedApprovalRequestStatus.Failed);+ expect(patch.details.statusReason).toContain(`more than ${DELEGATED_APPROVAL_CALLBACK_MAX_ATTEMPTS} times`);+ expect(tx).toBe(TX);+ expect(eventEmitter.emit).not.toHaveBeenCalled();+ });++ test("leaves an approval request that is no longer pending alone when attempts run out", async () => {+ const { service, delegatedApprovalRequestDAL, approvalRequestDAL } = makeCallbackService({+ attemptsAfterIncrement: DELEGATED_APPROVAL_CALLBACK_MAX_ATTEMPTS + 1,+ lockedApprovalRequest: { id: "request-1", status: ApprovalRequestStatus.Expired }+ });++ await expect(service.handleCallback(callback())).rejects.toBeInstanceOf(ForbiddenRequestError);++ expect(approvalRequestDAL.updateById).not.toHaveBeenCalled();+ const [, patch] = delegatedApprovalRequestDAL.updateWithDetails.mock.lastCall as unknown as [+ unknown,+ { status: string }+ ];+ expect(patch.status).toBe(DelegatedApprovalRequestStatus.Failed);+ });++ test("still accepts the callback at the limit", async () => {+ const { service, eventEmitter } = makeCallbackService({+ attemptsAfterIncrement: DELEGATED_APPROVAL_CALLBACK_MAX_ATTEMPTS+ });++ await expect(service.handleCallback(callback())).resolves.toEqual({ delegatedRequestId: "delegated-1" });+ expect(eventEmitter.emit).toHaveBeenCalledTimes(1);+ });++ test("emits an outbox event keyed on the delegated request", async () => {+ const { service, eventEmitter, kmsService } = makeCallbackService();++ await expect(service.handleCallback(callback())).resolves.toEqual({ delegatedRequestId: "delegated-1" });++ expect(kmsService.createCipherPairWithDataKey).toHaveBeenCalledWith({- type: KmsDataKey.Organization,- orgId: "org-1"++ type: KmsDataKey.SecretManager,++ projectId: "project-1"+ });+ expect(eventEmitter.emit).toHaveBeenCalledWith(+ {+ eventType: EVENT,+ idempotencyKey: "delegated-1:1",+ payload: {+ delegatedRequestId: "delegated-1",+ approvalRequestId: "request-1",+ orgId: "org-1",+ event: EVENT,+ externalId: EXTERNAL_ID+ }+ },+ TX+ );+ });++ test("claims the read-back in the emit's transaction, expiring claims older than their TTL", async () => {+ vi.useFakeTimers({ now: new Date("2026-10-21T12:00:00.000Z") });+ try {+ const { service, delegatedApprovalRequestDAL } = makeCallbackService();++ await service.handleCallback(callback());++ expect(delegatedApprovalRequestDAL.claimDecisionRead).toHaveBeenCalledWith(+ { id: "delegated-1", staleBefore: new Date(Date.now() - DELEGATED_APPROVAL_DECISION_READ_CLAIM_TTL_MS) },+ TX+ );+ } finally {+ vi.useRealTimers();+ }+ });++ test("accepts a repeat without emitting while another read-back holds the claim", async () => {+ const { service, delegatedApprovalRequestDAL, eventEmitter } = makeCallbackService();+ delegatedApprovalRequestDAL.claimDecisionRead.mockResolvedValue(null);+ delegatedApprovalRequestDAL.findById.mockResolvedValue(makeDelegatedRequest());++ await expect(service.handleCallback(callback())).resolves.toEqual({ delegatedRequestId: "delegated-1" });+ expect(eventEmitter.emit).not.toHaveBeenCalled();+ });++ test("rejects a callback whose request stopped awaiting a decision before the claim", async () => {+ const { service, delegatedApprovalRequestDAL, eventEmitter } = makeCallbackService();+ delegatedApprovalRequestDAL.claimDecisionRead.mockResolvedValue(null);+ delegatedApprovalRequestDAL.findById.mockResolvedValue(+ makeDelegatedRequest({ status: DelegatedApprovalRequestStatus.Approved })+ );++ await expect(service.handleCallback(callback())).rejects.toBeInstanceOf(ForbiddenRequestError);+ expect(eventEmitter.emit).not.toHaveBeenCalled();+ });+});diff --cc backend/src/services/delegated-approval-callback/delegated-approval-callback-service.tsindex 550ebfb462,e1057bbb5d..68a5bf293b--- a/backend/src/services/delegated-approval-callback/delegated-approval-callback-service.ts+++ b/backend/src/services/delegated-approval-callback/delegated-approval-callback-service.ts@@@ -60,95 -47,5 +61,95 @@@ export const delegatedApprovalCallbackSreturn decryptor({ cipherTextBlob: current.encryptedCallbackToken }).toString();};- return { getCallbackUrl, getOrIssueCallbackToken };+ const handleCallback = async ({ token, event, externalId }: THandleDelegatedApprovalCallbackDTO) => {+ const delegatedRequest = await delegatedApprovalRequestDAL.findByProviderRequestId(externalId);+ if (!delegatedRequest) {+ throw new NotFoundError({+ message: `No delegated approval request matches external ID '${externalId}'`+ });+ }++ const logContext = { delegatedRequestId: delegatedRequest.id, externalId };++ if (!token || !token.startsWith(DELEGATED_APPROVAL_CALLBACK_TOKEN_PREFIX)) {+ throw rejectApprovalCallback("missing or malformed token", logContext);+ }+ if (!delegatedRequest.encryptedCallbackToken) {+ throw rejectApprovalCallback("request has no callback token", logContext);+ }++ const { decryptor } = await kmsService.createCipherPairWithDataKey({- type: KmsDataKey.Organization,- orgId: delegatedRequest.approvalRequestOrganizationId++ type: KmsDataKey.SecretManager,++ projectId: delegatedRequest.approvalRequestProjectId+ });+ const storedToken = decryptor({ cipherTextBlob: delegatedRequest.encryptedCallbackToken }).toString();+ if (!isTokenMatch(token, storedToken)) {+ throw rejectApprovalCallback("token mismatch", logContext);+ }++ // Counted only after the token matches: the limit closes the request, so a refused callback must+ // not count toward it, or anyone who knows the external ID could cancel the request. The token is+ // 256 random bits, so refusals need no counter of their own to stop it being guessed.+ const [counted] = await delegatedApprovalRequestDAL.update(+ { id: delegatedRequest.id },+ { $incr: { callbackAttempts: 1 } }+ );+ const attempts = counted?.callbackAttempts ?? delegatedRequest.callbackAttempts + 1;+ if (attempts > DELEGATED_APPROVAL_CALLBACK_MAX_ATTEMPTS) {+ await failDelegatedApprovalRequest(+ {+ id: delegatedRequest.id,+ requestId: delegatedRequest.requestId,+ reason: DELEGATED_APPROVAL_CALLBACK_ATTEMPTS_EXHAUSTED_REASON+ },+ { approvalRequestDAL, delegatedApprovalRequestDAL }+ );+ throw rejectApprovalCallback("callback attempts exhausted", {+ ...logContext,+ attempts: String(attempts)+ });+ }++ if (delegatedRequest.status !== DelegatedApprovalRequestStatus.WaitingApproval) {+ throw rejectApprovalCallback("request is not awaiting a decision", {+ ...logContext,+ status: delegatedRequest.status+ });+ }++ const payload: TDelegatedApprovalCallbackEventPayload = {+ delegatedRequestId: delegatedRequest.id,+ approvalRequestId: delegatedRequest.requestId,+ orgId: delegatedRequest.approvalRequestOrganizationId,+ event,+ externalId+ };+ // A read-back already in flight will see the decision this callback announces, so a repeat only+ // starts another once that one has had time to finish.+ const outcome = await delegatedApprovalRequestDAL.transaction(async (tx) => {+ const claimed = await delegatedApprovalRequestDAL.claimDecisionRead(+ { id: delegatedRequest.id, staleBefore: new Date(Date.now() - DELEGATED_APPROVAL_DECISION_READ_CLAIM_TTL_MS) },+ tx+ );+ if (!claimed) {+ const current = await delegatedApprovalRequestDAL.findById(delegatedRequest.id, tx);+ return current?.status === DelegatedApprovalRequestStatus.WaitingApproval ? "deduplicated" : "closed";+ }++ await eventEmitter.emit({ eventType: event, idempotencyKey: `${delegatedRequest.id}:${attempts}`, payload }, tx);+ return "accepted";+ });++ if (outcome === "closed") {+ throw rejectApprovalCallback("request is not awaiting a decision", logContext);+ }++ logger.info(+ `Delegated approval callback ${outcome} [delegatedRequestId=${delegatedRequest.id}] [approvalRequestId=${delegatedRequest.requestId}] [event=${event}] [attempt=${attempts}]`+ );++ return { delegatedRequestId: delegatedRequest.id };+ };++ return { getCallbackUrl, getOrIssueCallbackToken, handleCallback };};diff --cc backend/src/services/delegated-approval-callback/delegated-approval-callback-types.tsindex 1cc4d09e7d,9b638cba1f..8a1862639c--- a/backend/src/services/delegated-approval-callback/delegated-approval-callback-types.ts+++ b/backend/src/services/delegated-approval-callback/delegated-approval-callback-types.ts@@@ -1,34 -1,14 +1,33 @@@import { TDelegatedApprovalRequests } from "@app/db/schemas";import { TApprovalRequestDALFactory } from "@app/services/approval-policy/approval-request-dal";import { TDelegatedApprovalRequestDALFactory } from "@app/services/delegated-approval/delegated-approval-request-dal";+import { TEventEmitter } from "@app/services/event-outbox/event-outbox-types";import { TKmsServiceFactory } from "@app/services/kms/kms-service";+import { DelegatedApprovalCallbackEvent } from "./delegated-approval-callback-enums";+export type TDelegatedApprovalCallbackServiceFactoryDep = {- delegatedApprovalRequestDAL: Pick<TDelegatedApprovalRequestDALFactory, "findById" | "primaryNode" | "update">;- approvalRequestDAL: Pick<TApprovalRequestDALFactory, "findById">;+ delegatedApprovalRequestDAL: Pick<+ TDelegatedApprovalRequestDALFactory,+ | "claimDecisionRead"+ | "findById"+ | "findByProviderRequestId"+ | "primaryNode"+ | "transaction"+ | "update"+ | "updateWithDetails"+ >;- approvalRequestDAL: Pick<TApprovalRequestDALFactory, "transaction" | "findByIdForUpdate" | "updateById">;++ approvalRequestDAL: Pick<TApprovalRequestDALFactory, "findById" | "transaction" | "findByIdForUpdate" | "updateById">;kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;+ eventEmitter: Pick<TEventEmitter, "emit">;};export type TGetOrIssueCallbackTokenDTO = {- delegatedRequest: Pick<TDelegatedApprovalRequests, "id" | "encryptedCallbackToken">;- orgId: string;+ delegatedRequest: Pick<TDelegatedApprovalRequests, "id" | "requestId" | "encryptedCallbackToken">;};++export type THandleDelegatedApprovalCallbackDTO = {+ token: string | undefined;+ event: DelegatedApprovalCallbackEvent;+ externalId: string;+};diff --cc backend/src/services/delegated-approval-decision/delegated-approval-decision-consumer.test.tsindex 60ac594473,0000000000..19f7eb1f85mode 100644,000000..100644--- a/backend/src/services/delegated-approval-decision/delegated-approval-decision-consumer.test.ts+++ b/backend/src/services/delegated-approval-decision/delegated-approval-decision-consumer.test.ts@@@ -1,592 -1,0 +1,593 @@@+import { UnrecoverableError } from "bullmq";+import { beforeEach, describe, expect, test, vi } from "vitest";++import { TEventOutbox } from "@app/db/schemas";+import { ApprovalPolicyType, ApprovalRequestStatus } from "@app/services/approval-policy/approval-policy-enums";+import {+ DelegatedApprovalPolicyType,+ DelegatedApprovalRequestStatus+} from "@app/services/delegated-approval/delegated-approval-enums";+import { TDelegatedApprovalRequestDetails } from "@app/services/delegated-approval/delegated-approval-schemas";+import { DelegatedApprovalCallbackEvent } from "@app/services/delegated-approval-callback/delegated-approval-callback-enums";+import { eventOutboxRegistryFactory } from "@app/services/event-outbox/event-outbox-registry";+import { eventOutboxServiceFactory } from "@app/services/event-outbox/event-outbox-service";+import { EventOutboxStatus, EventResultStatus, TEvent } from "@app/services/event-outbox/event-outbox-types";++import { DELEGATED_APPROVAL_DECISION_RETRY_HINT } from "./delegated-approval-decision-constants";+import { delegatedApprovalDecisionConsumerFactory } from "./delegated-approval-decision-consumer";+import { DelegatedApprovalDecision, DelegatedApprovalDecisionOutcome } from "./delegated-approval-decision-enums";+import { delegatedApprovalDecisionServiceFactory } from "./delegated-approval-decision-service";+import { TDelegatedApprovalDecisionReadResult } from "./delegated-approval-decision-types";++vi.mock("@app/lib/logger", () => ({+ logger: { info: () => {}, warn: () => {}, error: () => {}, debug: () => {} },+ initLogger: () => {}+}));++vi.mock("@app/lib/telemetry/metrics", () => ({+ recordEventOutboxLagMetric: () => {},+ recordEventOutboxExhaustedMetric: () => {}+}));++const { fetchDecision, REQUESTED_PERMISSIONS } = vi.hoisted(() => ({+ fetchDecision: vi.fn(),+ REQUESTED_PERMISSIONS: ["secrets: read, create", "secret-folders: edit"]+}));+vi.mock("@app/services/delegated-approval/dispatch/delegated-approval-dispatch-fns", () => ({+ getDelegatedApprovalProvider: () => ({ fetchDecision }),+ getDelegatedApprovalDispatchDetailsBuilder: () => () => ({+ policyType: "secret-access",+ environment: "dev",+ secretPath: "/",+ permissions: REQUESTED_PERMISSIONS,+ isTemporary: false,+ temporaryRange: null+ })+}));++vi.mock("@app/services/app-connection/app-connection-fns", () => ({+ decryptAppConnection: async (connection: unknown) => connection+}));++const DELEGATED_REQUEST_ID = "11111111-1111-1111-1111-111111111111";+const APPROVAL_REQUEST_ID = "33333333-3333-3333-3333-333333333333";+const ORG_ID = "22222222-2222-2222-2222-222222222222";+const EXTERNAL_ID = "snow-1";+const POLICY_NAME = "Production secrets";+const TX = { tx: true } as never;+const PRIMARY = { primary: true } as never;+const SERVICENOW_RECORD = { type: DelegatedApprovalPolicyType.ServiceNow, recordNumber: "INFAR1000000" };+const waitingDelegatedRequest = {+ id: DELEGATED_REQUEST_ID,+ requestId: APPROVAL_REQUEST_ID,+ status: DelegatedApprovalRequestStatus.WaitingApproval,+ details: { statusReason: null, provider: SERVICENOW_RECORD } as TDelegatedApprovalRequestDetails,+ providerRequestId: EXTERNAL_ID as string | null+};++type TDelegatedRow = typeof waitingDelegatedRequest;++const pendingApprovalRequest = {+ id: APPROVAL_REQUEST_ID,+ policyId: "policy-1",+ projectId: "project-1",+ organizationId: ORG_ID,+ requesterId: "user-1" as string | null,+ type: ApprovalPolicyType.SecretAccess,+ status: ApprovalRequestStatus.Pending as string,+ expiresAt: null as Date | null+};++type TApprovalRow = typeof pendingApprovalRequest;++const delegatedPolicy = {+ id: "delegated-policy-1",+ policyId: "policy-1",+ type: DelegatedApprovalPolicyType.ServiceNow,+ connectionId: "connection-1"+};++const decided = (+ decision: DelegatedApprovalDecision,+ overrides: Partial<Extract<TDelegatedApprovalDecisionReadResult, { status: "decided" }>> = {}+): TDelegatedApprovalDecisionReadResult => ({+ status: "decided",+ decision,+ approvalRequestId: APPROVAL_REQUEST_ID,+ permissions: ["secrets: create, read", "secret-folders: edit"],+ decidedBy: "Grace Hopper",+ decidedAt: "2026-10-20 10:15:00",+ notes: null,+ ...overrides+});++const buildConsumer = ({+ delegatedRequest = waitingDelegatedRequest as TDelegatedRow | null,+ approvalRequest = pendingApprovalRequest as TApprovalRow | null,+ policy = delegatedPolicy as typeof delegatedPolicy | null,+ connection = { id: "connection-1", orgId: ORG_ID, app: "servicenow" } as { id: string; orgId: string } | null,+ isRequesterProjectMember = true+} = {}) => {+ let row: TDelegatedRow | null = delegatedRequest ? { ...delegatedRequest } : null;+ let approval: TApprovalRow | null = approvalRequest ? { ...approvalRequest } : null;++ // Merges details the way the DAL's jsonb concatenation does.+ const updateWithDetails = vi.fn(+ async (+ filter: Partial<TDelegatedRow>,+ { details, ...columns }: Partial<TDelegatedRow> & { details?: Partial<TDelegatedRow["details"]> }+ ) => {+ const current = row;+ if (!current) return [];+ const matches = Object.entries(filter).every(([key, value]) => current[key as keyof TDelegatedRow] === value);+ if (!matches) return [];+ row = { ...current, ...columns, details: { ...current.details, ...details } };+ return [row];+ }+ );++ const updateById = vi.fn(async (_id: string, patch: Partial<TApprovalRow>) => {+ approval = approval ? { ...approval, ...patch } : approval;+ return approval;+ });+ const postApprovalTxRoutine = vi.fn(async () => ({ grantId: "grant-1" }));+ const createAuditLog = vi.fn(async () => {});+ const notify = vi.fn(async () => {});++ const delegatedApprovalDecisionService = delegatedApprovalDecisionServiceFactory({+ delegatedApprovalRequestDAL: {+ findById: vi.fn(async () => row),+ primaryNode: () => PRIMARY,+ updateWithDetails+ },+ delegatedApprovalPolicyDAL: { findOne: vi.fn().mockResolvedValue(policy) },+ approvalPolicyDAL: { findById: vi.fn().mockResolvedValue({ id: "policy-1", name: POLICY_NAME }) },+ approvalRequestDAL: {+ findById: vi.fn(async () => approval),+ findByIdForUpdate: vi.fn(async () => approval),+ updateById,+ transaction: vi.fn(async (fn: (tx: unknown) => Promise<unknown>) => fn(TX))+ },+ appConnectionDAL: { findById: vi.fn().mockResolvedValue(connection) },+ membershipDAL: { isUserProjectMember: vi.fn().mockResolvedValue(isRequesterProjectMember) },+ kmsService: { createCipherPairWithDataKey: vi.fn() },+ auditLogService: { createAuditLog },+ approvalResources: { [ApprovalPolicyType.SecretAccess]: { postApprovalTxRoutine } },+ decisionNotifiers: { [ApprovalPolicyType.SecretAccess]: notify }+ } as never);+ const consumer = delegatedApprovalDecisionConsumerFactory({ delegatedApprovalDecisionService });++ return {+ consumer,+ row: () => row,+ approval: () => approval,+ postApprovalTxRoutine,+ createAuditLog,+ notify,+ updateById+ };+};++const makeEvent = (overrides?: Partial<TEvent>): TEvent => ({+ id: 1,+ eventType: DelegatedApprovalCallbackEvent.SecretsManagementAccessRequest,+ payload: {+ delegatedRequestId: DELEGATED_REQUEST_ID,+ approvalRequestId: APPROVAL_REQUEST_ID,+ orgId: ORG_ID,+ event: DelegatedApprovalCallbackEvent.SecretsManagementAccessRequest,+ externalId: EXTERNAL_ID+ },+ occurredAt: new Date(),++ isFinalAttempt: false,+ ...overrides+});++const auditedWith = (createAuditLog: ReturnType<typeof vi.fn>, expected: Record<string, unknown>) => {+ expect(createAuditLog).toHaveBeenCalledTimes(1);+ expect(createAuditLog.mock.calls[0][0]).toMatchObject({+ orgId: ORG_ID,+ projectId: "project-1",+ event: {+ metadata: {+ requestId: APPROVAL_REQUEST_ID,+ policyName: POLICY_NAME,+ delegatedProviderRequestId: EXTERNAL_ID,+ permissions: REQUESTED_PERMISSIONS,+ ...expected+ }+ }+ });+};++beforeEach(() => {+ fetchDecision.mockReset();+});++describe("delegatedApprovalDecisionConsumer", () => {+ test("applies an approval: both rows move, the grant routine runs in the same transaction", async () => {+ fetchDecision.mockResolvedValueOnce(decided(DelegatedApprovalDecision.Approved));+ const { consumer, row, approval, postApprovalTxRoutine, createAuditLog, notify } = buildConsumer();++ const results = await consumer.handle([makeEvent()]);++ expect(results).toEqual([{ id: "1", status: EventResultStatus.Delivered }]);+ expect(fetchDecision.mock.calls[0][0]).toEqual({+ delegatedRequestId: DELEGATED_REQUEST_ID,+ approvalRequestId: APPROVAL_REQUEST_ID,+ providerRequestId: EXTERNAL_ID+ });+ expect(row()).toEqual({+ ...waitingDelegatedRequest,+ status: DelegatedApprovalRequestStatus.Approved,+ details: { statusReason: null, provider: SERVICENOW_RECORD }+ });+ expect(approval()?.status).toBe(ApprovalRequestStatus.Approved);+ expect(postApprovalTxRoutine).toHaveBeenCalledWith(expect.objectContaining({ id: APPROVAL_REQUEST_ID }), TX);+ auditedWith(createAuditLog, {+ outcome: DelegatedApprovalDecisionOutcome.Applied,+ decision: DelegatedApprovalDecision.Approved,+ decidedBy: "Grace Hopper",+ decidedAt: "2026-10-20 10:15:00",+ providerRecordNumber: "INFAR1000000"+ });+ expect(notify).toHaveBeenCalledWith({+ approvalRequestId: APPROVAL_REQUEST_ID,+ decision: DelegatedApprovalDecision.Approved+ });+ });++ test("applies a rejection without granting anything", async () => {+ fetchDecision.mockResolvedValueOnce(decided(DelegatedApprovalDecision.Rejected, { notes: "Not now." }));+ const { consumer, row, approval, postApprovalTxRoutine, createAuditLog } = buildConsumer();++ const results = await consumer.handle([makeEvent()]);++ expect(results).toEqual([{ id: "1", status: EventResultStatus.Delivered }]);+ expect(row()?.status).toBe(DelegatedApprovalRequestStatus.Rejected);+ expect(approval()?.status).toBe(ApprovalRequestStatus.Rejected);+ expect(postApprovalTxRoutine).not.toHaveBeenCalled();+ auditedWith(createAuditLog, { decision: DelegatedApprovalDecision.Rejected, decisionNotes: "Not now." });+ });++ test("accepts the record's permissions in whatever order and padding the system stores them", async () => {+ fetchDecision.mockResolvedValueOnce(+ decided(DelegatedApprovalDecision.Approved, { permissions: ["secret-folders:edit", "secrets:read,create"] })+ );+ const { consumer, row } = buildConsumer();++ await consumer.handle([makeEvent()]);++ expect(row()?.status).toBe(DelegatedApprovalRequestStatus.Approved);+ });++ test("fails for good when the approved permissions differ from the request, and closes the request", async () => {+ fetchDecision.mockResolvedValueOnce(+ decided(DelegatedApprovalDecision.Approved, {+ permissions: ["secrets: read, create, delete", "secret-folders: edit"]+ })+ );+ const { consumer, row, approval, postApprovalTxRoutine, createAuditLog, notify } = buildConsumer();++ const [result] = await consumer.handle([makeEvent()]);++ expect(result.status).toBe(EventResultStatus.Failed);+ expect(result.error).toContain("approved different permissions");+ expect(result.error).toContain("Requested: secret-folders: edit; secrets: create, read");+ expect(result.error).toContain("Approved in ServiceNow: secret-folders: edit; secrets: create, delete, read");+ expect(row()).toMatchObject({+ status: DelegatedApprovalRequestStatus.Failed,+ details: { statusReason: result.error, provider: SERVICENOW_RECORD }+ });+ expect(approval()?.status).toBe(ApprovalRequestStatus.Cancelled);+ expect(postApprovalTxRoutine).not.toHaveBeenCalled();+ expect(notify).not.toHaveBeenCalled();+ auditedWith(createAuditLog, { outcome: DelegatedApprovalDecisionOutcome.Failed, reason: result.error });+ });++ test("fails for good when the record belongs to another request", async () => {+ fetchDecision.mockResolvedValueOnce(decided(DelegatedApprovalDecision.Approved, { approvalRequestId: "other" }));+ const { consumer, row, approval } = buildConsumer();++ const [result] = await consumer.handle([makeEvent()]);++ expect(result.status).toBe(EventResultStatus.Failed);+ expect(row()?.status).toBe(DelegatedApprovalRequestStatus.Failed);+ expect(approval()?.status).toBe(ApprovalRequestStatus.Cancelled);+ });++ test("cancels a request whose requester was deleted without reading the decision", async () => {+ const { consumer, row, approval, postApprovalTxRoutine, createAuditLog } = buildConsumer({+ approvalRequest: { ...pendingApprovalRequest, requesterId: null }+ });++ const [result] = await consumer.handle([makeEvent()]);++ expect(result.status).toBe(EventResultStatus.Failed);+ expect(result.error).toContain("was deleted");+ expect(fetchDecision).not.toHaveBeenCalled();+ expect(row()).toMatchObject({+ status: DelegatedApprovalRequestStatus.Failed,+ details: { statusReason: result.error }+ });+ expect(approval()?.status).toBe(ApprovalRequestStatus.Cancelled);+ expect(postApprovalTxRoutine).not.toHaveBeenCalled();+ auditedWith(createAuditLog, { outcome: DelegatedApprovalDecisionOutcome.Failed, reason: result.error });+ });++ test("cancels a request whose requester left the project without reading the decision", async () => {+ const { consumer, row, approval, postApprovalTxRoutine } = buildConsumer({ isRequesterProjectMember: false });++ const [result] = await consumer.handle([makeEvent()]);++ expect(result.status).toBe(EventResultStatus.Failed);+ expect(result.error).toContain("no longer a member of this project");+ expect(fetchDecision).not.toHaveBeenCalled();+ expect(row()?.status).toBe(DelegatedApprovalRequestStatus.Failed);+ expect(approval()?.status).toBe(ApprovalRequestStatus.Cancelled);+ expect(postApprovalTxRoutine).not.toHaveBeenCalled();+ });++ test("retries while the system has not recorded a decision, telling the user why", async () => {+ fetchDecision.mockResolvedValueOnce({ status: "pending", reason: "ServiceNow has not recorded a decision yet." });+ const { consumer, row, approval, createAuditLog } = buildConsumer();++ const results = await consumer.handle([makeEvent()]);++ expect(results).toEqual([+ { id: "1", status: EventResultStatus.Retry, error: "ServiceNow has not recorded a decision yet." }+ ]);+ expect(row()).toMatchObject({+ status: DelegatedApprovalRequestStatus.WaitingApproval,+ details: {+ statusReason: `ServiceNow has not recorded a decision yet. ${DELEGATED_APPROVAL_DECISION_RETRY_HINT}`,+ provider: SERVICENOW_RECORD+ }+ });+ expect(approval()?.status).toBe(ApprovalRequestStatus.Pending);+ expect(createAuditLog).not.toHaveBeenCalled();+ });++ test("retries a transient read failure without touching the request", async () => {+ fetchDecision.mockRejectedValueOnce(new Error("ServiceNow could not be reached."));+ const { consumer, row, approval } = buildConsumer();++ const [result] = await consumer.handle([makeEvent()]);++ expect(result).toEqual({ id: "1", status: EventResultStatus.Retry, error: "ServiceNow could not be reached." });+ expect(row()).toMatchObject({ status: DelegatedApprovalRequestStatus.WaitingApproval });+ expect(row()?.details.statusReason).toContain(DELEGATED_APPROVAL_DECISION_RETRY_HINT);+ expect(approval()?.status).toBe(ApprovalRequestStatus.Pending);+ });++ test("fails for good on an unrecoverable read error", async () => {+ fetchDecision.mockRejectedValueOnce(new UnrecoverableError("ServiceNow rejected the credentials."));+ const { consumer, row, approval } = buildConsumer();++ const [result] = await consumer.handle([makeEvent()]);++ expect(result).toEqual({+ id: "1",+ status: EventResultStatus.Failed,+ error: "ServiceNow rejected the credentials."+ });+ expect(row()).toMatchObject({+ status: DelegatedApprovalRequestStatus.Failed,+ details: { statusReason: "ServiceNow rejected the credentials." }+ });+ expect(approval()?.status).toBe(ApprovalRequestStatus.Cancelled);+ });++ test("fails for good without reading when the policy names an unsupported delegated approval system", async () => {+ const { consumer, row, approval, createAuditLog } = buildConsumer({+ policy: { ...delegatedPolicy, type: "jira" as DelegatedApprovalPolicyType }+ });++ const [result] = await consumer.handle([makeEvent()]);++ expect(result.status).toBe(EventResultStatus.Failed);+ expect(result.error).toBe("The delegated approval system 'jira' is not supported. Create the request again.");+ expect(fetchDecision).not.toHaveBeenCalled();+ expect(row()).toMatchObject({+ status: DelegatedApprovalRequestStatus.Failed,+ details: { statusReason: result.error }+ });+ expect(approval()?.status).toBe(ApprovalRequestStatus.Cancelled);+ auditedWith(createAuditLog, {+ outcome: DelegatedApprovalDecisionOutcome.Failed,+ reason: result.error,+ delegatedApprovalType: "the delegated approval system"+ });+ });++ test.each([+ ["the delegated approver was removed from the policy", { policy: null }],+ ["the connection is gone", { connection: null }],+ ["the connection belongs to another org", { connection: { id: "connection-1", orgId: "other-org" } }]+ ])("fails for good without reading when %s", async (_, overrides) => {+ const { consumer, row, approval } = buildConsumer(overrides);++ const [result] = await consumer.handle([makeEvent()]);++ expect(result.status).toBe(EventResultStatus.Failed);+ expect(fetchDecision).not.toHaveBeenCalled();+ expect(row()?.status).toBe(DelegatedApprovalRequestStatus.Failed);+ expect(approval()?.status).toBe(ApprovalRequestStatus.Cancelled);+ });++ test("records a decision that arrives after the request was cancelled, without granting", async () => {+ fetchDecision.mockResolvedValueOnce(decided(DelegatedApprovalDecision.Approved));+ const { consumer, row, approval, postApprovalTxRoutine, createAuditLog } = buildConsumer({+ approvalRequest: { ...pendingApprovalRequest, status: ApprovalRequestStatus.Cancelled }+ });++ const results = await consumer.handle([makeEvent()]);++ expect(results).toEqual([{ id: "1", status: EventResultStatus.Delivered }]);+ expect(row()?.status).toBe(DelegatedApprovalRequestStatus.Failed);+ expect(row()?.details.statusReason).toContain("after the request was cancelled");+ expect(approval()?.status).toBe(ApprovalRequestStatus.Cancelled);+ expect(postApprovalTxRoutine).not.toHaveBeenCalled();+ auditedWith(createAuditLog, { outcome: DelegatedApprovalDecisionOutcome.Failed });+ });++ test("expires a request whose decision arrives after its deadline", async () => {+ fetchDecision.mockResolvedValueOnce(decided(DelegatedApprovalDecision.Approved));+ const { consumer, row, approval, postApprovalTxRoutine } = buildConsumer({+ approvalRequest: { ...pendingApprovalRequest, expiresAt: new Date(Date.now() - 60_000) }+ });++ await consumer.handle([makeEvent()]);++ expect(row()?.status).toBe(DelegatedApprovalRequestStatus.Failed);+ expect(row()?.details.statusReason).toContain("expired");+ expect(approval()?.status).toBe(ApprovalRequestStatus.Expired);+ expect(postApprovalTxRoutine).not.toHaveBeenCalled();+ });++ test.each([+ ["is gone", null],+ ["was approved", { ...waitingDelegatedRequest, status: DelegatedApprovalRequestStatus.Approved }],+ ["was rejected", { ...waitingDelegatedRequest, status: DelegatedApprovalRequestStatus.Rejected }],+ ["failed", { ...waitingDelegatedRequest, status: DelegatedApprovalRequestStatus.Failed }],+ ["was never sent", { ...waitingDelegatedRequest, status: DelegatedApprovalRequestStatus.PendingDispatch }]+ ])("marks the event delivered without reading when the request %s", async (_, delegatedRequest) => {+ const { consumer } = buildConsumer({ delegatedRequest });++ const results = await consumer.handle([makeEvent()]);++ expect(results).toEqual([{ id: "1", status: EventResultStatus.Delivered }]);+ expect(fetchDecision).not.toHaveBeenCalled();+ });++ test("audits without a record number when the provider never reported one", async () => {+ fetchDecision.mockResolvedValueOnce(decided(DelegatedApprovalDecision.Approved));+ const { consumer, createAuditLog } = buildConsumer({+ delegatedRequest: { ...waitingDelegatedRequest, details: { statusReason: null } }+ });++ await consumer.handle([makeEvent()]);++ expect(createAuditLog).toHaveBeenCalledTimes(1);+ const [entry] = createAuditLog.mock.calls[0] as unknown as [{ event: { metadata: Record<string, unknown> } }];+ expect(entry.event.metadata).not.toHaveProperty("providerRecordNumber");+ });++ test("fails the event, not the request, when the callback names another record", async () => {+ const { consumer, row } = buildConsumer({+ delegatedRequest: { ...waitingDelegatedRequest, providerRequestId: "snow-2" }+ });++ const [result] = await consumer.handle([makeEvent()]);++ expect(result.status).toBe(EventResultStatus.Failed);+ expect(fetchDecision).not.toHaveBeenCalled();+ expect(row()?.status).toBe(DelegatedApprovalRequestStatus.WaitingApproval);+ });++ test("fails an unreadable payload terminally", async () => {+ const { consumer } = buildConsumer();++ const [result] = await consumer.handle([makeEvent({ payload: { delegatedRequestId: "not-a-uuid" } })]);++ expect(result.status).toBe(EventResultStatus.Failed);+ expect(result.error).toContain("Unreadable delegated approval callback payload");+ expect(fetchDecision).not.toHaveBeenCalled();+ });+});++// Why the read-back is an outbox consumer: a record whose decision is not stored yet is tried again+// later, instead of being dropped by a callback that answered 200 before anything was read.+describe("delegatedApprovalDecisionConsumer through the outbox", () => {+ const buildOutbox = (consumer: ReturnType<typeof buildConsumer>["consumer"]) => {+ const registry = eventOutboxRegistryFactory();+ registry.register(consumer);++ const rows: TEventOutbox[] = [];+ const isDue = (row: TEventOutbox) =>+ (row.status === EventOutboxStatus.Pending || row.status === EventOutboxStatus.Retry) &&+ row.nextRetryAt <= new Date();++ const service = eventOutboxServiceFactory({+ eventOutboxDAL: {+ insertEvents: async (inserted: Pick<TEventOutbox, "consumer" | "eventType" | "payload">[]) => {+ inserted.forEach((row) =>+ rows.push({+ id: rows.length + 1,+ status: EventOutboxStatus.Pending,+ attempts: 0,+ nextRetryAt: new Date(0),+ occurredAt: new Date(),+ ...row+ } as TEventOutbox)+ );+ },+ claimBatch: async () => {+ const claimable = rows.filter(isDue);+ claimable.forEach((row) => Object.assign(row, { status: EventOutboxStatus.Processing }));+ return { lockToken: "token", rows: claimable.map((row) => ({ ...row })) };+ },+ extendClaims: async () => {},+ commitResults: async (input: {+ delivered: { ids: string[] }[];+ retriable: { ids: string[]; nextRetryDelayMs: number; error?: string }[];+ failed: { ids: string[]; error?: string }[];+ }) => {+ const apply = (+ groups: { ids: string[]; nextRetryDelayMs?: number; error?: string }[],+ status: EventOutboxStatus+ ) =>+ groups.forEach((group) =>+ group.ids.forEach((id) => {+ const row = rows.find((candidate) => String(candidate.id) === id);+ if (!row) return;+ row.status = status;+ row.attempts += 1;+ row.lastError = group.error ?? null;+ row.nextRetryAt = new Date(Date.now() + (group.nextRetryDelayMs ?? 0));+ })+ );+ apply(input.delivered, EventOutboxStatus.Delivered);+ apply(input.retriable, EventOutboxStatus.Retry);+ apply(input.failed, EventOutboxStatus.Failed);+ return [...input.delivered, ...input.retriable, ...input.failed].reduce(+ (n, group) => n + group.ids.length,+ 0+ );+ }+ } as never,+ eventOutboxRegistry: registry+ });++ const elapseBackoff = () => {+ rows.forEach((row) => Object.assign(row, { nextRetryAt: new Date(0) }));+ };++ return { service, rows, elapseBackoff };+ };++ test("retries a record without a decision and applies it on a later flush", async () => {+ fetchDecision+ .mockResolvedValueOnce({ status: "pending", reason: "Not yet." })+ .mockResolvedValueOnce(decided(DelegatedApprovalDecision.Approved));+ const built = buildConsumer();+ const { service, rows, elapseBackoff } = buildOutbox(built.consumer);+ const { payload } = makeEvent();++ await service.emit({+ eventType: DelegatedApprovalCallbackEvent.SecretsManagementAccessRequest,+ payload: payload as Record<string, unknown>+ });+ await service.drain({ consumer: built.consumer.name });++ expect(rows[0]).toMatchObject({ status: EventOutboxStatus.Retry, attempts: 1, lastError: "Not yet." });+ expect(built.row()?.status).toBe(DelegatedApprovalRequestStatus.WaitingApproval);++ elapseBackoff();+ await service.drain({ consumer: built.consumer.name });++ expect(rows[0]).toMatchObject({ status: EventOutboxStatus.Delivered, attempts: 2 });+ expect(built.row()?.status).toBe(DelegatedApprovalRequestStatus.Approved);+ expect(fetchDecision).toHaveBeenCalledTimes(2);+ });+});diff --cc backend/src/services/delegated-approval/delegated-approval-request-dal.tsindex 10c391d2b6,b03168321c..9843a8753e--- a/backend/src/services/delegated-approval/delegated-approval-request-dal.ts+++ b/backend/src/services/delegated-approval/delegated-approval-request-dal.ts@@@ -10,73 -4,10 +10,75 @@@ import { TDelegatedApprovalRequestDetaiexport type TDelegatedApprovalRequestDALFactory = ReturnType<typeof delegatedApprovalRequestDALFactory>;+export type TDelegatedApprovalRequestWithApprovalRequest = TDelegatedApprovalRequests & {+ approvalRequestOrganizationId: string;++ approvalRequestProjectId: string;+};+export const delegatedApprovalRequestDALFactory = (db: TDbClient) => {const orm = ormify(db, TableName.DelegatedApprovalRequests);const primaryNode = () => db.primaryNode();- return { ...orm, primaryNode };+ const findByProviderRequestId = async (providerRequestId: string) => {+ try {+ const row = await db+ .primaryNode()(TableName.DelegatedApprovalRequests)+ .join(+ TableName.ApprovalRequests,+ `${TableName.DelegatedApprovalRequests}.requestId`,+ `${TableName.ApprovalRequests}.id`+ )+ .where(`${TableName.DelegatedApprovalRequests}.providerRequestId`, providerRequestId)+ .select(selectAllTableCols(TableName.DelegatedApprovalRequests))+ .select(db.ref("organizationId").withSchema(TableName.ApprovalRequests).as("approvalRequestOrganizationId"))++ .select(db.ref("projectId").withSchema(TableName.ApprovalRequests).as("approvalRequestProjectId"))+ .first();+ return (row as TDelegatedApprovalRequestWithApprovalRequest | undefined) ?? null;+ } catch (error) {+ throw new DatabaseError({ error, name: "DelegatedApprovalRequest: findByProviderRequestId" });+ }+ };++ // Concurrent claims on one row serialize on its lock, and the loser re-evaluates the WHERE against the+ // winner's write, so only one caller gets the row back.+ const claimDecisionRead = async ({ id, staleBefore }: { id: string; staleBefore: Date }, tx?: Knex) => {+ try {+ const [row] = await (tx || db)(TableName.DelegatedApprovalRequests)+ .where({ id, status: DelegatedApprovalRequestStatus.WaitingApproval })+ .where((qb) => {+ void qb.whereNull("decisionReadRequestedAt").orWhere("decisionReadRequestedAt", "<", staleBefore);+ })+ .update({ decisionReadRequestedAt: new Date() })+ .returning("*");+ return (row as TDelegatedApprovalRequests | undefined) ?? null;+ } catch (error) {+ throw new DatabaseError({ error, name: "DelegatedApprovalRequest: claimDecisionRead" });+ }+ };++ const updateWithDetails = async (+ filter: Partial<Pick<TDelegatedApprovalRequests, "id" | "requestId" | "status">>,+ {+ details,+ ...columns+ }: Omit<TDelegatedApprovalRequestsUpdate, "details"> & { details?: Partial<TDelegatedApprovalRequestDetails> },+ tx?: Knex+ ) => {+ try {+ const patch = details ? JSON.stringify(details) : "{}";+ const rows = await (tx || db)(TableName.DelegatedApprovalRequests)+ .where(filter)+ .update({+ ...columns,+ ...(patch !== "{}" ? { details: db.raw(`COALESCE("details", '{}'::jsonb) || ?::jsonb`, [patch]) } : {})+ })+ .returning("*");+ return rows as TDelegatedApprovalRequests[];+ } catch (error) {+ throw new DatabaseError({ error, name: "DelegatedApprovalRequest: updateWithDetails" });+ }+ };++ return { ...orm, primaryNode, findByProviderRequestId, claimDecisionRead, updateWithDetails };};diff --cc backend/src/services/delegated-approval/delegated-approval-service.test.tsindex 7fed27cfd5,1fc4369419..46aeba3cb0--- a/backend/src/services/delegated-approval/delegated-approval-service.test.ts+++ b/backend/src/services/delegated-approval/delegated-approval-service.test.ts@@@ -11,7 -12,7 +12,8 @@@ const failedRequest =id: "delegated-1",requestId: "req-1",status: DelegatedApprovalRequestStatus.FailedDispatch,- details: { statusReason: "ServiceNow could not be reached." }++ details: { statusReason: "ServiceNow could not be reached." },+ updatedAt: UPDATED_AT};const serviceNowPolicy = {id: "delegated-policy-1",@@@ -34,8 -35,9 +36,9 @@@ const createService = (delegatedPolicy = serviceNowPolicy as unknown} = {}) => {const emit = vi.fn().mockResolvedValue(undefined);- const create = vi.fn().mockImplementation(async (row: { requestId: string; status: string }) => ({+ const create = vi.fn().mockImplementation(async (row: { requestId: string; status: string; details: object }) => ({id: "delegated-1",+ updatedAt: UPDATED_AT,...row}));const service = delegatedApprovalServiceFactory({diff --cc backend/src/services/delegated-approval/delegated-approval-service.tsindex 223b6f8a81,0be7efbd01..cf9011cecb--- a/backend/src/services/delegated-approval/delegated-approval-service.ts+++ b/backend/src/services/delegated-approval/delegated-approval-service.ts@@@ -160,12 -153,16 +160,16 @@@ export const delegatedApprovalServiceFaassertPolicyTypeSupportsDelegatedApproval(approvalRequest.type);try {- const request = (await delegatedApprovalRequestDAL.create(- { requestId: approvalRequest.id, status: DelegatedApprovalRequestStatus.PendingDispatch },+ const request = await delegatedApprovalRequestDAL.create(+ { requestId: approvalRequest.id, status: DelegatedApprovalRequestStatus.PendingDispatch, details: {} },tx- )) as TDelegatedApprovalRequest;+ );- await emitDelegatedApprovalDispatchRequested(eventEmitter, { delegatedRequestId: request.id }, tx);+ await emitDelegatedApprovalDispatchRequested(+ eventEmitter,+ { delegatedRequestId: request.id, updatedAt: request.updatedAt },+ tx+ );- return request;+ return toDelegatedApprovalRequest(request);} catch (err) {if (hasPostgresErrorCode(err, DatabaseErrorCode.UniqueViolation)) {throw new BadRequestError({diff --cc backend/src/services/delegated-approval/dispatch/delegated-approval-dispatch-consumer.test.tsindex 007e1fbc6c,ce5c299cdf..f74aa54f08--- a/backend/src/services/delegated-approval/dispatch/delegated-approval-dispatch-consumer.test.ts+++ b/backend/src/services/delegated-approval/dispatch/delegated-approval-dispatch-consumer.test.ts@@@ -85,23 -89,28 +91,26 @@@ const buildConsumer = (} = {}) => {let row: TRow | null = delegatedRequest ? { ...delegatedRequest } : null;- const update = vi.fn(async (filter: Partial<TRow>, patch: Partial<TRow>) => {- const current = row;- if (!current) return [];- const matches = Object.entries(filter).every(([key, value]) => current[key as keyof TRow] === value);- if (!matches) return [];- row = { ...current, ...patch };- return [row];- });- const updateById = vi.fn(async (_id: string, patch: Partial<TRow>) => {- row = row ? { ...row, ...patch } : row;- return row;- });+ // Merges details the way the DAL's jsonb concatenation does.+ const updateWithDetails = vi.fn(+ async (filter: Partial<TRow>, { details, ...columns }: Partial<TRow> & { details?: Partial<TRow["details"]> }) => {+ const current = row;+ if (!current) return [];+ const matches = Object.entries(filter).every(([key, value]) => current[key as keyof TRow] === value);+ if (!matches) return [];+ row = { ...current, ...columns, details: { ...current.details, ...details } };+ return [row];+ }+ );+ const approvalUpdate = vi.fn(async () => [approval]);+const consumer = delegatedApprovalDispatchConsumerFactory({delegatedApprovalRequestDAL: {findById: findById ?? vi.fn(async () => row),primaryNode: () => PRIMARY,- updateWithDetails- transaction: async (cb: (tx: never) => Promise<unknown>) => cb(TX),- update,- updateById++ updateWithDetails,++ transaction: async (cb: (tx: never) => Promise<unknown>) => cb(TX)},delegatedApprovalPolicyDAL: { findOne: vi.fn().mockResolvedValue(policy) },delegatedApprovalCallbackService: {@@@ -116,7 -125,7 +125,7 @@@kmsService: { createCipherPairWithDataKey: vi.fn() }} as never);- return { consumer, row: () => row, updateWithDetails };- return { consumer, row: () => row, update, approvalUpdate };++ return { consumer, row: () => row, updateWithDetails, approvalUpdate };};const makeEvent = (overrides?: Partial<TEvent>): TEvent => ({@@@ -196,6 -187,38 +206,40 @@@ describe("delegatedApprovalDispatchCons});});+ test("closes the request when a transient failure lands on the last attempt", async () => {+ dispatch.mockRejectedValueOnce(new Error("ServiceNow did not respond."));+ const { consumer, row, approvalUpdate } = buildConsumer();++ const results = await consumer.handle([makeEvent({ isFinalAttempt: true })]);++ expect(results).toEqual([{ id: "1", status: EventResultStatus.Failed, error: "ServiceNow did not respond." }]);+ expect(row()).toMatchObject({+ status: DelegatedApprovalRequestStatus.Failed,- statusReason: `ServiceNow did not respond. Infisical could not send this request after ${MAX_OUTBOX_ATTEMPTS} attempts and closed it. Create a new request.`++ details: {++ statusReason: `ServiceNow did not respond. Infisical could not send this request after ${MAX_OUTBOX_ATTEMPTS} attempts and closed it. Create a new request.`++ }+ });+ expect(approvalUpdate).toHaveBeenCalledWith(+ { id: "req-1", status: ApprovalRequestStatus.Pending },+ { status: ApprovalRequestStatus.Cancelled },+ TX+ );+ });++ test("keeps a terminal failure on the last attempt resendable", async () => {+ dispatch.mockRejectedValueOnce(new UnrecoverableError("ServiceNow rejected the credentials."));+ const { consumer, row, approvalUpdate } = buildConsumer();++ const [result] = await consumer.handle([makeEvent({ isFinalAttempt: true })]);++ expect(result.status).toBe(EventResultStatus.Failed);+ expect(row()).toMatchObject({+ status: DelegatedApprovalRequestStatus.FailedDispatch,- statusReason: "ServiceNow rejected the credentials."++ details: { statusReason: "ServiceNow rejected the credentials." }+ });+ expect(approvalUpdate).not.toHaveBeenCalled();+ });+test("fails terminally when the approval request is no longer pending", async () => {const { consumer, row } = buildConsumer({approval: { ...approvalRequest, status: ApprovalRequestStatus.Cancelled }diff --cc backend/src/services/delegated-approval/dispatch/delegated-approval-dispatch-consumer.tsindex e2448063ea,b81dad2903..b23528486c--- a/backend/src/services/delegated-approval/dispatch/delegated-approval-dispatch-consumer.ts+++ b/backend/src/services/delegated-approval/dispatch/delegated-approval-dispatch-consumer.ts@@@ -4,9 -5,10 +5,10 @@@ import { ProjectType } from "@app/db/scimport { logger } from "@app/lib/logger";import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";import { decryptAppConnection } from "@app/services/app-connection/app-connection-fns";-import { APP_CONNECTION_NAME_MAP } from "@app/services/app-connection/app-connection-maps";+ import { ApprovalRequestStatus } from "@app/services/approval-policy/approval-policy-enums";import { TApprovalRequestDALFactory } from "@app/services/approval-policy/approval-request-dal";import { TDelegatedApprovalCallbackServiceFactory } from "@app/services/delegated-approval-callback/delegated-approval-callback-service";+import { parseEventPayload, runEventsSerially } from "@app/services/event-outbox/event-outbox-fns";import {EventResultStatus,IEventConsumer,@@@ -43,20 -37,12 +46,22 @@@ import { TDelegatedApprovalDispatchInpuexport const DELEGATED_APPROVAL_DISPATCH_CONSUMER = "delegated-approval-dispatch";+ const DELEGATED_APPROVAL_DISPATCH_CONCURRENCY = 10;++const BLOCKER_MESSAGES: Record<DelegatedApprovalRequestBlocker, string> = {+ [DelegatedApprovalRequestBlocker.Missing]: "The approval request no longer exists.",+ [DelegatedApprovalRequestBlocker.NotPending]:+ "The approval request is no longer pending, so it was not sent to the delegated approval system.",+ [DelegatedApprovalRequestBlocker.Expired]:+ "The approval request expired before it could be sent to the delegated approval system. Create the request again.",+ [DelegatedApprovalRequestBlocker.PolicyRemoved]:+ "The policy's delegated approver was removed before the request could be sent. Configure a delegated approver on the policy and create the request again."+};+type TDelegatedApprovalDispatchConsumerDep = {delegatedApprovalRequestDAL: Pick<TDelegatedApprovalRequestDALFactory,- "findById" | "primaryNode" | "updateWithDetails"- "findById" | "primaryNode" | "transaction" | "update" | "updateById"++ "findById" | "primaryNode" | "transaction" | "updateWithDetails">;delegatedApprovalPolicyDAL: Pick<TDelegatedApprovalPolicyDALFactory, "findOne">;delegatedApprovalCallbackService: Pick<@@@ -97,13 -83,60 +102,49 @@@ export const delegatedApprovalDispatchC}};- const $dispatch = async (delegatedRequestId: string): Promise<Omit<TEventConsumerResult, "id">> => {+ const $closeAfterExhaustedAttempts = async ({+ delegatedRequestId,+ approvalRequestId,+ statusReason+ }: {+ delegatedRequestId: string;+ approvalRequestId: string;+ statusReason: string;+ }) => {+ try {+ await delegatedApprovalRequestDAL.transaction(async (tx) => {- await delegatedApprovalRequestDAL.update(++ await delegatedApprovalRequestDAL.updateWithDetails(+ { id: delegatedRequestId, status: DelegatedApprovalRequestStatus.PendingDispatch },+ {+ status: DelegatedApprovalRequestStatus.Failed,- statusReason: statusReason.slice(0, DELEGATED_APPROVAL_STATUS_REASON_MAX_CHARS)++ details: { statusReason: toDelegatedApprovalStatusReason(statusReason) }+ },+ tx+ );+ await approvalRequestDAL.update(+ { id: approvalRequestId, status: ApprovalRequestStatus.Pending },+ { status: ApprovalRequestStatus.Cancelled },+ tx+ );+ });+ } catch (error) {+ logger.error(+ error,+ `Failed to close a delegated approval request whose dispatch attempts ran out [delegatedRequestId=${delegatedRequestId}] [approvalRequestId=${approvalRequestId}]`+ );+ }+ };+- // Both rows were committed together with the event, so they are read from the primary.- const $loadRequests = async (delegatedRequestId: string) => {- const primary = delegatedApprovalRequestDAL.primaryNode();-- const delegatedRequest = await delegatedApprovalRequestDAL.findById(delegatedRequestId, primary);- if (!delegatedRequest) return null;-- const approvalRequest = await approvalRequestDAL.findById(delegatedRequest.requestId, primary);- const delegatedPolicy = approvalRequest?.policyId- ? await delegatedApprovalPolicyDAL.findOne({ policyId: approvalRequest.policyId }, primary)- : null;-- return { delegatedRequest, approvalRequest, delegatedPolicy };- };-+ const $dispatch = async (+ delegatedRequestId: string,+ isFinalAttempt: boolean+ ): Promise<Omit<TEventConsumerResult, "id">> => {- const requests = await $loadRequests(delegatedRequestId);- if (!requests) {+ const context = await loadDelegatedApprovalContext(delegatedRequestId, {+ delegatedApprovalRequestDAL,+ approvalRequestDAL,+ delegatedApprovalPolicyDAL+ });+ if (!context) {logger.warn(`Delegated approval request no longer exists, skipping dispatch [delegatedRequestId=${delegatedRequestId}]`);@@@ -162,20 -208,16 +203,17 @@@if (!project) {throw new UnrecoverableError("The project of the approval request no longer exists.");}- if (!rawConnection || rawConnection.orgId !== approvalRequest.organizationId) {- const connectionApp = DELEGATED_APPROVAL_CONNECTION_MAP[delegatedPolicy.type as DelegatedApprovalPolicyType];- throw new UnrecoverableError(- `App Connection with ID '${delegatedPolicy.connectionId}' was not found. Select a ${APP_CONNECTION_NAME_MAP[connectionApp]} Connection on the policy and create the request again.`- );- }- const connection = await decryptAppConnection(rawConnection, kmsService);+ const connection = await decryptAppConnection(+ requireDelegatedApprovalConnection({+ rawConnection,+ delegatedPolicy,+ organizationId: approvalRequest.organizationId+ }),+ kmsService+ );- const callbackToken = await delegatedApprovalCallbackService.getOrIssueCallbackToken({- delegatedRequest,- orgId: approvalRequest.organizationId- });+ const callbackToken = await delegatedApprovalCallbackService.getOrIssueCallbackToken({ delegatedRequest });if (!callbackToken) {throw new UnrecoverableError("A callback token could not be issued for this request. Create the request again."@@@ -220,18 -254,34 +258,30 @@@);return { status: EventResultStatus.Delivered };} catch (error) {- const isTerminal = error instanceof UnrecoverableError;- const message = error instanceof Error ? error.message : String(error);- const logContext = { err: { name: (error as Error)?.name, message } };+ const { terminal, message, logContext } = toDelegatedApprovalFailure(error);- // The outbox decides when retries run out and the consumer never sees the attempt count, so the- // reason has to read true on every attempt. The row is failed_dispatch throughout, which is what- // makes the manual resend available while the outbox is still retrying.- if (!isTerminal && isFinalAttempt && approvalRequest) {++ if (!terminal && isFinalAttempt && approvalRequest) {+ await $closeAfterExhaustedAttempts({+ delegatedRequestId,+ approvalRequestId: approvalRequest.id,+ statusReason: `${message} Infisical could not send this request after ${MAX_OUTBOX_ATTEMPTS} attempts and closed it. Create a new request.`+ });+ logger.error(+ logContext,+ `Delegated approval dispatch attempts ran out, request closed [delegatedRequestId=${delegatedRequestId}] [approvalRequestId=${approvalRequest.id}]`+ );+ return { status: EventResultStatus.Failed, error: message };+ }++ // The row is failed_dispatch throughout, which is what makes the manual resend available while the+ // outbox is still retrying.await $markDispatchFailed(delegatedRequestId,- isTerminal- ? message- : `${message} Infisical will retry automatically. If it keeps failing, send the request again.`+ terminal ? message : `${message} ${DELEGATED_APPROVAL_DISPATCH_RETRY_HINT}`);- const logMessage = `Delegated approval dispatch failed [delegatedRequestId=${delegatedRequestId}] [terminal=${isTerminal}]`;- if (isTerminal) {+ const logMessage = `Delegated approval dispatch failed [delegatedRequestId=${delegatedRequestId}] [terminal=${terminal}]`;+ if (terminal) {logger.error(logContext, logMessage);return { status: EventResultStatus.Failed, error: message };}@@@ -241,14 -291,69 +291,45 @@@};const $handleEvent = async (event: TEvent): Promise<TEventConsumerResult> => {- const id = String(event.id);-- const payload = DelegatedApprovalDispatchRequestedPayloadSchema.safeParse(event.payload);- if (!payload.success) {- return {- id,- status: EventResultStatus.Failed,- error: `Unreadable delegated approval dispatch payload: ${payload.error.issues.map((issue) => issue.message).join(", ")}`- };- }-- return { id, ...(await $dispatch(payload.data.delegatedRequestId, event.isFinalAttempt)) };- };+ const { data, failure } = parseEventPayload(+ event,+ DelegatedApprovalDispatchRequestedPayloadSchema,+ "delegated approval dispatch"+ );+ if (failure) return failure;- return { id: String(event.id), ...(await $dispatch(data.delegatedRequestId)) };- const $runEvent = async (event: TEvent): Promise<TEventConsumerResult> => {- try {- return await $handleEvent(event);- } catch (error) {- return {- id: String(event.id),- status: EventResultStatus.Retry,- error: error instanceof Error ? error.message : "Unknown error"- };- }++ return { id: String(event.id), ...(await $dispatch(data.delegatedRequestId, event.isFinalAttempt)) };+ };++ // Unreadable payloads have no request id, so each one is its own group and cannot block another request.+ const $groupByRequest = (events: TEvent[]): TEvent[][] => {+ const groups: TEvent[][] = [];+ const indexByRequest = new Map<string, number>();++ events.forEach((event) => {+ const payload = DelegatedApprovalDispatchRequestedPayloadSchema.safeParse(event.payload);+ const key = payload.success ? payload.data.delegatedRequestId : `event:${String(event.id)}`;+ const existing = indexByRequest.get(key);+ if (existing === undefined) {+ indexByRequest.set(key, groups.length);+ groups.push([event]);+ } else {+ groups[existing].push(event);+ }+ });++ return groups;+ };+++ // Events for one request run serially, so two of them cannot both pass the providerRequestId check.+ const handle = async (events: TEvent[]): Promise<TEventConsumerResult[]> => {+ const limit = pLimit(DELEGATED_APPROVAL_DISPATCH_CONCURRENCY);++ const groupResults = await Promise.all(- $groupByRequest(events).map((group) =>- limit(async () => {- const results: TEventConsumerResult[] = [];- for (const event of group) {- // eslint-disable-next-line no-await-in-loop -- two events for one request must not both pass the providerRequestId check- results.push(await $runEvent(event));- }- return results;- })- )++ $groupByRequest(events).map((group) => limit(() => runEventsSerially(group, $handleEvent)))+ );++ return groupResults.flat();};return {diff --cc backend/src/services/delegated-approval/providers/servicenow/servicenow-fns.test.tsindex dc708286d4,6205e1f251..e380fcf551--- a/backend/src/services/delegated-approval/providers/servicenow/servicenow-fns.test.ts+++ b/backend/src/services/delegated-approval/providers/servicenow/servicenow-fns.test.ts@@@ -4,21 -4,20 +4,22 @@@ import { describe, expect, test, vi } fimport { ProjectType } from "@app/db/schemas";import { BadRequestError } from "@app/lib/errors";+ import { logger } from "@app/lib/logger";import { ApprovalPolicyType } from "@app/services/approval-policy/approval-policy-enums";+import { DelegatedApprovalDecision } from "@app/services/delegated-approval-decision/delegated-approval-decision-enums";-import { TDelegatedApprovalDispatchInput } from "../../delegated-approval-dispatch-types";-import { ServiceNowRequestType } from "./servicenow-enums";+import { TDelegatedApprovalDispatchInput } from "../../dispatch/delegated-approval-dispatch-types";+import { ServiceNowRequestOperation, ServiceNowRequestType } from "./servicenow-enums";import {buildServiceNowAccessRequestPayload,parseServiceNowAccessRequestResponse,- toServiceNowDispatchError+ parseServiceNowDecision,+ toServiceNowRequestError} from "./servicenow-fns";- vi.mock("@app/lib/logger", () => ({- logger: { info: () => {}, warn: () => {}, error: () => {}, debug: () => {} },- initLogger: () => {}+ vi.mock("@app/lib/logger", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@app/lib/logger")>()),+ logger: { info: vi.fn(), error: vi.fn(), warn: vi.fn(), debug: vi.fn() }}));const INSTANCE_URL = "https://acme.service-now.com";@@@ -257,8 -188,18 +258,18 @@@ describe("toServiceNowRequestError", (expect(error.message).toContain("Missing required field: environment");});+ test("logs the rate limit instead of returning it to the user", () => {- const error = toServiceNowDispatchError(makeAxiosError(429), INSTANCE_URL);++ const error = toServiceNowRequestError(makeAxiosError(429), INSTANCE_URL);++ expect(error.message).not.toMatch(/rate limit/);+ expect(logger.warn).toHaveBeenCalledWith(+ { status: 429, instance: "acme.service-now.com" },+ expect.stringMatching(/rate limiting requests from Infisical \(HTTP 429\)/)+ );+ });+test("retries when there was no response at all", () => {- const error = toServiceNowDispatchError(makeAxiosError(undefined, undefined, "ECONNABORTED"), INSTANCE_URL);+ const error = toServiceNowRequestError(makeAxiosError(undefined, undefined, "ECONNABORTED"), INSTANCE_URL);expect(error).toBeInstanceOf(BadRequestError);expect(error.message).toMatch(/could not be reached \(ECONNABORTED\)/);diff --cc backend/src/services/delegated-approval/providers/servicenow/servicenow-fns.tsindex e2cdfa7142,0000000000..28b6abf492mode 100644,000000..100644--- a/backend/src/services/delegated-approval/providers/servicenow/servicenow-fns.ts+++ b/backend/src/services/delegated-approval/providers/servicenow/servicenow-fns.ts@@@ -1,366 -1,0 +1,370 @@@+import { AxiosError, AxiosRequestConfig } from "axios";+import { UnrecoverableError } from "bullmq";++import { BadRequestError } from "@app/lib/errors";+import { logger, sanitizeUrlForLog } from "@app/lib/logger";+import { safeRequest } from "@app/lib/validator/safe-request";+import { AppConnection } from "@app/services/app-connection/app-connection-enums";+import { TAppConnection } from "@app/services/app-connection/app-connection-types";+import { TServiceNowConnection } from "@app/services/app-connection/servicenow";+import { ApprovalPolicyType } from "@app/services/approval-policy/approval-policy-enums";+import { DelegatedApprovalPolicyType } from "@app/services/delegated-approval/delegated-approval-enums";+import { DelegatedApprovalCallbackEvent } from "@app/services/delegated-approval-callback/delegated-approval-callback-enums";+import { DelegatedApprovalDecision } from "@app/services/delegated-approval-decision/delegated-approval-decision-enums";+import { TDelegatedApprovalDecisionReadResult } from "@app/services/delegated-approval-decision/delegated-approval-decision-types";++import {+ TDelegatedApprovalDispatchDetails,+ TDelegatedApprovalDispatchInput,+ TDelegatedApprovalProvider+} from "../../dispatch/delegated-approval-dispatch-types";+import {+ SERVICENOW_ACCESS_REQUEST_PATH,+ SERVICENOW_DISPATCH_MAX_CONTENT_LENGTH,+ SERVICENOW_DISPATCH_TIMEOUT_MS,+ SERVICENOW_ERROR_DETAIL_MAX_CHARS,+ SERVICENOW_PERMISSIONS_MAX_CHARS+} from "./servicenow-constants";+import { ServiceNowDecision, ServiceNowRequestOperation, ServiceNowRequestType } from "./servicenow-enums";+import {+ ServiceNowAccessRequestPayloadSchema,+ ServiceNowAccessRequestResponseSchema,+ ServiceNowAccessResponseRecordSchema,+ ServiceNowErrorResponseSchema+} from "./servicenow-schemas";+import {+ TServiceNowAccessRequestOutcome,+ TServiceNowAccessRequestPayload,+ TServiceNowRequestFailureContext+} from "./servicenow-types";++const describeInstance = (instanceUrl: string) => {+ try {+ return new URL(instanceUrl).host;+ } catch {+ return "the configured instance";+ }+};++function assertServiceNowConnection(connection: TAppConnection): asserts connection is TServiceNowConnection {+ if (connection.app !== AppConnection.ServiceNow) {+ throw new UnrecoverableError(`App Connection with ID '${connection.id}' is not a ServiceNow Connection.`);+ }+}++const buildServiceNowRequestConfig = (+ { username, password }: TServiceNowConnection["credentials"],+ overrides: Partial<AxiosRequestConfig> = {}+): AxiosRequestConfig => ({+ auth: { username, password },+ timeout: SERVICENOW_DISPATCH_TIMEOUT_MS,+ maxContentLength: SERVICENOW_DISPATCH_MAX_CONTENT_LENGTH,+ "axios-retry": { retries: 0 },+ ...overrides,+ headers: { Accept: "application/json", ...overrides.headers }+});++// Scripted REST responses may arrive bare or wrapped in the platform's `result` envelope.+const unwrapServiceNowResult = (data: unknown) =>+ data && typeof data === "object" && "result" in data ? (data as { result: unknown }).result : data;++const toOptionalText = (value: string | null | undefined) => {+ const text = value?.trim() ?? "";+ return text || null;+};++const buildRequestTypeFields = (details: TDelegatedApprovalDispatchDetails) => {+ switch (details.policyType) {+ case ApprovalPolicyType.SecretAccess:+ return {+ event: DelegatedApprovalCallbackEvent.SecretsManagementAccessRequest,+ request_type: ServiceNowRequestType.SecretAccess,+ environment: details.environment,+ secret_path: details.secretPath,+ permissions: details.permissions,+ is_temporary: details.isTemporary,+ ...(details.isTemporary && details.temporaryRange ? { temporary_range: details.temporaryRange } : {})+ };+ default: {+ const { policyType } = details as { policyType: string };+ throw new UnrecoverableError(`ServiceNow cannot review '${policyType}' requests.`);+ }+ }+};++export const buildServiceNowAccessRequestPayload = (+ input: TDelegatedApprovalDispatchInput+): TServiceNowAccessRequestPayload => {+ const parsed = ServiceNowAccessRequestPayloadSchema.safeParse({+ request_id: input.approvalRequestId,+ callback_url: input.callback.url,+ callback_token: input.callback.token,+ product_type: input.productType,+ ...(input.project ? { project_id: input.project.id, project_name: input.project.name } : {}),+ requestor_email: input.requester.email,+ ...(input.requester.name ? { requestor_name: input.requester.name } : {}),+ ...(input.justification ? { justification: input.justification } : {}),+ ...buildRequestTypeFields(input.details)+ });++ if (!parsed.success) {+ const issues = parsed.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join("; ");+ throw new UnrecoverableError(+ `The request does not meet what the Infisical Approvals ServiceNow application accepts (${issues}).`+ );+ }++ return parsed.data;+};++export const parseServiceNowAccessRequestResponse = (+ status: number,+ data: unknown+): TServiceNowAccessRequestOutcome => {+ const parsed = ServiceNowAccessRequestResponseSchema.safeParse(unwrapServiceNowResult(data));+ const sysId = parsed.success ? parsed.data.sys_id : null;+ const recordNumber = parsed.success ? toOptionalText(parsed.data.request_number) : null;++ if (status === 409) {+ if (!sysId) {+ throw new UnrecoverableError(+ "ServiceNow reported that it already holds this request but did not return the record ID."+ );+ }+ return { sysId, recordNumber, duplicate: true };+ }++ if (!sysId) {+ throw new BadRequestError({+ message: "ServiceNow accepted the request but returned a response without the record ID."+ });+ }++ return { sysId, recordNumber, duplicate: false };+};++const extractErrorDetail = (data: unknown) => {+ const parsed = ServiceNowErrorResponseSchema.safeParse(unwrapServiceNowResult(data));+ if (!parsed.success) return null;++ const { error } = parsed.data;+ if (error === undefined || error === null) return null;++ const detail = typeof error === "string" ? error : JSON.stringify(error);+ return detail.slice(0, SERVICENOW_ERROR_DETAIL_MAX_CHARS);+};++// Retryable failures are BadRequestError; anything a retry cannot fix is UnrecoverableError.+export const toServiceNowRequestError = (+ err: unknown,+ instanceUrl: string,+ operation: ServiceNowRequestOperation = ServiceNowRequestOperation.Dispatch+) => {+ const instance = describeInstance(instanceUrl);+ const unreachable = (code?: string) =>+ new BadRequestError({+ message: `ServiceNow instance ${instance} could not be reached${code ? ` (${code})` : ""}. Check the instance URL and that the instance is reachable from Infisical.`+ });++ if (!(err instanceof AxiosError)) return unreachable();++ const status = err.response?.status;+ if (!status) return unreachable(err.code);++ // ServiceNow answers an unauthenticated request with a redirect to its login page, and safeRequest+ // does not follow redirects, so a rejected credential arrives as a 3xx rather than a 401.+ if ((status >= 300 && status < 400) || status === 401 || status === 403) {+ return new UnrecoverableError(+ `ServiceNow instance ${instance} rejected the integration user's credentials (HTTP ${status}). Verify the username and password of the ServiceNow Connection and that the account is active.`+ );+ }++ if (status === 404) {+ return new UnrecoverableError(+ operation === ServiceNowRequestOperation.Read+ ? `ServiceNow instance ${instance} no longer has the record for this request (HTTP 404). Create the request again.`+ : `ServiceNow instance ${instance} has no Infisical Approvals application endpoint (HTTP 404). Install and activate the Infisical Approvals application on the instance.`+ );+ }++ if (status === 400 || status === 422) {+ const detail = extractErrorDetail(err.response?.data);+ return new UnrecoverableError(+ `ServiceNow instance ${instance} rejected the request (HTTP ${status})${detail ? `: ${detail}` : ""}.`+ );+ }++ if (status === 429) {++ logger.warn(++ { status, instance },++ `ServiceNow instance ${instance} is rate limiting requests from Infisical (HTTP 429).`++ );+ return new BadRequestError({- message: `ServiceNow instance ${instance} is rate limiting requests from Infisical (HTTP 429).`++ message: `ServiceNow instance ${instance} could not accept the request.`+ });+ }++ return new BadRequestError({+ message: `ServiceNow instance ${instance} returned a server error (HTTP ${status}).`+ });+};++// safeRequest's own refusals (private IP, unresolvable host, credentials in the URL) already name+// what is wrong and pass through. Everything else is logged without the raw error, which carries the+// password at config.auth.password and, on dispatch, the callback token in config.data.+const toLoggedServiceNowRequestError = (+ error: unknown,+ {+ instanceUrl,+ connectionId,+ operation,+ action,+ delegatedRequestId,+ approvalRequestId+ }: TServiceNowRequestFailureContext+) => {+ if (error instanceof BadRequestError) return error;++ const responseStatus = error instanceof AxiosError ? error.response?.status : undefined;+ const code = error instanceof AxiosError ? error.code : undefined;++ logger.warn(+ {+ status: responseStatus,+ code,+ message: (error as Error)?.message,+ instanceUrl: sanitizeUrlForLog(instanceUrl)+ },+ `${action} [delegatedRequestId=${delegatedRequestId}] [approvalRequestId=${approvalRequestId}] [connectionId=${connectionId}] [status=${responseStatus ?? "none"}]`+ );++ return toServiceNowRequestError(error, instanceUrl, operation);+};++const dispatchServiceNowRequest: TDelegatedApprovalProvider["dispatch"] = async (input, connection) => {+ assertServiceNowConnection(connection);++ const { instanceUrl } = connection.credentials;+ const payload = buildServiceNowAccessRequestPayload(input);++ let status: number;+ let data: unknown;+ try {+ const response = await safeRequest.post<unknown>(+ `${instanceUrl}${SERVICENOW_ACCESS_REQUEST_PATH}`,+ payload,+ buildServiceNowRequestConfig(connection.credentials, {+ headers: { "Content-Type": "application/json" },+ validateStatus: (code) => (code >= 200 && code < 300) || code === 409+ })+ );+ status = response.status;+ data = response.data;+ } catch (error) {+ throw toLoggedServiceNowRequestError(error, {+ instanceUrl,+ connectionId: connection.id,+ operation: ServiceNowRequestOperation.Dispatch,+ action: "Failed to send delegated approval request to ServiceNow",+ delegatedRequestId: input.delegatedRequestId,+ approvalRequestId: input.approvalRequestId+ });+ }++ const outcome = parseServiceNowAccessRequestResponse(status, data);++ if (outcome.duplicate) {+ logger.warn(+ `ServiceNow already held a record for this delegated approval request from an earlier attempt [delegatedRequestId=${input.delegatedRequestId}] [approvalRequestId=${input.approvalRequestId}] [sysId=${outcome.sysId}]`+ );+ }++ if (!outcome.recordNumber) {+ logger.warn(+ `ServiceNow did not return a record number for this delegated approval request [delegatedRequestId=${input.delegatedRequestId}] [approvalRequestId=${input.approvalRequestId}] [sysId=${outcome.sysId}]`+ );+ return { providerRequestId: outcome.sysId };+ }++ return {+ providerRequestId: outcome.sysId,+ providerDetails: { type: DelegatedApprovalPolicyType.ServiceNow, recordNumber: outcome.recordNumber }+ };+};++// The application stamps `decision` before it posts the callback and never changes it afterwards,+// so it alone says whether the request was decided; `state` only describes where the record is.+export const parseServiceNowDecision = (data: unknown): TDelegatedApprovalDecisionReadResult => {+ const parsed = ServiceNowAccessResponseRecordSchema.safeParse(unwrapServiceNowResult(data));+ if (!parsed.success) {+ throw new BadRequestError({+ message: "ServiceNow returned the access request in a form Infisical could not read."+ });+ }++ const { data: record } = parsed.data;+ const recorded = toOptionalText(record.decision)?.toLowerCase() ?? null;++ if (!recorded) {+ return {+ status: "pending",+ reason: `ServiceNow has not recorded a decision for this request yet${record.state ? ` (state: ${record.state})` : ""}.`+ };+ }++ const decision = {+ [ServiceNowDecision.Approved]: DelegatedApprovalDecision.Approved,+ [ServiceNowDecision.Rejected]: DelegatedApprovalDecision.Rejected+ }[recorded as ServiceNowDecision];+ if (!decision) {+ throw new UnrecoverableError(`ServiceNow recorded a decision Infisical does not recognise ('${recorded}').`);+ }++ const permissions = record.permissions ?? "";+ if (permissions.length >= SERVICENOW_PERMISSIONS_MAX_CHARS) {+ throw new UnrecoverableError(+ "The permission list on the ServiceNow record was cut short, so Infisical cannot verify what was approved. Split the request into smaller ones."+ );+ }++ return {+ status: "decided",+ decision,+ approvalRequestId: toOptionalText(record.request_id),+ permissions: permissions.split(/\r?\n/),+ decidedBy: toOptionalText(record.approved_by),+ decidedAt: toOptionalText(record.decision_date),+ notes: toOptionalText(record.decision_notes)+ };+};++const fetchServiceNowDecision: TDelegatedApprovalProvider["fetchDecision"] = async (input, connection) => {+ assertServiceNowConnection(connection);++ const { instanceUrl } = connection.credentials;++ let data: unknown;+ try {+ const response = await safeRequest.get<unknown>(+ `${instanceUrl}${SERVICENOW_ACCESS_REQUEST_PATH}/${encodeURIComponent(input.providerRequestId)}`,+ buildServiceNowRequestConfig(connection.credentials)+ );+ data = response.data;+ } catch (error) {+ throw toLoggedServiceNowRequestError(error, {+ instanceUrl,+ connectionId: connection.id,+ operation: ServiceNowRequestOperation.Read,+ action: "Failed to read the delegated approval decision from ServiceNow",+ delegatedRequestId: input.delegatedRequestId,+ approvalRequestId: input.approvalRequestId+ });+ }++ return parseServiceNowDecision(data);+};++export const serviceNowProvider: TDelegatedApprovalProvider = {+ dispatch: dispatchServiceNowRequest,+ fetchDecision: fetchServiceNowDecision+};