Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat: add record id and details on db
adilson4dce9519bdd2
diff --git a/backend/src/db/migrations/20261015145100_external-approvals.ts b/backend/src/db/migrations/20261015145100_external-approvals.tsindex e3ff62a94a..2ff0899dfb 100644--- a/backend/src/db/migrations/20261015145100_external-approvals.ts+++ b/backend/src/db/migrations/20261015145100_external-approvals.ts@@ -30,7 +30,7 @@ export async function up(knex: Knex): Promise<void> {t.string("status", 50).notNullable();t.binary("encryptedCallbackToken").nullable();- t.text("statusReason").nullable();+ t.jsonb("details").notNullable();t.string("providerRequestId").nullable().index();t.timestamp("decisionReadRequestedAt", { useTz: true }).nullable();diff --git a/backend/src/db/schemas/delegated-approval-requests.ts b/backend/src/db/schemas/delegated-approval-requests.tsindex d302b92a11..5ed314c0c5 100644--- a/backend/src/db/schemas/delegated-approval-requests.ts+++ b/backend/src/db/schemas/delegated-approval-requests.ts@@ -14,7 +14,7 @@ export const DelegatedApprovalRequestsSchema = z.object({requestId: z.string().uuid(),status: z.string(),encryptedCallbackToken: zodBuffer.nullable().optional(),- statusReason: z.string().nullable().optional(),+ details: z.unknown(),providerRequestId: z.string().nullable().optional(),decisionReadRequestedAt: z.date().nullable().optional(),createdAt: z.date(),diff --git a/backend/src/ee/services/access-approval-request/access-approval-request-types.ts b/backend/src/ee/services/access-approval-request/access-approval-request-types.tsindex df66fc9d4e..566f9c5d0b 100644--- a/backend/src/ee/services/access-approval-request/access-approval-request-types.ts+++ b/backend/src/ee/services/access-approval-request/access-approval-request-types.ts@@ -3,6 +3,7 @@ import {DelegatedApprovalPolicyType,DelegatedApprovalRequestStatus} from "@app/services/delegated-approval/delegated-approval-enums";+import { TDelegatedApprovalProviderDetails } from "@app/services/delegated-approval/delegated-approval-types";export enum ApprovalStatus {PENDING = "pending",@@ -132,7 +133,11 @@ export interface TAccessApprovalRequestServiceFactory {requestExpirationTime?: string | null;delegatedApproval?: { type: DelegatedApprovalPolicyType } | null;};- delegatedApproval?: { status: DelegatedApprovalRequestStatus; statusReason: string | null } | null;+ delegatedApproval?: {+ status: DelegatedApprovalRequestStatus;+ statusReason: string | null;+ provider: TDelegatedApprovalProviderDetails | null;+ } | null;projectId: string;environment: string;environmentName: string;diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.tsindex 482e60cda7..f948e50158 100644--- a/backend/src/ee/services/audit-log/audit-log-types.ts+++ b/backend/src/ee/services/audit-log/audit-log-types.ts@@ -7193,6 +7193,7 @@ interface AccessApprovalRequestDelegatedDecisionEvent {policyId: string;delegatedApprovalType: string;providerRequestId: string;+ providerRecordNumber?: string;outcome: string;decision?: string;decidedBy?: string;diff --git 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.tsindex 888bc1f665..cf741939c9 100644--- 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@@ -43,6 +43,9 @@ const makeService = ({}: { stored?: boolean; currentRow?: { encryptedCallbackToken: Buffer | null } | null } = {}) => {const delegatedApprovalRequestDAL = {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 (): Promise<unknown> => currentRow),@@ -235,14 +238,14 @@ describe("handleCallback", () => {{ status: ApprovalRequestStatus.Cancelled },TX);- const [filter, patch, tx] = delegatedApprovalRequestDAL.update.mock.lastCall as unknown as [+ const [filter, patch, tx] = delegatedApprovalRequestDAL.updateWithDetails.mock.lastCall as unknown as [unknown,- { status: string; statusReason: string },+ { status: string; details: { statusReason: string } },unknown];expect(filter).toEqual({ id: "delegated-1", status: DelegatedApprovalRequestStatus.WaitingApproval });expect(patch.status).toBe(DelegatedApprovalRequestStatus.Failed);- expect(patch.statusReason).toContain(`more than ${DELEGATED_APPROVAL_CALLBACK_MAX_ATTEMPTS} times`);+ expect(patch.details.statusReason).toContain(`more than ${DELEGATED_APPROVAL_CALLBACK_MAX_ATTEMPTS} times`);expect(tx).toBe(TX);expect(kmsService.createCipherPairWithDataKey).not.toHaveBeenCalled();expect(eventEmitter.emit).not.toHaveBeenCalled();@@ -257,7 +260,10 @@ describe("handleCallback", () => {await expect(service.handleCallback(callback())).rejects.toBeInstanceOf(ForbiddenRequestError);expect(approvalRequestDAL.updateById).not.toHaveBeenCalled();- const [, patch] = delegatedApprovalRequestDAL.update.mock.lastCall as unknown as [unknown, { status: string }];+ const [, patch] = delegatedApprovalRequestDAL.updateWithDetails.mock.lastCall as unknown as [+ unknown,+ { status: string }+ ];expect(patch.status).toBe(DelegatedApprovalRequestStatus.Failed);});diff --git a/backend/src/services/delegated-approval-callback/delegated-approval-callback-types.ts b/backend/src/services/delegated-approval-callback/delegated-approval-callback-types.tsindex 3a12bb94d4..1cc4d09e7d 100644--- a/backend/src/services/delegated-approval-callback/delegated-approval-callback-types.ts+++ b/backend/src/services/delegated-approval-callback/delegated-approval-callback-types.ts@@ -9,7 +9,13 @@ import { DelegatedApprovalCallbackEvent } from "./delegated-approval-callback-enexport type TDelegatedApprovalCallbackServiceFactoryDep = {delegatedApprovalRequestDAL: Pick<TDelegatedApprovalRequestDALFactory,- "claimDecisionRead" | "findById" | "findByProviderRequestId" | "primaryNode" | "transaction" | "update"+ | "claimDecisionRead"+ | "findById"+ | "findByProviderRequestId"+ | "primaryNode"+ | "transaction"+ | "update"+ | "updateWithDetails">;approvalRequestDAL: Pick<TApprovalRequestDALFactory, "transaction" | "findByIdForUpdate" | "updateById">;kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;diff --git 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.tsindex 7d7eaf25f7..d1d9520265 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@@ -7,6 +7,7 @@ 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";@@ -51,11 +52,12 @@ const ORG_ID = "22222222-2222-2222-2222-222222222222";const EXTERNAL_ID = "snow-1";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,- statusReason: null as string | null,+ details: { statusReason: null, provider: SERVICENOW_RECORD } as TDelegatedApprovalRequestDetails,providerRequestId: EXTERNAL_ID as string | null};@@ -103,14 +105,20 @@ const buildConsumer = ({let row: TDelegatedRow | null = delegatedRequest ? { ...delegatedRequest } : null;let approval: TApprovalRow | null = approvalRequest ? { ...approvalRequest } : null;- const update = vi.fn(async (filter: Partial<TDelegatedRow>, patch: Partial<TDelegatedRow>) => {- 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, ...patch };- return [row];- });+ // 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;@@ -124,7 +132,7 @@ const buildConsumer = ({delegatedApprovalRequestDAL: {findById: vi.fn(async () => row),primaryNode: () => PRIMARY,- update+ updateWithDetails},delegatedApprovalPolicyDAL: { findOne: vi.fn().mockResolvedValue(policy) },approvalRequestDAL: {@@ -192,14 +200,19 @@ describe("delegatedApprovalDecisionConsumer", () => {approvalRequestId: APPROVAL_REQUEST_ID,providerRequestId: EXTERNAL_ID});- expect(row()).toMatchObject({ status: DelegatedApprovalRequestStatus.Approved, statusReason: null });+ 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"+ decidedAt: "2026-10-20 10:15:00",+ providerRecordNumber: "INFAR1000000"});expect(notify).toHaveBeenCalledWith({approvalRequestId: APPROVAL_REQUEST_ID,@@ -245,7 +258,10 @@ describe("delegatedApprovalDecisionConsumer", () => {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, statusReason: result.error });+ 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();@@ -274,7 +290,10 @@ describe("delegatedApprovalDecisionConsumer", () => {]);expect(row()).toMatchObject({status: DelegatedApprovalRequestStatus.WaitingApproval,- statusReason: `ServiceNow has not recorded a decision yet. ${DELEGATED_APPROVAL_DECISION_RETRY_HINT}`+ 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();@@ -288,7 +307,7 @@ describe("delegatedApprovalDecisionConsumer", () => {expect(result).toEqual({ id: "1", status: EventResultStatus.Retry, error: "ServiceNow could not be reached." });expect(row()).toMatchObject({ status: DelegatedApprovalRequestStatus.WaitingApproval });- expect(row()?.statusReason).toContain(DELEGATED_APPROVAL_DECISION_RETRY_HINT);+ expect(row()?.details.statusReason).toContain(DELEGATED_APPROVAL_DECISION_RETRY_HINT);expect(approval()?.status).toBe(ApprovalRequestStatus.Pending);});@@ -305,7 +324,7 @@ describe("delegatedApprovalDecisionConsumer", () => {});expect(row()).toMatchObject({status: DelegatedApprovalRequestStatus.Failed,- statusReason: "ServiceNow rejected the credentials."+ details: { statusReason: "ServiceNow rejected the credentials." }});expect(approval()?.status).toBe(ApprovalRequestStatus.Cancelled);});@@ -320,7 +339,10 @@ describe("delegatedApprovalDecisionConsumer", () => {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, statusReason: result.error });+ expect(row()).toMatchObject({+ status: DelegatedApprovalRequestStatus.Failed,+ details: { statusReason: result.error }+ });expect(approval()?.status).toBe(ApprovalRequestStatus.Cancelled);auditedWith(createAuditLog, {outcome: DelegatedApprovalDecisionOutcome.Failed,@@ -354,7 +376,7 @@ describe("delegatedApprovalDecisionConsumer", () => {expect(results).toEqual([{ id: "1", status: EventResultStatus.Delivered }]);expect(row()?.status).toBe(DelegatedApprovalRequestStatus.Failed);- expect(row()?.statusReason).toContain("after the request was cancelled");+ 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 });@@ -369,7 +391,7 @@ describe("delegatedApprovalDecisionConsumer", () => {await consumer.handle([makeEvent()]);expect(row()?.status).toBe(DelegatedApprovalRequestStatus.Failed);- expect(row()?.statusReason).toContain("expired");+ expect(row()?.details.statusReason).toContain("expired");expect(approval()?.status).toBe(ApprovalRequestStatus.Expired);expect(postApprovalTxRoutine).not.toHaveBeenCalled();});@@ -389,6 +411,19 @@ describe("delegatedApprovalDecisionConsumer", () => {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" }diff --git a/backend/src/services/delegated-approval-decision/delegated-approval-decision-service.ts b/backend/src/services/delegated-approval-decision/delegated-approval-decision-service.tsindex 3a07e789b8..dc769b731c 100644--- a/backend/src/services/delegated-approval-decision/delegated-approval-decision-service.ts+++ b/backend/src/services/delegated-approval-decision/delegated-approval-decision-service.ts@@ -76,6 +76,7 @@ export const delegatedApprovalDecisionServiceFactory = ({policyId: context.approvalRequest.policyId ?? "",delegatedApprovalType: context.delegatedApprovalType,providerRequestId: context.providerRequestId,+ ...(context.providerRecordNumber ? { providerRecordNumber: context.providerRecordNumber } : {}),outcome: metadata.outcome,...(metadata.decided? {@@ -99,9 +100,13 @@ export const delegatedApprovalDecisionServiceFactory = ({const $keepWaiting = async (delegatedRequestId: string, reason: string) => {try {- await delegatedApprovalRequestDAL.update(+ await delegatedApprovalRequestDAL.updateWithDetails({ id: delegatedRequestId, status: DelegatedApprovalRequestStatus.WaitingApproval },- { statusReason: toDelegatedApprovalStatusReason(`${reason} ${DELEGATED_APPROVAL_DECISION_RETRY_HINT}`) }+ {+ details: {+ statusReason: toDelegatedApprovalStatusReason(`${reason} ${DELEGATED_APPROVAL_DECISION_RETRY_HINT}`)+ }+ });} catch (error) {logger.error(@@ -156,11 +161,11 @@ export const delegatedApprovalDecisionServiceFactory = ({}const isApproved = decided.decision === DelegatedApprovalDecision.Approved;- const [finalized] = await delegatedApprovalRequestDAL.update(+ const [finalized] = await delegatedApprovalRequestDAL.updateWithDetails({ id: context.delegatedRequestId, status: DelegatedApprovalRequestStatus.WaitingApproval },{status: isApproved ? DelegatedApprovalRequestStatus.Approved : DelegatedApprovalRequestStatus.Rejected,- statusReason: null+ details: { statusReason: null }},tx);@@ -216,7 +221,7 @@ export const delegatedApprovalDecisionServiceFactory = ({}const { delegatedRequest, approvalRequest, delegatedPolicy } = delegatedApprovalContext;- if (DELEGATED_APPROVAL_FINAL_STATE.has(delegatedRequest.status as DelegatedApprovalRequestStatus)) {+ if (DELEGATED_APPROVAL_FINAL_STATE.has(delegatedRequest.status)) {logger.info(`Delegated approval request was already finalized, skipping decision [delegatedRequestId=${delegatedRequestId}] [status=${delegatedRequest.status}]`);@@ -251,6 +256,7 @@ export const delegatedApprovalDecisionServiceFactory = ({const context: TDelegatedApprovalDecisionContext = {delegatedRequestId,providerRequestId: delegatedRequest.providerRequestId,+ providerRecordNumber: delegatedRequest.details.provider?.recordNumber,approvalRequest,delegatedApprovalType: delegatedApprovalName ?? "the delegated approval system"};diff --git a/backend/src/services/delegated-approval-decision/delegated-approval-decision-types.ts b/backend/src/services/delegated-approval-decision/delegated-approval-decision-types.tsindex 022336abb5..722a9cb7f0 100644--- a/backend/src/services/delegated-approval-decision/delegated-approval-decision-types.ts+++ b/backend/src/services/delegated-approval-decision/delegated-approval-decision-types.ts@@ -46,7 +46,10 @@ export type TDelegatedApprovalDecisionAuditMetadata = {};export type TDelegatedApprovalDecisionServiceFactoryDep = {- delegatedApprovalRequestDAL: Pick<TDelegatedApprovalRequestDALFactory, "findById" | "primaryNode" | "update">;+ delegatedApprovalRequestDAL: Pick<+ TDelegatedApprovalRequestDALFactory,+ "findById" | "primaryNode" | "updateWithDetails"+ >;delegatedApprovalPolicyDAL: Pick<TDelegatedApprovalPolicyDALFactory, "findOne">;approvalRequestDAL: Pick<TApprovalRequestDALFactory, "findById" | "findByIdForUpdate" | "updateById" | "transaction">;appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">;@@ -59,6 +62,7 @@ export type TDelegatedApprovalDecisionServiceFactoryDep = {export type TDelegatedApprovalDecisionContext = {delegatedRequestId: string;providerRequestId: string;+ providerRecordNumber?: string;approvalRequest: { id: string; organizationId: string; projectId: string; policyId?: string | null };delegatedApprovalType: string;};@@ -74,7 +78,4 @@ export type TApplyDelegatedApprovalDecisionResult = {};export type TDelegatedApprovalFinalizeOutcome = // this feels weird to me honestly- | { kind: "applied" }- | { kind: "late"; reason: string }- | { kind: "gone" }- | { kind: "raced" };+ { kind: "applied" } | { kind: "late"; reason: string } | { kind: "gone" } | { kind: "raced" };diff --git a/backend/src/services/delegated-approval/delegated-approval-request-dal.ts b/backend/src/services/delegated-approval/delegated-approval-request-dal.tsindex 5b54e20bac..10c391d2b6 100644--- a/backend/src/services/delegated-approval/delegated-approval-request-dal.ts+++ b/backend/src/services/delegated-approval/delegated-approval-request-dal.ts@@ -1,11 +1,12 @@import { Knex } from "knex";import { TDbClient } from "@app/db";-import { TableName, TDelegatedApprovalRequests } from "@app/db/schemas";+import { TableName, TDelegatedApprovalRequests, TDelegatedApprovalRequestsUpdate } from "@app/db/schemas";import { DatabaseError } from "@app/lib/errors";import { ormify, selectAllTableCols } from "@app/lib/knex";import { DelegatedApprovalRequestStatus } from "./delegated-approval-enums";+import { TDelegatedApprovalRequestDetails } from "./delegated-approval-schemas";export type TDelegatedApprovalRequestDALFactory = ReturnType<typeof delegatedApprovalRequestDALFactory>;@@ -54,5 +55,28 @@ export const delegatedApprovalRequestDALFactory = (db: TDbClient) => {}};- return { ...orm, primaryNode, findByProviderRequestId, 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 --git a/backend/src/services/delegated-approval/delegated-approval-request-fns.test.ts b/backend/src/services/delegated-approval/delegated-approval-request-fns.test.tsnew file mode 100644index 0000000000..a86d9d2ec8--- /dev/null+++ b/backend/src/services/delegated-approval/delegated-approval-request-fns.test.ts@@ -0,0 +1,32 @@+import { describe, expect, test, vi } from "vitest";++import { DelegatedApprovalPolicyType } from "./delegated-approval-enums";+import { parseDelegatedApprovalRequestDetails } from "./delegated-approval-request-fns";++vi.mock("@app/lib/logger", () => ({+ logger: { info: () => {}, warn: () => {}, error: () => {}, debug: () => {} },+ initLogger: () => {}+}));++describe("parseDelegatedApprovalRequestDetails", () => {+ const provider = { type: DelegatedApprovalPolicyType.ServiceNow, recordNumber: "INFAR1000000" };++ test("reads what the workers stored", () => {+ expect(parseDelegatedApprovalRequestDetails({ id: "d1", details: {} })).toEqual({});+ expect(parseDelegatedApprovalRequestDetails({ id: "d1", details: { statusReason: null } })).toEqual({+ statusReason: null+ });+ expect(+ parseDelegatedApprovalRequestDetails({ id: "d1", details: { statusReason: "Retrying.", provider } })+ ).toEqual({ statusReason: "Retrying.", provider });+ });++ test("serves a row whose details cannot be read as if it had none", () => {+ expect(parseDelegatedApprovalRequestDetails({ id: "d1", details: null })).toEqual({});+ expect(parseDelegatedApprovalRequestDetails({ id: "d1", details: "oops" })).toEqual({});+ expect(parseDelegatedApprovalRequestDetails({ id: "d1", details: { statusReason: 42 } })).toEqual({});+ expect(+ parseDelegatedApprovalRequestDetails({ id: "d1", details: { provider: { type: "jira", recordNumber: "J-1" } } })+ ).toEqual({});+ });+});diff --git a/backend/src/services/delegated-approval/delegated-approval-request-fns.ts b/backend/src/services/delegated-approval/delegated-approval-request-fns.tsindex dff4e0f6f0..c174e2c515 100644--- a/backend/src/services/delegated-approval/delegated-approval-request-fns.ts+++ b/backend/src/services/delegated-approval/delegated-approval-request-fns.ts@@ -1,10 +1,15 @@import { UnrecoverableError } from "bullmq";import { Knex } from "knex";+import { TDelegatedApprovalRequests } from "@app/db/schemas";+import { logger } from "@app/lib/logger";import { ApprovalRequestStatus } from "@app/services/approval-policy/approval-policy-enums";import { DelegatedApprovalRequestStatus } from "./delegated-approval-enums";+import { DelegatedApprovalRequestDetailsSchema } from "./delegated-approval-schemas";import {+ TDelegatedApprovalRequest,+ TDelegatedApprovalRequestDetails,TFailDelegatedApprovalRequestDeps,TFailDelegatedApprovalRequestDTO,TLoadDelegatedApprovalContextDeps@@ -14,6 +19,27 @@ import { DELEGATED_APPROVAL_STATUS_REASON_MAX_CHARS } from "./dispatch/delegatedexport const toDelegatedApprovalStatusReason = (reason: string) =>reason.slice(0, DELEGATED_APPROVAL_STATUS_REASON_MAX_CHARS);+// A row whose details cannot be read is served as if it had none, so one bad row cannot take the+// request list down with it.+export const parseDelegatedApprovalRequestDetails = (+ row: Pick<TDelegatedApprovalRequests, "id" | "details">+): TDelegatedApprovalRequestDetails => {+ const parsed = DelegatedApprovalRequestDetailsSchema.safeParse(row.details ?? {});+ if (parsed.success) return parsed.data;++ logger.warn(+ { issues: parsed.error.issues },+ `Delegated approval request has unreadable details, treating them as empty [delegatedRequestId=${row.id}]`+ );+ return {};+};++export const toDelegatedApprovalRequest = (row: TDelegatedApprovalRequests): TDelegatedApprovalRequest => ({+ ...row,+ status: row.status as DelegatedApprovalRequestStatus,+ details: parseDelegatedApprovalRequestDetails(row)+});+// A delegated approval worker tells its failures apart by class: bullmq's UnrecoverableError means a// retry cannot help, anything else is tried again by the outbox.export const toDelegatedApprovalFailure = (error: unknown) => {@@ -35,9 +61,12 @@ export const failDelegatedApprovalRequest = () => {const run = async (trx: Knex) => {const approvalRequest = await approvalRequestDAL.findByIdForUpdate(requestId, trx);- const [failed] = await delegatedApprovalRequestDAL.update(+ const [failed] = await delegatedApprovalRequestDAL.updateWithDetails({ id, status: DelegatedApprovalRequestStatus.WaitingApproval },- { status: DelegatedApprovalRequestStatus.Failed, statusReason: toDelegatedApprovalStatusReason(reason) },+ {+ status: DelegatedApprovalRequestStatus.Failed,+ details: { statusReason: toDelegatedApprovalStatusReason(reason) }+ },trx);if (failed && approvalRequest?.status === ApprovalRequestStatus.Pending) {@@ -57,9 +86,10 @@ export const loadDelegatedApprovalContext = async () => {const primary = delegatedApprovalRequestDAL.primaryNode();- const delegatedRequest = await delegatedApprovalRequestDAL.findById(delegatedRequestId, primary);- if (!delegatedRequest) return null;+ const row = await delegatedApprovalRequestDAL.findById(delegatedRequestId, primary);+ if (!row) return null;+ const delegatedRequest = toDelegatedApprovalRequest(row);const approvalRequest = await approvalRequestDAL.findById(delegatedRequest.requestId, primary);const delegatedPolicy = approvalRequest?.policyId? await delegatedApprovalPolicyDAL.findOne({ policyId: approvalRequest.policyId }, primary)diff --git a/backend/src/services/delegated-approval/delegated-approval-schemas.ts b/backend/src/services/delegated-approval/delegated-approval-schemas.tsindex e8936f49bc..215ccc8941 100644--- a/backend/src/services/delegated-approval/delegated-approval-schemas.ts+++ b/backend/src/services/delegated-approval/delegated-approval-schemas.ts@@ -1,6 +1,7 @@import { z } from "zod";import { DelegatedApprovalPolicyType, DelegatedApprovalRequestStatus } from "./delegated-approval-enums";+import { DELEGATED_APPROVAL_PROVIDER_RECORD_NUMBER_MAX_CHARS } from "./dispatch/delegated-approval-dispatch-constants";export const DelegatedApprovalSchema = z.object({type: z@@ -9,6 +10,27 @@ export const DelegatedApprovalSchema = z.object({connectionId: z.string().uuid().describe("The ID of the App Connection used to reach the delegated approval system.")});+export const DelegatedApprovalProviderDetailsSchema = z.discriminatedUnion("type", [+ z.object({+ type: z.literal(DelegatedApprovalPolicyType.ServiceNow),+ recordNumber: z+ .string()+ .min(1)+ .max(DELEGATED_APPROVAL_PROVIDER_RECORD_NUMBER_MAX_CHARS)+ .describe("The number of the ServiceNow record that tracks this request, as shown in ServiceNow.")+ })+]);++// Shape of the `details` column. Bounds are enforced where values enter (the provider response schemas+// and toDelegatedApprovalStatusReason), so a stored row always reads back.+export const DelegatedApprovalRequestDetailsSchema = z.object({+ statusReason: z.string().nullable().optional(),+ provider: DelegatedApprovalProviderDetailsSchema.optional()+});++export type TDelegatedApprovalProviderDetails = z.infer<typeof DelegatedApprovalProviderDetailsSchema>;+export type TDelegatedApprovalRequestDetails = z.infer<typeof DelegatedApprovalRequestDetailsSchema>;+export const DelegatedApprovalRequestSchema = z.object({status: z.nativeEnum(DelegatedApprovalRequestStatus)@@ -18,5 +40,8 @@ export const DelegatedApprovalRequestSchema = z.object({.nullable().describe("Why the request is not progressing in, or could not be completed by, the delegated approval system, when that is the case."- )+ ),+ provider: DelegatedApprovalProviderDetailsSchema.nullable().describe(+ "How the delegated approval system identifies this request to its own users, when it reported that."+ )});diff --git a/backend/src/services/delegated-approval/delegated-approval-service.test.ts b/backend/src/services/delegated-approval/delegated-approval-service.test.tsindex 8f3118b4ab..7fed27cfd5 100644--- a/backend/src/services/delegated-approval/delegated-approval-service.test.ts+++ b/backend/src/services/delegated-approval/delegated-approval-service.test.ts@@ -7,7 +7,12 @@ import { DelegatedApprovalPolicyType, DelegatedApprovalRequestStatus } from "./dimport { DELEGATED_APPROVAL_DISPATCH_REQUESTED_EVENT } from "./delegated-approval-events";import { delegatedApprovalServiceFactory } from "./delegated-approval-service";-const failedRequest = { id: "delegated-1", requestId: "req-1", status: DelegatedApprovalRequestStatus.FailedDispatch };+const failedRequest = {+ id: "delegated-1",+ requestId: "req-1",+ status: DelegatedApprovalRequestStatus.FailedDispatch,+ details: { statusReason: "ServiceNow could not be reached." }+};const serviceNowPolicy = {id: "delegated-policy-1",policyId: "policy-1",@@ -29,7 +34,7 @@ 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",...row}));@@ -54,7 +59,7 @@ describe("delegatedApprovalService.createRequest", () => {expect(request).toMatchObject({ id: "delegated-1", status: DelegatedApprovalRequestStatus.PendingDispatch });expect(create).toHaveBeenCalledWith(- { requestId: "req-1", status: DelegatedApprovalRequestStatus.PendingDispatch },+ { requestId: "req-1", status: DelegatedApprovalRequestStatus.PendingDispatch, details: {} },TX);expect(emit).toHaveBeenCalledTimes(1);diff --git a/backend/src/services/delegated-approval/delegated-approval-service.ts b/backend/src/services/delegated-approval/delegated-approval-service.tsindex bc0f24c938..223b6f8a81 100644--- a/backend/src/services/delegated-approval/delegated-approval-service.ts+++ b/backend/src/services/delegated-approval/delegated-approval-service.ts@@ -18,14 +18,13 @@ import { DelegatedApprovalRequestBlocker, getDelegatedApprovalRequestBlocker } fimport { DELEGATED_APPROVAL_CONNECTION_MAP, DELEGATED_APPROVAL_NAME_MAP } from "./delegated-approval-maps";import { TDelegatedApprovalPolicyDALFactory } from "./delegated-approval-policy-dal";import { TDelegatedApprovalRequestDALFactory } from "./delegated-approval-request-dal";+import { toDelegatedApprovalRequest } from "./delegated-approval-request-fns";import {TCreateDelegatedApprovalPolicyDTO,TCreateDelegatedApprovalRequestDTO,TDelegatedApprovalPolicy,- TDelegatedApprovalRequest,TRetryDelegatedApprovalRequestDispatchDTO,TUpdateDelegatedApprovalPolicyDTO,- TUpdateDelegatedApprovalRequestDTO,TValidateDelegatedApprovalConnectionDTO} from "./delegated-approval-types";@@ -161,12 +160,12 @@ export const delegatedApprovalServiceFactory = ({assertPolicyTypeSupportsDelegatedApproval(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);- return request;+ return toDelegatedApprovalRequest(request);} catch (err) {if (hasPostgresErrorCode(err, DatabaseErrorCode.UniqueViolation)) {throw new BadRequestError({@@ -182,13 +181,13 @@ export const delegatedApprovalServiceFactory = ({const getRequestByRequestId = async (requestId: string, tx?: Knex) => {const request = await delegatedApprovalRequestDAL.findOne({ requestId }, tx);- return (request as TDelegatedApprovalRequest | undefined) ?? null;+ return request ? toDelegatedApprovalRequest(request) : null;};const getRequestsByRequestIds = async (requestIds: string[], tx?: Knex) => {if (!requestIds.length) return [];const requests = await delegatedApprovalRequestDAL.find({ $in: { requestId: requestIds } }, { tx });- return requests as TDelegatedApprovalRequest[];+ return requests.map(toDelegatedApprovalRequest);};const retryDispatch = async ({ approvalRequest }: TRetryDelegatedApprovalRequestDispatchDTO) => {@@ -218,32 +217,9 @@ export const delegatedApprovalServiceFactory = ({return { delegatedRequest, delegatedPolicy };};- const updateRequest = async ({ requestId, status, statusReason }: TUpdateDelegatedApprovalRequestDTO, tx?: Knex) => {- const patch = {- ...(status !== undefined && { status }),- ...(statusReason !== undefined && { statusReason })- };-- if (Object.keys(patch).length === 0) {- const existing = await delegatedApprovalRequestDAL.findOne({ requestId }, tx);- if (!existing) {- throw new NotFoundError({- message: `Approval request with ID '${requestId}' has no delegated approval request`- });- }- return existing as TDelegatedApprovalRequest;- }-- const [request] = await delegatedApprovalRequestDAL.update({ requestId }, patch, tx);- if (!request) {- throw new NotFoundError({ message: `Approval request with ID '${requestId}' has no delegated approval request` });- }- return request as TDelegatedApprovalRequest;- };-const deleteRequestByRequestId = async (requestId: string, tx?: Knex) => {const [request] = await delegatedApprovalRequestDAL.delete({ requestId }, tx);- return (request as TDelegatedApprovalRequest | undefined) ?? null;+ return request ? toDelegatedApprovalRequest(request) : null;};return {@@ -257,7 +233,6 @@ export const delegatedApprovalServiceFactory = ({getRequestByRequestId,getRequestsByRequestIds,retryDispatch,- updateRequest,deleteRequestByRequestId};};diff --git a/backend/src/services/delegated-approval/delegated-approval-types.ts b/backend/src/services/delegated-approval/delegated-approval-types.tsindex 6b9691133a..fa63cf6b8b 100644--- a/backend/src/services/delegated-approval/delegated-approval-types.ts+++ b/backend/src/services/delegated-approval/delegated-approval-types.ts@@ -11,6 +11,7 @@ import { TApprovalRequestDALFactory } from "@app/services/approval-policy/approvimport { DelegatedApprovalPolicyType, DelegatedApprovalRequestStatus } from "./delegated-approval-enums";import { TDelegatedApprovalPolicyDALFactory } from "./delegated-approval-policy-dal";import { TDelegatedApprovalRequestDALFactory } from "./delegated-approval-request-dal";+import { TDelegatedApprovalProviderDetails, TDelegatedApprovalRequestDetails } from "./delegated-approval-schemas";export type TDelegatedApprovalListItem = {name: string;@@ -22,8 +23,11 @@ export type TDelegatedApprovalPolicy = Omit<TDelegatedApprovalPolicies, "type">type: DelegatedApprovalPolicyType;};-export type TDelegatedApprovalRequest = Omit<TDelegatedApprovalRequests, "status"> & {+export type { TDelegatedApprovalProviderDetails, TDelegatedApprovalRequestDetails };++export type TDelegatedApprovalRequest = Omit<TDelegatedApprovalRequests, "status" | "details"> & {status: DelegatedApprovalRequestStatus;+ details: TDelegatedApprovalRequestDetails;};export type TValidateDelegatedApprovalConnectionDTO = {@@ -55,12 +59,6 @@ export type TRetryDelegatedApprovalRequestDispatchDTO = {approvalRequest: Pick<TApprovalRequests, "id" | "policyId" | "status" | "expiresAt">;};-export type TUpdateDelegatedApprovalRequestDTO = {- requestId: string;- status?: DelegatedApprovalRequestStatus;- statusReason?: string | null;-};-export type TApprovalRequestExpiry = { expiresAt?: Date | string | null };export type TLoadDelegatedApprovalContextDeps = {@@ -77,7 +75,7 @@ export type TRequireDelegatedApprovalConnectionDTO<T extends Pick<TAppConnectionexport type TFailDelegatedApprovalRequestDeps = {approvalRequestDAL: Pick<TApprovalRequestDALFactory, "transaction" | "findByIdForUpdate" | "updateById">;- delegatedApprovalRequestDAL: Pick<TDelegatedApprovalRequestDALFactory, "update">;+ delegatedApprovalRequestDAL: Pick<TDelegatedApprovalRequestDALFactory, "updateWithDetails">;};export type TFailDelegatedApprovalRequestDTO = {diff --git a/backend/src/services/delegated-approval/dispatch/delegated-approval-dispatch-constants.ts b/backend/src/services/delegated-approval/dispatch/delegated-approval-dispatch-constants.tsindex 6cd0cb7008..557216ed88 100644--- a/backend/src/services/delegated-approval/dispatch/delegated-approval-dispatch-constants.ts+++ b/backend/src/services/delegated-approval/dispatch/delegated-approval-dispatch-constants.ts@@ -1,4 +1,5 @@export const DELEGATED_APPROVAL_STATUS_REASON_MAX_CHARS = 1_000;+export const DELEGATED_APPROVAL_PROVIDER_RECORD_NUMBER_MAX_CHARS = 64;export const DELEGATED_APPROVAL_DISPATCH_RETRY_HINT ="Infisical will retry automatically. If it keeps failing, send the request again.";diff --git 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.tsindex 0018143764..007e1fbc6c 100644--- 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@@ -9,6 +9,7 @@ import { EventOutboxStatus, EventResultStatus, TEvent } from "@app/services/evenimport { DelegatedApprovalPolicyType, DelegatedApprovalRequestStatus } from "../delegated-approval-enums";import { DELEGATED_APPROVAL_DISPATCH_REQUESTED_EVENT } from "../delegated-approval-events";+import { TDelegatedApprovalRequestDetails } from "../delegated-approval-schemas";import { delegatedApprovalDispatchConsumerFactory } from "./delegated-approval-dispatch-consumer";vi.mock("@app/lib/logger", () => ({@@ -42,12 +43,13 @@ const DELEGATED_REQUEST_ID = "11111111-1111-1111-1111-111111111111";const ORG_ID = "22222222-2222-2222-2222-222222222222";const RETRY_REASON ="ServiceNow did not respond. Infisical will retry automatically. If it keeps failing, send the request again.";+const SERVICENOW_RECORD = { type: DelegatedApprovalPolicyType.ServiceNow, recordNumber: "INFAR1000000" };const pendingDelegatedRequest = {id: DELEGATED_REQUEST_ID,requestId: "req-1",status: DelegatedApprovalRequestStatus.PendingDispatch,- statusReason: null as string | null,+ details: {} as TDelegatedApprovalRequestDetails,providerRequestId: null as string | null,encryptedCallbackToken: null};@@ -83,25 +85,23 @@ 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 consumer = delegatedApprovalDispatchConsumerFactory({delegatedApprovalRequestDAL: {findById: findById ?? vi.fn(async () => row),primaryNode: () => PRIMARY,- update,- updateById+ updateWithDetails},delegatedApprovalPolicyDAL: { findOne: vi.fn().mockResolvedValue(policy) },delegatedApprovalCallbackService: {@@ -116,7 +116,7 @@ const buildConsumer = ({kmsService: { createCipherPairWithDataKey: vi.fn() }} as never);- return { consumer, row: () => row, update };+ return { consumer, row: () => row, updateWithDetails };};const makeEvent = (overrides?: Partial<TEvent>): TEvent => ({@@ -132,8 +132,8 @@ beforeEach(() => {});describe("delegatedApprovalDispatchConsumer", () => {- test("delivers the request and records the provider's record id", async () => {- dispatch.mockResolvedValueOnce({ providerRequestId: "snow-1" });+ test("delivers the request and records the provider's record id and number", async () => {+ dispatch.mockResolvedValueOnce({ providerRequestId: "snow-1", providerDetails: SERVICENOW_RECORD });const { consumer, row } = buildConsumer();const results = await consumer.handle([makeEvent()]);@@ -145,10 +145,26 @@ describe("delegatedApprovalDispatchConsumer", () => {approvalRequestId: "req-1",callback: { token: "callback-token" }});- expect(row()).toMatchObject({+ expect(row()).toEqual({+ ...pendingDelegatedRequest,status: DelegatedApprovalRequestStatus.WaitingApproval,providerRequestId: "snow-1",- statusReason: null+ details: { statusReason: null, provider: SERVICENOW_RECORD }+ });+ });++ test("delivers a request whose provider reported no record number", async () => {+ dispatch.mockResolvedValueOnce({ providerRequestId: "snow-1" });+ const { consumer, row } = buildConsumer();++ const results = await consumer.handle([makeEvent()]);++ expect(results).toEqual([{ id: "1", status: EventResultStatus.Delivered }]);+ expect(row()).toEqual({+ ...pendingDelegatedRequest,+ status: DelegatedApprovalRequestStatus.WaitingApproval,+ providerRequestId: "snow-1",+ details: { statusReason: null }});});@@ -159,7 +175,10 @@ describe("delegatedApprovalDispatchConsumer", () => {const results = await consumer.handle([makeEvent()]);expect(results).toEqual([{ id: "1", status: EventResultStatus.Retry, error: "ServiceNow did not respond." }]);- expect(row()).toMatchObject({ status: DelegatedApprovalRequestStatus.FailedDispatch, statusReason: RETRY_REASON });+ expect(row()).toMatchObject({+ status: DelegatedApprovalRequestStatus.FailedDispatch,+ details: { statusReason: RETRY_REASON }+ });});test("fails terminally on an unrecoverable error without promising a retry", async () => {@@ -173,7 +192,7 @@ describe("delegatedApprovalDispatchConsumer", () => {]);expect(row()).toMatchObject({status: DelegatedApprovalRequestStatus.FailedDispatch,- statusReason: "ServiceNow rejected the credentials."+ details: { statusReason: "ServiceNow rejected the credentials." }});});@@ -199,7 +218,7 @@ describe("delegatedApprovalDispatchConsumer", () => {expect(result.status).toBe(EventResultStatus.Failed);expect(dispatch).not.toHaveBeenCalled();expect(row()?.status).toBe(DelegatedApprovalRequestStatus.FailedDispatch);- expect(row()?.statusReason).toContain("expired");+ expect(row()?.details.statusReason).toContain("expired");});test.each([@@ -316,7 +335,10 @@ describe("delegatedApprovalDispatchConsumer through the outbox", () => {attempts: 1,lastError: "ServiceNow did not respond."});- expect(row()).toMatchObject({ status: DelegatedApprovalRequestStatus.FailedDispatch, statusReason: RETRY_REASON });+ expect(row()).toMatchObject({+ status: DelegatedApprovalRequestStatus.FailedDispatch,+ details: { statusReason: RETRY_REASON }+ });await service.drain({ consumer: consumer.name });expect(rows[0].status).toBe(EventOutboxStatus.Retry);@@ -329,7 +351,7 @@ describe("delegatedApprovalDispatchConsumer through the outbox", () => {expect(row()).toMatchObject({status: DelegatedApprovalRequestStatus.WaitingApproval,providerRequestId: "snow-1",- statusReason: null+ details: { statusReason: null }});expect(dispatch).toHaveBeenCalledTimes(2);});diff --git a/backend/src/services/delegated-approval/dispatch/delegated-approval-dispatch-consumer.ts b/backend/src/services/delegated-approval/dispatch/delegated-approval-dispatch-consumer.tsindex c42ef3c7e0..e2448063ea 100644--- a/backend/src/services/delegated-approval/dispatch/delegated-approval-dispatch-consumer.ts+++ b/backend/src/services/delegated-approval/dispatch/delegated-approval-dispatch-consumer.ts@@ -56,7 +56,7 @@ const BLOCKER_MESSAGES: Record<DelegatedApprovalRequestBlocker, string> = {type TDelegatedApprovalDispatchConsumerDep = {delegatedApprovalRequestDAL: Pick<TDelegatedApprovalRequestDALFactory,- "findById" | "primaryNode" | "update" | "updateById"+ "findById" | "primaryNode" | "updateWithDetails">;delegatedApprovalPolicyDAL: Pick<TDelegatedApprovalPolicyDALFactory, "findOne">;delegatedApprovalCallbackService: Pick<@@ -82,11 +82,11 @@ export const delegatedApprovalDispatchConsumerFactory = ({}: TDelegatedApprovalDispatchConsumerDep): IEventConsumer<TDelegatedApprovalDispatchRequestedPayload> => {const $markDispatchFailed = async (delegatedRequestId: string, statusReason: string) => {try {- await delegatedApprovalRequestDAL.update(+ await delegatedApprovalRequestDAL.updateWithDetails({ id: delegatedRequestId, status: DelegatedApprovalRequestStatus.PendingDispatch },{status: DelegatedApprovalRequestStatus.FailedDispatch,- statusReason: toDelegatedApprovalStatusReason(statusReason)+ details: { statusReason: toDelegatedApprovalStatusReason(statusReason) }});} catch (error) {@@ -131,9 +131,9 @@ export const delegatedApprovalDispatchConsumerFactory = ({}if (delegatedRequest.status === DelegatedApprovalRequestStatus.FailedDispatch) {- await delegatedApprovalRequestDAL.update(+ await delegatedApprovalRequestDAL.updateWithDetails({ id: delegatedRequestId, status: DelegatedApprovalRequestStatus.FailedDispatch },- { status: DelegatedApprovalRequestStatus.PendingDispatch, statusReason: null }+ { status: DelegatedApprovalRequestStatus.PendingDispatch, details: { statusReason: null } });}@@ -194,21 +194,29 @@ export const delegatedApprovalDispatchConsumerFactory = ({details};- const { providerRequestId } = await provider.dispatch(input, connection);+ const { providerRequestId, providerDetails } = await provider.dispatch(input, connection);+ const providerPatch = providerDetails ? { provider: providerDetails } : {};- const [waitingRequest] = await delegatedApprovalRequestDAL.update(+ const [waitingRequest] = await delegatedApprovalRequestDAL.updateWithDetails({ id: delegatedRequestId, status: DelegatedApprovalRequestStatus.PendingDispatch },- { status: DelegatedApprovalRequestStatus.WaitingApproval, statusReason: null, providerRequestId }+ {+ status: DelegatedApprovalRequestStatus.WaitingApproval,+ providerRequestId,+ details: { statusReason: null, ...providerPatch }+ });if (!waitingRequest) {- await delegatedApprovalRequestDAL.updateById(delegatedRequestId, { providerRequestId });+ await delegatedApprovalRequestDAL.updateWithDetails(+ { id: delegatedRequestId },+ { providerRequestId, details: providerPatch }+ );logger.warn(`Delegated approval request left pending dispatch while it was being delivered [delegatedRequestId=${delegatedRequestId}] [providerRequestId=${providerRequestId}]`);}logger.info(- `Delegated approval request delivered [delegatedRequestId=${delegatedRequestId}] [approvalRequestId=${approvalRequest.id}] [provider=${delegatedPolicy.type}] [providerRequestId=${providerRequestId}]`+ `Delegated approval request delivered [delegatedRequestId=${delegatedRequestId}] [approvalRequestId=${approvalRequest.id}] [provider=${delegatedPolicy.type}] [providerRequestId=${providerRequestId}] [recordNumber=${providerDetails?.recordNumber ?? "none"}]`);return { status: EventResultStatus.Delivered };} catch (error) {diff --git a/backend/src/services/delegated-approval/dispatch/delegated-approval-dispatch-types.ts b/backend/src/services/delegated-approval/dispatch/delegated-approval-dispatch-types.tsindex 26c01b9e3f..0fd2a0af5a 100644--- a/backend/src/services/delegated-approval/dispatch/delegated-approval-dispatch-types.ts+++ b/backend/src/services/delegated-approval/dispatch/delegated-approval-dispatch-types.ts@@ -6,6 +6,8 @@ import {TDelegatedApprovalReadDecisionInput} from "@app/services/delegated-approval-decision/delegated-approval-decision-types";+import { TDelegatedApprovalProviderDetails } from "../delegated-approval-types";+export type TSecretAccessDispatchDetails = {policyType: ApprovalPolicyType.SecretAccess;environment: string;@@ -34,6 +36,7 @@ export type TDelegatedApprovalDispatchInput = {export type TDelegatedApprovalDispatchResult = {providerRequestId: string;+ providerDetails?: TDelegatedApprovalProviderDetails;};export type TDelegatedApprovalProvider = {diff --git a/backend/src/services/delegated-approval/providers/servicenow/servicenow-fns.test.ts b/backend/src/services/delegated-approval/providers/servicenow/servicenow-fns.test.tsindex 0aa4830b48..672a9f7484 100644--- a/backend/src/services/delegated-approval/providers/servicenow/servicenow-fns.test.ts+++ b/backend/src/services/delegated-approval/providers/servicenow/servicenow-fns.test.ts@@ -147,26 +147,53 @@ describe("buildServiceNowAccessRequestPayload", () => {});describe("parseServiceNowAccessRequestResponse", () => {- test("reads the record ID from a bare or enveloped 201", () => {+ test("reads the record ID and number from a bare or enveloped 201", () => {expect(parseServiceNowAccessRequestResponse(201, { success: true, request_number: "INFAR0001", sys_id: "abc" })).toEqual({sysId: "abc",+ recordNumber: "INFAR0001",duplicate: false});expect(parseServiceNowAccessRequestResponse(201, { result: { success: true, sys_id: "abc" } })).toEqual({sysId: "abc",+ recordNumber: null,duplicate: false});});test("treats a 409 as the record ServiceNow already holds", () => {- expect(parseServiceNowAccessRequestResponse(409, { success: false, error: "duplicate", sys_id: "abc" })).toEqual({+ expect(+ parseServiceNowAccessRequestResponse(409, {+ success: false,+ error: "duplicate",+ request_number: "INFAR0001",+ sys_id: "abc"+ })+ ).toEqual({sysId: "abc",+ recordNumber: "INFAR0001",duplicate: true});expect(parseServiceNowAccessRequestResponse(409, { result: { success: false, sys_id: "abc" } })).toEqual({sysId: "abc",+ recordNumber: null,+ duplicate: true+ });+ });++ test("never lets a bad record number hide the record ID", () => {+ expect(parseServiceNowAccessRequestResponse(201, { success: true, request_number: " ", sys_id: "abc" })).toEqual({+ sysId: "abc",+ recordNumber: null,+ duplicate: false+ });+ expect(+ parseServiceNowAccessRequestResponse(201, { success: true, request_number: "X".repeat(65), sys_id: "abc" })+ ).toEqual({ sysId: "abc", recordNumber: null, duplicate: false });+ expect(parseServiceNowAccessRequestResponse(409, { success: false, request_number: 42, sys_id: "abc" })).toEqual({+ sysId: "abc",+ recordNumber: null,duplicate: true});});diff --git a/backend/src/services/delegated-approval/providers/servicenow/servicenow-fns.ts b/backend/src/services/delegated-approval/providers/servicenow/servicenow-fns.tsindex f81fe2d263..2af2f0f2ef 100644--- a/backend/src/services/delegated-approval/providers/servicenow/servicenow-fns.ts+++ b/backend/src/services/delegated-approval/providers/servicenow/servicenow-fns.ts@@ -8,6 +8,7 @@ import { AppConnection } from "@app/services/app-connection/app-connection-enumsimport { 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";@@ -67,6 +68,11 @@ const buildServiceNowRequestConfig = (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:@@ -91,7 +97,7 @@ export const buildServiceNowAccessRequestPayload = (): TServiceNowAccessRequestPayload => {const parsed = ServiceNowAccessRequestPayloadSchema.safeParse({request_id: input.approvalRequestId,- callback_url: input.callback.url,+ callback_url: "https://columbus-stretchable-omega.ngrok-free.dev/api/v1/delegated-approvals/callback",callback_token: input.callback.token,product_type: input.productType,...(input.project ? { project_id: input.project.id, project_name: input.project.name } : {}),@@ -117,6 +123,7 @@ export const parseServiceNowAccessRequestResponse = (): 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) {@@ -124,7 +131,7 @@ export const parseServiceNowAccessRequestResponse = ("ServiceNow reported that it already holds this request but did not return the record ID.");}- return { sysId, duplicate: true };+ return { sysId, recordNumber, duplicate: true };}if (!sysId) {@@ -133,7 +140,7 @@ export const parseServiceNowAccessRequestResponse = (});}- return { sysId, duplicate: false };+ return { sysId, recordNumber, duplicate: false };};const extractErrorDetail = (data: unknown) => {@@ -268,12 +275,17 @@ const dispatchServiceNowRequest: TDelegatedApprovalProvider["dispatch"] = async);}- return { providerRequestId: 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 };+ }-const toOptionalText = (value: string | null | undefined) => {- const text = value?.trim() ?? "";- return text || null;+ 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,diff --git a/backend/src/services/delegated-approval/providers/servicenow/servicenow-schemas.ts b/backend/src/services/delegated-approval/providers/servicenow/servicenow-schemas.tsindex dabde2463a..df9f503634 100644--- a/backend/src/services/delegated-approval/providers/servicenow/servicenow-schemas.ts+++ b/backend/src/services/delegated-approval/providers/servicenow/servicenow-schemas.ts@@ -1,5 +1,6 @@import { z } from "zod";+import { DELEGATED_APPROVAL_PROVIDER_RECORD_NUMBER_MAX_CHARS } from "../../dispatch/delegated-approval-dispatch-constants";import { SERVICENOW_PERMISSIONS_MAX_CHARS } from "./servicenow-constants";import { ServiceNowRequestType } from "./servicenow-enums";@@ -35,8 +36,10 @@ export const ServiceNowAccessRequestPayloadSchema = z.object({justification: z.string().optional()});+// `request_number` is display only, so a bad value must never fail the parse that `sys_id` depends on.export const ServiceNowAccessRequestResponseSchema = z.object({- sys_id: z.string().min(1)+ sys_id: z.string().min(1),+ request_number: z.string().max(DELEGATED_APPROVAL_PROVIDER_RECORD_NUMBER_MAX_CHARS).nullish().catch(undefined)});export const ServiceNowErrorResponseSchema = z.object({diff --git a/backend/src/services/delegated-approval/providers/servicenow/servicenow-types.ts b/backend/src/services/delegated-approval/providers/servicenow/servicenow-types.tsindex 7811fb3c77..eeb2dc4d10 100644--- a/backend/src/services/delegated-approval/providers/servicenow/servicenow-types.ts+++ b/backend/src/services/delegated-approval/providers/servicenow/servicenow-types.ts@@ -7,6 +7,7 @@ export type TServiceNowAccessRequestPayload = z.infer<typeof ServiceNowAccessReqexport type TServiceNowAccessRequestOutcome = {sysId: string;+ recordNumber: string | null;duplicate: boolean;};diff --git a/backend/src/services/secret-access-approval-global-request-bridge/secret-access-approval-global-request-bridge-fns.test.ts b/backend/src/services/secret-access-approval-global-request-bridge/secret-access-approval-global-request-bridge-fns.test.tsindex 82f208f06f..591495fa2b 100644--- a/backend/src/services/secret-access-approval-global-request-bridge/secret-access-approval-global-request-bridge-fns.test.ts+++ b/backend/src/services/secret-access-approval-global-request-bridge/secret-access-approval-global-request-bridge-fns.test.ts@@ -432,7 +432,7 @@ describe("composeSecretAccessRequestRows", () => {{requestId: "req-1",status: DelegatedApprovalRequestStatus.FailedDispatch,- statusReason: "ServiceNow could not be reached."+ details: { statusReason: "ServiceNow could not be reached." }}]})@@ -440,12 +440,30 @@ describe("composeSecretAccessRequestRows", () => {expect(rows[0].delegatedApproval).toEqual({status: DelegatedApprovalRequestStatus.FailedDispatch,- statusReason: "ServiceNow could not be reached."+ statusReason: "ServiceNow could not be reached.",+ provider: null});expect(rows[1].delegatedApproval).toBeNull();expect(rows[0].policy?.delegatedApproval).toEqual({ type: DelegatedApprovalPolicyType.ServiceNow });});+ test("reports how the delegated approval system identifies the request", () => {+ const provider = { type: DelegatedApprovalPolicyType.ServiceNow, recordNumber: "INFAR1000000" };+ const [row] = composeSecretAccessRequestRows(+ listInput({+ delegatedRequests: [+ { requestId: "req-1", status: DelegatedApprovalRequestStatus.WaitingApproval, details: { provider } }+ ]+ })+ );++ expect(row.delegatedApproval).toEqual({+ status: DelegatedApprovalRequestStatus.WaitingApproval,+ statusReason: null,+ provider+ });+ });+test("a policy reviewed in Infisical reports no delegated approval", () => {const [row] = composeSecretAccessRequestRows(listInput({ policies: [policy({ delegatedApproval: null })] }));@@ -501,14 +519,15 @@ describe("toSecretAccessRequestListItem", () => {const item = toItem({requests: [request({ policyId: null, status: ApprovalRequestStatus.Cancelled })],delegatedRequests: [- { requestId: "req-1", status: DelegatedApprovalRequestStatus.WaitingApproval, statusReason: null }+ { requestId: "req-1", status: DelegatedApprovalRequestStatus.WaitingApproval, details: { statusReason: null } }]});expect(item?.policy.delegatedApproval).toBeNull();expect(item?.delegatedApproval).toEqual({status: DelegatedApprovalRequestStatus.WaitingApproval,- statusReason: null+ statusReason: null,+ provider: null});});diff --git a/backend/src/services/secret-access-approval-global-request-bridge/secret-access-approval-global-request-bridge-fns.ts b/backend/src/services/secret-access-approval-global-request-bridge/secret-access-approval-global-request-bridge-fns.tsindex 5d5736fa67..544327ff6d 100644--- a/backend/src/services/secret-access-approval-global-request-bridge/secret-access-approval-global-request-bridge-fns.ts+++ b/backend/src/services/secret-access-approval-global-request-bridge/secret-access-approval-global-request-bridge-fns.ts@@ -332,7 +332,7 @@ export type TSecretAccessRequestListInput = {groupMembers: { groupId: string; userId: string }[];users: Pick<TUsers, "id" | "email" | "username" | "firstName" | "lastName">[];orgMemberships: { actorUserId?: string | null; isActive: boolean }[];- delegatedRequests: Pick<TDelegatedApprovalRequest, "requestId" | "status" | "statusReason">[];+ delegatedRequests: Pick<TDelegatedApprovalRequest, "requestId" | "status" | "details">[];};export type TPolicySubject = { type: string; id?: string | null };@@ -489,7 +489,8 @@ export const composeSecretAccessRequestRows = ({delegatedApproval: delegatedRequest? {status: delegatedRequest.status,- statusReason: delegatedRequest.statusReason ?? null+ statusReason: delegatedRequest.details.statusReason ?? null,+ provider: delegatedRequest.details.provider ?? null}: null,environment: policy?.environment ?? null,diff --git a/docs/documentation/platform/workflow-integrations/servicenow-integration.mdx b/docs/documentation/platform/workflow-integrations/servicenow-integration.mdxindex cb82a63d38..023e00d0d4 100644--- a/docs/documentation/platform/workflow-integrations/servicenow-integration.mdx+++ b/docs/documentation/platform/workflow-integrations/servicenow-integration.mdx@@ -142,7 +142,7 @@ If ServiceNow never returns a decision, the request expires in Infisical accordi## What ServiceNow receives-Each request becomes one **Infisical Access Request** record, numbered `INFAR<number>`:+Each request becomes one **Infisical Access Request** record, numbered `INFAR<number>`. Infisical shows that number on the request's review sheet, so you can find the matching record in ServiceNow.| Field | Contents || ------------------------- | --------------------------------------------------------------------------- |