Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

feat: add implementation to create approval request inside external system (servicenow)

adilson557be06c9c23
diff --git a/CLAUDE.md b/CLAUDE.md
index 162bea9446..0c2516f13a 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -158,6 +158,24 @@ rules in `assertDelegatedApprovalPolicyConstraints` when another policy type opt
policies may opt in today: `assertPolicyTypeSupportsDelegatedApproval` refuses the rest, and secret change
policies return it as a 400 rather than dropping the field.
+Delivery to the delegated system is asynchronous and lives in `delegated-approval/dispatch/`. The request
+bridge creates the `delegated_approval_requests` row inside the request's own transaction (through the
+`onCreated` hook of `createApprovalRequestWithSteps`) and enqueues the `DelegatedApprovalDispatch` job after
+commit; the worker moves the row `pending_dispatch` → `waiting_approval` (storing the provider's record id in
+`providerRequestId`) or `failed_dispatch` with a `statusReason` a user can read, and BullMQ retries put it back
+to `pending_dispatch`. 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
+builder in `DELEGATED_APPROVAL_DISPATCH_DETAILS_BUILDER_MAP` rather than branching in a provider. The worker
+reads from the primary, never checks the license, and throws bullmq's `UnrecoverableError` for anything a retry
+cannot fix. The callback contract (token issuance now, the inbound route and approve / reject later) is its own
+module, `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 encrypted under the org KMS key in `encryptedCallbackToken` 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.
+
### 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 --git a/backend/src/@types/fastify.d.ts b/backend/src/@types/fastify.d.ts
index 80f5044b7d..f2eae74279 100644
--- a/backend/src/@types/fastify.d.ts
+++ b/backend/src/@types/fastify.d.ts
@@ -112,6 +112,7 @@ import { TCertificateV3ServiceFactory } from "@app/services/certificate-v3/certi
import { TCmekServiceFactory } from "@app/services/cmek/cmek-service";
import { TConvertorServiceFactory } from "@app/services/convertor/convertor-service";
import { TDelegatedApprovalServiceFactory } from "@app/services/delegated-approval/delegated-approval-service";
+import { TDelegatedApprovalCallbackServiceFactory } from "@app/services/delegated-approval-callback/delegated-approval-callback-service";
import { TEncryptionKeyRotationServiceFactory } from "@app/services/encryption-key-rotation/encryption-key-rotation-service";
import { TExternalGroupOrgRoleMappingServiceFactory } from "@app/services/external-group-org-role-mapping/external-group-org-role-mapping-service";
import { TExternalMigrationServiceFactory } from "@app/services/external-migration/external-migration-service";
@@ -491,6 +492,7 @@ declare module "fastify" {
pkiAlertV2: TPkiAlertV2ServiceFactory;
approvalPolicy: TApprovalPolicyServiceFactory;
delegatedApproval: TDelegatedApprovalServiceFactory;
+ delegatedApprovalCallback: TDelegatedApprovalCallbackServiceFactory;
appConnectionCredentialRotation: TAppConnectionCredentialRotationServiceFactory;
caSigningConfig: TCaSigningConfigServiceFactory;
caAutoRenewalQueue: TCaAutoRenewalQueueFactory;
diff --git a/backend/src/db/migrations/20261015145100_external-approvals.ts b/backend/src/db/migrations/20261015145100_external-approvals.ts
index 8c7a92b235..c37e1329c8 100644
--- a/backend/src/db/migrations/20261015145100_external-approvals.ts
+++ b/backend/src/db/migrations/20261015145100_external-approvals.ts
@@ -29,7 +29,7 @@ export async function up(knex: Knex): Promise<void> {
t.foreign("requestId").references("id").inTable(TableName.ApprovalRequests).onDelete("CASCADE");
t.string("status", 50).notNullable();
- t.binary("callbackTokenHash").nullable().unique();
+ t.binary("encryptedCallbackToken").nullable();
t.text("statusReason").nullable();
t.string("providerRequestId").nullable();
diff --git a/backend/src/db/schemas/delegated-approval-requests.ts b/backend/src/db/schemas/delegated-approval-requests.ts
index eb3d0ba28f..950f8c0f7e 100644
--- a/backend/src/db/schemas/delegated-approval-requests.ts
+++ b/backend/src/db/schemas/delegated-approval-requests.ts
@@ -13,7 +13,7 @@ export const DelegatedApprovalRequestsSchema = z.object({
id: z.string().uuid(),
requestId: z.string().uuid(),
status: z.string(),
- callbackTokenHash: zodBuffer.nullable().optional(),
+ encryptedCallbackToken: zodBuffer.nullable().optional(),
statusReason: z.string().nullable().optional(),
providerRequestId: z.string().nullable().optional(),
createdAt: z.date(),
diff --git a/backend/src/queue/queue-service.ts b/backend/src/queue/queue-service.ts
index 829ad846a0..2c8d320198 100644
--- a/backend/src/queue/queue-service.ts
+++ b/backend/src/queue/queue-service.ts
@@ -45,6 +45,7 @@ import {
TAppConnectionCredentialRotationSendNotificationJobPayload
} from "@app/services/app-connection/credential-rotation/app-connection-credential-rotation-types";
import { CaType } from "@app/services/certificate-authority/certificate-authority-enums";
+import { TDelegatedApprovalDispatchJobPayload } from "@app/services/delegated-approval/dispatch/delegated-approval-dispatch-types";
import {
ExternalPlatforms,
TVaultImportSideEffectsJobPayload
@@ -121,6 +122,7 @@ export enum QueueName {
PamDiscoveryScan = "pam-discovery-scan",
PkiAcmeChallengeValidation = "pki-acme-challenge-validation",
PkiDiscoveryScan = "pki-discovery-scan",
+ DelegatedApprovalDispatch = "delegated-approval-dispatch",
AppConnectionCredentialRotation = "app-connection-credential-rotation",
AppConnectionCredentialRotationRotate = "app-connection-credential-rotation-rotate",
AuditLogClickHouseBatch = "audit-log-clickhouse-batch",
@@ -205,6 +207,7 @@ export enum QueueJobs {
PkiAcmeChallengeValidation = "pki-acme-challenge-validation",
PkiDiscoveryRunScan = "pki-discovery-run-scan",
PkiDiscoveryScheduledScan = "pki-discovery-scheduled-scan",
+ DelegatedApprovalDispatch = "delegated-approval-dispatch-job",
AppConnectionCredentialRotationQueueRotations = "app-connection-credential-rotation-queue-rotations",
AppConnectionCredentialRotationRotate = "app-connection-credential-rotation-rotate",
AppConnectionCredentialRotationSendNotification = "app-connection-credential-rotation-send-notification",
@@ -566,6 +569,10 @@ export type TQueueJobTypes = {
name: QueueJobs.PkiAcmeChallengeValidation;
payload: { challengeId: string };
};
+ [QueueName.DelegatedApprovalDispatch]: {
+ name: QueueJobs.DelegatedApprovalDispatch;
+ payload: TDelegatedApprovalDispatchJobPayload;
+ };
[QueueName.PkiDiscoveryScan]:
| {
name: QueueJobs.PkiDiscoveryRunScan;
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index b90dd49dc0..acd3b8f1d9 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -355,6 +355,9 @@ import { convertorServiceFactory } from "@app/services/convertor/convertor-servi
import { delegatedApprovalPolicyDALFactory } from "@app/services/delegated-approval/delegated-approval-policy-dal";
import { delegatedApprovalRequestDALFactory } from "@app/services/delegated-approval/delegated-approval-request-dal";
import { delegatedApprovalServiceFactory } from "@app/services/delegated-approval/delegated-approval-service";
+import { delegatedApprovalDispatchQueueFactory } from "@app/services/delegated-approval/dispatch/delegated-approval-dispatch-queue";
+import { delegatedApprovalCallbackDALFactory } from "@app/services/delegated-approval-callback/delegated-approval-callback-dal";
+import { delegatedApprovalCallbackServiceFactory } from "@app/services/delegated-approval-callback/delegated-approval-callback-service";
import { encryptionKeyRotationServiceFactory } from "@app/services/encryption-key-rotation/encryption-key-rotation-service";
import { acmeEnrollmentConfigDALFactory } from "@app/services/enrollment-config/acme-enrollment-config-dal";
import { apiEnrollmentConfigDALFactory } from "@app/services/enrollment-config/api-enrollment-config-dal";
@@ -862,6 +865,7 @@ export const registerRoutes = async (
const approvalRequestDAL = approvalRequestDALFactory(db);
const delegatedApprovalPolicyDAL = delegatedApprovalPolicyDALFactory(db);
const delegatedApprovalRequestDAL = delegatedApprovalRequestDALFactory(db);
+ const delegatedApprovalCallbackDAL = delegatedApprovalCallbackDALFactory(db);
const secretChangeGlobalPolicyBridgeDAL = secretChangeGlobalPolicyBridgeDALFactory(db);
const roleDAL = roleDALFactory(db);
const pkiAlertHistoryDAL = pkiAlertHistoryDALFactory(db);
@@ -2650,53 +2654,6 @@ export const registerRoutes = async (
additionalPrivilegeDAL
});
- const secretAccessApprovalGlobalRequestBridgeService = secretAccessApprovalGlobalRequestBridgeServiceFactory({
- projectDAL,
- projectEnvDAL,
- permissionService,
- userDAL,
- userGroupMembershipDAL,
- approvalRequestDAL,
- approvalRequestStepsDAL,
- approvalRequestStepEligibleApproversDAL,
- approvalRequestApprovalsDAL,
- approvalRequestGrantsDAL,
- additionalPrivilegeDAL,
- secretAccessApprovalGlobalPolicyBridgeDAL,
- secretAccessApprovalGlobalRequestBridgeDAL,
- delegatedApprovalPolicyDAL,
- smtpService,
- notificationService,
- kmsService,
- projectSlackConfigDAL,
- microsoftTeamsService,
- projectMicrosoftTeamsConfigDAL,
- queueService,
- secretAccessApprovalGlobalResource
- });
-
- const accessApprovalRequestService = accessApprovalRequestServiceFactory({
- projectDAL,
- permissionService,
- accessApprovalRequestReviewerDAL,
- accessApprovalPolicyDAL,
- secretAccessApprovalGlobalResource,
- secretAccessApprovalGlobalRequestBridge: secretAccessApprovalGlobalRequestBridgeService,
- accessApprovalRequestDAL,
- projectEnvDAL,
- userDAL,
- smtpService,
- accessApprovalPolicyApproverDAL,
- projectSlackConfigDAL,
- kmsService,
- groupDAL,
- microsoftTeamsService,
- projectMicrosoftTeamsConfigDAL,
- notificationService,
- additionalPrivilegeDAL,
- queueService
- });
-
const secretReplicationService = secretReplicationServiceFactory({
secretTagDAL,
secretVersionTagDAL,
@@ -3291,7 +3248,6 @@ export const registerRoutes = async (
delegatedApprovalPolicyDAL,
delegatedApprovalRequestDAL,
approvalPolicyDAL,
- approvalRequestDAL,
appConnectionDAL,
appConnectionService
});
@@ -3957,6 +3913,69 @@ export const registerRoutes = async (
resources: approvalResources
});
+ const delegatedApprovalCallbackService = delegatedApprovalCallbackServiceFactory({
+ delegatedApprovalCallbackDAL,
+ kmsService
+ });
+
+ const delegatedApprovalDispatchQueue = delegatedApprovalDispatchQueueFactory({
+ delegatedApprovalRequestDAL,
+ delegatedApprovalPolicyDAL,
+ delegatedApprovalCallbackService,
+ approvalPolicyService,
+ projectService,
+ appConnectionService,
+ queueService
+ });
+
+ const secretAccessApprovalGlobalRequestBridgeService = secretAccessApprovalGlobalRequestBridgeServiceFactory({
+ projectDAL,
+ projectEnvDAL,
+ permissionService,
+ userDAL,
+ userGroupMembershipDAL,
+ approvalRequestDAL,
+ approvalRequestStepsDAL,
+ approvalRequestStepEligibleApproversDAL,
+ approvalRequestApprovalsDAL,
+ approvalRequestGrantsDAL,
+ additionalPrivilegeDAL,
+ secretAccessApprovalGlobalPolicyBridgeDAL,
+ secretAccessApprovalGlobalRequestBridgeDAL,
+ delegatedApprovalService,
+ delegatedApprovalDispatchQueue,
+ smtpService,
+ notificationService,
+ kmsService,
+ projectSlackConfigDAL,
+ microsoftTeamsService,
+ projectMicrosoftTeamsConfigDAL,
+ queueService,
+ secretAccessApprovalGlobalResource
+ });
+
+ const accessApprovalRequestService = accessApprovalRequestServiceFactory({
+ projectDAL,
+ permissionService,
+ accessApprovalRequestReviewerDAL,
+ accessApprovalPolicyDAL,
+ secretAccessApprovalGlobalResource,
+ secretAccessApprovalGlobalRequestBridge: secretAccessApprovalGlobalRequestBridgeService,
+ accessApprovalRequestDAL,
+ projectEnvDAL,
+ userDAL,
+ smtpService,
+ accessApprovalPolicyApproverDAL,
+ projectSlackConfigDAL,
+ kmsService,
+ groupDAL,
+ microsoftTeamsService,
+ projectMicrosoftTeamsConfigDAL,
+ notificationService,
+ additionalPrivilegeDAL,
+ queueService
+ });
+
const pkiApplicationEnrollmentService = pkiApplicationEnrollmentServiceFactory({
pkiApplicationDAL,
pkiApplicationProfileDAL,
@@ -4578,6 +4597,7 @@ export const registerRoutes = async (
healthAlert.init();
alertQueue.init();
eventOutboxQueue.init();
+ delegatedApprovalDispatchQueue.init();
auditLogStreamOutboxQueue.init();
pkiSyncCleanup.init();
pkiSyncHealthCheckQueue.init();
@@ -4793,6 +4813,7 @@ export const registerRoutes = async (
pkiAlertV2: pkiAlertV2Service,
approvalPolicy: approvalPolicyService,
delegatedApproval: delegatedApprovalService,
+ delegatedApprovalCallback: delegatedApprovalCallbackService,
appConnectionCredentialRotation: appConnectionCredentialRotationService,
caAutoRenewalQueue
});
diff --git a/backend/src/services/app-connection/app-connection-service.ts b/backend/src/services/app-connection/app-connection-service.ts
index 7b5b7cdf05..d2d471df4a 100644
--- a/backend/src/services/app-connection/app-connection-service.ts
+++ b/backend/src/services/app-connection/app-connection-service.ts
@@ -464,6 +464,15 @@ export const appConnectionServiceFactory = ({
return decryptAppConnection(appConnection, kmsService);
};
+ // For background work that has no actor. It performs no authorization or scope check, so it must not
+ // back a route, and the caller still has to check the connection's org and app.
+ const findDecryptedAppConnectionById = async (connectionId: string) => {
+ const appConnection = await appConnectionDAL.findById(connectionId);
+ if (!appConnection) return null;
+
+ return decryptAppConnection(appConnection, kmsService);
+ };
+
const findAppConnectionByName = async (
app: AppConnection,
{ connectionName, projectId }: TGetAppConnectionByNameDTO,
@@ -1434,6 +1443,7 @@ export const appConnectionServiceFactory = ({
listAppConnections,
findAppConnectionById,
findAppConnectionByName,
+ findDecryptedAppConnectionById,
createAppConnection,
updateAppConnection,
deleteAppConnection,
diff --git a/backend/src/services/approval-policy/approval-policy-service.ts b/backend/src/services/approval-policy/approval-policy-service.ts
index 10da716c92..bc2e00b6a2 100644
--- a/backend/src/services/approval-policy/approval-policy-service.ts
+++ b/backend/src/services/approval-policy/approval-policy-service.ts
@@ -1166,6 +1166,9 @@ export const approvalPolicyServiceFactory = ({
actorAuthMethod: actor.authMethod
});
+ // For background work that has no actor. It performs no authorization, so it must not back a route.
+ const findRequestById = (requestId: string, tx?: Knex) => approvalRequestDAL.findById(requestId, tx);
+
const getRequestById = async (requestId: string, actor: TApprovalActor) => {
const request = await approvalRequestDAL.findById(requestId);
if (!request) {
@@ -2459,6 +2462,7 @@ export const approvalPolicyServiceFactory = ({
createRequest,
createRequestFromPolicy,
listRequests,
+ findRequestById,
getRequestById,
approveRequest,
rejectRequest,
diff --git a/backend/src/services/delegated-approval-callback/delegated-approval-callback-constants.ts b/backend/src/services/delegated-approval-callback/delegated-approval-callback-constants.ts
new file mode 100644
index 0000000000..fbe6f2fd9b
--- /dev/null
+++ b/backend/src/services/delegated-approval-callback/delegated-approval-callback-constants.ts
@@ -0,0 +1,3 @@
+export const DELEGATED_APPROVAL_CALLBACK_PATH = "/api/v1/delegated-approvals/callback";
+
+export const DELEGATED_APPROVAL_CALLBACK_TOKEN_BYTES = 32;
diff --git a/backend/src/services/delegated-approval-callback/delegated-approval-callback-dal.ts b/backend/src/services/delegated-approval-callback/delegated-approval-callback-dal.ts
new file mode 100644
index 0000000000..435a2cacdf
--- /dev/null
+++ b/backend/src/services/delegated-approval-callback/delegated-approval-callback-dal.ts
@@ -0,0 +1,7 @@
+import { TDbClient } from "@app/db";
+import { TableName } from "@app/db/schemas";
+import { ormify } from "@app/lib/knex";
+
+export type TDelegatedApprovalCallbackDALFactory = ReturnType<typeof delegatedApprovalCallbackDALFactory>;
+
+export const delegatedApprovalCallbackDALFactory = (db: TDbClient) => ormify(db, TableName.DelegatedApprovalRequests);
diff --git a/backend/src/services/delegated-approval-callback/delegated-approval-callback-fns.test.ts b/backend/src/services/delegated-approval-callback/delegated-approval-callback-fns.test.ts
new file mode 100644
index 0000000000..486562f25d
--- /dev/null
+++ b/backend/src/services/delegated-approval-callback/delegated-approval-callback-fns.test.ts
@@ -0,0 +1,28 @@
+import { describe, expect, test } from "vitest";
+
+import { DELEGATED_APPROVAL_CALLBACK_PATH } from "./delegated-approval-callback-constants";
+import {
+ buildDelegatedApprovalCallbackUrl,
+ generateDelegatedApprovalCallbackToken
+} from "./delegated-approval-callback-fns";
+
+describe("generateDelegatedApprovalCallbackToken", () => {
+ test("returns a fresh base64url token of 32 random bytes", () => {
+ const token = generateDelegatedApprovalCallbackToken();
+
+ expect(token).toMatch(/^[A-Za-z0-9_-]+$/);
+ expect(Buffer.from(token, "base64url")).toHaveLength(32);
+ expect(generateDelegatedApprovalCallbackToken()).not.toBe(token);
+ });
+});
+
+describe("buildDelegatedApprovalCallbackUrl", () => {
+ test("joins the site URL and the callback path", () => {
+ expect(buildDelegatedApprovalCallbackUrl("https://app.infisical.com")).toBe(
+ `https://app.infisical.com${DELEGATED_APPROVAL_CALLBACK_PATH}`
+ );
+ expect(buildDelegatedApprovalCallbackUrl("https://app.infisical.com/")).toBe(
+ `https://app.infisical.com${DELEGATED_APPROVAL_CALLBACK_PATH}`
+ );
+ });
+});
diff --git a/backend/src/services/delegated-approval-callback/delegated-approval-callback-fns.ts b/backend/src/services/delegated-approval-callback/delegated-approval-callback-fns.ts
new file mode 100644
index 0000000000..a868398a69
--- /dev/null
+++ b/backend/src/services/delegated-approval-callback/delegated-approval-callback-fns.ts
@@ -0,0 +1,13 @@
+import { crypto } from "@app/lib/crypto/cryptography";
+import { removeTrailingSlash } from "@app/lib/fn";
+
+import {
+ DELEGATED_APPROVAL_CALLBACK_PATH,
+ DELEGATED_APPROVAL_CALLBACK_TOKEN_BYTES
+} from "./delegated-approval-callback-constants";
+
+export const generateDelegatedApprovalCallbackToken = () =>
+ crypto.randomBytes(DELEGATED_APPROVAL_CALLBACK_TOKEN_BYTES).toString("base64url");
+
+export const buildDelegatedApprovalCallbackUrl = (siteUrl: string) =>
+ `${removeTrailingSlash(siteUrl)}${DELEGATED_APPROVAL_CALLBACK_PATH}`;
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.ts
new file mode 100644
index 0000000000..0e2eb2c23a
--- /dev/null
+++ b/backend/src/services/delegated-approval-callback/delegated-approval-callback-service.test.ts
@@ -0,0 +1,108 @@
+import { describe, expect, test, vi } from "vitest";
+
+vi.mock("@app/lib/config/env", () => ({
+ getConfig: () => ({ SITE_URL: "https://app.infisical.com" })
+}));
+
+// eslint-disable-next-line import/first
+import { KmsDataKey } from "@app/services/kms/kms-types";
+
+// eslint-disable-next-line import/first
+import { DELEGATED_APPROVAL_CALLBACK_PATH } from "./delegated-approval-callback-constants";
+// eslint-disable-next-line import/first
+import { delegatedApprovalCallbackServiceFactory } from "./delegated-approval-callback-service";
+
+const CIPHER_PREFIX = Buffer.from("enc:");
+
+const encrypt = (plainText: Buffer) => Buffer.concat([CIPHER_PREFIX, plainText]);
+const decrypt = (cipherTextBlob: Buffer) => cipherTextBlob.subarray(CIPHER_PREFIX.length);
+
+const makeService = ({
+ stored = true,
+ currentRow = null
+}: { stored?: boolean; currentRow?: { encryptedCallbackToken: Buffer | null } | null } = {}) => {
+ const delegatedApprovalCallbackDAL = {
+ update: vi.fn(async () => (stored ? [{ id: "delegated-1" }] : [])),
+ transaction: vi.fn(async (cb: (tx: unknown) => Promise<unknown>) => cb({})),
+ findById: vi.fn(async () => currentRow)
+ };
+ const kmsService = {
+ createCipherPairWithDataKey: vi.fn(async () => ({
+ encryptor: ({ plainText }: { plainText: Buffer }) => ({ cipherTextBlob: encrypt(plainText) }),
+ decryptor: ({ cipherTextBlob }: { cipherTextBlob: Buffer }) => decrypt(cipherTextBlob)
+ }))
+ };
+
+ const service = delegatedApprovalCallbackServiceFactory({
+ delegatedApprovalCallbackDAL: delegatedApprovalCallbackDAL as never,
+ kmsService: kmsService as never
+ });
+
+ return { service, delegatedApprovalCallbackDAL, kmsService };
+};
+
+describe("getCallbackUrl", () => {
+ test("builds the callback URL from SITE_URL", () => {
+ const { service } = makeService();
+
+ expect(service.getCallbackUrl()).toBe(`https://app.infisical.com${DELEGATED_APPROVAL_CALLBACK_PATH}`);
+ });
+});
+
+describe("getOrIssueCallbackToken", () => {
+ test("issues a token once and stores it encrypted under the org key", async () => {
+ const { service, delegatedApprovalCallbackDAL, kmsService } = makeService();
+
+ const token = await service.getOrIssueCallbackToken({
+ delegatedRequest: { id: "delegated-1", encryptedCallbackToken: null },
+ orgId: "org-1"
+ });
+
+ expect(token).toBeTruthy();
+ expect(kmsService.createCipherPairWithDataKey).toHaveBeenCalledWith({
+ type: KmsDataKey.Organization,
+ orgId: "org-1"
+ });
+ expect(delegatedApprovalCallbackDAL.update).toHaveBeenCalledWith(
+ { id: "delegated-1", encryptedCallbackToken: null },
+ { encryptedCallbackToken: encrypt(Buffer.from(token as string)) }
+ );
+ });
+
+ test("resends the token the request already holds instead of issuing another", async () => {
+ const { service, delegatedApprovalCallbackDAL } = makeService();
+
+ const token = await service.getOrIssueCallbackToken({
+ delegatedRequest: { id: "delegated-1", encryptedCallbackToken: encrypt(Buffer.from("first-token")) },
+ orgId: "org-1"
+ });
+
+ expect(token).toBe("first-token");
+ expect(delegatedApprovalCallbackDAL.update).not.toHaveBeenCalled();
+ });
+
+ test("falls back to the token a concurrent attempt stored first", async () => {
+ const { service } = makeService({
+ stored: false,
+ currentRow: { encryptedCallbackToken: encrypt(Buffer.from("winner-token")) }
+ });
+
+ const token = await service.getOrIssueCallbackToken({
+ delegatedRequest: { id: "delegated-1", encryptedCallbackToken: null },
+ orgId: "org-1"
+ });
+
+ expect(token).toBe("winner-token");
+ });
+
+ test("returns null when the request vanished before a token could be stored", async () => {
+ const { service } = makeService({ stored: false, currentRow: { encryptedCallbackToken: null } });
+
+ const token = await service.getOrIssueCallbackToken({
+ delegatedRequest: { id: "delegated-1", encryptedCallbackToken: null },
+ orgId: "org-1"
+ });
+
+ expect(token).toBeNull();
+ });
+});
diff --git a/backend/src/services/delegated-approval-callback/delegated-approval-callback-service.ts b/backend/src/services/delegated-approval-callback/delegated-approval-callback-service.ts
new file mode 100644
index 0000000000..46e99bc663
--- /dev/null
+++ b/backend/src/services/delegated-approval-callback/delegated-approval-callback-service.ts
@@ -0,0 +1,50 @@
+import { getConfig } from "@app/lib/config/env";
+import { KmsDataKey } from "@app/services/kms/kms-types";
+
+import {
+ buildDelegatedApprovalCallbackUrl,
+ generateDelegatedApprovalCallbackToken
+} from "./delegated-approval-callback-fns";
+import {
+ TDelegatedApprovalCallbackServiceFactoryDep,
+ TGetOrIssueCallbackTokenDTO
+} from "./delegated-approval-callback-types";
+
+export type TDelegatedApprovalCallbackServiceFactory = ReturnType<typeof delegatedApprovalCallbackServiceFactory>;
+
+export const delegatedApprovalCallbackServiceFactory = ({
+ delegatedApprovalCallbackDAL,
+ kmsService
+}: TDelegatedApprovalCallbackServiceFactoryDep) => {
+ const getCallbackUrl = () => {
+ const { SITE_URL } = getConfig();
+ return SITE_URL ? buildDelegatedApprovalCallbackUrl(SITE_URL) : null;
+ };
+
+ const getOrIssueCallbackToken = async ({ delegatedRequest, orgId }: TGetOrIssueCallbackTokenDTO) => {
+ const { encryptor, decryptor } = await kmsService.createCipherPairWithDataKey({
+ type: KmsDataKey.Organization,
+ orgId
+ });
+
+ if (delegatedRequest.encryptedCallbackToken) {
+ return decryptor({ cipherTextBlob: delegatedRequest.encryptedCallbackToken }).toString();
+ }
+
+ const token = generateDelegatedApprovalCallbackToken();
+ const [issued] = await delegatedApprovalCallbackDAL.update(
+ { id: delegatedRequest.id, encryptedCallbackToken: null },
+ { encryptedCallbackToken: encryptor({ plainText: Buffer.from(token) }).cipherTextBlob }
+ );
+ if (issued) return token;
+
+ const current = await delegatedApprovalCallbackDAL.transaction((tx) =>
+ delegatedApprovalCallbackDAL.findById(delegatedRequest.id, tx)
+ );
+ if (!current?.encryptedCallbackToken) return null;
+
+ return decryptor({ cipherTextBlob: current.encryptedCallbackToken }).toString();
+ };
+
+ return { getCallbackUrl, getOrIssueCallbackToken };
+};
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.ts
new file mode 100644
index 0000000000..2081e748b1
--- /dev/null
+++ b/backend/src/services/delegated-approval-callback/delegated-approval-callback-types.ts
@@ -0,0 +1,14 @@
+import { TDelegatedApprovalRequests } from "@app/db/schemas";
+import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+
+import { TDelegatedApprovalCallbackDALFactory } from "./delegated-approval-callback-dal";
+
+export type TDelegatedApprovalCallbackServiceFactoryDep = {
+ delegatedApprovalCallbackDAL: Pick<TDelegatedApprovalCallbackDALFactory, "findById" | "transaction" | "update">;
+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
+};
+
+export type TGetOrIssueCallbackTokenDTO = {
+ delegatedRequest: Pick<TDelegatedApprovalRequests, "id" | "encryptedCallbackToken">;
+ orgId: string;
+};
diff --git a/backend/src/services/delegated-approval/delegated-approval-fns.ts b/backend/src/services/delegated-approval/delegated-approval-fns.ts
index ac831f3df3..776e41442c 100644
--- a/backend/src/services/delegated-approval/delegated-approval-fns.ts
+++ b/backend/src/services/delegated-approval/delegated-approval-fns.ts
@@ -5,7 +5,7 @@ import { DelegatedApprovalPolicyType } from "./delegated-approval-enums";
import {
DELEGATED_APPROVAL_CONNECTION_MAP,
DELEGATED_APPROVAL_NAME_MAP,
- DELEGATED_APPROVAL_SUPPORTED_POLICY_TYPES
+ isDelegatedApprovalSupportedPolicyType
} from "./delegated-approval-maps";
import { TDelegatedApprovalListItem } from "./delegated-approval-types";
@@ -56,7 +56,7 @@ export const assertDelegatedApprovalPolicyConstraints = ({
};
export const assertPolicyTypeSupportsDelegatedApproval = (policyType: string) => {
- if (!DELEGATED_APPROVAL_SUPPORTED_POLICY_TYPES.includes(policyType)) {
+ if (!isDelegatedApprovalSupportedPolicyType(policyType)) {
throw new BadRequestError({
message:
"Only secret access policies can be handled by a delegated approval system. Remove delegatedApproval from the request."
diff --git a/backend/src/services/delegated-approval/delegated-approval-maps.ts b/backend/src/services/delegated-approval/delegated-approval-maps.ts
index 3a9a038c62..cc3089e34c 100644
--- a/backend/src/services/delegated-approval/delegated-approval-maps.ts
+++ b/backend/src/services/delegated-approval/delegated-approval-maps.ts
@@ -11,4 +11,11 @@ export const DELEGATED_APPROVAL_CONNECTION_MAP: Record<DelegatedApprovalPolicyTy
[DelegatedApprovalPolicyType.ServiceNow]: AppConnection.ServiceNow
};
-export const DELEGATED_APPROVAL_SUPPORTED_POLICY_TYPES: readonly string[] = [ApprovalPolicyType.SecretAccess];
+export const DELEGATED_APPROVAL_SUPPORTED_POLICY_TYPES = [ApprovalPolicyType.SecretAccess] as const;
+
+export type DelegatedApprovalSupportedPolicyType = (typeof DELEGATED_APPROVAL_SUPPORTED_POLICY_TYPES)[number];
+
+export const isDelegatedApprovalSupportedPolicyType = (
+ policyType: string
+): policyType is DelegatedApprovalSupportedPolicyType =>
+ (DELEGATED_APPROVAL_SUPPORTED_POLICY_TYPES as readonly string[]).includes(policyType);
diff --git a/backend/src/services/delegated-approval/delegated-approval-service.ts b/backend/src/services/delegated-approval/delegated-approval-service.ts
index 99d1905c19..1a33be4ed8 100644
--- a/backend/src/services/delegated-approval/delegated-approval-service.ts
+++ b/backend/src/services/delegated-approval/delegated-approval-service.ts
@@ -8,7 +8,6 @@ import { AppConnection } from "@app/services/app-connection/app-connection-enums
import { APP_CONNECTION_NAME_MAP } from "@app/services/app-connection/app-connection-maps";
import { TAppConnectionServiceFactory } from "@app/services/app-connection/app-connection-service";
import { TApprovalPolicyDALFactory } from "@app/services/approval-policy/approval-policy-dal";
-import { TApprovalRequestDALFactory } from "@app/services/approval-policy/approval-request-dal";
import { DelegatedApprovalPolicyType, DelegatedApprovalRequestStatus } from "./delegated-approval-enums";
import { assertPolicyTypeSupportsDelegatedApproval, listDelegatedApprovalOptions } from "./delegated-approval-fns";
@@ -29,21 +28,23 @@ type TDelegatedApprovalServiceFactoryDep = {
delegatedApprovalPolicyDAL: TDelegatedApprovalPolicyDALFactory;
delegatedApprovalRequestDAL: TDelegatedApprovalRequestDALFactory;
approvalPolicyDAL: Pick<TApprovalPolicyDALFactory, "findById">;
- approvalRequestDAL: Pick<TApprovalRequestDALFactory, "findById">;
appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">;
appConnectionService: Pick<TAppConnectionServiceFactory, "validateAppConnectionUsageById">;
};
export type TDelegatedApprovalServiceFactory = ReturnType<typeof delegatedApprovalServiceFactory>;
-const isUniqueViolation = (err: unknown) =>
- err instanceof DatabaseError && (err.error as { code?: string })?.code === DatabaseErrorCode.UniqueViolation;
+const getDatabaseErrorCode = (err: unknown) =>
+ err instanceof DatabaseError ? (err.error as { code?: string })?.code : undefined;
+
+const isUniqueViolation = (err: unknown) => getDatabaseErrorCode(err) === DatabaseErrorCode.UniqueViolation;
+
+const isForeignKeyViolation = (err: unknown) => getDatabaseErrorCode(err) === DatabaseErrorCode.ForeignKeyViolation;
export const delegatedApprovalServiceFactory = ({
delegatedApprovalPolicyDAL,
delegatedApprovalRequestDAL,
approvalPolicyDAL,
- approvalRequestDAL,
appConnectionDAL,
appConnectionService
}: TDelegatedApprovalServiceFactoryDep) => {
@@ -150,26 +151,29 @@ export const delegatedApprovalServiceFactory = ({
const createRequest = async (
{
- requestId,
+ approvalRequest,
status = DelegatedApprovalRequestStatus.PendingDispatch,
statusReason
}: TCreateDelegatedApprovalRequestDTO,
tx?: Knex
) => {
- const approvalRequest = await approvalRequestDAL.findById(requestId, tx);
- if (!approvalRequest) {
- throw new NotFoundError({ message: `Approval request with ID '${requestId}' not found` });
- }
+ assertPolicyTypeSupportsDelegatedApproval(approvalRequest.type);
try {
- const request = await delegatedApprovalRequestDAL.create({ requestId, status, statusReason }, tx);
+ const request = await delegatedApprovalRequestDAL.create(
+ { requestId: approvalRequest.id, status, statusReason },
+ tx
+ );
return request as TDelegatedApprovalRequest;
} catch (err) {
if (isUniqueViolation(err)) {
throw new BadRequestError({
- message: `Approval request with ID '${requestId}' already has a delegated approval request`
+ message: `Approval request with ID '${approvalRequest.id}' already has a delegated approval request`
});
}
+ if (isForeignKeyViolation(err)) {
+ throw new NotFoundError({ message: `Approval request with ID '${approvalRequest.id}' not found` });
+ }
throw err;
}
};
diff --git a/backend/src/services/delegated-approval/delegated-approval-types.ts b/backend/src/services/delegated-approval/delegated-approval-types.ts
index aa73d18dff..acceae0f47 100644
--- a/backend/src/services/delegated-approval/delegated-approval-types.ts
+++ b/backend/src/services/delegated-approval/delegated-approval-types.ts
@@ -1,4 +1,4 @@
-import { TDelegatedApprovalPolicies, TDelegatedApprovalRequests } from "@app/db/schemas";
+import { TApprovalRequests, TDelegatedApprovalPolicies, TDelegatedApprovalRequests } from "@app/db/schemas";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
import { DelegatedApprovalPolicyType, DelegatedApprovalRequestStatus } from "./delegated-approval-enums";
@@ -39,7 +39,7 @@ export type TUpdateDelegatedApprovalPolicyDTO = {
};
export type TCreateDelegatedApprovalRequestDTO = {
- requestId: string;
+ approvalRequest: Pick<TApprovalRequests, "id" | "type">;
status?: DelegatedApprovalRequestStatus;
statusReason?: string | null;
};
diff --git a/backend/src/services/delegated-approval/dispatch/delegated-approval-dispatch-builders.test.ts b/backend/src/services/delegated-approval/dispatch/delegated-approval-dispatch-builders.test.ts
new file mode 100644
index 0000000000..b41337c33a
--- /dev/null
+++ b/backend/src/services/delegated-approval/dispatch/delegated-approval-dispatch-builders.test.ts
@@ -0,0 +1,86 @@
+import { packRules } from "@casl/ability/extra";
+import { UnrecoverableError } from "bullmq";
+import { describe, expect, test, vi } from "vitest";
+
+// logger is initialized at app boot and is undefined under unit tests; stub it so
+// validateHandlebarTemplate's reject path surfaces its BadRequestError rather than a logger error.
+vi.mock("@app/lib/logger", () => ({
+ logger: { error: vi.fn(), info: vi.fn(), warn: vi.fn(), debug: vi.fn() }
+}));
+
+// eslint-disable-next-line import/first
+import { TApprovalRequests } from "@app/db/schemas";
+// eslint-disable-next-line import/first
+import { ApprovalPolicyType, ApprovalRequestStatus } from "@app/services/approval-policy/approval-policy-enums";
+
+// eslint-disable-next-line import/first
+import { buildSecretAccessDispatchDetails } from "./delegated-approval-dispatch-builders";
+
+const makeRule = (action: string, env: string, secretPath: string, subject = "secrets") => ({
+ action,
+ subject,
+ conditions: { environment: env, secretPath: { $glob: secretPath } }
+});
+
+const makeRequest = (requestData: unknown): TApprovalRequests => ({
+ id: "request-1",
+ projectId: "project-1",
+ organizationId: "org-1",
+ policyId: "policy-1",
+ requesterId: "user-1",
+ requesterName: "Ada Lovelace",
+ requesterEmail: "[email protected]",
+ type: ApprovalPolicyType.SecretAccess,
+ status: ApprovalRequestStatus.Pending,
+ justification: null,
+ currentStep: 1,
+ requestData,
+ expiresAt: null,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ machineIdentityId: null,
+ scopeType: null,
+ scopeId: null
+});
+
+describe("buildSecretAccessDispatchDetails", () => {
+ test("derives the environment, path and flattened permissions from the stored request", () => {
+ const permissions = packRules([
+ makeRule("read", "prod", "/db"),
+ makeRule("edit", "prod", "/db"),
+ makeRule("read", "prod", "/db", "secret-folders")
+ ]);
+
+ expect(
+ buildSecretAccessDispatchDetails(
+ makeRequest({ version: 1, requestData: { permissions, isTemporary: true, temporaryRange: "1h" } })
+ )
+ ).toEqual({
+ policyType: ApprovalPolicyType.SecretAccess,
+ environment: "prod",
+ secretPath: "/db",
+ permissions: ["secrets:read", "secrets:edit", "secret-folders:read"],
+ isTemporary: true,
+ temporaryRange: "1h"
+ });
+ });
+
+ test("drops the temporary range on a permanent request", () => {
+ const permissions = packRules([makeRule("read", "dev", "/")]);
+
+ expect(
+ buildSecretAccessDispatchDetails(
+ makeRequest({ version: 1, requestData: { permissions, isTemporary: false, temporaryRange: "1h" } })
+ ).temporaryRange
+ ).toBeNull();
+ });
+
+ test("does not retry a request whose stored data cannot be interpreted", () => {
+ expect(() => buildSecretAccessDispatchDetails(makeRequest({ version: 2 }))).toThrow(UnrecoverableError);
+ expect(() =>
+ buildSecretAccessDispatchDetails(
+ makeRequest({ version: 1, requestData: { permissions: [], isTemporary: false, temporaryRange: null } })
+ )
+ ).toThrow(UnrecoverableError);
+ });
+});
diff --git a/backend/src/services/delegated-approval/dispatch/delegated-approval-dispatch-builders.ts b/backend/src/services/delegated-approval/dispatch/delegated-approval-dispatch-builders.ts
new file mode 100644
index 0000000000..af51570619
--- /dev/null
+++ b/backend/src/services/delegated-approval/dispatch/delegated-approval-dispatch-builders.ts
@@ -0,0 +1,34 @@
+import { UnrecoverableError } from "bullmq";
+
+import { verifyRequestedPermissions } from "@app/ee/services/access-approval-request/access-approval-request-fns";
+import { BadRequestError } from "@app/lib/errors";
+import { ApprovalPolicyType } from "@app/services/approval-policy/approval-policy-enums";
+import { getSecretAccessRequestData } from "@app/services/approval-policy/secret-access/secret-access-policy-fns";
+
+import { TDelegatedApprovalDispatchDetailsBuilder } from "./delegated-approval-dispatch-types";
+
+// A stored row that fails validation will fail the same way on every retry.
+export const buildSecretAccessDispatchDetails: TDelegatedApprovalDispatchDetailsBuilder = (request) => {
+ try {
+ const { permissions, isTemporary, temporaryRange } = getSecretAccessRequestData(request);
+ const { envSlug, secretPath, requestedPermissions } = verifyRequestedPermissions({ permissions });
+
+ return {
+ policyType: ApprovalPolicyType.SecretAccess,
+ environment: envSlug,
+ secretPath,
+ permissions: requestedPermissions.flatMap(({ subject, actions }) =>
+ actions.map((action) => `${subject}:${action}`)
+ ),
+ isTemporary,
+ temporaryRange: isTemporary ? temporaryRange : null
+ };
+ } catch (error) {
+ if (error instanceof BadRequestError) {
+ throw new UnrecoverableError(
+ `The access request cannot be sent to the delegated approval system: ${error.message}`
+ );
+ }
+ throw error;
+ }
+};
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.ts
new file mode 100644
index 0000000000..14a2753080
--- /dev/null
+++ b/backend/src/services/delegated-approval/dispatch/delegated-approval-dispatch-constants.ts
@@ -0,0 +1,7 @@
+export const DELEGATED_APPROVAL_DISPATCH_ATTEMPTS = 5;
+
+export const DELEGATED_APPROVAL_DISPATCH_BACKOFF_MS = 5_000;
+
+export const DELEGATED_APPROVAL_DISPATCH_CONCURRENCY = 5;
+
+export const DELEGATED_APPROVAL_STATUS_REASON_MAX_CHARS = 1_000;
diff --git a/backend/src/services/delegated-approval/dispatch/delegated-approval-dispatch-fns.ts b/backend/src/services/delegated-approval/dispatch/delegated-approval-dispatch-fns.ts
new file mode 100644
index 0000000000..b3d981cea8
--- /dev/null
+++ b/backend/src/services/delegated-approval/dispatch/delegated-approval-dispatch-fns.ts
@@ -0,0 +1,29 @@
+import { UnrecoverableError } from "bullmq";
+
+import { DelegatedApprovalPolicyType } from "../delegated-approval-enums";
+import { isDelegatedApprovalSupportedPolicyType } from "../delegated-approval-maps";
+import {
+ DELEGATED_APPROVAL_DISPATCH_DETAILS_BUILDER_MAP,
+ DELEGATED_APPROVAL_PROVIDER_MAP
+} from "./delegated-approval-dispatch-maps";
+import {
+ TDelegatedApprovalDispatchDetailsBuilder,
+ TDelegatedApprovalProvider
+} from "./delegated-approval-dispatch-types";
+
+export const getDelegatedApprovalProvider = (type: string): TDelegatedApprovalProvider => {
+ const provider = DELEGATED_APPROVAL_PROVIDER_MAP[type as DelegatedApprovalPolicyType];
+ if (!provider) {
+ throw new UnrecoverableError(`The delegated approval system '${type}' is not supported.`);
+ }
+ return provider;
+};
+
+export const getDelegatedApprovalDispatchDetailsBuilder = (
+ policyType: string
+): TDelegatedApprovalDispatchDetailsBuilder => {
+ if (!isDelegatedApprovalSupportedPolicyType(policyType)) {
+ throw new UnrecoverableError(`Requests of type '${policyType}' cannot be sent to a delegated approval system.`);
+ }
+ return DELEGATED_APPROVAL_DISPATCH_DETAILS_BUILDER_MAP[policyType];
+};
diff --git a/backend/src/services/delegated-approval/dispatch/delegated-approval-dispatch-maps.ts b/backend/src/services/delegated-approval/dispatch/delegated-approval-dispatch-maps.ts
new file mode 100644
index 0000000000..5e1e86f162
--- /dev/null
+++ b/backend/src/services/delegated-approval/dispatch/delegated-approval-dispatch-maps.ts
@@ -0,0 +1,21 @@
+import { ApprovalPolicyType } from "@app/services/approval-policy/approval-policy-enums";
+
+import { DelegatedApprovalPolicyType } from "../delegated-approval-enums";
+import { DelegatedApprovalSupportedPolicyType } from "../delegated-approval-maps";
+import { buildSecretAccessDispatchDetails } from "./delegated-approval-dispatch-builders";
+import {
+ TDelegatedApprovalDispatchDetailsBuilder,
+ TDelegatedApprovalProvider
+} from "./delegated-approval-dispatch-types";
+import { servicenowProviderFactory } from "./providers/servicenow";
+
+export const DELEGATED_APPROVAL_PROVIDER_MAP: Record<DelegatedApprovalPolicyType, TDelegatedApprovalProvider> = {
+ [DelegatedApprovalPolicyType.ServiceNow]: servicenowProviderFactory()
+};
+
+export const DELEGATED_APPROVAL_DISPATCH_DETAILS_BUILDER_MAP: Record<
+ DelegatedApprovalSupportedPolicyType,
+ TDelegatedApprovalDispatchDetailsBuilder
+> = {
+ [ApprovalPolicyType.SecretAccess]: buildSecretAccessDispatchDetails
+};
diff --git a/backend/src/services/delegated-approval/dispatch/delegated-approval-dispatch-queue.ts b/backend/src/services/delegated-approval/dispatch/delegated-approval-dispatch-queue.ts
new file mode 100644
index 0000000000..adb20bb05d
--- /dev/null
+++ b/backend/src/services/delegated-approval/dispatch/delegated-approval-dispatch-queue.ts
@@ -0,0 +1,259 @@
+import { UnrecoverableError } from "bullmq";
+
+import { ProjectType } from "@app/db/schemas";
+import { logger } from "@app/lib/logger";
+import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
+import { AppConnection } from "@app/services/app-connection/app-connection-enums";
+import { APP_CONNECTION_NAME_MAP } from "@app/services/app-connection/app-connection-maps";
+import { TAppConnectionServiceFactory } from "@app/services/app-connection/app-connection-service";
+import { ApprovalRequestStatus } from "@app/services/approval-policy/approval-policy-enums";
+import { TApprovalPolicyServiceFactory } from "@app/services/approval-policy/approval-policy-service";
+import { TDelegatedApprovalCallbackServiceFactory } from "@app/services/delegated-approval-callback/delegated-approval-callback-service";
+import { TProjectServiceFactory } from "@app/services/project/project-service";
+
+import { DelegatedApprovalRequestStatus } from "../delegated-approval-enums";
+import { DELEGATED_APPROVAL_NAME_MAP } from "../delegated-approval-maps";
+import { TDelegatedApprovalPolicyDALFactory } from "../delegated-approval-policy-dal";
+import { TDelegatedApprovalRequestDALFactory } from "../delegated-approval-request-dal";
+import {
+ DELEGATED_APPROVAL_DISPATCH_ATTEMPTS,
+ DELEGATED_APPROVAL_DISPATCH_BACKOFF_MS,
+ DELEGATED_APPROVAL_DISPATCH_CONCURRENCY,
+ DELEGATED_APPROVAL_STATUS_REASON_MAX_CHARS
+} from "./delegated-approval-dispatch-constants";
+import {
+ getDelegatedApprovalDispatchDetailsBuilder,
+ getDelegatedApprovalProvider
+} from "./delegated-approval-dispatch-fns";
+import {
+ TDelegatedApprovalDispatchInput,
+ TDelegatedApprovalDispatchJobPayload
+} from "./delegated-approval-dispatch-types";
+
+type TDelegatedApprovalDispatchQueueFactoryDep = {
+ delegatedApprovalRequestDAL: Pick<
+ TDelegatedApprovalRequestDALFactory,
+ "findById" | "transaction" | "update" | "updateById"
+ >;
+ delegatedApprovalPolicyDAL: Pick<TDelegatedApprovalPolicyDALFactory, "findOne">;
+ delegatedApprovalCallbackService: Pick<
+ TDelegatedApprovalCallbackServiceFactory,
+ "getCallbackUrl" | "getOrIssueCallbackToken"
+ >;
+ approvalPolicyService: Pick<TApprovalPolicyServiceFactory, "findRequestById">;
+ projectService: Pick<TProjectServiceFactory, "findProjectById">;
+ appConnectionService: Pick<TAppConnectionServiceFactory, "findDecryptedAppConnectionById">;
+ queueService: Pick<TQueueServiceFactory, "queue" | "start">;
+};
+
+export type TDelegatedApprovalDispatchQueueFactory = ReturnType<typeof delegatedApprovalDispatchQueueFactory>;
+
+export const delegatedApprovalDispatchQueueFactory = ({
+ delegatedApprovalRequestDAL,
+ delegatedApprovalPolicyDAL,
+ delegatedApprovalCallbackService,
+ approvalPolicyService,
+ projectService,
+ appConnectionService,
+ queueService
+}: TDelegatedApprovalDispatchQueueFactoryDep) => {
+ const $markDispatchFailed = async (delegatedRequestId: string, statusReason: string) => {
+ try {
+ await delegatedApprovalRequestDAL.update(
+ { id: delegatedRequestId, status: DelegatedApprovalRequestStatus.PendingDispatch },
+ {
+ status: DelegatedApprovalRequestStatus.FailedDispatch,
+ statusReason: statusReason.slice(0, DELEGATED_APPROVAL_STATUS_REASON_MAX_CHARS)
+ }
+ );
+ } catch (error) {
+ logger.error(
+ error,
+ `Failed to record delegated approval dispatch failure [delegatedRequestId=${delegatedRequestId}]`
+ );
+ }
+ };
+
+ const queueDispatch = async ({ delegatedRequestId }: TDelegatedApprovalDispatchJobPayload) => {
+ try {
+ await queueService.queue(
+ QueueName.DelegatedApprovalDispatch,
+ QueueJobs.DelegatedApprovalDispatch,
+ { delegatedRequestId },
+ {
+ jobId: `delegated-approval-dispatch-${delegatedRequestId}`,
+ attempts: DELEGATED_APPROVAL_DISPATCH_ATTEMPTS,
+ backoff: { type: "exponential", delay: DELEGATED_APPROVAL_DISPATCH_BACKOFF_MS },
+ removeOnComplete: true,
+ removeOnFail: true
+ }
+ );
+ } catch (error) {
+ logger.error(error, `Failed to queue delegated approval dispatch [delegatedRequestId=${delegatedRequestId}]`);
+ await $markDispatchFailed(
+ delegatedRequestId,
+ "Infisical could not schedule delivery to the delegated approval system."
+ );
+ }
+ };
+
+ // Both rows were committed together moments before the job runs, so they are read from the primary.
+ const $loadRequests = (delegatedRequestId: string) =>
+ delegatedApprovalRequestDAL.transaction(async (tx) => {
+ const delegatedRequest = await delegatedApprovalRequestDAL.findById(delegatedRequestId, tx);
+ if (!delegatedRequest) return null;
+
+ const approvalRequest = await approvalPolicyService.findRequestById(delegatedRequest.requestId, tx);
+ const delegatedPolicy = approvalRequest?.policyId
+ ? await delegatedApprovalPolicyDAL.findOne({ policyId: approvalRequest.policyId }, tx)
+ : null;
+
+ return { delegatedRequest, approvalRequest, delegatedPolicy };
+ });
+
+ const init = () => {
+ queueService.start(
+ QueueName.DelegatedApprovalDispatch,
+ async (job) => {
+ const { delegatedRequestId } = job.data;
+ const attempt = job.attemptsMade + 1;
+ const maxAttempts = job.opts.attempts ?? 1;
+ const isFinalAttempt = attempt >= maxAttempts;
+
+ const requests = await $loadRequests(delegatedRequestId);
+ if (!requests) {
+ logger.warn(
+ `Delegated approval request no longer exists, skipping dispatch [delegatedRequestId=${delegatedRequestId}]`
+ );
+ return;
+ }
+
+ const { delegatedRequest, approvalRequest, delegatedPolicy } = requests;
+
+ if (
+ delegatedRequest.status !== DelegatedApprovalRequestStatus.PendingDispatch &&
+ delegatedRequest.status !== DelegatedApprovalRequestStatus.FailedDispatch
+ ) {
+ logger.info(
+ `Delegated approval request is not awaiting dispatch, skipping [delegatedRequestId=${delegatedRequestId}] [status=${delegatedRequest.status}]`
+ );
+ return;
+ }
+
+ if (delegatedRequest.providerRequestId) {
+ logger.info(
+ `Delegated approval request was already delivered, skipping [delegatedRequestId=${delegatedRequestId}] [providerRequestId=${delegatedRequest.providerRequestId}]`
+ );
+ return;
+ }
+
+ await delegatedApprovalRequestDAL.updateById(delegatedRequestId, {
+ status: DelegatedApprovalRequestStatus.PendingDispatch,
+ statusReason: null
+ });
+
+ try {
+ if (!approvalRequest) {
+ throw new UnrecoverableError("The approval request no longer exists.");
+ }
+ if (approvalRequest.status !== ApprovalRequestStatus.Pending) {
+ throw new UnrecoverableError(
+ "The access request is no longer pending, so it was not sent to the delegated approval system."
+ );
+ }
+ if (!delegatedPolicy) {
+ throw new UnrecoverableError(
+ "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."
+ );
+ }
+
+ const provider = getDelegatedApprovalProvider(delegatedPolicy.type);
+ const providerName = DELEGATED_APPROVAL_NAME_MAP[provider.type];
+
+ const project = await projectService.findProjectById(approvalRequest.projectId);
+ if (!project) {
+ throw new UnrecoverableError("The project of the access request no longer exists.");
+ }
+
+ const connection = await appConnectionService.findDecryptedAppConnectionById(delegatedPolicy.connectionId);
+ if (!connection || connection.orgId !== approvalRequest.organizationId) {
+ throw new UnrecoverableError(
+ `App Connection with ID '${delegatedPolicy.connectionId}' was not found. Select a ${APP_CONNECTION_NAME_MAP[provider.app]} Connection on the policy and create the request again.`
+ );
+ }
+ if (connection.app !== provider.app) {
+ throw new UnrecoverableError(
+ `${APP_CONNECTION_NAME_MAP[connection.app as AppConnection]} Connection with ID '${connection.id}' cannot be used as a ${providerName} delegated approver. Select a ${APP_CONNECTION_NAME_MAP[provider.app]} Connection on the policy instead.`
+ );
+ }
+
+ const callbackUrl = delegatedApprovalCallbackService.getCallbackUrl();
+ if (!callbackUrl) {
+ throw new UnrecoverableError(
+ "SITE_URL must be configured so the delegated approval system can call Infisical back."
+ );
+ }
+
+ const callbackToken = await delegatedApprovalCallbackService.getOrIssueCallbackToken({
+ delegatedRequest,
+ orgId: approvalRequest.organizationId
+ });
+ if (!callbackToken) {
+ throw new UnrecoverableError(
+ "A callback token could not be issued for this request. Create the request again."
+ );
+ }
+
+ const buildDetails = getDelegatedApprovalDispatchDetailsBuilder(approvalRequest.type);
+
+ const input: TDelegatedApprovalDispatchInput = {
+ delegatedRequestId,
+ approvalRequestId: approvalRequest.id,
+ organizationId: approvalRequest.organizationId,
+ productType: project.type as ProjectType,
+ project: { id: project.id, name: project.name },
+ requester: { name: approvalRequest.requesterName, email: approvalRequest.requesterEmail },
+ justification: approvalRequest.justification ?? null,
+ callback: { url: callbackUrl, token: callbackToken },
+ details: buildDetails(approvalRequest)
+ };
+
+ const { providerRequestId } = await provider.dispatch(input, connection);
+
+ const [waitingRequest] = await delegatedApprovalRequestDAL.update(
+ { id: delegatedRequestId, status: DelegatedApprovalRequestStatus.PendingDispatch },
+ { status: DelegatedApprovalRequestStatus.WaitingApproval, statusReason: null, providerRequestId }
+ );
+ if (!waitingRequest) {
+ await delegatedApprovalRequestDAL.updateById(delegatedRequestId, { providerRequestId });
+ 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=${provider.type}] [providerRequestId=${providerRequestId}]`
+ );
+ } catch (error) {
+ const isTerminal = isFinalAttempt || error instanceof UnrecoverableError;
+ const message = error instanceof Error ? error.message : String(error);
+
+ await $markDispatchFailed(delegatedRequestId, isTerminal ? message : `${message} Infisical will retry.`);
+
+ const logContext = { err: { name: (error as Error)?.name, message } };
+ const logMessage = `Delegated approval dispatch failed [delegatedRequestId=${delegatedRequestId}] [attempt=${attempt}/${maxAttempts}] [terminal=${isTerminal}]`;
+ if (isTerminal) {
+ logger.error(logContext, logMessage);
+ } else {
+ logger.warn(logContext, logMessage);
+ }
+
+ throw error;
+ }
+ },
+ { concurrency: DELEGATED_APPROVAL_DISPATCH_CONCURRENCY }
+ );
+ };
+
+ return { queueDispatch, init };
+};
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.ts
new file mode 100644
index 0000000000..7c3b4d3460
--- /dev/null
+++ b/backend/src/services/delegated-approval/dispatch/delegated-approval-dispatch-types.ts
@@ -0,0 +1,54 @@
+import { ProjectType, TApprovalRequests } from "@app/db/schemas";
+import { AppConnection } from "@app/services/app-connection/app-connection-enums";
+import { TAppConnection } from "@app/services/app-connection/app-connection-types";
+import { ApprovalPolicyType } from "@app/services/approval-policy/approval-policy-enums";
+
+import { DelegatedApprovalPolicyType } from "../delegated-approval-enums";
+
+export type TSecretAccessDispatchDetails = {
+ policyType: ApprovalPolicyType.SecretAccess;
+ environment: string;
+ secretPath: string;
+ permissions: string[];
+ isTemporary: boolean;
+ temporaryRange: string | null;
+};
+
+// Discriminated by the approval policy type. Another policy type is dispatched by adding its arm here
+// and a builder for it in DELEGATED_APPROVAL_DISPATCH_DETAILS_BUILDER_MAP.
+export type TDelegatedApprovalDispatchDetails = TSecretAccessDispatchDetails;
+
+export type TDelegatedApprovalDispatchInput = {
+ delegatedRequestId: string;
+ approvalRequestId: string;
+ organizationId: string;
+ productType: ProjectType;
+ project?: { id: string; name: string }; // project is optional because it is possible that PAM and PKI don't need it
+ requester: { name: string; email: string };
+ justification: string | null;
+ // The token is plaintext only here, on its way to the provider. It is never persisted or logged.
+ callback: { url: string; token: string };
+ details: TDelegatedApprovalDispatchDetails;
+};
+
+export type TDelegatedApprovalDispatchResult = {
+ providerRequestId: string;
+ // The provider already held this request from an earlier attempt whose response was lost. Safe to treat
+ // as delivered because every attempt sends the same callback token.
+ duplicate: boolean;
+};
+
+export type TDelegatedApprovalProvider = {
+ type: DelegatedApprovalPolicyType;
+ app: AppConnection;
+ dispatch: (
+ input: TDelegatedApprovalDispatchInput,
+ connection: TAppConnection
+ ) => Promise<TDelegatedApprovalDispatchResult>;
+};
+
+export type TDelegatedApprovalDispatchDetailsBuilder = (
+ request: TApprovalRequests
+) => TDelegatedApprovalDispatchDetails;
+
+export type TDelegatedApprovalDispatchJobPayload = { delegatedRequestId: string };
diff --git a/backend/src/services/delegated-approval/dispatch/providers/servicenow/index.ts b/backend/src/services/delegated-approval/dispatch/providers/servicenow/index.ts
new file mode 100644
index 0000000000..c07ff0057c
--- /dev/null
+++ b/backend/src/services/delegated-approval/dispatch/providers/servicenow/index.ts
@@ -0,0 +1,5 @@
+export * from "./servicenow-constants";
+export * from "./servicenow-enums";
+export * from "./servicenow-fns";
+export * from "./servicenow-schemas";
+export * from "./servicenow-types";
diff --git a/backend/src/services/delegated-approval/dispatch/providers/servicenow/servicenow-constants.ts b/backend/src/services/delegated-approval/dispatch/providers/servicenow/servicenow-constants.ts
new file mode 100644
index 0000000000..c52ad968cc
--- /dev/null
+++ b/backend/src/services/delegated-approval/dispatch/providers/servicenow/servicenow-constants.ts
@@ -0,0 +1,22 @@
+import { ApprovalPolicyType } from "@app/services/approval-policy/approval-policy-enums";
+
+import { DelegatedApprovalSupportedPolicyType } from "../../../delegated-approval-maps";
+import { ServiceNowRequestType } from "./servicenow-enums";
+
+export const SERVICENOW_ACCESS_REQUEST_PATH = "/api/x_infis_approvals/v1/infisical/access_request";
+
+export const SERVICENOW_DISPATCH_TIMEOUT_MS = 15_000;
+
+export const SERVICENOW_DISPATCH_MAX_CONTENT_LENGTH = 64 * 1024;
+
+export const SERVICENOW_ERROR_DETAIL_MAX_CHARS = 200;
+
+export const SERVICENOW_EVENT_MAP: Record<
+ DelegatedApprovalSupportedPolicyType,
+ { event: string; requestType: ServiceNowRequestType }
+> = {
+ [ApprovalPolicyType.SecretAccess]: {
+ event: "secrets_management.access_request",
+ requestType: ServiceNowRequestType.SecretAccess
+ }
+};
diff --git a/backend/src/services/delegated-approval/dispatch/providers/servicenow/servicenow-enums.ts b/backend/src/services/delegated-approval/dispatch/providers/servicenow/servicenow-enums.ts
new file mode 100644
index 0000000000..507c9a27ff
--- /dev/null
+++ b/backend/src/services/delegated-approval/dispatch/providers/servicenow/servicenow-enums.ts
@@ -0,0 +1,3 @@
+export enum ServiceNowRequestType {
+ SecretAccess = "secret_access"
+}
diff --git a/backend/src/services/delegated-approval/dispatch/providers/servicenow/servicenow-fns.test.ts b/backend/src/services/delegated-approval/dispatch/providers/servicenow/servicenow-fns.test.ts
new file mode 100644
index 0000000000..94e5c22529
--- /dev/null
+++ b/backend/src/services/delegated-approval/dispatch/providers/servicenow/servicenow-fns.test.ts
@@ -0,0 +1,198 @@
+import { AxiosError, AxiosHeaders } from "axios";
+import { UnrecoverableError } from "bullmq";
+import { describe, expect, test } from "vitest";
+
+import { ProjectType } from "@app/db/schemas";
+import { BadRequestError } from "@app/lib/errors";
+import { ApprovalPolicyType } from "@app/services/approval-policy/approval-policy-enums";
+
+import { TDelegatedApprovalDispatchInput } from "../../delegated-approval-dispatch-types";
+import { ServiceNowRequestType } from "./servicenow-enums";
+import {
+ buildServiceNowAccessRequestPayload,
+ parseServiceNowAccessRequestResponse,
+ toServiceNowDispatchError
+} from "./servicenow-fns";
+
+const INSTANCE_URL = "https://acme.service-now.com";
+const CALLBACK_TOKEN = "callback-token-plaintext";
+
+const makeInput = (overrides: Partial<TDelegatedApprovalDispatchInput> = {}): TDelegatedApprovalDispatchInput => ({
+ delegatedRequestId: "delegated-1",
+ approvalRequestId: "request-1",
+ organizationId: "org-1",
+ productType: ProjectType.SecretManager,
+ project: { id: "project-1", name: "Payments" },
+ requester: { name: "Ada Lovelace", email: "[email protected]" },
+ justification: "Rotating the database password",
+ callback: { url: "https://app.infisical.com/api/v1/delegated-approvals/callback", token: CALLBACK_TOKEN },
+ details: {
+ policyType: ApprovalPolicyType.SecretAccess,
+ environment: "prod",
+ secretPath: "/db",
+ permissions: ["secrets:read", "secrets:edit"],
+ isTemporary: true,
+ temporaryRange: "1h"
+ },
+ ...overrides
+});
+
+const makeAxiosError = (status?: number, data?: unknown, code?: string) =>
+ new AxiosError(
+ "request failed",
+ code,
+ undefined,
+ undefined,
+ status ? { status, statusText: "", headers: {}, config: { headers: new AxiosHeaders() }, data } : undefined
+ );
+
+describe("buildServiceNowAccessRequestPayload", () => {
+ test("maps a temporary secret access request onto the ServiceNow contract", () => {
+ expect(buildServiceNowAccessRequestPayload(makeInput())).toEqual({
+ request_id: "request-1",
+ callback_url: "https://app.infisical.com/api/v1/delegated-approvals/callback",
+ callback_token: CALLBACK_TOKEN,
+ event: "secrets_management.access_request",
+ request_type: ServiceNowRequestType.SecretAccess,
+ product_type: ProjectType.SecretManager,
+ project_id: "project-1",
+ project_name: "Payments",
+ environment: "prod",
+ requestor_email: "[email protected]",
+ requestor_name: "Ada Lovelace",
+ justification: "Rotating the database password",
+ secret_path: "/db",
+ permissions: ["secrets:read", "secrets:edit"],
+ is_temporary: true,
+ temporary_range: "1h"
+ });
+ });
+
+ test("marks a permanent request and omits the empty optional fields", () => {
+ const payload = buildServiceNowAccessRequestPayload(
+ makeInput({
+ requester: { name: "", email: "[email protected]" },
+ justification: null,
+ details: {
+ policyType: ApprovalPolicyType.SecretAccess,
+ environment: "prod",
+ secretPath: "/",
+ permissions: ["secrets:read"],
+ isTemporary: false,
+ temporaryRange: null
+ }
+ })
+ );
+
+ expect(payload.is_temporary).toBe(false);
+ expect(payload).not.toHaveProperty("temporary_range");
+ expect(payload).not.toHaveProperty("requestor_name");
+ expect(payload).not.toHaveProperty("justification");
+ });
+
+ test("refuses a request without a project, which ServiceNow requires", () => {
+ expect(() => buildServiceNowAccessRequestPayload(makeInput({ project: undefined }))).toThrow(/project_id/);
+ });
+
+ test("refuses a callback URL that is not https", () => {
+ expect(() =>
+ buildServiceNowAccessRequestPayload(
+ makeInput({
+ callback: { url: "http://localhost:8080/api/v1/delegated-approvals/callback", token: CALLBACK_TOKEN }
+ })
+ )
+ ).toThrow(UnrecoverableError);
+ });
+
+ test("refuses a temporary range longer than ServiceNow stores", () => {
+ expect(() =>
+ buildServiceNowAccessRequestPayload(
+ makeInput({
+ details: {
+ policyType: ApprovalPolicyType.SecretAccess,
+ environment: "prod",
+ secretPath: "/",
+ permissions: ["secrets:read"],
+ isTemporary: true,
+ temporaryRange: "x".repeat(51)
+ }
+ })
+ )
+ ).toThrow(/temporary_range/);
+ });
+});
+
+describe("parseServiceNowAccessRequestResponse", () => {
+ test("reads the record ID from a bare or enveloped 201", () => {
+ expect(
+ parseServiceNowAccessRequestResponse(201, { success: true, request_number: "INFAR0001", sys_id: "abc" })
+ ).toEqual({
+ sysId: "abc",
+ duplicate: false
+ });
+ expect(parseServiceNowAccessRequestResponse(201, { result: { success: true, sys_id: "abc" } })).toEqual({
+ sysId: "abc",
+ duplicate: false
+ });
+ });
+
+ test("treats a 409 as the record ServiceNow already holds", () => {
+ expect(parseServiceNowAccessRequestResponse(409, { success: false, error: "duplicate", sys_id: "abc" })).toEqual({
+ sysId: "abc",
+ duplicate: true
+ });
+ expect(parseServiceNowAccessRequestResponse(409, { result: { success: false, sys_id: "abc" } })).toEqual({
+ sysId: "abc",
+ duplicate: true
+ });
+ });
+
+ test("retries an accepted response without a record ID and gives up on a 409 without one", () => {
+ expect(() => parseServiceNowAccessRequestResponse(201, { success: true })).toThrow(BadRequestError);
+ expect(() => parseServiceNowAccessRequestResponse(201, "<html>")).toThrow(BadRequestError);
+ expect(() => parseServiceNowAccessRequestResponse(409, { success: false })).toThrow(UnrecoverableError);
+ });
+});
+
+describe("toServiceNowDispatchError", () => {
+ test.each([
+ [302, UnrecoverableError, /credentials/],
+ [401, UnrecoverableError, /credentials/],
+ [403, UnrecoverableError, /credentials/],
+ [404, UnrecoverableError, /Infisical Approvals application/],
+ [400, UnrecoverableError, /rejected the request \(HTTP 400\)/],
+ [422, UnrecoverableError, /rejected the request \(HTTP 422\)/],
+ [429, BadRequestError, /rate limiting/],
+ [500, BadRequestError, /server error \(HTTP 500\)/],
+ [503, BadRequestError, /server error \(HTTP 503\)/]
+ ])("maps HTTP %s", (status, errorClass, message) => {
+ const error = toServiceNowDispatchError(makeAxiosError(status), INSTANCE_URL);
+
+ expect(error).toBeInstanceOf(errorClass);
+ expect(error.message).toMatch(message);
+ expect(error.message).toContain("acme.service-now.com");
+ });
+
+ test("includes the detail ServiceNow returned on a validation failure", () => {
+ const error = toServiceNowDispatchError(
+ makeAxiosError(400, { result: { error: "Missing required field: environment" } }),
+ INSTANCE_URL
+ );
+
+ expect(error.message).toContain("Missing required field: environment");
+ });
+
+ test("retries when there was no response at all", () => {
+ const error = toServiceNowDispatchError(makeAxiosError(undefined, undefined, "ECONNABORTED"), INSTANCE_URL);
+
+ expect(error).toBeInstanceOf(BadRequestError);
+ expect(error.message).toMatch(/could not be reached \(ECONNABORTED\)/);
+ });
+
+ test("never echoes the request path, credentials or token", () => {
+ const error = toServiceNowDispatchError(makeAxiosError(401), INSTANCE_URL);
+
+ expect(error.message).not.toContain("x_infis_approvals");
+ expect(error.message).not.toContain(CALLBACK_TOKEN);
+ });
+});
diff --git a/backend/src/services/delegated-approval/dispatch/providers/servicenow/servicenow-fns.ts b/backend/src/services/delegated-approval/dispatch/providers/servicenow/servicenow-fns.ts
new file mode 100644
index 0000000000..3247f3cc8f
--- /dev/null
+++ b/backend/src/services/delegated-approval/dispatch/providers/servicenow/servicenow-fns.ts
@@ -0,0 +1,238 @@
+import { AxiosError } 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 "../../../delegated-approval-enums";
+import {
+ TDelegatedApprovalDispatchDetails,
+ TDelegatedApprovalDispatchInput,
+ TDelegatedApprovalProvider
+} from "../../delegated-approval-dispatch-types";
+import {
+ SERVICENOW_ACCESS_REQUEST_PATH,
+ SERVICENOW_DISPATCH_MAX_CONTENT_LENGTH,
+ SERVICENOW_DISPATCH_TIMEOUT_MS,
+ SERVICENOW_ERROR_DETAIL_MAX_CHARS,
+ SERVICENOW_EVENT_MAP
+} from "./servicenow-constants";
+import {
+ ServiceNowAccessRequestPayloadSchema,
+ ServiceNowAccessRequestResponseSchema,
+ ServiceNowErrorResponseSchema
+} from "./servicenow-schemas";
+import {
+ TServiceNowAccessRequestOutcome,
+ TServiceNowAccessRequestPayload,
+ TServiceNowAccessRequestRecord
+} from "./servicenow-types";
+
+const describeInstance = (instanceUrl: string) => {
+ try {
+ return new URL(instanceUrl).host;
+ } catch {
+ return "the configured instance";
+ }
+};
+
+const isServiceNowConnection = (connection: TAppConnection): connection is TServiceNowConnection =>
+ connection.app === AppConnection.ServiceNow;
+
+const buildRequestTypeFields = (details: TDelegatedApprovalDispatchDetails) => {
+ switch (details.policyType) {
+ case ApprovalPolicyType.SecretAccess:
+ return {
+ 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 { event, requestType } = SERVICENOW_EVENT_MAP[input.details.policyType];
+
+ const parsed = ServiceNowAccessRequestPayloadSchema.safeParse({
+ request_id: input.approvalRequestId,
+ callback_url: input.callback.url,
+ callback_token: input.callback.token,
+ event,
+ request_type: requestType,
+ 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(data);
+ let record: TServiceNowAccessRequestRecord | null = null;
+ if (parsed.success) {
+ record = "result" in parsed.data ? parsed.data.result : parsed.data;
+ }
+
+ if (status === 409) {
+ if (!record) {
+ throw new UnrecoverableError(
+ "ServiceNow reported that it already holds this request but did not return the record ID."
+ );
+ }
+ return { sysId: record.sys_id, duplicate: true };
+ }
+
+ if (!record) {
+ throw new BadRequestError({
+ message: "ServiceNow accepted the request but returned a response without the record ID."
+ });
+ }
+
+ return { sysId: record.sys_id, duplicate: false };
+};
+
+const extractErrorDetail = (data: unknown) => {
+ const parsed = ServiceNowErrorResponseSchema.safeParse(data);
+ if (!parsed.success) return null;
+
+ const error = "result" in parsed.data ? parsed.data.result.error : parsed.data.error;
+ 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 toServiceNowDispatchError = (err: unknown, instanceUrl: string) => {
+ 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(
+ `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) {
+ return new BadRequestError({
+ message: `ServiceNow instance ${instance} is rate limiting requests from Infisical (HTTP 429).`
+ });
+ }
+
+ return new BadRequestError({
+ message: `ServiceNow instance ${instance} returned a server error (HTTP ${status}).`
+ });
+};
+
+export const servicenowProviderFactory = (): TDelegatedApprovalProvider => {
+ const dispatch: TDelegatedApprovalProvider["dispatch"] = async (input, connection) => {
+ if (!isServiceNowConnection(connection)) {
+ throw new UnrecoverableError(`App Connection with ID '${connection.id}' is not a ServiceNow Connection.`);
+ }
+
+ const { instanceUrl, username, password } = 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, {
+ auth: { username, password },
+ headers: { Accept: "application/json", "Content-Type": "application/json" },
+ timeout: SERVICENOW_DISPATCH_TIMEOUT_MS,
+ maxContentLength: SERVICENOW_DISPATCH_MAX_CONTENT_LENGTH,
+ validateStatus: (code) => (code >= 200 && code < 300) || code === 409,
+ "axios-retry": { retries: 0 }
+ });
+ status = response.status;
+ data = response.data;
+ } catch (error) {
+ // safeRequest's own refusals (private IP, unresolvable host, credentials in the URL) already
+ // name what is wrong.
+ if (error instanceof BadRequestError) throw error;
+
+ const responseStatus = error instanceof AxiosError ? error.response?.status : undefined;
+ const code = error instanceof AxiosError ? error.code : undefined;
+
+ // The raw error is deliberately not logged: it carries the password at config.auth.password and
+ // the callback token in config.data.
+ logger.warn(
+ {
+ status: responseStatus,
+ code,
+ message: (error as Error)?.message,
+ instanceUrl: sanitizeUrlForLog(instanceUrl)
+ },
+ `Failed to send delegated approval request to ServiceNow [delegatedRequestId=${input.delegatedRequestId}] [approvalRequestId=${input.approvalRequestId}] [connectionId=${connection.id}] [status=${responseStatus ?? "none"}]`
+ );
+
+ throw toServiceNowDispatchError(error, instanceUrl);
+ }
+
+ 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}]`
+ );
+ }
+
+ return { providerRequestId: outcome.sysId, duplicate: outcome.duplicate };
+ };
+
+ return {
+ type: DelegatedApprovalPolicyType.ServiceNow,
+ app: AppConnection.ServiceNow,
+ dispatch
+ };
+};
diff --git a/backend/src/services/delegated-approval/dispatch/providers/servicenow/servicenow-schemas.ts b/backend/src/services/delegated-approval/dispatch/providers/servicenow/servicenow-schemas.ts
new file mode 100644
index 0000000000..15fa827999
--- /dev/null
+++ b/backend/src/services/delegated-approval/dispatch/providers/servicenow/servicenow-schemas.ts
@@ -0,0 +1,46 @@
+import { z } from "zod";
+
+import { ServiceNowRequestType } from "./servicenow-enums";
+
+// Mirrors what the Infisical Approvals ServiceNow application accepts, so a request that would be
+// rejected there fails here with the field named instead of as an opaque 400.
+export const ServiceNowAccessRequestPayloadSchema = z.object({
+ request_id: z.string().min(1).max(255),
+ callback_url: z
+ .string()
+ .max(1000)
+ .url()
+ .refine((value) => value.startsWith("https://"), "Callback URL must use HTTPS"),
+ callback_token: z.string().min(1).max(1000),
+ event: z.string().min(1).max(255),
+ request_type: z.nativeEnum(ServiceNowRequestType),
+ product_type: z.string().min(1).max(100),
+ project_id: z.string().min(1).max(255),
+ project_name: z.string().min(1).max(255),
+ environment: z.string().min(1).max(100),
+ requestor_email: z.string().min(1).max(255),
+ secret_path: z.string().optional(),
+ permissions: z.string().array().optional(),
+ requestor_name: z.string().min(1).max(255).optional(),
+ is_temporary: z.boolean().optional(),
+ temporary_range: z.string().min(1).max(50).optional(),
+ justification: z.string().optional()
+});
+
+export const ServiceNowAccessRequestRecordSchema = z.object({
+ success: z.boolean().optional(),
+ request_number: z.string().nullish(),
+ sys_id: z.string().min(1),
+ error: z.unknown().optional()
+});
+
+// Scripted REST responses may arrive bare or wrapped in the platform's `result` envelope.
+export const ServiceNowAccessRequestResponseSchema = z.union([
+ z.object({ result: ServiceNowAccessRequestRecordSchema }),
+ ServiceNowAccessRequestRecordSchema
+]);
+
+export const ServiceNowErrorResponseSchema = z.union([
+ z.object({ result: z.object({ error: z.unknown().optional() }) }),
+ z.object({ error: z.unknown().optional() })
+]);
diff --git a/backend/src/services/delegated-approval/dispatch/providers/servicenow/servicenow-types.ts b/backend/src/services/delegated-approval/dispatch/providers/servicenow/servicenow-types.ts
new file mode 100644
index 0000000000..331ed62fea
--- /dev/null
+++ b/backend/src/services/delegated-approval/dispatch/providers/servicenow/servicenow-types.ts
@@ -0,0 +1,12 @@
+import { z } from "zod";
+
+import { ServiceNowAccessRequestPayloadSchema, ServiceNowAccessRequestRecordSchema } from "./servicenow-schemas";
+
+export type TServiceNowAccessRequestPayload = z.infer<typeof ServiceNowAccessRequestPayloadSchema>;
+
+export type TServiceNowAccessRequestRecord = z.infer<typeof ServiceNowAccessRequestRecordSchema>;
+
+export type TServiceNowAccessRequestOutcome = {
+ sysId: string;
+ duplicate: boolean;
+};
diff --git a/backend/src/services/project/project-service.ts b/backend/src/services/project/project-service.ts
index bccf3e83b6..e1d450fa2c 100644
--- a/backend/src/services/project/project-service.ts
+++ b/backend/src/services/project/project-service.ts
@@ -971,6 +971,9 @@ export const projectServiceFactory = ({
return projects.map(({ id, orgId, name, slug, type }) => ({ id, orgId, name, slug, type }));
};
+ // For background work that has no actor. It performs no authorization, so it must not back a route.
+ const findProjectById = (projectId: string) => projectDAL.findById(projectId);
+
const getAProject = async ({ actorId, actorOrgId, actorAuthMethod, filter, actor }: TGetProjectDTO) => {
const project = await projectDAL.findProjectByFilter(filter);
@@ -2376,6 +2379,7 @@ export const projectServiceFactory = ({
getAccessibleProjectsWithSubOrgs,
updateProject,
getProjectUpgradeStatus,
+ findProjectById,
getAProject,
toggleAutoCapitalization,
toggleDeleteProtection,
diff --git a/backend/src/services/secret-access-approval-global-request-bridge/secret-access-approval-global-request-bridge-service.ts b/backend/src/services/secret-access-approval-global-request-bridge/secret-access-approval-global-request-bridge-service.ts
index ce9ad288ed..52299a149a 100644
--- a/backend/src/services/secret-access-approval-global-request-bridge/secret-access-approval-global-request-bridge-service.ts
+++ b/backend/src/services/secret-access-approval-global-request-bridge/secret-access-approval-global-request-bridge-service.ts
@@ -30,6 +30,7 @@ import {
} from "@app/services/approval-policy/secret-access/secret-access-policy-fns";
import { TSecretAccessRequestData } from "@app/services/approval-policy/secret-access/secret-access-policy-types";
import { ActorType } from "@app/services/auth/auth-type";
+import { TDelegatedApprovalRequest } from "@app/services/delegated-approval/delegated-approval-types";
import { AccessRequestWebhookAction, WebhookEvents } from "@app/services/webhook/webhook-types";
import {
@@ -70,7 +71,8 @@ export const secretAccessApprovalGlobalRequestBridgeServiceFactory = ({
additionalPrivilegeDAL,
secretAccessApprovalGlobalPolicyBridgeDAL,
secretAccessApprovalGlobalRequestBridgeDAL,
- delegatedApprovalPolicyDAL,
+ delegatedApprovalService,
+ delegatedApprovalDispatchQueue,
smtpService,
notificationService,
kmsService,
@@ -292,11 +294,9 @@ export const secretAccessApprovalGlobalRequestBridgeServiceFactory = ({
]);
if (!requestedByUser) throw new ForbiddenRequestError({ message: "User not found" });
if (!project) throw new NotFoundError({ message: `Project with ID '${projectId}' not found` });
- if (!policy.steps.length) {
- const delegatedPolicy = await delegatedApprovalPolicyDAL.findOne({ policyId: policy.id });
- if (!delegatedPolicy) {
- throw new BadRequestError({ message: `Policy '${policy.name}' has no approvers configured` });
- }
+ const delegatedPolicy = policy.steps.length ? null : await delegatedApprovalService.getPolicyByPolicyId(policy.id);
+ if (!policy.steps.length && !delegatedPolicy) {
+ throw new BadRequestError({ message: `Policy '${policy.name}' has no approvers configured` });
}
const activeGrant = await secretAccessApprovalGlobalResource.canAccess(projectId, requestedByUserId, {
@@ -324,6 +324,7 @@ export const secretAccessApprovalGlobalRequestBridgeServiceFactory = ({
const parsedMs = requestExpirationTime ? ms(requestExpirationTime) : null;
const expiresAt = parsedMs && !Number.isNaN(parsedMs) ? new Date(Date.now() + parsedMs) : null;
+ let delegatedRequest: TDelegatedApprovalRequest | undefined;
const created = await approvalRequestDAL.transaction((tx) =>
createApprovalRequestWithSteps(
{
@@ -341,10 +342,19 @@ export const secretAccessApprovalGlobalRequestBridgeServiceFactory = ({
requesterEmail: requestedByUser.email || requestedByUser.username
},
{ approvalRequestDAL, approvalRequestStepsDAL, approvalRequestStepEligibleApproversDAL },
- tx
+ tx,
+ delegatedPolicy
+ ? async (approvalRequest, trx) => {
+ delegatedRequest = await delegatedApprovalService.createRequest({ approvalRequest }, trx);
+ }
+ : undefined
)
);
+ if (delegatedRequest) {
+ await delegatedApprovalDispatchQueue.queueDispatch({ delegatedRequestId: delegatedRequest.id });
+ }
+
const request = await $findRequestById(created.id);
const [firstStep] = policy.steps;
if (firstStep) {
diff --git a/backend/src/services/secret-access-approval-global-request-bridge/secret-access-approval-global-request-bridge-types.ts b/backend/src/services/secret-access-approval-global-request-bridge/secret-access-approval-global-request-bridge-types.ts
index b2a0759044..64af143a0b 100644
--- a/backend/src/services/secret-access-approval-global-request-bridge/secret-access-approval-global-request-bridge-types.ts
+++ b/backend/src/services/secret-access-approval-global-request-bridge/secret-access-approval-global-request-bridge-types.ts
@@ -15,7 +15,8 @@ import {
} from "@app/services/approval-policy/approval-request-dal";
import { TSecretAccessApprovalGlobalResource } from "@app/services/approval-policy/secret-access/secret-access-policy-factory";
import { TSecretAccessPolicy } from "@app/services/approval-policy/secret-access/secret-access-policy-types";
-import { TDelegatedApprovalPolicyDALFactory } from "@app/services/delegated-approval/delegated-approval-policy-dal";
+import { TDelegatedApprovalServiceFactory } from "@app/services/delegated-approval/delegated-approval-service";
+import { TDelegatedApprovalDispatchQueueFactory } from "@app/services/delegated-approval/dispatch/delegated-approval-dispatch-queue";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { TMicrosoftTeamsServiceFactory } from "@app/services/microsoft-teams/microsoft-teams-service";
import { TProjectMicrosoftTeamsConfigDALFactory } from "@app/services/microsoft-teams/project-microsoft-teams-config-dal";
@@ -60,7 +61,8 @@ export type TSecretAccessApprovalGlobalRequestBridgeServiceFactoryDep = {
| "findUsersByIds"
| "findOrgMembershipActivity"
>;
- delegatedApprovalPolicyDAL: Pick<TDelegatedApprovalPolicyDALFactory, "findOne">;
+ delegatedApprovalService: Pick<TDelegatedApprovalServiceFactory, "getPolicyByPolicyId" | "createRequest">;
+ delegatedApprovalDispatchQueue: Pick<TDelegatedApprovalDispatchQueueFactory, "queueDispatch">;
smtpService: Pick<TSmtpService, "sendMail">;
notificationService: Pick<TNotificationServiceFactory, "createUserNotifications">;
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;