Skip to content

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

add the call to external systems so it is possible to fetch the decision stored there

adilsonc1064268e0b5
diff --git a/CLAUDE.md b/CLAUDE.md
index aa387f9a54..35418e6857 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -178,7 +178,7 @@ no Infisical approvers, so `POST /api/v1/access-approvals/requests/:requestId/ca
one from Infisical: the requester, or anyone who can edit the policy, sets it `cancelled`, which is also how a
policy blocked by pending requests is freed for editing. Every provider implements `TDelegatedApprovalProvider` against the same
`TDelegatedApprovalDispatchInput` and registers in `DELEGATED_APPROVAL_PROVIDER_MAP`
-(`dispatch/providers/<name>/`); a new policy type adds an arm to `TDelegatedApprovalDispatchDetails` and a
+(`delegated-approval/providers/<name>/`); a new policy type adds an arm to `TDelegatedApprovalDispatchDetails` and a
builder in `DELEGATED_APPROVAL_DISPATCH_DETAILS_BUILDER_MAP` rather than branching in a provider. The consumer
reads from the primary, never checks the license, and treats bullmq's `UnrecoverableError` as the terminal failure
signal, returning `Failed` for it and `Retry` for anything else. The callback contract (token issuance now, the inbound route and approve / reject later) is its own
@@ -194,9 +194,23 @@ the body carries no decision, which a later worker reads back from the provider.
wrong token for a known record still burns the request, and on the sixth callback sets the row `failed` with a
readable `statusReason` and cancels the attached approval request in the same transaction, so the policy is freed
and the UI stops offering Cancel. Every other refusal (bad or missing token, request not `waiting_approval`)
-gets one neutral 403 while the reason goes to the log. An accepted callback only emits an outbox event: `eventType` is the body's event,
-`idempotencyKey` is the delegated request id so a repeat is dropped, and the `delegated-approval-callback`
-consumer is a placeholder that marks the row delivered until the read-back worker replaces it.
+gets one neutral 403 while the reason goes to the log. An accepted callback only emits an outbox event: `eventType` is the body's event and
+`idempotencyKey` is the delegated request id plus the attempt count, so a repeat of one delivery is dropped
+while a fresh notification after an earlier read-back ran out of retries is not. The
+`delegated-approval-decision` consumer (`backend/src/services/delegated-approval-decision/`, a thin outbox
+adapter over `delegatedApprovalDecisionService.applyDecision`) then reads the decision back through the
+policy's app connection: `TDelegatedApprovalProvider.fetchDecision` returns `pending` or a decision with
+the permissions the provider holds, and the consumer answers `Retry` for `pending`, compares the approved
+permissions with the ones it dispatched after both go through `normalizeDelegatedApprovalPermissions` (set
+comparison: padding, order, duplicates and case never count as a change), and finalizes in one transaction
+that locks the approval request, moves the delegated row `waiting_approval` → `approved` / `rejected`, and
+runs the policy type's `postApprovalTxRoutine` from `approvalResources`. A mismatch, a record for another
+request, or any other `UnrecoverableError` goes through `failDelegatedApprovalRequest`: the delegated row
+becomes `failed` with a readable `statusReason`, the approval request is cancelled, and nothing can retry
+it. Every outcome is audited as `ACCESS_APPROVAL_REQUEST_DELEGATED_DECISION` with the `PLATFORM` actor, and
+product notifications (the access request webhook) go through `decisionNotifiers`, never through the
+consumer itself. ServiceNow stamps an immutable `decision` on its record before it posts the callback, so
+the provider reads that field alone and ignores `state`.
### API Layer (Frontend)
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.md
index 1d82e1bd92..579b49833b 100644
--- a/backend/CLAUDE.md
+++ b/backend/CLAUDE.md
@@ -836,7 +836,9 @@ await someDAL.transaction(async (tx) => {
- **Discovery only looks at consumers registered in this process.** A row for any other name has nowhere
to go here. It waits and shows up on the oldest-pending gauge instead.
- **Don't let one event's failure escape `handle`.** The outbox retries the whole batch when `handle`
- throws. Catch per event and report `Retry` for that event alone (see `alert-event-consumer.ts`).
+ throws. Catch per event and report `Retry` for that event alone: `runEventsSerially` and
+ `parseEventPayload` in `event-outbox-fns.ts` are that loop and the payload check, and every consumer
+ uses them rather than its own copy.
- **BullMQ owns latency, not correctness.** `attempts: 1` on the flush job is intentional; retry lives
on the row. A lost job costs one relay interval.
- **The relay is a `setInterval`, not a cron job.** It doesn't need exactly-once (`FOR UPDATE SKIP
diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.ts
index fff506f0d9..482e60cda7 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -854,6 +854,7 @@ export enum EventType {
ACCESS_APPROVAL_REQUEST_REVIEW = "access-approval-request-review",
ACCESS_APPROVAL_REQUEST_REVOKE = "access-approval-request-revoke",
ACCESS_APPROVAL_REQUEST_DELEGATED_DISPATCH_RETRY = "access-approval-request-delegated-dispatch-retry",
+ ACCESS_APPROVAL_REQUEST_DELEGATED_DECISION = "access-approval-request-delegated-decision",
ACCESS_APPROVAL_REQUEST_CANCEL = "access-approval-request-cancel",
ACCESS_APPROVAL_REQUEST_UPDATE = "access-approval-request-update",
VIEW_AUDIT_LOGS = "view-audit-logs",
@@ -7185,6 +7186,22 @@ interface AccessApprovalRequestDelegatedDispatchRetryEvent {
};
}
+interface AccessApprovalRequestDelegatedDecisionEvent {
+ type: EventType.ACCESS_APPROVAL_REQUEST_DELEGATED_DECISION;
+ metadata: {
+ requestId: string;
+ policyId: string;
+ delegatedApprovalType: string;
+ providerRequestId: string;
+ outcome: string;
+ decision?: string;
+ decidedBy?: string;
+ decidedAt?: string;
+ decisionNotes?: string;
+ reason?: string;
+ };
+}
+
interface AccessApprovalRequestCancelEvent {
type: EventType.ACCESS_APPROVAL_REQUEST_CANCEL;
metadata: {
@@ -8683,6 +8700,7 @@ export type Event =
| AccessApprovalRequestReviewEvent
| AccessApprovalRequestRevokeEvent
| AccessApprovalRequestDelegatedDispatchRetryEvent
+ | AccessApprovalRequestDelegatedDecisionEvent
| AccessApprovalRequestCancelEvent
| AccessApprovalRequestUpdateEvent
| CreateAcmeAccountEvent
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 9581b7b846..41c809692c 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -359,6 +359,8 @@ import { delegatedApprovalRequestDALFactory } from "@app/services/delegated-appr
import { delegatedApprovalServiceFactory } from "@app/services/delegated-approval/delegated-approval-service";
import { delegatedApprovalDispatchConsumerFactory } from "@app/services/delegated-approval/dispatch/delegated-approval-dispatch-consumer";
import { delegatedApprovalCallbackServiceFactory } from "@app/services/delegated-approval-callback/delegated-approval-callback-service";
+import { delegatedApprovalDecisionConsumerFactory } from "@app/services/delegated-approval-decision/delegated-approval-decision-consumer";
+import { delegatedApprovalDecisionServiceFactory } from "@app/services/delegated-approval-decision/delegated-approval-decision-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";
@@ -1214,7 +1216,6 @@ export const registerRoutes = async (
alertProviderRegistry
})
);
- eventOutboxRegistry.register(delegatedApprovalCallbackEventConsumerFactory());
const eventOutboxService = eventOutboxServiceFactory({ eventOutboxDAL, eventOutboxRegistry });
const eventOutboxQueue = eventOutboxQueueFactory({
queueService,
@@ -3294,6 +3295,22 @@ export const registerRoutes = async (
secretAccessApprovalGlobalResource
});
+ const delegatedApprovalDecisionService = delegatedApprovalDecisionServiceFactory({
+ delegatedApprovalRequestDAL,
+ delegatedApprovalPolicyDAL,
+ approvalRequestDAL,
+ appConnectionDAL,
+ kmsService,
+ auditLogService,
+ approvalResources: { [ApprovalPolicyType.SecretAccess]: secretAccessApprovalGlobalResource },
+ decisionNotifiers: {
+ // maybe we can have it in a better place
+ [ApprovalPolicyType.SecretAccess]: ({ approvalRequestId }) =>
+ secretAccessApprovalGlobalRequestBridgeService.notifyDelegatedDecision({ requestId: approvalRequestId })
+ }
+ });
+ eventOutboxRegistry.register(delegatedApprovalDecisionConsumerFactory({ delegatedApprovalDecisionService }));
+
const accessApprovalRequestService = accessApprovalRequestServiceFactory({
projectDAL,
permissionService,
diff --git a/backend/src/services/alert/alert-event-consumer.ts b/backend/src/services/alert/alert-event-consumer.ts
index 4765954f3c..c39a57ce6a 100644
--- a/backend/src/services/alert/alert-event-consumer.ts
+++ b/backend/src/services/alert/alert-event-consumer.ts
@@ -1,6 +1,7 @@
import { z } from "zod";
import { AlertDispatchOutcome, recordAlertDispatchOutcomeMetric } from "@app/lib/telemetry/metrics";
+import { runEventsSerially } from "@app/services/event-outbox/event-outbox-fns";
import {
EventResultStatus,
IEventConsumer,
@@ -128,20 +129,7 @@ export const alertEventConsumerFactory = ({
return lookup;
};
- const results: TEventConsumerResult[] = [];
-
- for (const event of events) {
- try {
- // eslint-disable-next-line no-await-in-loop -- ordering is the point
- results.push(await $handleEvent(event, findAlerts));
- } catch (error) {
- results.push({
- id: String(event.id),
- status: EventResultStatus.Retry,
- error: error instanceof Error ? error.message : "Unknown error"
- });
- }
- }
+ const results = await runEventsSerially(events, (event) => $handleEvent(event, findAlerts));
return results;
};
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
index 9cac38ac7b..2481cd3a28 100644
--- a/backend/src/services/delegated-approval-callback/delegated-approval-callback-constants.ts
+++ b/backend/src/services/delegated-approval-callback/delegated-approval-callback-constants.ts
@@ -12,8 +12,6 @@ export const DELEGATED_APPROVAL_CALLBACK_TOKEN_MAX_LENGTH = 256;
export const DELEGATED_APPROVAL_CALLBACK_MAX_ATTEMPTS = 5;
-export const DELEGATED_APPROVAL_CALLBACK_EVENT_CONSUMER = "delegated-approval-callback";
-
export const DELEGATED_APPROVAL_CALLBACK_REJECTED_MESSAGE = "Callback rejected.";
export const DELEGATED_APPROVAL_CALLBACK_ATTEMPTS_EXHAUSTED_REASON = `The delegated approval system called back more than ${DELEGATED_APPROVAL_CALLBACK_MAX_ATTEMPTS} times, so Infisical no longer accepts its decision for this request. Create the request again.`;
diff --git a/backend/src/services/delegated-approval-callback/delegated-approval-callback-event-consumer.test.ts b/backend/src/services/delegated-approval-callback/delegated-approval-callback-event-consumer.test.ts
deleted file mode 100644
index 0765afb577..0000000000
--- a/backend/src/services/delegated-approval-callback/delegated-approval-callback-event-consumer.test.ts
+++ /dev/null
@@ -1,67 +0,0 @@
-import { describe, expect, test, vi } from "vitest";
-
-import { EventResultStatus, TEvent } from "@app/services/event-outbox/event-outbox-types";
-
-import { DELEGATED_APPROVAL_CALLBACK_EVENT_CONSUMER } from "./delegated-approval-callback-constants";
-import { DelegatedApprovalCallbackEvent } from "./delegated-approval-callback-enums";
-import { delegatedApprovalCallbackEventConsumerFactory } from "./delegated-approval-callback-event-consumer";
-
-vi.mock("@app/lib/logger", () => ({
- logger: { info: () => {}, warn: () => {}, error: () => {}, debug: () => {} },
- initLogger: () => {}
-}));
-
-const makePayload = (overrides?: Record<string, unknown>) => ({
- delegatedRequestId: "11111111-1111-1111-1111-111111111111",
- approvalRequestId: "22222222-2222-2222-2222-222222222222",
- orgId: "33333333-3333-3333-3333-333333333333",
- event: DelegatedApprovalCallbackEvent.SecretsManagementAccessRequest,
- externalId: "9d41f2a7c3b24e1088f6a05e7b1d4c93",
- ...overrides
-});
-
-const makeEvent = (overrides?: Partial<TEvent>): TEvent =>
- ({
- id: 1,
- eventType: DelegatedApprovalCallbackEvent.SecretsManagementAccessRequest,
- payload: makePayload(),
- occurredAt: new Date(),
- ...overrides
- }) as TEvent;
-
-describe("delegatedApprovalCallbackEventConsumer", () => {
- const consumer = delegatedApprovalCallbackEventConsumerFactory();
-
- test("is registered under the callback consumer name", () => {
- expect(consumer.name).toBe(DELEGATED_APPROVAL_CALLBACK_EVENT_CONSUMER);
- });
-
- test("subscribes only to the callback events", () => {
- expect(consumer.subscribesTo(DelegatedApprovalCallbackEvent.SecretsManagementAccessRequest)).toBe(true);
- expect(consumer.subscribesTo("approval.workflow.request_opened")).toBe(false);
- });
-
- test("accepts a valid payload at emit", () => {
- expect(consumer.payloadSchema.safeParse(makePayload()).success).toBe(true);
- expect(consumer.payloadSchema.safeParse(makePayload({ orgId: "not-a-uuid" })).success).toBe(false);
- });
-
- test("marks a readable event delivered", async () => {
- const [result] = await consumer.handle([makeEvent()]);
-
- expect(result).toEqual({ id: "1", status: EventResultStatus.Delivered });
- });
-
- test("fails an unreadable payload instead of retrying it", async () => {
- const [result] = await consumer.handle([makeEvent({ payload: { delegatedRequestId: "nope" } })]);
-
- expect(result.status).toBe(EventResultStatus.Failed);
- expect(result.error).toContain("Unreadable");
- });
-
- test("returns one result per event", async () => {
- const results = await consumer.handle([makeEvent({ id: 1 }), makeEvent({ id: 2 } as never)]);
-
- expect(results.map((result) => result.id)).toEqual(["1", "2"]);
- });
-});
diff --git a/backend/src/services/delegated-approval-callback/delegated-approval-callback-event-consumer.ts b/backend/src/services/delegated-approval-callback/delegated-approval-callback-event-consumer.ts
deleted file mode 100644
index dc13d44081..0000000000
--- a/backend/src/services/delegated-approval-callback/delegated-approval-callback-event-consumer.ts
+++ /dev/null
@@ -1,64 +0,0 @@
-import { z } from "zod";
-
-import { logger } from "@app/lib/logger";
-import {
- EventResultStatus,
- IEventConsumer,
- TEvent,
- TEventConsumerResult
-} from "@app/services/event-outbox/event-outbox-types";
-
-import { DELEGATED_APPROVAL_CALLBACK_EVENT_CONSUMER } from "./delegated-approval-callback-constants";
-import { DelegatedApprovalCallbackEvent } from "./delegated-approval-callback-enums";
-
-export const DelegatedApprovalCallbackEventPayloadSchema = z.object({
- delegatedRequestId: z.string().uuid(),
- approvalRequestId: z.string().uuid(),
- orgId: z.string().uuid(),
- event: z.nativeEnum(DelegatedApprovalCallbackEvent),
- externalId: z.string().trim().min(1).max(255)
-});
-
-type TDelegatedApprovalCallbackEventPayload = z.infer<typeof DelegatedApprovalCallbackEventPayloadSchema>;
-
-const CALLBACK_EVENTS = new Set<string>(Object.values(DelegatedApprovalCallbackEvent));
-
-export const delegatedApprovalCallbackEventConsumerFactory =
- (): IEventConsumer<TDelegatedApprovalCallbackEventPayload> => {
- const subscribesTo = (eventType: string) => CALLBACK_EVENTS.has(eventType);
-
- // Placeholder until the worker that reads the decision back from the delegated approval system
- // exists. It only has to accept the row so the callback is recorded.
- const $handleEvent = (event: TEvent): TEventConsumerResult => {
- const id = String(event.id);
- const payload = DelegatedApprovalCallbackEventPayloadSchema.safeParse(event.payload);
- if (!payload.success) {
- return { id, status: EventResultStatus.Failed, error: "Unreadable delegated approval callback payload" };
- }
-
- logger.info(
- `Delegated approval callback event received; processing is not implemented yet [eventId=${id}] [delegatedRequestId=${payload.data.delegatedRequestId}] [event=${payload.data.event}]`
- );
- return { id, status: EventResultStatus.Delivered };
- };
-
- const handle = async (events: TEvent[]): Promise<TEventConsumerResult[]> =>
- events.map((event) => {
- try {
- return $handleEvent(event);
- } catch (error) {
- return {
- id: String(event.id),
- status: EventResultStatus.Retry,
- error: error instanceof Error ? error.message : "Unknown error"
- };
- }
- });
-
- return {
- name: DELEGATED_APPROVAL_CALLBACK_EVENT_CONSUMER,
- payloadSchema: DelegatedApprovalCallbackEventPayloadSchema,
- subscribesTo,
- handle
- };
- };
diff --git a/backend/src/services/delegated-approval-callback/delegated-approval-callback-events.ts b/backend/src/services/delegated-approval-callback/delegated-approval-callback-events.ts
new file mode 100644
index 0000000000..cdb053f3b1
--- /dev/null
+++ b/backend/src/services/delegated-approval-callback/delegated-approval-callback-events.ts
@@ -0,0 +1,18 @@
+import { z } from "zod";
+
+import { DelegatedApprovalCallbackEvent } from "./delegated-approval-callback-enums";
+
+// What the callback route emits once it has accepted a decision notification. The consumer that reads
+// the decision back lives in delegated-approval-decision; the contract stays with the emitter.
+export const DelegatedApprovalCallbackEventPayloadSchema = z.object({
+ delegatedRequestId: z.string().uuid(),
+ approvalRequestId: z.string().uuid(),
+ orgId: z.string().uuid(),
+ event: z.nativeEnum(DelegatedApprovalCallbackEvent),
+ externalId: z.string().trim().min(1).max(255)
+});
+
+export type TDelegatedApprovalCallbackEventPayload = z.infer<typeof DelegatedApprovalCallbackEventPayloadSchema>;
+
+export const isDelegatedApprovalCallbackEvent = (eventType: string): eventType is DelegatedApprovalCallbackEvent =>
+ (Object.values(DelegatedApprovalCallbackEvent) as string[]).includes(eventType);
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
index 7535e0f6eb..59cc713abd 100644
--- 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
@@ -14,38 +14,34 @@ import {
DELEGATED_APPROVAL_CALLBACK_TOKEN_PREFIX
} from "./delegated-approval-callback-constants";
// eslint-disable-next-line import/first
-import {
- generateDelegatedApprovalCallbackToken,
- isDelegatedApprovalCallbackTokenMatch,
- rejectDelegatedApprovalCallback
-} from "./delegated-approval-callback-fns";
+import { generateCallbackToken, isTokenMatch, rejectApprovalCallback } from "./delegated-approval-callback-fns";
-describe("generateDelegatedApprovalCallbackToken", () => {
+describe("generateCallbackToken", () => {
test("returns a prefixed base64url token of 32 random bytes", () => {
- const token = generateDelegatedApprovalCallbackToken();
+ const token = generateCallbackToken();
expect(token.startsWith(DELEGATED_APPROVAL_CALLBACK_TOKEN_PREFIX)).toBe(true);
const random = token.slice(DELEGATED_APPROVAL_CALLBACK_TOKEN_PREFIX.length);
expect(random).toMatch(/^[A-Za-z0-9_-]+$/);
expect(Buffer.from(random, "base64url")).toHaveLength(32);
- expect(generateDelegatedApprovalCallbackToken()).not.toBe(token);
+ expect(generateCallbackToken()).not.toBe(token);
});
});
-describe("isDelegatedApprovalCallbackTokenMatch", () => {
+describe("isTokenMatch", () => {
test("matches only the exact stored token", () => {
- const token = generateDelegatedApprovalCallbackToken();
+ const token = generateCallbackToken();
- expect(isDelegatedApprovalCallbackTokenMatch(token, token)).toBe(true);
- expect(isDelegatedApprovalCallbackTokenMatch(`${token}x`, token)).toBe(false);
- expect(isDelegatedApprovalCallbackTokenMatch(token.slice(0, -1), token)).toBe(false);
- expect(isDelegatedApprovalCallbackTokenMatch(generateDelegatedApprovalCallbackToken(), token)).toBe(false);
+ expect(isTokenMatch(token, token)).toBe(true);
+ expect(isTokenMatch(`${token}x`, token)).toBe(false);
+ expect(isTokenMatch(token.slice(0, -1), token)).toBe(false);
+ expect(isTokenMatch(generateCallbackToken(), token)).toBe(false);
});
});
-describe("rejectDelegatedApprovalCallback", () => {
+describe("rejectApprovalCallback", () => {
test("returns a 403 whose message never carries the reason", () => {
- const error = rejectDelegatedApprovalCallback("token mismatch", { delegatedRequestId: "delegated-1" });
+ const error = rejectApprovalCallback("token mismatch", { delegatedRequestId: "delegated-1" });
expect(error).toBeInstanceOf(ForbiddenRequestError);
expect(error.message).toBe(DELEGATED_APPROVAL_CALLBACK_REJECTED_MESSAGE);
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
index 7c2e450c2c..a3948313b3 100644
--- a/backend/src/services/delegated-approval-callback/delegated-approval-callback-fns.ts
+++ b/backend/src/services/delegated-approval-callback/delegated-approval-callback-fns.ts
@@ -1,56 +1,27 @@
import { crypto } from "@app/lib/crypto/cryptography";
import { ForbiddenRequestError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
-import { ApprovalRequestStatus } from "@app/services/approval-policy/approval-policy-enums";
-import { DelegatedApprovalRequestStatus } from "@app/services/delegated-approval/delegated-approval-enums";
-import { DELEGATED_APPROVAL_STATUS_REASON_MAX_CHARS } from "@app/services/delegated-approval/dispatch/delegated-approval-dispatch-constants";
import {
- DELEGATED_APPROVAL_CALLBACK_ATTEMPTS_EXHAUSTED_REASON,
DELEGATED_APPROVAL_CALLBACK_REJECTED_MESSAGE,
DELEGATED_APPROVAL_CALLBACK_TOKEN_BYTES,
DELEGATED_APPROVAL_CALLBACK_TOKEN_PREFIX
} from "./delegated-approval-callback-constants";
-import { TFailExhaustedDelegatedApprovalRequestDTO } from "./delegated-approval-callback-types";
-export const generateDelegatedApprovalCallbackToken = () =>
+export const generateCallbackToken = () =>
`${DELEGATED_APPROVAL_CALLBACK_TOKEN_PREFIX}${crypto.randomBytes(DELEGATED_APPROVAL_CALLBACK_TOKEN_BYTES).toString("base64url")}`;
-export const isDelegatedApprovalCallbackTokenMatch = (presented: string, stored: string) => {
+export const isTokenMatch = (presented: string, stored: string) => {
const presentedBytes = Buffer.from(presented);
const storedBytes = Buffer.from(stored);
if (presentedBytes.length !== storedBytes.length) return false;
return crypto.nativeCrypto.timingSafeEqual(presentedBytes, storedBytes);
};
-export const rejectDelegatedApprovalCallback = (reason: string, context: Record<string, string>) => {
+export const rejectApprovalCallback = (reason: string, context: Record<string, string>) => {
const formatted = Object.entries(context)
.map(([key, value]) => `[${key}=${value}]`)
.join(" ");
logger.warn(`Delegated approval callback rejected: ${reason} ${formatted}`);
return new ForbiddenRequestError({ message: DELEGATED_APPROVAL_CALLBACK_REJECTED_MESSAGE });
};
-
-export const failExhaustedDelegatedApprovalRequest = ({
- id,
- requestId,
- approvalRequestDAL,
- delegatedApprovalRequestDAL
-}: TFailExhaustedDelegatedApprovalRequestDTO) =>
- approvalRequestDAL.transaction(async (tx) => {
- const approvalRequest = await approvalRequestDAL.findByIdForUpdate(requestId, tx);
- if (approvalRequest?.status === ApprovalRequestStatus.Pending) {
- await approvalRequestDAL.updateById(requestId, { status: ApprovalRequestStatus.Cancelled }, tx);
- }
- await delegatedApprovalRequestDAL.update(
- { id, status: DelegatedApprovalRequestStatus.WaitingApproval },
- {
- status: DelegatedApprovalRequestStatus.Failed,
- statusReason: DELEGATED_APPROVAL_CALLBACK_ATTEMPTS_EXHAUSTED_REASON.slice(
- 0,
- DELEGATED_APPROVAL_STATUS_REASON_MAX_CHARS
- )
- },
- tx
- );
- });
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
index 13ef232356..aaa4686f37 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
@@ -40,8 +40,8 @@ const makeService = ({
currentRow = null
}: { stored?: boolean; currentRow?: { encryptedCallbackToken: Buffer | null } | null } = {}) => {
const delegatedApprovalRequestDAL = {
- update: vi.fn(async () => (stored ? [{ id: "delegated-1" }] : [])),
- primaryNode: vi.fn(() => ({})),
+ update: vi.fn(async (_filter: unknown, patch: object) => (stored ? [{ id: "delegated-1", ...patch }] : [])),
+ transaction: vi.fn(async (cb: (tx: unknown) => Promise<unknown>) => cb(TX)),
findById: vi.fn(async () => currentRow),
findByProviderRequestId: vi.fn(async (): Promise<unknown> => null)
};
@@ -92,7 +92,8 @@ describe("getOrIssueCallbackToken", () => {
});
expect(delegatedApprovalRequestDAL.update).toHaveBeenCalledWith(
{ id: "delegated-1", encryptedCallbackToken: null },
- { encryptedCallbackToken: encrypt(Buffer.from(token as string)) }
+ { encryptedCallbackToken: encrypt(Buffer.from(token as string)) },
+ TX
);
});
@@ -277,7 +278,7 @@ describe("handleCallback", () => {
});
expect(eventEmitter.emit).toHaveBeenCalledWith({
eventType: EVENT,
- idempotencyKey: "delegated-1",
+ idempotencyKey: "delegated-1:1",
payload: {
delegatedRequestId: "delegated-1",
approvalRequestId: "request-1",
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
index d2843aa270..5bac5ed8ee 100644
--- a/backend/src/services/delegated-approval-callback/delegated-approval-callback-service.ts
+++ b/backend/src/services/delegated-approval-callback/delegated-approval-callback-service.ts
@@ -2,21 +2,18 @@ import { getConfig } from "@app/lib/config/env";
import { NotFoundError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
import { DelegatedApprovalRequestStatus } from "@app/services/delegated-approval/delegated-approval-enums";
+import { failDelegatedApprovalRequest } from "@app/services/delegated-approval/delegated-approval-request-fns";
import { KmsDataKey } from "@app/services/kms/kms-types";
import {
+ DELEGATED_APPROVAL_CALLBACK_ATTEMPTS_EXHAUSTED_REASON,
DELEGATED_APPROVAL_CALLBACK_MAX_ATTEMPTS,
DELEGATED_APPROVAL_CALLBACK_PATH,
DELEGATED_APPROVAL_CALLBACK_TOKEN_PREFIX
} from "./delegated-approval-callback-constants";
+import { TDelegatedApprovalCallbackEventPayload } from "./delegated-approval-callback-events";
+import { generateCallbackToken, isTokenMatch, rejectApprovalCallback } from "./delegated-approval-callback-fns";
import {
- failExhaustedDelegatedApprovalRequest,
- generateDelegatedApprovalCallbackToken,
- isDelegatedApprovalCallbackTokenMatch,
- rejectDelegatedApprovalCallback
-} from "./delegated-approval-callback-fns";
-import {
- TDelegatedApprovalCallbackEventPayload,
TDelegatedApprovalCallbackServiceFactoryDep,
TGetOrIssueCallbackTokenDTO,
THandleDelegatedApprovalCallbackDTO
@@ -45,17 +42,16 @@ export const delegatedApprovalCallbackServiceFactory = ({
return decryptor({ cipherTextBlob: delegatedRequest.encryptedCallbackToken }).toString();
}
- const token = generateDelegatedApprovalCallbackToken();
- const [issued] = await delegatedApprovalRequestDAL.update(
- { id: delegatedRequest.id, encryptedCallbackToken: null },
- { encryptedCallbackToken: encryptor({ plainText: Buffer.from(token) }).cipherTextBlob }
- );
- if (issued) return token;
-
- const current = await delegatedApprovalRequestDAL.findById(
- delegatedRequest.id,
- delegatedApprovalRequestDAL.primaryNode()
- );
+ const token = generateCallbackToken();
+ const encryptedCallbackToken = encryptor({ plainText: Buffer.from(token) }).cipherTextBlob;
+ const current = await delegatedApprovalRequestDAL.transaction(async (tx) => {
+ const [issued] = await delegatedApprovalRequestDAL.update(
+ { id: delegatedRequest.id, encryptedCallbackToken: null },
+ { encryptedCallbackToken },
+ tx
+ );
+ return issued ?? delegatedApprovalRequestDAL.findById(delegatedRequest.id, tx);
+ });
if (!current?.encryptedCallbackToken) return null;
return decryptor({ cipherTextBlob: current.encryptedCallbackToken }).toString();
@@ -79,23 +75,25 @@ export const delegatedApprovalCallbackServiceFactory = ({
);
const attempts = counted?.callbackAttempts ?? delegatedRequest.callbackAttempts + 1;
if (attempts > DELEGATED_APPROVAL_CALLBACK_MAX_ATTEMPTS) {
- await failExhaustedDelegatedApprovalRequest({
- id: delegatedRequest.id,
- requestId: delegatedRequest.requestId,
- approvalRequestDAL,
- delegatedApprovalRequestDAL
- });
- throw rejectDelegatedApprovalCallback("callback attempts exhausted", {
+ await failDelegatedApprovalRequest(
+ {
+ id: delegatedRequest.id,
+ requestId: delegatedRequest.requestId,
+ reason: DELEGATED_APPROVAL_CALLBACK_ATTEMPTS_EXHAUSTED_REASON
+ },
+ { approvalRequestDAL, delegatedApprovalRequestDAL }
+ );
+ throw rejectApprovalCallback("callback attempts exhausted", {
...logContext,
attempts: String(attempts)
});
}
if (!token || !token.startsWith(DELEGATED_APPROVAL_CALLBACK_TOKEN_PREFIX)) {
- throw rejectDelegatedApprovalCallback("missing or malformed token", logContext);
+ throw rejectApprovalCallback("missing or malformed token", logContext);
}
if (!delegatedRequest.encryptedCallbackToken) {
- throw rejectDelegatedApprovalCallback("request has no callback token", logContext);
+ throw rejectApprovalCallback("request has no callback token", logContext);
}
const { decryptor } = await kmsService.createCipherPairWithDataKey({
@@ -103,12 +101,12 @@ export const delegatedApprovalCallbackServiceFactory = ({
orgId: delegatedRequest.approvalRequestOrganizationId
});
const storedToken = decryptor({ cipherTextBlob: delegatedRequest.encryptedCallbackToken }).toString();
- if (!isDelegatedApprovalCallbackTokenMatch(token, storedToken)) {
- throw rejectDelegatedApprovalCallback("token mismatch", logContext);
+ if (!isTokenMatch(token, storedToken)) {
+ throw rejectApprovalCallback("token mismatch", logContext);
}
if (delegatedRequest.status !== DelegatedApprovalRequestStatus.WaitingApproval) {
- throw rejectDelegatedApprovalCallback("request is not awaiting a decision", {
+ throw rejectApprovalCallback("request is not awaiting a decision", {
...logContext,
status: delegatedRequest.status
});
@@ -121,9 +119,7 @@ export const delegatedApprovalCallbackServiceFactory = ({
event,
externalId
};
- // No tx: the attempt counter is already committed and the outbox's (consumer, idempotencyKey)
- // index drops a repeat callback for the same request.
- await eventEmitter.emit({ eventType: event, idempotencyKey: delegatedRequest.id, payload });
+ await eventEmitter.emit({ eventType: event, idempotencyKey: `${delegatedRequest.id}:${attempts}`, payload });
logger.info(
`Delegated approval callback accepted [delegatedRequestId=${delegatedRequest.id}] [approvalRequestId=${delegatedRequest.requestId}] [event=${event}] [attempt=${attempts}]`
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
index 128655f4da..b21d0ea30d 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,16 +9,13 @@ import { DelegatedApprovalCallbackEvent } from "./delegated-approval-callback-en
export type TDelegatedApprovalCallbackServiceFactoryDep = {
delegatedApprovalRequestDAL: Pick<
TDelegatedApprovalRequestDALFactory,
- "findById" | "findByProviderRequestId" | "primaryNode" | "update"
+ "findById" | "findByProviderRequestId" | "transaction" | "update"
>;
approvalRequestDAL: Pick<TApprovalRequestDALFactory, "transaction" | "findByIdForUpdate" | "updateById">;
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
eventEmitter: Pick<TEventEmitter, "emit">;
};
-export type TFailExhaustedDelegatedApprovalRequestDTO = Pick<TDelegatedApprovalRequests, "id" | "requestId"> &
- Pick<TDelegatedApprovalCallbackServiceFactoryDep, "approvalRequestDAL" | "delegatedApprovalRequestDAL">;
-
export type TGetOrIssueCallbackTokenDTO = {
delegatedRequest: Pick<TDelegatedApprovalRequests, "id" | "encryptedCallbackToken">;
orgId: string;
@@ -29,11 +26,3 @@ export type THandleDelegatedApprovalCallbackDTO = {
event: DelegatedApprovalCallbackEvent;
externalId: string;
};
-
-export type TDelegatedApprovalCallbackEventPayload = {
- delegatedRequestId: string;
- approvalRequestId: string;
- orgId: string;
- event: DelegatedApprovalCallbackEvent;
- externalId: string;
-};
diff --git a/backend/src/services/delegated-approval-decision/delegated-approval-decision-constants.ts b/backend/src/services/delegated-approval-decision/delegated-approval-decision-constants.ts
new file mode 100644
index 0000000000..bf96eaa113
--- /dev/null
+++ b/backend/src/services/delegated-approval-decision/delegated-approval-decision-constants.ts
@@ -0,0 +1,4 @@
+export const DELEGATED_APPROVAL_DECISION_CONSUMER = "delegated-approval-decision";
+
+export const DELEGATED_APPROVAL_DECISION_RETRY_HINT =
+ "Infisical will check again automatically. If this does not change, send the decision again from the delegated approval system.";
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.ts
new file mode 100644
index 0000000000..752a8f7d70
--- /dev/null
+++ b/backend/src/services/delegated-approval-decision/delegated-approval-decision-consumer.test.ts
@@ -0,0 +1,508 @@
+import { UnrecoverableError } from "bullmq";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+
+import { TEventOutbox } from "@app/db/schemas";
+import { ApprovalPolicyType, ApprovalRequestStatus } from "@app/services/approval-policy/approval-policy-enums";
+import {
+ DelegatedApprovalPolicyType,
+ DelegatedApprovalRequestStatus
+} from "@app/services/delegated-approval/delegated-approval-enums";
+import { DelegatedApprovalCallbackEvent } from "@app/services/delegated-approval-callback/delegated-approval-callback-enums";
+import { eventOutboxRegistryFactory } from "@app/services/event-outbox/event-outbox-registry";
+import { eventOutboxServiceFactory } from "@app/services/event-outbox/event-outbox-service";
+import { EventOutboxStatus, EventResultStatus, TEvent } from "@app/services/event-outbox/event-outbox-types";
+
+import { DELEGATED_APPROVAL_DECISION_RETRY_HINT } from "./delegated-approval-decision-constants";
+import { delegatedApprovalDecisionConsumerFactory } from "./delegated-approval-decision-consumer";
+import { DelegatedApprovalDecision, DelegatedApprovalDecisionOutcome } from "./delegated-approval-decision-enums";
+import { delegatedApprovalDecisionServiceFactory } from "./delegated-approval-decision-service";
+import { TDelegatedApprovalDecisionReadResult } from "./delegated-approval-decision-types";
+
+vi.mock("@app/lib/logger", () => ({
+ logger: { info: () => {}, warn: () => {}, error: () => {}, debug: () => {} },
+ initLogger: () => {}
+}));
+
+vi.mock("@app/lib/telemetry/metrics", () => ({
+ recordEventOutboxLagMetric: () => {},
+ recordEventOutboxExhaustedMetric: () => {}
+}));
+
+const { fetchDecision } = vi.hoisted(() => ({ fetchDecision: vi.fn() }));
+vi.mock("@app/services/delegated-approval/dispatch/delegated-approval-dispatch-fns", () => ({
+ getDelegatedApprovalProvider: () => ({ fetchDecision }),
+ getDelegatedApprovalDispatchDetailsBuilder: () => () => ({
+ policyType: "secret-access",
+ environment: "dev",
+ secretPath: "/",
+ permissions: ["secrets: read, create", "secret-folders: edit"],
+ isTemporary: false,
+ temporaryRange: null
+ })
+}));
+
+vi.mock("@app/services/app-connection/app-connection-fns", () => ({
+ decryptAppConnection: async (connection: unknown) => connection
+}));
+
+const DELEGATED_REQUEST_ID = "11111111-1111-1111-1111-111111111111";
+const APPROVAL_REQUEST_ID = "33333333-3333-3333-3333-333333333333";
+const ORG_ID = "22222222-2222-2222-2222-222222222222";
+const EXTERNAL_ID = "snow-1";
+const TX = { tx: true } as never;
+const waitingDelegatedRequest = {
+ id: DELEGATED_REQUEST_ID,
+ requestId: APPROVAL_REQUEST_ID,
+ status: DelegatedApprovalRequestStatus.WaitingApproval,
+ statusReason: null as string | null,
+ providerRequestId: EXTERNAL_ID as string | null
+};
+
+type TDelegatedRow = typeof waitingDelegatedRequest;
+
+const pendingApprovalRequest = {
+ id: APPROVAL_REQUEST_ID,
+ policyId: "policy-1",
+ projectId: "project-1",
+ organizationId: ORG_ID,
+ type: ApprovalPolicyType.SecretAccess,
+ status: ApprovalRequestStatus.Pending as string,
+ expiresAt: null as Date | null
+};
+
+type TApprovalRow = typeof pendingApprovalRequest;
+
+const delegatedPolicy = {
+ id: "delegated-policy-1",
+ policyId: "policy-1",
+ type: DelegatedApprovalPolicyType.ServiceNow,
+ connectionId: "connection-1"
+};
+
+const decided = (
+ decision: DelegatedApprovalDecision,
+ overrides: Partial<Extract<TDelegatedApprovalDecisionReadResult, { status: "decided" }>> = {}
+): TDelegatedApprovalDecisionReadResult => ({
+ status: "decided",
+ decision,
+ approvalRequestId: APPROVAL_REQUEST_ID,
+ permissions: ["secrets: create, read", "secret-folders: edit"],
+ decidedBy: "Grace Hopper",
+ decidedAt: "2026-10-20 10:15:00",
+ notes: null,
+ ...overrides
+});
+
+const buildConsumer = ({
+ delegatedRequest = waitingDelegatedRequest as TDelegatedRow | null,
+ approvalRequest = pendingApprovalRequest as TApprovalRow | null,
+ policy = delegatedPolicy as typeof delegatedPolicy | null,
+ connection = { id: "connection-1", orgId: ORG_ID, app: "servicenow" } as { id: string; orgId: string } | null
+} = {}) => {
+ 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];
+ });
+
+ const updateById = vi.fn(async (_id: string, patch: Partial<TApprovalRow>) => {
+ approval = approval ? { ...approval, ...patch } : approval;
+ return approval;
+ });
+ const postApprovalTxRoutine = vi.fn(async () => ({ grantId: "grant-1" }));
+ const createAuditLog = vi.fn(async () => {});
+ const notify = vi.fn(async () => {});
+
+ const delegatedApprovalDecisionService = delegatedApprovalDecisionServiceFactory({
+ delegatedApprovalRequestDAL: {
+ findById: vi.fn(async () => row),
+ transaction: async (cb: (tx: never) => Promise<unknown>) => cb(TX),
+ update
+ },
+ delegatedApprovalPolicyDAL: { findOne: vi.fn().mockResolvedValue(policy) },
+ approvalRequestDAL: {
+ findById: vi.fn(async () => approval),
+ findByIdForUpdate: vi.fn(async () => approval),
+ updateById,
+ transaction: vi.fn(async (fn: (tx: unknown) => Promise<unknown>) => fn(TX))
+ },
+ appConnectionDAL: { findById: vi.fn().mockResolvedValue(connection) },
+ kmsService: { createCipherPairWithDataKey: vi.fn() },
+ auditLogService: { createAuditLog },
+ approvalResources: { [ApprovalPolicyType.SecretAccess]: { postApprovalTxRoutine } },
+ decisionNotifiers: { [ApprovalPolicyType.SecretAccess]: notify }
+ } as never);
+ const consumer = delegatedApprovalDecisionConsumerFactory({ delegatedApprovalDecisionService });
+
+ return {
+ consumer,
+ row: () => row,
+ approval: () => approval,
+ postApprovalTxRoutine,
+ createAuditLog,
+ notify,
+ updateById
+ };
+};
+
+const makeEvent = (overrides?: Partial<TEvent>): TEvent => ({
+ id: 1,
+ eventType: DelegatedApprovalCallbackEvent.SecretsManagementAccessRequest,
+ payload: {
+ delegatedRequestId: DELEGATED_REQUEST_ID,
+ approvalRequestId: APPROVAL_REQUEST_ID,
+ orgId: ORG_ID,
+ event: DelegatedApprovalCallbackEvent.SecretsManagementAccessRequest,
+ externalId: EXTERNAL_ID
+ },
+ occurredAt: new Date(),
+ ...overrides
+});
+
+const auditedWith = (createAuditLog: ReturnType<typeof vi.fn>, expected: Record<string, unknown>) => {
+ expect(createAuditLog).toHaveBeenCalledTimes(1);
+ expect(createAuditLog.mock.calls[0][0]).toMatchObject({
+ orgId: ORG_ID,
+ projectId: "project-1",
+ event: { metadata: { requestId: APPROVAL_REQUEST_ID, providerRequestId: EXTERNAL_ID, ...expected } }
+ });
+};
+
+beforeEach(() => {
+ fetchDecision.mockReset();
+});
+
+describe("delegatedApprovalDecisionConsumer", () => {
+ test("applies an approval: both rows move, the grant routine runs in the same transaction", async () => {
+ fetchDecision.mockResolvedValueOnce(decided(DelegatedApprovalDecision.Approved));
+ const { consumer, row, approval, postApprovalTxRoutine, createAuditLog, notify } = buildConsumer();
+
+ const results = await consumer.handle([makeEvent()]);
+
+ expect(results).toEqual([{ id: "1", status: EventResultStatus.Delivered }]);
+ expect(fetchDecision.mock.calls[0][0]).toEqual({
+ delegatedRequestId: DELEGATED_REQUEST_ID,
+ approvalRequestId: APPROVAL_REQUEST_ID,
+ providerRequestId: EXTERNAL_ID
+ });
+ expect(row()).toMatchObject({ status: DelegatedApprovalRequestStatus.Approved, statusReason: null });
+ 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"
+ });
+ expect(notify).toHaveBeenCalledWith({
+ approvalRequestId: APPROVAL_REQUEST_ID,
+ decision: DelegatedApprovalDecision.Approved
+ });
+ });
+
+ test("applies a rejection without granting anything", async () => {
+ fetchDecision.mockResolvedValueOnce(decided(DelegatedApprovalDecision.Rejected, { notes: "Not now." }));
+ const { consumer, row, approval, postApprovalTxRoutine, createAuditLog } = buildConsumer();
+
+ const results = await consumer.handle([makeEvent()]);
+
+ expect(results).toEqual([{ id: "1", status: EventResultStatus.Delivered }]);
+ expect(row()?.status).toBe(DelegatedApprovalRequestStatus.Rejected);
+ expect(approval()?.status).toBe(ApprovalRequestStatus.Rejected);
+ expect(postApprovalTxRoutine).not.toHaveBeenCalled();
+ auditedWith(createAuditLog, { decision: DelegatedApprovalDecision.Rejected, decisionNotes: "Not now." });
+ });
+
+ test("accepts the record's permissions in whatever order and padding the system stores them", async () => {
+ fetchDecision.mockResolvedValueOnce(
+ decided(DelegatedApprovalDecision.Approved, { permissions: ["secret-folders:edit", "secrets:read,create"] })
+ );
+ const { consumer, row } = buildConsumer();
+
+ await consumer.handle([makeEvent()]);
+
+ expect(row()?.status).toBe(DelegatedApprovalRequestStatus.Approved);
+ });
+
+ test("fails for good when the approved permissions differ from the request, and closes the request", async () => {
+ fetchDecision.mockResolvedValueOnce(
+ decided(DelegatedApprovalDecision.Approved, {
+ permissions: ["secrets: read, create, delete", "secret-folders: edit"]
+ })
+ );
+ const { consumer, row, approval, postApprovalTxRoutine, createAuditLog, notify } = buildConsumer();
+
+ const [result] = await consumer.handle([makeEvent()]);
+
+ expect(result.status).toBe(EventResultStatus.Failed);
+ expect(result.error).toContain("approved different permissions");
+ expect(result.error).toContain("Requested: secret-folders: edit; secrets: create, read");
+ expect(result.error).toContain("Approved in ServiceNow: secret-folders: edit; secrets: create, delete, read");
+ expect(row()).toMatchObject({ status: DelegatedApprovalRequestStatus.Failed, statusReason: result.error });
+ expect(approval()?.status).toBe(ApprovalRequestStatus.Cancelled);
+ expect(postApprovalTxRoutine).not.toHaveBeenCalled();
+ expect(notify).not.toHaveBeenCalled();
+ auditedWith(createAuditLog, { outcome: DelegatedApprovalDecisionOutcome.Failed, reason: result.error });
+ });
+
+ test("fails for good when the record belongs to another request", async () => {
+ fetchDecision.mockResolvedValueOnce(decided(DelegatedApprovalDecision.Approved, { approvalRequestId: "other" }));
+ const { consumer, row, approval } = buildConsumer();
+
+ const [result] = await consumer.handle([makeEvent()]);
+
+ expect(result.status).toBe(EventResultStatus.Failed);
+ expect(row()?.status).toBe(DelegatedApprovalRequestStatus.Failed);
+ expect(approval()?.status).toBe(ApprovalRequestStatus.Cancelled);
+ });
+
+ test("retries while the system has not recorded a decision, telling the user why", async () => {
+ fetchDecision.mockResolvedValueOnce({ status: "pending", reason: "ServiceNow has not recorded a decision yet." });
+ const { consumer, row, approval, createAuditLog } = buildConsumer();
+
+ const results = await consumer.handle([makeEvent()]);
+
+ expect(results).toEqual([
+ { id: "1", status: EventResultStatus.Retry, error: "ServiceNow has not recorded a decision yet." }
+ ]);
+ expect(row()).toMatchObject({
+ status: DelegatedApprovalRequestStatus.WaitingApproval,
+ statusReason: `ServiceNow has not recorded a decision yet. ${DELEGATED_APPROVAL_DECISION_RETRY_HINT}`
+ });
+ expect(approval()?.status).toBe(ApprovalRequestStatus.Pending);
+ expect(createAuditLog).not.toHaveBeenCalled();
+ });
+
+ test("retries a transient read failure without touching the request", async () => {
+ fetchDecision.mockRejectedValueOnce(new Error("ServiceNow could not be reached."));
+ const { consumer, row, approval } = buildConsumer();
+
+ const [result] = await consumer.handle([makeEvent()]);
+
+ expect(result).toEqual({ id: "1", status: EventResultStatus.Retry, error: "ServiceNow could not be reached." });
+ expect(row()).toMatchObject({ status: DelegatedApprovalRequestStatus.WaitingApproval });
+ expect(row()?.statusReason).toContain(DELEGATED_APPROVAL_DECISION_RETRY_HINT);
+ expect(approval()?.status).toBe(ApprovalRequestStatus.Pending);
+ });
+
+ test("fails for good on an unrecoverable read error", async () => {
+ fetchDecision.mockRejectedValueOnce(new UnrecoverableError("ServiceNow rejected the credentials."));
+ const { consumer, row, approval } = buildConsumer();
+
+ const [result] = await consumer.handle([makeEvent()]);
+
+ expect(result).toEqual({
+ id: "1",
+ status: EventResultStatus.Failed,
+ error: "ServiceNow rejected the credentials."
+ });
+ expect(row()).toMatchObject({
+ status: DelegatedApprovalRequestStatus.Failed,
+ statusReason: "ServiceNow rejected the credentials."
+ });
+ expect(approval()?.status).toBe(ApprovalRequestStatus.Cancelled);
+ });
+
+ test("fails for good without reading when the policy names an unsupported delegated approval system", async () => {
+ const { consumer, row, approval, createAuditLog } = buildConsumer({
+ policy: { ...delegatedPolicy, type: "jira" as DelegatedApprovalPolicyType }
+ });
+
+ const [result] = await consumer.handle([makeEvent()]);
+
+ expect(result.status).toBe(EventResultStatus.Failed);
+ expect(result.error).toBe("The delegated approval system 'jira' is not supported. Create the request again.");
+ expect(fetchDecision).not.toHaveBeenCalled();
+ expect(row()).toMatchObject({ status: DelegatedApprovalRequestStatus.Failed, statusReason: result.error });
+ expect(approval()?.status).toBe(ApprovalRequestStatus.Cancelled);
+ auditedWith(createAuditLog, {
+ outcome: DelegatedApprovalDecisionOutcome.Failed,
+ reason: result.error,
+ delegatedApprovalType: "the delegated approval system"
+ });
+ });
+
+ test.each([
+ ["the delegated approver was removed from the policy", { policy: null }],
+ ["the connection is gone", { connection: null }],
+ ["the connection belongs to another org", { connection: { id: "connection-1", orgId: "other-org" } }]
+ ])("fails for good without reading when %s", async (_, overrides) => {
+ const { consumer, row, approval } = buildConsumer(overrides);
+
+ const [result] = await consumer.handle([makeEvent()]);
+
+ expect(result.status).toBe(EventResultStatus.Failed);
+ expect(fetchDecision).not.toHaveBeenCalled();
+ expect(row()?.status).toBe(DelegatedApprovalRequestStatus.Failed);
+ expect(approval()?.status).toBe(ApprovalRequestStatus.Cancelled);
+ });
+
+ test("records a decision that arrives after the request was cancelled, without granting", async () => {
+ fetchDecision.mockResolvedValueOnce(decided(DelegatedApprovalDecision.Approved));
+ const { consumer, row, approval, postApprovalTxRoutine, createAuditLog } = buildConsumer({
+ approvalRequest: { ...pendingApprovalRequest, status: ApprovalRequestStatus.Cancelled }
+ });
+
+ const results = await consumer.handle([makeEvent()]);
+
+ expect(results).toEqual([{ id: "1", status: EventResultStatus.Delivered }]);
+ expect(row()?.status).toBe(DelegatedApprovalRequestStatus.Failed);
+ expect(row()?.statusReason).toContain("after the request was cancelled");
+ expect(approval()?.status).toBe(ApprovalRequestStatus.Cancelled);
+ expect(postApprovalTxRoutine).not.toHaveBeenCalled();
+ auditedWith(createAuditLog, { outcome: DelegatedApprovalDecisionOutcome.Failed });
+ });
+
+ test("expires a request whose decision arrives after its deadline", async () => {
+ fetchDecision.mockResolvedValueOnce(decided(DelegatedApprovalDecision.Approved));
+ const { consumer, row, approval, postApprovalTxRoutine } = buildConsumer({
+ approvalRequest: { ...pendingApprovalRequest, expiresAt: new Date(Date.now() - 60_000) }
+ });
+
+ await consumer.handle([makeEvent()]);
+
+ expect(row()?.status).toBe(DelegatedApprovalRequestStatus.Failed);
+ expect(row()?.statusReason).toContain("expired");
+ expect(approval()?.status).toBe(ApprovalRequestStatus.Expired);
+ expect(postApprovalTxRoutine).not.toHaveBeenCalled();
+ });
+
+ test.each([
+ ["is gone", null],
+ ["was approved", { ...waitingDelegatedRequest, status: DelegatedApprovalRequestStatus.Approved }],
+ ["was rejected", { ...waitingDelegatedRequest, status: DelegatedApprovalRequestStatus.Rejected }],
+ ["failed", { ...waitingDelegatedRequest, status: DelegatedApprovalRequestStatus.Failed }],
+ ["was never sent", { ...waitingDelegatedRequest, status: DelegatedApprovalRequestStatus.PendingDispatch }]
+ ])("marks the event delivered without reading when the request %s", async (_, delegatedRequest) => {
+ const { consumer } = buildConsumer({ delegatedRequest });
+
+ const results = await consumer.handle([makeEvent()]);
+
+ expect(results).toEqual([{ id: "1", status: EventResultStatus.Delivered }]);
+ expect(fetchDecision).not.toHaveBeenCalled();
+ });
+
+ test("fails the event, not the request, when the callback names another record", async () => {
+ const { consumer, row } = buildConsumer({
+ delegatedRequest: { ...waitingDelegatedRequest, providerRequestId: "snow-2" }
+ });
+
+ const [result] = await consumer.handle([makeEvent()]);
+
+ expect(result.status).toBe(EventResultStatus.Failed);
+ expect(fetchDecision).not.toHaveBeenCalled();
+ expect(row()?.status).toBe(DelegatedApprovalRequestStatus.WaitingApproval);
+ });
+
+ test("fails an unreadable payload terminally", async () => {
+ const { consumer } = buildConsumer();
+
+ const [result] = await consumer.handle([makeEvent({ payload: { delegatedRequestId: "not-a-uuid" } })]);
+
+ expect(result.status).toBe(EventResultStatus.Failed);
+ expect(result.error).toContain("Unreadable delegated approval callback payload");
+ expect(fetchDecision).not.toHaveBeenCalled();
+ });
+});
+
+// Why the read-back is an outbox consumer: a record whose decision is not stored yet is tried again
+// later, instead of being dropped by a callback that answered 200 before anything was read.
+describe("delegatedApprovalDecisionConsumer through the outbox", () => {
+ const buildOutbox = (consumer: ReturnType<typeof buildConsumer>["consumer"]) => {
+ const registry = eventOutboxRegistryFactory();
+ registry.register(consumer);
+
+ const rows: TEventOutbox[] = [];
+ const isDue = (row: TEventOutbox) =>
+ (row.status === EventOutboxStatus.Pending || row.status === EventOutboxStatus.Retry) &&
+ row.nextRetryAt <= new Date();
+
+ const service = eventOutboxServiceFactory({
+ eventOutboxDAL: {
+ insertEvents: async (inserted: Pick<TEventOutbox, "consumer" | "eventType" | "payload">[]) => {
+ inserted.forEach((row) =>
+ rows.push({
+ id: rows.length + 1,
+ status: EventOutboxStatus.Pending,
+ attempts: 0,
+ nextRetryAt: new Date(0),
+ occurredAt: new Date(),
+ ...row
+ } as TEventOutbox)
+ );
+ },
+ claimBatch: async () => {
+ const claimable = rows.filter(isDue);
+ claimable.forEach((row) => Object.assign(row, { status: EventOutboxStatus.Processing }));
+ return { lockToken: "token", rows: claimable.map((row) => ({ ...row })) };
+ },
+ extendClaims: async () => {},
+ commitResults: async (input: {
+ delivered: { ids: string[] }[];
+ retriable: { ids: string[]; nextRetryDelayMs: number; error?: string }[];
+ failed: { ids: string[]; error?: string }[];
+ }) => {
+ const apply = (
+ groups: { ids: string[]; nextRetryDelayMs?: number; error?: string }[],
+ status: EventOutboxStatus
+ ) =>
+ groups.forEach((group) =>
+ group.ids.forEach((id) => {
+ const row = rows.find((candidate) => String(candidate.id) === id);
+ if (!row) return;
+ row.status = status;
+ row.attempts += 1;
+ row.lastError = group.error ?? null;
+ row.nextRetryAt = new Date(Date.now() + (group.nextRetryDelayMs ?? 0));
+ })
+ );
+ apply(input.delivered, EventOutboxStatus.Delivered);
+ apply(input.retriable, EventOutboxStatus.Retry);
+ apply(input.failed, EventOutboxStatus.Failed);
+ return [...input.delivered, ...input.retriable, ...input.failed].reduce(
+ (n, group) => n + group.ids.length,
+ 0
+ );
+ }
+ } as never,
+ eventOutboxRegistry: registry
+ });
+
+ const elapseBackoff = () => {
+ rows.forEach((row) => Object.assign(row, { nextRetryAt: new Date(0) }));
+ };
+
+ return { service, rows, elapseBackoff };
+ };
+
+ test("retries a record without a decision and applies it on a later flush", async () => {
+ fetchDecision
+ .mockResolvedValueOnce({ status: "pending", reason: "Not yet." })
+ .mockResolvedValueOnce(decided(DelegatedApprovalDecision.Approved));
+ const built = buildConsumer();
+ const { service, rows, elapseBackoff } = buildOutbox(built.consumer);
+ const { payload } = makeEvent();
+
+ await service.emit({
+ eventType: DelegatedApprovalCallbackEvent.SecretsManagementAccessRequest,
+ payload: payload as Record<string, unknown>
+ });
+ await service.drain({ consumer: built.consumer.name });
+
+ expect(rows[0]).toMatchObject({ status: EventOutboxStatus.Retry, attempts: 1, lastError: "Not yet." });
+ expect(built.row()?.status).toBe(DelegatedApprovalRequestStatus.WaitingApproval);
+
+ elapseBackoff();
+ await service.drain({ consumer: built.consumer.name });
+
+ expect(rows[0]).toMatchObject({ status: EventOutboxStatus.Delivered, attempts: 2 });
+ expect(built.row()?.status).toBe(DelegatedApprovalRequestStatus.Approved);
+ expect(fetchDecision).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/backend/src/services/delegated-approval-decision/delegated-approval-decision-consumer.ts b/backend/src/services/delegated-approval-decision/delegated-approval-decision-consumer.ts
new file mode 100644
index 0000000000..76590849d5
--- /dev/null
+++ b/backend/src/services/delegated-approval-decision/delegated-approval-decision-consumer.ts
@@ -0,0 +1,40 @@
+import {
+ DelegatedApprovalCallbackEventPayloadSchema,
+ isDelegatedApprovalCallbackEvent,
+ TDelegatedApprovalCallbackEventPayload
+} from "@app/services/delegated-approval-callback/delegated-approval-callback-events";
+import { parseEventPayload, runEventsSerially } from "@app/services/event-outbox/event-outbox-fns";
+import { IEventConsumer, TEvent, TEventConsumerResult } from "@app/services/event-outbox/event-outbox-types";
+
+import { DELEGATED_APPROVAL_DECISION_CONSUMER } from "./delegated-approval-decision-constants";
+import { TDelegatedApprovalDecisionServiceFactory } from "./delegated-approval-decision-service";
+
+type TDelegatedApprovalDecisionConsumerDep = {
+ delegatedApprovalDecisionService: Pick<TDelegatedApprovalDecisionServiceFactory, "applyDecision">;
+};
+
+export const delegatedApprovalDecisionConsumerFactory = ({
+ delegatedApprovalDecisionService
+}: TDelegatedApprovalDecisionConsumerDep): IEventConsumer<TDelegatedApprovalCallbackEventPayload> => {
+ const $handleEvent = async (event: TEvent): Promise<TEventConsumerResult> => {
+ const id = String(event.id);
+
+ const { data, failure } = parseEventPayload(
+ event,
+ DelegatedApprovalCallbackEventPayloadSchema,
+ "delegated approval callback"
+ );
+ if (failure) return failure;
+
+ const { delegatedRequestId, externalId } = data;
+ const outcome = await delegatedApprovalDecisionService.applyDecision({ delegatedRequestId, externalId });
+ return { id, ...outcome };
+ };
+
+ return {
+ name: DELEGATED_APPROVAL_DECISION_CONSUMER,
+ payloadSchema: DelegatedApprovalCallbackEventPayloadSchema,
+ subscribesTo: isDelegatedApprovalCallbackEvent,
+ handle: (events) => runEventsSerially(events, $handleEvent)
+ };
+};
diff --git a/backend/src/services/delegated-approval-decision/delegated-approval-decision-enums.ts b/backend/src/services/delegated-approval-decision/delegated-approval-decision-enums.ts
new file mode 100644
index 0000000000..8015858e72
--- /dev/null
+++ b/backend/src/services/delegated-approval-decision/delegated-approval-decision-enums.ts
@@ -0,0 +1,9 @@
+export enum DelegatedApprovalDecision {
+ Approved = "approved",
+ Rejected = "rejected"
+}
+
+export enum DelegatedApprovalDecisionOutcome {
+ Applied = "applied",
+ Failed = "failed"
+}
diff --git a/backend/src/services/delegated-approval-decision/delegated-approval-decision-fns.test.ts b/backend/src/services/delegated-approval-decision/delegated-approval-decision-fns.test.ts
new file mode 100644
index 0000000000..9c3b193abe
--- /dev/null
+++ b/backend/src/services/delegated-approval-decision/delegated-approval-decision-fns.test.ts
@@ -0,0 +1,76 @@
+import { describe, expect, test } from "vitest";
+
+import {
+ describeDelegatedApprovalPermissions,
+ haveSameDelegatedApprovalPermissions,
+ normalizeDelegatedApprovalPermissions
+} from "./delegated-approval-decision-fns";
+
+const DISPATCHED = ["secrets: read, create", "secret-folders: edit"];
+
+describe("normalizeDelegatedApprovalPermissions", () => {
+ test("turns padded lines into sorted subject:action pairs", () => {
+ expect(normalizeDelegatedApprovalPermissions(DISPATCHED)).toEqual([
+ "secret-folders:edit",
+ "secrets:create",
+ "secrets:read"
+ ]);
+ });
+
+ test("reads what the ServiceNow application stores back to the same pairs", () => {
+ const stored = "secrets: create, read\r\n\r\nsecret-folders: edit\n";
+
+ expect(normalizeDelegatedApprovalPermissions(stored)).toEqual(normalizeDelegatedApprovalPermissions(DISPATCHED));
+ });
+
+ test("ignores order, duplicates, case and stray whitespace", () => {
+ expect(normalizeDelegatedApprovalPermissions([" Secrets : Read , read, CREATE", "secrets:create"])).toEqual([
+ "secrets:create",
+ "secrets:read"
+ ]);
+ });
+
+ test("accepts compact pairs and several pairs on one line", () => {
+ expect(normalizeDelegatedApprovalPermissions("secrets:read, secret-folders:edit")).toEqual([
+ "secret-folders:edit",
+ "secrets:read"
+ ]);
+ });
+
+ test("keeps a subject without actions and drops empty input", () => {
+ expect(normalizeDelegatedApprovalPermissions("secrets:\nsecret-folders")).toEqual(["secret-folders", "secrets"]);
+ expect(normalizeDelegatedApprovalPermissions(null)).toEqual([]);
+ expect(normalizeDelegatedApprovalPermissions(" \n ")).toEqual([]);
+ });
+});
+
+describe("haveSameDelegatedApprovalPermissions", () => {
+ const requested = normalizeDelegatedApprovalPermissions(DISPATCHED);
+
+ test("matches an untouched record", () => {
+ expect(
+ haveSameDelegatedApprovalPermissions(
+ requested,
+ normalizeDelegatedApprovalPermissions("secrets: create, read\nsecret-folders: edit")
+ )
+ ).toBe(true);
+ });
+
+ test.each([
+ ["an added action", "secrets: create, read, delete\nsecret-folders: edit"],
+ ["a removed subject", "secrets: create, read"],
+ ["a changed action", "secrets: create, edit\nsecret-folders: edit"],
+ ["an emptied record", ""]
+ ])("flags %s", (_, stored) => {
+ expect(haveSameDelegatedApprovalPermissions(requested, normalizeDelegatedApprovalPermissions(stored))).toBe(false);
+ });
+});
+
+describe("describeDelegatedApprovalPermissions", () => {
+ test("groups pairs by subject for a reason a user can read", () => {
+ expect(describeDelegatedApprovalPermissions(normalizeDelegatedApprovalPermissions(DISPATCHED))).toBe(
+ "secret-folders: edit; secrets: create, read"
+ );
+ expect(describeDelegatedApprovalPermissions([])).toBe("none");
+ });
+});
diff --git a/backend/src/services/delegated-approval-decision/delegated-approval-decision-fns.ts b/backend/src/services/delegated-approval-decision/delegated-approval-decision-fns.ts
new file mode 100644
index 0000000000..83d80ad577
--- /dev/null
+++ b/backend/src/services/delegated-approval-decision/delegated-approval-decision-fns.ts
@@ -0,0 +1,108 @@
+import { logger } from "@app/lib/logger";
+import { EventResultStatus } from "@app/services/event-outbox/event-outbox-types";
+
+import { DelegatedApprovalDecisionOutcome } from "./delegated-approval-decision-enums";
+import {
+ TApplyDelegatedApprovalDecisionResult,
+ TDecidedDelegatedApprovalReadResult,
+ TDelegatedApprovalDecisionAuditMetadata,
+ TDelegatedApprovalDecisionContext,
+ TDelegatedApprovalFinalizeOutcome
+} from "./delegated-approval-decision-types";
+
+const PAIR_SEPARATOR = ":";
+
+const normalizeToken = (token: string) => token.replace(/\s+/g, " ").trim().toLowerCase();
+
+const toPairs = (line: string): string[] => {
+ const separatorIndex = line.indexOf(PAIR_SEPARATOR);
+ if (separatorIndex === -1) {
+ const subject = normalizeToken(line);
+ return subject ? [subject] : [];
+ }
+
+ const subject = normalizeToken(line.slice(0, separatorIndex));
+ if (!subject) return [];
+
+ const pairs: string[] = [];
+ for (const token of line.slice(separatorIndex + 1).split(",")) {
+ if (token.includes(PAIR_SEPARATOR)) {
+ pairs.push(...toPairs(token));
+ continue;
+ }
+ const action = normalizeToken(token);
+ if (action) pairs.push(`${subject}${PAIR_SEPARATOR}${action}`);
+ }
+ return pairs.length ? pairs : [subject];
+};
+
+// Both the permissions Infisical dispatched and the ones a delegated approval system hands back go
+// through this before they are compared, so padding, line endings, ordering, duplicates and case can
+// never count as a change while a different subject or action always does.
+export const normalizeDelegatedApprovalPermissions = (raw: string | string[] | null | undefined): string[] => {
+ const text = Array.isArray(raw) ? raw.join("\n") : (raw ?? "");
+ const pairs = text
+ .split(/\r?\n/)
+ .map((line) => line.trim())
+ .filter(Boolean)
+ .flatMap(toPairs);
+ return Array.from(new Set(pairs)).sort();
+};
+
+export const haveSameDelegatedApprovalPermissions = (requested: string[], approved: string[]) =>
+ requested.length === approved.length && requested.every((pair, index) => pair === approved[index]);
+
+export const describeDelegatedApprovalPermissions = (normalized: string[]) => {
+ if (!normalized.length) return "none";
+
+ const actionsBySubject = new Map<string, string[]>();
+ for (const pair of normalized) {
+ const separatorIndex = pair.indexOf(PAIR_SEPARATOR);
+ const subject = separatorIndex === -1 ? pair : pair.slice(0, separatorIndex);
+ const action = separatorIndex === -1 ? null : pair.slice(separatorIndex + 1);
+ const actions = actionsBySubject.get(subject) ?? [];
+ if (action) actions.push(action);
+ actionsBySubject.set(subject, actions);
+ }
+
+ return Array.from(actionsBySubject.entries())
+ .map(([subject, actions]) => (actions.length ? `${subject}: ${actions.join(", ")}` : subject))
+ .join("; ");
+};
+
+export const recordDelegatedApprovalDecisionOutcome = async (
+ outcome: TDelegatedApprovalFinalizeOutcome,
+ {
+ context,
+ decided,
+ audit
+ }: {
+ context: TDelegatedApprovalDecisionContext;
+ decided: TDecidedDelegatedApprovalReadResult;
+ audit: (
+ context: TDelegatedApprovalDecisionContext,
+ metadata: TDelegatedApprovalDecisionAuditMetadata
+ ) => Promise<void>;
+ }
+): Promise<TApplyDelegatedApprovalDecisionResult> => {
+ switch (outcome.kind) {
+ case "applied": {
+ await audit(context, { outcome: DelegatedApprovalDecisionOutcome.Applied, decided });
+ logger.info(
+ `Delegated approval decision applied [delegatedRequestId=${context.delegatedRequestId}] [approvalRequestId=${context.approvalRequest.id}] [decision=${decided.decision}]`
+ );
+ return { status: EventResultStatus.Delivered };
+ }
+ case "late":
+ await audit(context, { outcome: DelegatedApprovalDecisionOutcome.Failed, reason: outcome.reason, decided });
+ logger.warn(
+ `Delegated approval decision arrived too late [delegatedRequestId=${context.delegatedRequestId}] [approvalRequestId=${context.approvalRequest.id}] [reason=${outcome.reason}]`
+ );
+ return { status: EventResultStatus.Delivered };
+ default:
+ logger.info(
+ `Delegated approval request was finalized while its decision was being read, skipping [delegatedRequestId=${context.delegatedRequestId}] [outcome=${outcome.kind}]`
+ );
+ return { status: EventResultStatus.Delivered };
+ }
+};
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.ts
new file mode 100644
index 0000000000..7e1abe5322
--- /dev/null
+++ b/backend/src/services/delegated-approval-decision/delegated-approval-decision-service.ts
@@ -0,0 +1,348 @@
+import { UnrecoverableError } from "bullmq";
+
+import { EventType } from "@app/ee/services/audit-log/audit-log-types";
+import { logger } from "@app/lib/logger";
+import { decryptAppConnection } from "@app/services/app-connection/app-connection-fns";
+import { ApprovalRequestStatus } from "@app/services/approval-policy/approval-policy-enums";
+import { TApprovalRequest, TApprovalResource } from "@app/services/approval-policy/approval-policy-types";
+import { ActorType } from "@app/services/auth/auth-type";
+import {
+ DelegatedApprovalPolicyType,
+ DelegatedApprovalRequestStatus
+} from "@app/services/delegated-approval/delegated-approval-enums";
+import { isApprovalRequestExpired } from "@app/services/delegated-approval/delegated-approval-guards";
+import {
+ DELEGATED_APPROVAL_FINAL_STATE,
+ DELEGATED_APPROVAL_NAME_MAP,
+ isDelegatedApprovalSupportedPolicyType
+} from "@app/services/delegated-approval/delegated-approval-maps";
+import {
+ failDelegatedApprovalRequest,
+ loadDelegatedApprovalContext,
+ toDelegatedApprovalFailure,
+ toDelegatedApprovalStatusReason
+} from "@app/services/delegated-approval/delegated-approval-request-fns";
+import {
+ getDelegatedApprovalDispatchDetailsBuilder,
+ getDelegatedApprovalProvider
+} from "@app/services/delegated-approval/dispatch/delegated-approval-dispatch-fns";
+import { EventResultStatus } from "@app/services/event-outbox/event-outbox-types";
+
+import { DELEGATED_APPROVAL_DECISION_RETRY_HINT } from "./delegated-approval-decision-constants";
+import { DelegatedApprovalDecision, DelegatedApprovalDecisionOutcome } from "./delegated-approval-decision-enums";
+import {
+ describeDelegatedApprovalPermissions,
+ haveSameDelegatedApprovalPermissions,
+ normalizeDelegatedApprovalPermissions,
+ recordDelegatedApprovalDecisionOutcome
+} from "./delegated-approval-decision-fns";
+import {
+ TApplyDelegatedApprovalDecisionDTO,
+ TApplyDelegatedApprovalDecisionResult,
+ TDecidedDelegatedApprovalReadResult,
+ TDelegatedApprovalDecisionAuditMetadata,
+ TDelegatedApprovalDecisionContext,
+ TDelegatedApprovalDecisionServiceFactoryDep,
+ TDelegatedApprovalFinalizeOutcome
+} from "./delegated-approval-decision-types";
+
+export type TDelegatedApprovalDecisionServiceFactory = ReturnType<typeof delegatedApprovalDecisionServiceFactory>;
+
+export const delegatedApprovalDecisionServiceFactory = ({
+ delegatedApprovalRequestDAL,
+ delegatedApprovalPolicyDAL,
+ approvalRequestDAL,
+ appConnectionDAL,
+ kmsService,
+ auditLogService,
+ approvalResources,
+ decisionNotifiers
+}: TDelegatedApprovalDecisionServiceFactoryDep) => {
+ const $audit = async (
+ context: TDelegatedApprovalDecisionContext,
+ metadata: TDelegatedApprovalDecisionAuditMetadata
+ ) => {
+ try {
+ await auditLogService.createAuditLog({
+ actor: { type: ActorType.PLATFORM, metadata: {} },
+ orgId: context.approvalRequest.organizationId,
+ projectId: context.approvalRequest.projectId,
+ event: {
+ type: EventType.ACCESS_APPROVAL_REQUEST_DELEGATED_DECISION,
+ metadata: {
+ requestId: context.approvalRequest.id,
+ policyId: context.approvalRequest.policyId ?? "",
+ delegatedApprovalType: context.delegatedApprovalType,
+ providerRequestId: context.providerRequestId,
+ outcome: metadata.outcome,
+ ...(metadata.decided
+ ? {
+ decision: metadata.decided.decision,
+ decidedBy: metadata.decided.decidedBy ?? undefined,
+ decidedAt: metadata.decided.decidedAt ?? undefined,
+ decisionNotes: metadata.decided.notes ?? undefined
+ }
+ : {}),
+ ...(metadata.reason ? { reason: metadata.reason } : {})
+ }
+ }
+ });
+ } catch (error) {
+ logger.error(
+ error,
+ `Failed to record delegated approval decision audit log [delegatedRequestId=${context.delegatedRequestId}] [approvalRequestId=${context.approvalRequest.id}]`
+ );
+ }
+ };
+
+ const $keepWaiting = async (delegatedRequestId: string, reason: string) => {
+ try {
+ await delegatedApprovalRequestDAL.update(
+ { id: delegatedRequestId, status: DelegatedApprovalRequestStatus.WaitingApproval },
+ { statusReason: toDelegatedApprovalStatusReason(`${reason} ${DELEGATED_APPROVAL_DECISION_RETRY_HINT}`) }
+ );
+ } catch (error) {
+ logger.error(
+ error,
+ `Failed to record why the delegated approval decision is still pending [delegatedRequestId=${delegatedRequestId}]`
+ );
+ }
+ };
+
+ const $fail = async (context: TDelegatedApprovalDecisionContext, reason: string) => {
+ try {
+ await failDelegatedApprovalRequest(
+ { id: context.delegatedRequestId, requestId: context.approvalRequest.id, reason },
+ { approvalRequestDAL, delegatedApprovalRequestDAL }
+ );
+ } catch (error) {
+ logger.error(
+ error,
+ `Failed to record delegated approval decision failure [delegatedRequestId=${context.delegatedRequestId}]`
+ );
+ }
+ await $audit(context, { outcome: DelegatedApprovalDecisionOutcome.Failed, reason });
+ };
+
+ const $finalize = async (
+ context: TDelegatedApprovalDecisionContext,
+ decided: TDecidedDelegatedApprovalReadResult,
+ postApprovalTxRoutine: TApprovalResource["postApprovalTxRoutine"]
+ ): Promise<{
+ outcome: TDelegatedApprovalFinalizeOutcome;
+ result: TApplyDelegatedApprovalDecisionResult;
+ }> => {
+ const outcome = await approvalRequestDAL.transaction(async (tx): Promise<TDelegatedApprovalFinalizeOutcome> => {
+ const locked = await approvalRequestDAL.findByIdForUpdate(context.approvalRequest.id, tx);
+ if (!locked) return { kind: "gone" };
+
+ const isExpired = isApprovalRequestExpired(locked);
+ if (locked.status !== ApprovalRequestStatus.Pending || isExpired) {
+ const reason = isExpired
+ ? `The decision from ${context.delegatedApprovalType} arrived after the request expired in Infisical. Create the request again.`
+ : `The decision from ${context.delegatedApprovalType} arrived after the request was ${locked.status} in Infisical.`;
+ const failed = await failDelegatedApprovalRequest(
+ { id: context.delegatedRequestId, requestId: locked.id, reason, closeAs: ApprovalRequestStatus.Expired },
+ { approvalRequestDAL, delegatedApprovalRequestDAL },
+ tx
+ );
+ return failed ? { kind: "late", reason } : { kind: "raced" };
+ }
+
+ const isApproved = decided.decision === DelegatedApprovalDecision.Approved;
+ const [finalized] = await delegatedApprovalRequestDAL.update(
+ { id: context.delegatedRequestId, status: DelegatedApprovalRequestStatus.WaitingApproval },
+ {
+ status: isApproved ? DelegatedApprovalRequestStatus.Approved : DelegatedApprovalRequestStatus.Rejected,
+ statusReason: null
+ },
+ tx
+ );
+ if (!finalized) return { kind: "raced" };
+
+ if (isApproved) {
+ await approvalRequestDAL.updateById(locked.id, { status: ApprovalRequestStatus.Approved }, tx);
+ await postApprovalTxRoutine?.(locked as TApprovalRequest, tx);
+ } else {
+ await approvalRequestDAL.updateById(locked.id, { status: ApprovalRequestStatus.Rejected }, tx);
+ }
+ return { kind: "applied" };
+ });
+
+ const result = await recordDelegatedApprovalDecisionOutcome(outcome, { context, decided, audit: $audit });
+ return { outcome, result };
+ };
+
+ const $terminal = async (
+ context: TDelegatedApprovalDecisionContext,
+ reason: string
+ ): Promise<TApplyDelegatedApprovalDecisionResult> => {
+ await $fail(context, reason);
+ logger.error(
+ `Delegated approval decision failed [delegatedRequestId=${context.delegatedRequestId}] [approvalRequestId=${context.approvalRequest.id}] [reason=${reason}]`
+ );
+ return { status: EventResultStatus.Failed, error: reason };
+ };
+
+ // Reads the decision back from the delegated approval system and finalizes the request. Retry
+ // means the system has not recorded a decision yet and the caller should try again later; Failed
+ // means the request was closed and nothing can retry it.
+ const applyDecision = async ({
+ delegatedRequestId,
+ externalId
+ }: TApplyDelegatedApprovalDecisionDTO): Promise<TApplyDelegatedApprovalDecisionResult> => {
+ const delegatedApprovalContext = await loadDelegatedApprovalContext(delegatedRequestId, {
+ delegatedApprovalRequestDAL,
+ approvalRequestDAL,
+ delegatedApprovalPolicyDAL
+ });
+ if (!delegatedApprovalContext) {
+ logger.warn(
+ `Delegated approval request no longer exists, skipping decision [delegatedRequestId=${delegatedRequestId}]`
+ );
+ return { status: EventResultStatus.Delivered };
+ }
+ const { delegatedRequest, approvalRequest, delegatedPolicy } = delegatedApprovalContext;
+
+ // move this to a helper function
+ if (DELEGATED_APPROVAL_FINAL_STATE.has(delegatedRequest.status as DelegatedApprovalRequestStatus)) {
+ logger.info(
+ `Delegated approval request was already finalized, skipping decision [delegatedRequestId=${delegatedRequestId}] [status=${delegatedRequest.status}]`
+ );
+ return { status: EventResultStatus.Delivered };
+ }
+ if (delegatedRequest.status !== DelegatedApprovalRequestStatus.WaitingApproval) {
+ logger.warn(
+ `Delegated approval request is not awaiting a decision, skipping [delegatedRequestId=${delegatedRequestId}] [status=${delegatedRequest.status}]`
+ );
+ return { status: EventResultStatus.Delivered };
+ }
+ if (delegatedRequest.providerRequestId !== externalId) {
+ const reason = `The callback named record '${externalId}' but the request is tracked as '${delegatedRequest.providerRequestId ?? "none"}'.`;
+ logger.error(
+ `Delegated approval callback does not match its request [delegatedRequestId=${delegatedRequestId}] ${reason}`
+ );
+ return { status: EventResultStatus.Failed, error: reason };
+ }
+
+ if (!approvalRequest) {
+ logger.warn(
+ `Approval request no longer exists, skipping delegated decision [delegatedRequestId=${delegatedRequestId}] [approvalRequestId=${delegatedRequest.requestId}]`
+ );
+ return { status: EventResultStatus.Delivered };
+ }
+
+ // finished helper function
+
+ const delegatedApprovalName =
+ delegatedPolicy && Object.hasOwn(DELEGATED_APPROVAL_NAME_MAP, delegatedPolicy.type)
+ ? DELEGATED_APPROVAL_NAME_MAP[delegatedPolicy.type as DelegatedApprovalPolicyType]
+ : undefined;
+
+ const context: TDelegatedApprovalDecisionContext = {
+ delegatedRequestId,
+ providerRequestId: delegatedRequest.providerRequestId,
+ approvalRequest,
+ delegatedApprovalType: delegatedApprovalName ?? "the delegated approval system"
+ };
+
+ // move this to a helper function
+
+ if (!delegatedPolicy) {
+ return $terminal(
+ context,
+ "The policy's delegated approver was removed before its decision could be read. Configure a delegated approver on the policy and create the request again."
+ );
+ }
+
+ if (!delegatedApprovalName) {
+ return $terminal(
+ context,
+ `The delegated approval system '${delegatedPolicy.type}' is not supported. Create the request again.`
+ );
+ }
+
+ const rawConnection = await appConnectionDAL.findById(delegatedPolicy.connectionId);
+ if (!rawConnection) {
+ return $terminal(context, "The policy's App Connection was not found.");
+ }
+
+ const providerName = context.delegatedApprovalType;
+ let decided: TDecidedDelegatedApprovalReadResult;
+ let postApprovalTxRoutine: TApprovalResource["postApprovalTxRoutine"]; // no need to be a let
+ try {
+ const provider = getDelegatedApprovalProvider(delegatedPolicy.type);
+ const connection = await decryptAppConnection(rawConnection, kmsService);
+ const result = await provider.fetchDecision(
+ { delegatedRequestId, approvalRequestId: approvalRequest.id, providerRequestId: context.providerRequestId },
+ connection
+ );
+
+ if (result.status === "pending") {
+ await $keepWaiting(delegatedRequestId, result.reason);
+ logger.info(
+ `Delegated approval decision not recorded yet, will check again [delegatedRequestId=${delegatedRequestId}] [approvalRequestId=${approvalRequest.id}]`
+ );
+ return { status: EventResultStatus.Retry, error: result.reason };
+ }
+
+ if (result.approvalRequestId && result.approvalRequestId !== approvalRequest.id) {
+ throw new UnrecoverableError(
+ `${providerName} returned the record of a different request ('${result.approvalRequestId}'). Create the request again.`
+ );
+ }
+
+ if (result.decision === DelegatedApprovalDecision.Approved) {
+ const buildDetails = getDelegatedApprovalDispatchDetailsBuilder(approvalRequest.type);
+ const requested = normalizeDelegatedApprovalPermissions(buildDetails(approvalRequest).permissions);
+ const approved = normalizeDelegatedApprovalPermissions(result.permissions);
+ if (!haveSameDelegatedApprovalPermissions(requested, approved)) {
+ throw new UnrecoverableError(
+ `${providerName} approved different permissions than this request asked for. Requested: ${describeDelegatedApprovalPermissions(requested)}. Approved in ${providerName}: ${describeDelegatedApprovalPermissions(approved)}. The request was closed. Create the request again.`
+ );
+ }
+
+ postApprovalTxRoutine = isDelegatedApprovalSupportedPolicyType(approvalRequest.type)
+ ? approvalResources[approvalRequest.type]?.postApprovalTxRoutine
+ : undefined;
+ if (!postApprovalTxRoutine) {
+ throw new UnrecoverableError(
+ `Requests of type '${approvalRequest.type}' cannot be granted from a decision made in ${providerName}.`
+ );
+ }
+ }
+
+ decided = result;
+ } catch (error) {
+ const { terminal: isTerminal, message, logContext } = toDelegatedApprovalFailure(error);
+ if (isTerminal) return $terminal(context, message);
+
+ await $keepWaiting(delegatedRequestId, message);
+ logger.warn(
+ logContext,
+ `Failed to read the delegated approval decision, will retry [delegatedRequestId=${delegatedRequestId}] [approvalRequestId=${approvalRequest.id}]`
+ );
+ return { status: EventResultStatus.Retry, error: message };
+ }
+
+ const { outcome: finalized, result } = await $finalize(context, decided, postApprovalTxRoutine);
+ if (finalized.kind === "applied") {
+ const notify = isDelegatedApprovalSupportedPolicyType(approvalRequest.type)
+ ? decisionNotifiers[approvalRequest.type]
+ : undefined;
+ if (notify) {
+ try {
+ await notify({ approvalRequestId: approvalRequest.id, decision: decided.decision });
+ } catch (error) {
+ logger.error(
+ error,
+ `Failed to notify about the delegated approval decision [delegatedRequestId=${delegatedRequestId}] [approvalRequestId=${approvalRequest.id}]`
+ );
+ }
+ }
+ }
+ return result;
+ };
+
+ return { applyDecision };
+};
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.ts
new file mode 100644
index 0000000000..ecd33d5174
--- /dev/null
+++ b/backend/src/services/delegated-approval-decision/delegated-approval-decision-types.ts
@@ -0,0 +1,80 @@
+import { TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";
+import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";
+import { TApprovalResource } from "@app/services/approval-policy/approval-policy-types";
+import { TApprovalRequestDALFactory } from "@app/services/approval-policy/approval-request-dal";
+import { DelegatedApprovalSupportedPolicyType } from "@app/services/delegated-approval/delegated-approval-maps";
+import { TDelegatedApprovalPolicyDALFactory } from "@app/services/delegated-approval/delegated-approval-policy-dal";
+import { TDelegatedApprovalRequestDALFactory } from "@app/services/delegated-approval/delegated-approval-request-dal";
+import { EventResultStatus } from "@app/services/event-outbox/event-outbox-types";
+import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+
+import { DelegatedApprovalDecision, DelegatedApprovalDecisionOutcome } from "./delegated-approval-decision-enums";
+
+export type TDelegatedApprovalReadDecisionInput = {
+ delegatedRequestId: string;
+ approvalRequestId: string;
+ providerRequestId: string;
+};
+
+export type TDelegatedApprovalDecisionReadResult =
+ | { status: "pending"; reason: string }
+ | {
+ status: "decided";
+ decision: DelegatedApprovalDecision;
+ approvalRequestId: string | null;
+ permissions: string[];
+ decidedBy: string | null;
+ decidedAt: string | null;
+ notes: string | null;
+ };
+
+export type TDecidedDelegatedApprovalReadResult = Extract<TDelegatedApprovalDecisionReadResult, { status: "decided" }>;
+
+export type TDelegatedApprovalDecisionNotification = {
+ approvalRequestId: string;
+ decision: DelegatedApprovalDecision;
+};
+
+export type TDelegatedApprovalDecisionNotifier = (
+ notification: TDelegatedApprovalDecisionNotification
+) => Promise<void>;
+
+export type TDelegatedApprovalDecisionAuditMetadata = {
+ outcome: DelegatedApprovalDecisionOutcome;
+ reason?: string;
+ decided?: TDecidedDelegatedApprovalReadResult;
+};
+
+export type TDelegatedApprovalDecisionServiceFactoryDep = {
+ delegatedApprovalRequestDAL: Pick<TDelegatedApprovalRequestDALFactory, "findById" | "transaction" | "update">;
+ delegatedApprovalPolicyDAL: Pick<TDelegatedApprovalPolicyDALFactory, "findOne">;
+ approvalRequestDAL: Pick<TApprovalRequestDALFactory, "findById" | "findByIdForUpdate" | "updateById" | "transaction">;
+ appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">;
+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
+ auditLogService: Pick<TAuditLogServiceFactory, "createAuditLog">;
+ approvalResources: Record<DelegatedApprovalSupportedPolicyType, Pick<TApprovalResource, "postApprovalTxRoutine">>;
+ decisionNotifiers: Partial<Record<DelegatedApprovalSupportedPolicyType, TDelegatedApprovalDecisionNotifier>>;
+};
+
+export type TDelegatedApprovalDecisionContext = {
+ delegatedRequestId: string;
+ providerRequestId: string;
+ approvalRequest: { id: string; organizationId: string; projectId: string; policyId?: string | null };
+ delegatedApprovalType: string;
+};
+
+export type TApplyDelegatedApprovalDecisionDTO = {
+ delegatedRequestId: string;
+ externalId: string;
+};
+
+export type TApplyDelegatedApprovalDecisionResult = {
+ status: EventResultStatus;
+ error?: string;
+};
+
+export type TDelegatedApprovalFinalizeOutcome = // this feels weird to me honestly
+ | { kind: "applied" }
+ | { kind: "late"; reason: string }
+ | { kind: "gone" }
+ | { kind: "raced" };
diff --git a/backend/src/services/delegated-approval/delegated-approval-guards.test.ts b/backend/src/services/delegated-approval/delegated-approval-guards.test.ts
new file mode 100644
index 0000000000..4c7dc59eb3
--- /dev/null
+++ b/backend/src/services/delegated-approval/delegated-approval-guards.test.ts
@@ -0,0 +1,67 @@
+import { describe, expect, test } from "vitest";
+
+import { ApprovalRequestStatus } from "@app/services/approval-policy/approval-policy-enums";
+
+import { DelegatedApprovalPolicyType } from "./delegated-approval-enums";
+import {
+ DelegatedApprovalRequestBlocker,
+ getDelegatedApprovalConnectionError,
+ getDelegatedApprovalRequestBlocker,
+ isApprovalRequestExpired
+} from "./delegated-approval-guards";
+
+const pending = { status: ApprovalRequestStatus.Pending, expiresAt: null as Date | null };
+const policy = { type: DelegatedApprovalPolicyType.ServiceNow, connectionId: "connection-1" };
+
+describe("isApprovalRequestExpired", () => {
+ test("is false without a deadline or before it, true after it", () => {
+ const now = new Date("2026-10-21T10:00:00Z");
+
+ expect(isApprovalRequestExpired({ expiresAt: null }, now)).toBe(false);
+ expect(isApprovalRequestExpired({ expiresAt: new Date("2026-10-21T11:00:00Z") }, now)).toBe(false);
+ expect(isApprovalRequestExpired({ expiresAt: "2026-10-21T09:00:00Z" }, now)).toBe(true);
+ });
+});
+
+describe("getDelegatedApprovalRequestBlocker", () => {
+ test.each([
+ ["the request is gone", null, policy, DelegatedApprovalRequestBlocker.Missing],
+ [
+ "the request is no longer pending",
+ { ...pending, status: ApprovalRequestStatus.Cancelled },
+ policy,
+ DelegatedApprovalRequestBlocker.NotPending
+ ],
+ ["the request expired", { ...pending, expiresAt: new Date(0) }, policy, DelegatedApprovalRequestBlocker.Expired],
+ ["the delegated policy was removed", pending, null, DelegatedApprovalRequestBlocker.PolicyRemoved],
+ ["nothing blocks it", pending, policy, null]
+ ])("reports when %s", (_, request, delegatedPolicy, expected) => {
+ expect(getDelegatedApprovalRequestBlocker(request, delegatedPolicy)).toBe(expected);
+ });
+});
+
+describe("getDelegatedApprovalConnectionError", () => {
+ test("accepts the policy's connection in the request's org", () => {
+ expect(
+ getDelegatedApprovalConnectionError({
+ rawConnection: { orgId: "org-1" },
+ delegatedPolicy: policy,
+ organizationId: "org-1"
+ })
+ ).toBeNull();
+ });
+
+ test.each([
+ ["is missing", null],
+ ["belongs to another org", { orgId: "org-2" }]
+ ])("names the connection and the app to pick when the connection %s", (_, rawConnection) => {
+ const error = getDelegatedApprovalConnectionError({
+ rawConnection,
+ delegatedPolicy: policy,
+ organizationId: "org-1"
+ });
+
+ expect(error).toContain("App Connection with ID 'connection-1' was not found");
+ expect(error).toContain("ServiceNow Connection");
+ });
+});
diff --git a/backend/src/services/delegated-approval/delegated-approval-guards.ts b/backend/src/services/delegated-approval/delegated-approval-guards.ts
new file mode 100644
index 0000000000..c3d1c75f35
--- /dev/null
+++ b/backend/src/services/delegated-approval/delegated-approval-guards.ts
@@ -0,0 +1,44 @@
+import { TApprovalRequests } from "@app/db/schemas";
+import { APP_CONNECTION_NAME_MAP } from "@app/services/app-connection/app-connection-maps";
+import { ApprovalRequestStatus } from "@app/services/approval-policy/approval-policy-enums";
+
+import { DelegatedApprovalPolicyType } from "./delegated-approval-enums";
+import { DELEGATED_APPROVAL_CONNECTION_MAP } from "./delegated-approval-maps";
+import { TApprovalRequestExpiry, TGetDelegatedApprovalConnectionErrorDTO } from "./delegated-approval-types";
+
+// let's create this helper function inside the access approval global request bridge service
+export const isApprovalRequestExpired = (request: TApprovalRequestExpiry, now: Date = new Date()): boolean =>
+ Boolean(request.expiresAt && new Date(request.expiresAt) < now);
+
+export enum DelegatedApprovalRequestBlocker {
+ Missing = "missing",
+ NotPending = "not_pending",
+ Expired = "expired",
+ PolicyRemoved = "policy_removed"
+}
+
+// Why a request can no longer be handed to, or decided by, a delegated approval system, in the order
+// the callers check it. Each caller words the refusal for its own audience.
+export const getDelegatedApprovalRequestBlocker = (
+ approvalRequest: Pick<TApprovalRequests, "status" | "expiresAt"> | null | undefined,
+ delegatedPolicy: object | null | undefined
+): DelegatedApprovalRequestBlocker | null => {
+ if (!approvalRequest) return DelegatedApprovalRequestBlocker.Missing;
+ if (approvalRequest.status !== ApprovalRequestStatus.Pending) return DelegatedApprovalRequestBlocker.NotPending;
+ if (isApprovalRequestExpired(approvalRequest)) return DelegatedApprovalRequestBlocker.Expired;
+ if (!delegatedPolicy) return DelegatedApprovalRequestBlocker.PolicyRemoved;
+ return null;
+};
+
+// The connection a policy names must still exist in the request's org; anything else reads as "not
+// found" so one org cannot learn another org's connection ids.
+export const getDelegatedApprovalConnectionError = ({
+ rawConnection,
+ delegatedPolicy,
+ organizationId
+}: TGetDelegatedApprovalConnectionErrorDTO): string | null => {
+ if (rawConnection && rawConnection.orgId === organizationId) return null;
+
+ const connectionApp = DELEGATED_APPROVAL_CONNECTION_MAP[delegatedPolicy.type as DelegatedApprovalPolicyType];
+ return `App Connection with ID '${delegatedPolicy.connectionId}' was not found. Select a ${APP_CONNECTION_NAME_MAP[connectionApp]} Connection on the policy and create the request again.`;
+};
diff --git a/backend/src/services/delegated-approval/delegated-approval-maps.ts b/backend/src/services/delegated-approval/delegated-approval-maps.ts
index e6ae8c04ca..65b24319f1 100644
--- a/backend/src/services/delegated-approval/delegated-approval-maps.ts
+++ b/backend/src/services/delegated-approval/delegated-approval-maps.ts
@@ -1,7 +1,7 @@
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
import { ApprovalPolicyType } from "@app/services/approval-policy/approval-policy-enums";
-import { DelegatedApprovalPolicyType } from "./delegated-approval-enums";
+import { DelegatedApprovalPolicyType, DelegatedApprovalRequestStatus } from "./delegated-approval-enums";
export const DELEGATED_APPROVAL_NAME_MAP: Record<DelegatedApprovalPolicyType, string> = {
[DelegatedApprovalPolicyType.ServiceNow]: "ServiceNow"
@@ -11,6 +11,12 @@ export const DELEGATED_APPROVAL_CONNECTION_MAP: Record<DelegatedApprovalPolicyTy
[DelegatedApprovalPolicyType.ServiceNow]: AppConnection.ServiceNow
};
+export const DELEGATED_APPROVAL_FINAL_STATE = new Set<DelegatedApprovalRequestStatus>([
+ DelegatedApprovalRequestStatus.Approved,
+ DelegatedApprovalRequestStatus.Rejected,
+ DelegatedApprovalRequestStatus.Failed
+]);
+
const DELEGATED_APPROVAL_SUPPORTED_POLICY_TYPES = [ApprovalPolicyType.SecretAccess] as const;
export type DelegatedApprovalSupportedPolicyType = (typeof DELEGATED_APPROVAL_SUPPORTED_POLICY_TYPES)[number];
diff --git a/backend/src/services/delegated-approval/delegated-approval-request-dal.ts b/backend/src/services/delegated-approval/delegated-approval-request-dal.ts
index 03fc3aa9ab..92154ce09d 100644
--- a/backend/src/services/delegated-approval/delegated-approval-request-dal.ts
+++ b/backend/src/services/delegated-approval/delegated-approval-request-dal.ts
@@ -13,8 +13,6 @@ export type TDelegatedApprovalRequestWithApprovalRequest = TDelegatedApprovalReq
export const delegatedApprovalRequestDALFactory = (db: TDbClient) => {
const orm = ormify(db, TableName.DelegatedApprovalRequests);
- const primaryNode = () => db.primaryNode();
-
const findByProviderRequestId = async (providerRequestId: string) => {
try {
const row = await db
@@ -37,5 +35,5 @@ export const delegatedApprovalRequestDALFactory = (db: TDbClient) => {
}
};
- return { ...orm, primaryNode, findByProviderRequestId };
+ return { ...orm, findByProviderRequestId };
};
diff --git a/backend/src/services/delegated-approval/delegated-approval-request-fns.ts b/backend/src/services/delegated-approval/delegated-approval-request-fns.ts
new file mode 100644
index 0000000000..025c259fa2
--- /dev/null
+++ b/backend/src/services/delegated-approval/delegated-approval-request-fns.ts
@@ -0,0 +1,69 @@
+import { UnrecoverableError } from "bullmq";
+import { Knex } from "knex";
+
+import { ApprovalRequestStatus } from "@app/services/approval-policy/approval-policy-enums";
+
+import { DelegatedApprovalRequestStatus } from "./delegated-approval-enums";
+import {
+ TFailDelegatedApprovalRequestDeps,
+ TFailDelegatedApprovalRequestDTO,
+ TLoadDelegatedApprovalContextDeps
+} from "./delegated-approval-types";
+import { DELEGATED_APPROVAL_STATUS_REASON_MAX_CHARS } from "./dispatch/delegated-approval-dispatch-constants";
+
+export const toDelegatedApprovalStatusReason = (reason: string) =>
+ reason.slice(0, DELEGATED_APPROVAL_STATUS_REASON_MAX_CHARS);
+
+// 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) => {
+ const message = error instanceof Error ? error.message : String(error);
+ return {
+ terminal: error instanceof UnrecoverableError,
+ message,
+ logContext: { err: { name: (error as Error)?.name, message } }
+ };
+};
+
+// A delegated request that can no longer be decided closes the approval request with it, so the
+// requester is not left waiting and the policy is freed for editing. Only waiting_approval rows are
+// moved: a row that was already decided keeps its outcome.
+export const failDelegatedApprovalRequest = (
+ { id, requestId, reason, closeAs = ApprovalRequestStatus.Cancelled }: TFailDelegatedApprovalRequestDTO,
+ { approvalRequestDAL, delegatedApprovalRequestDAL }: TFailDelegatedApprovalRequestDeps,
+ tx?: Knex
+) => {
+ const run = async (trx: Knex) => {
+ const approvalRequest = await approvalRequestDAL.findByIdForUpdate(requestId, trx);
+ const [failed] = await delegatedApprovalRequestDAL.update(
+ { id, status: DelegatedApprovalRequestStatus.WaitingApproval },
+ { status: DelegatedApprovalRequestStatus.Failed, statusReason: toDelegatedApprovalStatusReason(reason) },
+ trx
+ );
+ if (failed && approvalRequest?.status === ApprovalRequestStatus.Pending) {
+ await approvalRequestDAL.updateById(requestId, { status: closeAs }, trx);
+ }
+ return Boolean(failed);
+ };
+
+ return tx ? run(tx) : approvalRequestDAL.transaction(run);
+};
+
+export const loadDelegatedApprovalContext = async (
+ delegatedRequestId: string,
+ { delegatedApprovalRequestDAL, approvalRequestDAL, delegatedApprovalPolicyDAL }: TLoadDelegatedApprovalContextDeps
+) => {
+ // The rows a worker needs to act on a delegated request, read from the primary because they were
+ // committed together with the event that woke the worker.
+ return delegatedApprovalRequestDAL.transaction(async (tx) => {
+ const delegatedRequest = await delegatedApprovalRequestDAL.findById(delegatedRequestId, tx);
+ if (!delegatedRequest) return null;
+
+ const approvalRequest = await approvalRequestDAL.findById(delegatedRequest.requestId, tx);
+ const delegatedPolicy = approvalRequest?.policyId
+ ? await delegatedApprovalPolicyDAL.findOne({ policyId: approvalRequest.policyId }, tx)
+ : null;
+
+ return { delegatedRequest, approvalRequest, delegatedPolicy };
+ });
+};
diff --git a/backend/src/services/delegated-approval/delegated-approval-schemas.ts b/backend/src/services/delegated-approval/delegated-approval-schemas.ts
index c1245e60d7..e8936f49bc 100644
--- a/backend/src/services/delegated-approval/delegated-approval-schemas.ts
+++ b/backend/src/services/delegated-approval/delegated-approval-schemas.ts
@@ -16,5 +16,7 @@ export const DelegatedApprovalRequestSchema = z.object({
statusReason: z
.string()
.nullable()
- .describe("Why the request could not be sent to the delegated approval system, when it could not.")
+ .describe(
+ "Why the request is not progressing in, or could not be completed by, the delegated approval system, when that is the case."
+ )
});
diff --git a/backend/src/services/delegated-approval/delegated-approval-service.ts b/backend/src/services/delegated-approval/delegated-approval-service.ts
index e2fe2f857a..bc0f24c938 100644
--- a/backend/src/services/delegated-approval/delegated-approval-service.ts
+++ b/backend/src/services/delegated-approval/delegated-approval-service.ts
@@ -9,12 +9,12 @@ 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 { ApprovalRequestStatus } from "@app/services/approval-policy/approval-policy-enums";
import { TEventEmitter } from "@app/services/event-outbox/event-outbox-types";
import { DelegatedApprovalPolicyType, DelegatedApprovalRequestStatus } from "./delegated-approval-enums";
import { emitDelegatedApprovalDispatchRequested } from "./delegated-approval-events";
import { assertPolicyTypeSupportsDelegatedApproval, listDelegatedApprovalOptions } from "./delegated-approval-fns";
+import { DelegatedApprovalRequestBlocker, getDelegatedApprovalRequestBlocker } from "./delegated-approval-guards";
import { 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";
@@ -38,6 +38,14 @@ type TDelegatedApprovalServiceFactoryDep = {
eventEmitter: TEventEmitter;
};
+const RETRY_DISPATCH_BLOCKER_MESSAGES: Record<DelegatedApprovalRequestBlocker, string> = {
+ [DelegatedApprovalRequestBlocker.Missing]: "Only pending requests can be sent again",
+ [DelegatedApprovalRequestBlocker.NotPending]: "Only pending requests can be sent again",
+ [DelegatedApprovalRequestBlocker.Expired]: "This request has expired. Create a new request instead.",
+ [DelegatedApprovalRequestBlocker.PolicyRemoved]:
+ "The policy for this request no longer uses an external approval system. Create a new request instead."
+};
+
export type TDelegatedApprovalServiceFactory = ReturnType<typeof delegatedApprovalServiceFactory>;
export const delegatedApprovalServiceFactory = ({
@@ -191,18 +199,11 @@ export const delegatedApprovalServiceFactory = ({
});
}
- if (approvalRequest.status !== ApprovalRequestStatus.Pending) {
- throw new BadRequestError({ message: "Only pending requests can be sent again" });
- }
-
- if (approvalRequest.expiresAt && new Date(approvalRequest.expiresAt) < new Date()) {
- throw new BadRequestError({ message: "This request has expired. Create a new request instead." });
- }
-
const delegatedPolicy = approvalRequest.policyId ? await getPolicyByPolicyId(approvalRequest.policyId) : null;
- if (!delegatedPolicy) {
+ const blocker = getDelegatedApprovalRequestBlocker(approvalRequest, delegatedPolicy);
+ if (blocker || !delegatedPolicy) {
throw new BadRequestError({
- message: "The policy for this request no longer uses an external approval system. Create a new request instead."
+ message: RETRY_DISPATCH_BLOCKER_MESSAGES[blocker ?? DelegatedApprovalRequestBlocker.PolicyRemoved]
});
}
diff --git a/backend/src/services/delegated-approval/delegated-approval-types.ts b/backend/src/services/delegated-approval/delegated-approval-types.ts
index c051fc5c25..343617cd21 100644
--- a/backend/src/services/delegated-approval/delegated-approval-types.ts
+++ b/backend/src/services/delegated-approval/delegated-approval-types.ts
@@ -1,7 +1,16 @@
-import { TApprovalRequests, TDelegatedApprovalPolicies, TDelegatedApprovalRequests } from "@app/db/schemas";
+import {
+ TAppConnections,
+ TApprovalRequests,
+ TDelegatedApprovalPolicies,
+ TDelegatedApprovalRequests
+} from "@app/db/schemas";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
+import { ApprovalRequestStatus } from "@app/services/approval-policy/approval-policy-enums";
+import { TApprovalRequestDALFactory } from "@app/services/approval-policy/approval-request-dal";
import { DelegatedApprovalPolicyType, DelegatedApprovalRequestStatus } from "./delegated-approval-enums";
+import { TDelegatedApprovalPolicyDALFactory } from "./delegated-approval-policy-dal";
+import { TDelegatedApprovalRequestDALFactory } from "./delegated-approval-request-dal";
export type TDelegatedApprovalListItem = {
name: string;
@@ -51,3 +60,29 @@ export type TUpdateDelegatedApprovalRequestDTO = {
status?: DelegatedApprovalRequestStatus;
statusReason?: string | null;
};
+
+export type TApprovalRequestExpiry = { expiresAt?: Date | string | null };
+
+export type TLoadDelegatedApprovalContextDeps = {
+ delegatedApprovalRequestDAL: Pick<TDelegatedApprovalRequestDALFactory, "findById" | "transaction">;
+ approvalRequestDAL: Pick<TApprovalRequestDALFactory, "findById">;
+ delegatedApprovalPolicyDAL: Pick<TDelegatedApprovalPolicyDALFactory, "findOne">;
+};
+
+export type TGetDelegatedApprovalConnectionErrorDTO = {
+ rawConnection: Pick<TAppConnections, "orgId"> | null | undefined;
+ delegatedPolicy: Pick<TDelegatedApprovalPolicies, "type" | "connectionId">;
+ organizationId: string;
+};
+
+export type TFailDelegatedApprovalRequestDeps = {
+ approvalRequestDAL: Pick<TApprovalRequestDALFactory, "transaction" | "findByIdForUpdate" | "updateById">;
+ delegatedApprovalRequestDAL: Pick<TDelegatedApprovalRequestDALFactory, "update">;
+};
+
+export type TFailDelegatedApprovalRequestDTO = {
+ id: string;
+ requestId: string;
+ reason: string;
+ closeAs?: ApprovalRequestStatus.Cancelled | ApprovalRequestStatus.Expired;
+};
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
index 866dc63a60..6cd0cb7008 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 +1,4 @@
export const DELEGATED_APPROVAL_STATUS_REASON_MAX_CHARS = 1_000;
+
+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.ts
index 0018143764..e5592bab52 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
@@ -99,7 +99,7 @@ const buildConsumer = ({
const consumer = delegatedApprovalDispatchConsumerFactory({
delegatedApprovalRequestDAL: {
findById: findById ?? vi.fn(async () => row),
- primaryNode: () => PRIMARY,
+ transaction: async (cb: (tx: never) => Promise<unknown>) => cb(PRIMARY),
update,
updateById
},
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.ts
index 311ab65386..26a8dc7713 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
@@ -4,10 +4,9 @@ import { ProjectType } from "@app/db/schemas";
import { logger } from "@app/lib/logger";
import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";
import { decryptAppConnection } from "@app/services/app-connection/app-connection-fns";
-import { APP_CONNECTION_NAME_MAP } from "@app/services/app-connection/app-connection-maps";
-import { ApprovalRequestStatus } from "@app/services/approval-policy/approval-policy-enums";
import { TApprovalRequestDALFactory } from "@app/services/approval-policy/approval-request-dal";
import { TDelegatedApprovalCallbackServiceFactory } from "@app/services/delegated-approval-callback/delegated-approval-callback-service";
+import { parseEventPayload, runEventsSerially } from "@app/services/event-outbox/event-outbox-fns";
import {
EventResultStatus,
IEventConsumer,
@@ -17,16 +16,25 @@ import {
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { TProjectDALFactory } from "@app/services/project/project-dal";
-import { DelegatedApprovalPolicyType, DelegatedApprovalRequestStatus } from "../delegated-approval-enums";
+import { DelegatedApprovalRequestStatus } from "../delegated-approval-enums";
import {
DELEGATED_APPROVAL_DISPATCH_REQUESTED_EVENT,
DelegatedApprovalDispatchRequestedPayloadSchema,
TDelegatedApprovalDispatchRequestedPayload
} from "../delegated-approval-events";
-import { DELEGATED_APPROVAL_CONNECTION_MAP } from "../delegated-approval-maps";
+import {
+ DelegatedApprovalRequestBlocker,
+ getDelegatedApprovalConnectionError,
+ getDelegatedApprovalRequestBlocker
+} from "../delegated-approval-guards";
import { TDelegatedApprovalPolicyDALFactory } from "../delegated-approval-policy-dal";
import { TDelegatedApprovalRequestDALFactory } from "../delegated-approval-request-dal";
-import { DELEGATED_APPROVAL_STATUS_REASON_MAX_CHARS } from "./delegated-approval-dispatch-constants";
+import {
+ loadDelegatedApprovalContext,
+ toDelegatedApprovalFailure,
+ toDelegatedApprovalStatusReason
+} from "../delegated-approval-request-fns";
+import { DELEGATED_APPROVAL_DISPATCH_RETRY_HINT } from "./delegated-approval-dispatch-constants";
import {
getDelegatedApprovalDispatchDetailsBuilder,
getDelegatedApprovalProvider
@@ -35,10 +43,20 @@ import { TDelegatedApprovalDispatchInput } from "./delegated-approval-dispatch-t
export const DELEGATED_APPROVAL_DISPATCH_CONSUMER = "delegated-approval-dispatch";
+const BLOCKER_MESSAGES: Record<DelegatedApprovalRequestBlocker, string> = {
+ [DelegatedApprovalRequestBlocker.Missing]: "The approval request no longer exists.",
+ [DelegatedApprovalRequestBlocker.NotPending]:
+ "The approval request is no longer pending, so it was not sent to the delegated approval system.",
+ [DelegatedApprovalRequestBlocker.Expired]:
+ "The approval request expired before it could be sent to the delegated approval system. Create the request again.",
+ [DelegatedApprovalRequestBlocker.PolicyRemoved]:
+ "The policy's delegated approver was removed before the request could be sent. Configure a delegated approver on the policy and create the request again."
+};
+
type TDelegatedApprovalDispatchConsumerDep = {
delegatedApprovalRequestDAL: Pick<
TDelegatedApprovalRequestDALFactory,
- "findById" | "primaryNode" | "update" | "updateById"
+ "findById" | "transaction" | "update" | "updateById"
>;
delegatedApprovalPolicyDAL: Pick<TDelegatedApprovalPolicyDALFactory, "findOne">;
delegatedApprovalCallbackService: Pick<
@@ -68,7 +86,7 @@ export const delegatedApprovalDispatchConsumerFactory = ({
{ id: delegatedRequestId, status: DelegatedApprovalRequestStatus.PendingDispatch },
{
status: DelegatedApprovalRequestStatus.FailedDispatch,
- statusReason: statusReason.slice(0, DELEGATED_APPROVAL_STATUS_REASON_MAX_CHARS)
+ statusReason: toDelegatedApprovalStatusReason(statusReason)
}
);
} catch (error) {
@@ -79,36 +97,26 @@ export const delegatedApprovalDispatchConsumerFactory = ({
}
};
- // Both rows were committed together with the event, so they are read from the primary.
- const $loadRequests = async (delegatedRequestId: string) => {
- const primary = delegatedApprovalRequestDAL.primaryNode();
-
- const delegatedRequest = await delegatedApprovalRequestDAL.findById(delegatedRequestId, primary);
- if (!delegatedRequest) return null;
-
- const approvalRequest = await approvalRequestDAL.findById(delegatedRequest.requestId, primary);
- const delegatedPolicy = approvalRequest?.policyId
- ? await delegatedApprovalPolicyDAL.findOne({ policyId: approvalRequest.policyId }, primary)
- : null;
-
- return { delegatedRequest, approvalRequest, delegatedPolicy };
- };
-
const $dispatch = async (delegatedRequestId: string): Promise<Omit<TEventConsumerResult, "id">> => {
- const requests = await $loadRequests(delegatedRequestId);
- if (!requests) {
+ const context = await loadDelegatedApprovalContext(delegatedRequestId, {
+ delegatedApprovalRequestDAL,
+ approvalRequestDAL,
+ delegatedApprovalPolicyDAL
+ });
+ if (!context) {
logger.warn(
`Delegated approval request no longer exists, skipping dispatch [delegatedRequestId=${delegatedRequestId}]`
);
return { status: EventResultStatus.Delivered };
}
- const { delegatedRequest, approvalRequest, delegatedPolicy } = requests;
+ const { delegatedRequest, approvalRequest, delegatedPolicy } = context;
+
+ const canDispatch =
+ delegatedRequest.status === DelegatedApprovalRequestStatus.PendingDispatch ||
+ delegatedRequest.status === DelegatedApprovalRequestStatus.FailedDispatch;
- if (
- delegatedRequest.status !== DelegatedApprovalRequestStatus.PendingDispatch &&
- delegatedRequest.status !== DelegatedApprovalRequestStatus.FailedDispatch
- ) {
+ if (!canDispatch) {
logger.info(
`Delegated approval request is not awaiting dispatch, skipping [delegatedRequestId=${delegatedRequestId}] [status=${delegatedRequest.status}]`
);
@@ -130,23 +138,9 @@ export const delegatedApprovalDispatchConsumerFactory = ({
}
try {
- if (!approvalRequest) {
- throw new UnrecoverableError("The approval request no longer exists.");
- }
- if (approvalRequest.status !== ApprovalRequestStatus.Pending) {
- throw new UnrecoverableError(
- "The approval request is no longer pending, so it was not sent to the delegated approval system."
- );
- }
- if (approvalRequest.expiresAt && new Date(approvalRequest.expiresAt) < new Date()) {
- throw new UnrecoverableError(
- "The approval request expired before it could be sent to the delegated approval system. Create the request again."
- );
- }
- 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 blocker = getDelegatedApprovalRequestBlocker(approvalRequest, delegatedPolicy);
+ if (blocker || !approvalRequest || !delegatedPolicy) {
+ throw new UnrecoverableError(BLOCKER_MESSAGES[blocker ?? DelegatedApprovalRequestBlocker.Missing]);
}
const provider = getDelegatedApprovalProvider(delegatedPolicy.type);
@@ -160,19 +154,20 @@ export const delegatedApprovalDispatchConsumerFactory = ({
);
}
- const primary = delegatedApprovalRequestDAL.primaryNode();
const [project, rawConnection] = await Promise.all([
- projectDAL.findById(approvalRequest.projectId, primary),
- appConnectionDAL.findById(delegatedPolicy.connectionId, primary)
+ projectDAL.findById(approvalRequest.projectId),
+ appConnectionDAL.findById(delegatedPolicy.connectionId)
]);
if (!project) {
throw new UnrecoverableError("The project of the approval request no longer exists.");
}
- if (!rawConnection || rawConnection.orgId !== approvalRequest.organizationId) {
- const connectionApp = DELEGATED_APPROVAL_CONNECTION_MAP[delegatedPolicy.type as DelegatedApprovalPolicyType];
- throw new UnrecoverableError(
- `App Connection with ID '${delegatedPolicy.connectionId}' was not found. Select a ${APP_CONNECTION_NAME_MAP[connectionApp]} Connection on the policy and create the request again.`
- );
+ const connectionError = getDelegatedApprovalConnectionError({
+ rawConnection,
+ delegatedPolicy,
+ organizationId: approvalRequest.organizationId
+ });
+ if (connectionError || !rawConnection) {
+ throw new UnrecoverableError(connectionError ?? "The policy's App Connection was not found.");
}
const connection = await decryptAppConnection(rawConnection, kmsService);
@@ -217,22 +212,18 @@ export const delegatedApprovalDispatchConsumerFactory = ({
);
return { status: EventResultStatus.Delivered };
} catch (error) {
- const isTerminal = error instanceof UnrecoverableError;
- const message = error instanceof Error ? error.message : String(error);
+ const { terminal, message, logContext } = toDelegatedApprovalFailure(error);
// The outbox decides when retries run out and the consumer never sees the attempt count, so the
// reason has to read true on every attempt. The row is failed_dispatch throughout, which is what
// makes the manual resend available while the outbox is still retrying.
await $markDispatchFailed(
delegatedRequestId,
- isTerminal
- ? message
- : `${message} Infisical will retry automatically. If it keeps failing, send the request again.`
+ terminal ? message : `${message} ${DELEGATED_APPROVAL_DISPATCH_RETRY_HINT}`
);
- const logContext = { err: { name: (error as Error)?.name, message } };
- const logMessage = `Delegated approval dispatch failed [delegatedRequestId=${delegatedRequestId}] [terminal=${isTerminal}]`;
- if (isTerminal) {
+ const logMessage = `Delegated approval dispatch failed [delegatedRequestId=${delegatedRequestId}] [terminal=${terminal}]`;
+ if (terminal) {
logger.error(logContext, logMessage);
return { status: EventResultStatus.Failed, error: message };
}
@@ -242,43 +233,20 @@ export const delegatedApprovalDispatchConsumerFactory = ({
};
const $handleEvent = async (event: TEvent): Promise<TEventConsumerResult> => {
- const id = String(event.id);
-
- const payload = DelegatedApprovalDispatchRequestedPayloadSchema.safeParse(event.payload);
- if (!payload.success) {
- return {
- id,
- status: EventResultStatus.Failed,
- error: `Unreadable delegated approval dispatch payload: ${payload.error.issues.map((issue) => issue.message).join(", ")}`
- };
- }
-
- return { id, ...(await $dispatch(payload.data.delegatedRequestId)) };
- };
-
- const handle = async (events: TEvent[]): Promise<TEventConsumerResult[]> => {
- const results: TEventConsumerResult[] = [];
-
- for (const event of events) {
- try {
- // eslint-disable-next-line no-await-in-loop -- one dispatch at a time, so two events for the same request never race
- results.push(await $handleEvent(event));
- } catch (error) {
- results.push({
- id: String(event.id),
- status: EventResultStatus.Retry,
- error: error instanceof Error ? error.message : "Unknown error"
- });
- }
- }
-
- return results;
+ const { data, failure } = parseEventPayload(
+ event,
+ DelegatedApprovalDispatchRequestedPayloadSchema,
+ "delegated approval dispatch"
+ );
+ if (failure) return failure;
+
+ return { id: String(event.id), ...(await $dispatch(data.delegatedRequestId)) };
};
return {
name: DELEGATED_APPROVAL_DISPATCH_CONSUMER,
payloadSchema: DelegatedApprovalDispatchRequestedPayloadSchema,
subscribesTo: (eventType: string) => eventType === DELEGATED_APPROVAL_DISPATCH_REQUESTED_EVENT,
- handle
+ handle: (events) => runEventsSerially(events, $handleEvent)
};
};
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
index 2eda92f61d..3380ff1c18 100644
--- a/backend/src/services/delegated-approval/dispatch/delegated-approval-dispatch-maps.ts
+++ b/backend/src/services/delegated-approval/dispatch/delegated-approval-dispatch-maps.ts
@@ -2,12 +2,12 @@ import { ApprovalPolicyType } from "@app/services/approval-policy/approval-polic
import { DelegatedApprovalPolicyType } from "../delegated-approval-enums";
import { DelegatedApprovalSupportedPolicyType } from "../delegated-approval-maps";
+import { serviceNowProvider } from "../providers/servicenow";
import { buildSecretAccessDispatchDetails } from "./delegated-approval-dispatch-builders";
import {
TDelegatedApprovalDispatchDetailsBuilder,
TDelegatedApprovalProvider
} from "./delegated-approval-dispatch-types";
-import { serviceNowProvider } from "./providers/servicenow";
export const DELEGATED_APPROVAL_PROVIDER_MAP: Record<DelegatedApprovalPolicyType, TDelegatedApprovalProvider> = {
[DelegatedApprovalPolicyType.ServiceNow]: serviceNowProvider
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
index 39e5838c93..26c01b9e3f 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
@@ -1,6 +1,10 @@
import { ProjectType, TApprovalRequests } from "@app/db/schemas";
import { TAppConnection } from "@app/services/app-connection/app-connection-types";
import { ApprovalPolicyType } from "@app/services/approval-policy/approval-policy-enums";
+import {
+ TDelegatedApprovalDecisionReadResult,
+ TDelegatedApprovalReadDecisionInput
+} from "@app/services/delegated-approval-decision/delegated-approval-decision-types";
export type TSecretAccessDispatchDetails = {
policyType: ApprovalPolicyType.SecretAccess;
@@ -37,6 +41,10 @@ export type TDelegatedApprovalProvider = {
input: TDelegatedApprovalDispatchInput,
connection: TAppConnection
) => Promise<TDelegatedApprovalDispatchResult>;
+ fetchDecision: (
+ input: TDelegatedApprovalReadDecisionInput,
+ connection: TAppConnection
+ ) => Promise<TDelegatedApprovalDecisionReadResult>;
};
export type TDelegatedApprovalDispatchDetailsBuilder = (
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
deleted file mode 100644
index 507c9a27ff..0000000000
--- a/backend/src/services/delegated-approval/dispatch/providers/servicenow/servicenow-enums.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-export enum ServiceNowRequestType {
- SecretAccess = "secret_access"
-}
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
deleted file mode 100644
index e7a222d2f4..0000000000
--- a/backend/src/services/delegated-approval/dispatch/providers/servicenow/servicenow-fns.ts
+++ /dev/null
@@ -1,232 +0,0 @@
-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 { DelegatedApprovalCallbackEvent } from "@app/services/delegated-approval-callback/delegated-approval-callback-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
-} from "./servicenow-constants";
-import { ServiceNowRequestType } from "./servicenow-enums";
-import {
- ServiceNowAccessRequestPayloadSchema,
- ServiceNowAccessRequestResponseSchema,
- ServiceNowErrorResponseSchema
-} from "./servicenow-schemas";
-import { TServiceNowAccessRequestOutcome, TServiceNowAccessRequestPayload } 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;
-
-// Scripted REST responses may arrive bare or wrapped in the platform's `result` envelope.
-const unwrapServiceNowResult = (data: unknown) =>
- data && typeof data === "object" && "result" in data ? (data as { result: unknown }).result : data;
-
-const buildRequestTypeFields = (details: TDelegatedApprovalDispatchDetails) => {
- switch (details.policyType) {
- case ApprovalPolicyType.SecretAccess:
- return {
- event: DelegatedApprovalCallbackEvent.SecretsManagementAccessRequest,
- request_type: ServiceNowRequestType.SecretAccess,
- environment: details.environment,
- secret_path: details.secretPath,
- permissions: details.permissions,
- is_temporary: details.isTemporary,
- ...(details.isTemporary && details.temporaryRange ? { temporary_range: details.temporaryRange } : {})
- };
- default: {
- const { policyType } = details as { policyType: string };
- throw new UnrecoverableError(`ServiceNow cannot review '${policyType}' requests.`);
- }
- }
-};
-
-export const buildServiceNowAccessRequestPayload = (
- input: TDelegatedApprovalDispatchInput
-): TServiceNowAccessRequestPayload => {
- const parsed = ServiceNowAccessRequestPayloadSchema.safeParse({
- request_id: input.approvalRequestId,
- callback_url: input.callback.url,
- callback_token: input.callback.token,
- product_type: input.productType,
- ...(input.project ? { project_id: input.project.id, project_name: input.project.name } : {}),
- requestor_email: input.requester.email,
- ...(input.requester.name ? { requestor_name: input.requester.name } : {}),
- ...(input.justification ? { justification: input.justification } : {}),
- ...buildRequestTypeFields(input.details)
- });
-
- if (!parsed.success) {
- const issues = parsed.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join("; ");
- throw new UnrecoverableError(
- `The request does not meet what the Infisical Approvals ServiceNow application accepts (${issues}).`
- );
- }
-
- return parsed.data;
-};
-
-export const parseServiceNowAccessRequestResponse = (
- status: number,
- data: unknown
-): TServiceNowAccessRequestOutcome => {
- const parsed = ServiceNowAccessRequestResponseSchema.safeParse(unwrapServiceNowResult(data));
- const sysId = parsed.success ? parsed.data.sys_id : null;
-
- if (status === 409) {
- if (!sysId) {
- throw new UnrecoverableError(
- "ServiceNow reported that it already holds this request but did not return the record ID."
- );
- }
- return { sysId, duplicate: true };
- }
-
- if (!sysId) {
- throw new BadRequestError({
- message: "ServiceNow accepted the request but returned a response without the record ID."
- });
- }
-
- return { sysId, duplicate: false };
-};
-
-const extractErrorDetail = (data: unknown) => {
- const parsed = ServiceNowErrorResponseSchema.safeParse(unwrapServiceNowResult(data));
- if (!parsed.success) return null;
-
- const { error } = parsed.data;
- if (error === undefined || error === null) return null;
-
- const detail = typeof error === "string" ? error : JSON.stringify(error);
- return detail.slice(0, SERVICENOW_ERROR_DETAIL_MAX_CHARS);
-};
-
-// Retryable failures are BadRequestError; anything a retry cannot fix is UnrecoverableError.
-export const 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) {
- logger.warn(
- { status, instance },
- `ServiceNow instance ${instance} is rate limiting requests from Infisical (HTTP 429).`
- );
- return new BadRequestError({
- message: `ServiceNow instance ${instance} could not accept the request.`
- });
- }
-
- return new BadRequestError({
- message: `ServiceNow instance ${instance} returned a server error (HTTP ${status}).`
- });
-};
-
-const dispatchServiceNowRequest: 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 };
-};
-
-export const serviceNowProvider: TDelegatedApprovalProvider = { dispatch: dispatchServiceNowRequest };
diff --git a/backend/src/services/delegated-approval/dispatch/providers/servicenow/index.ts b/backend/src/services/delegated-approval/providers/servicenow/index.ts
similarity index 100%
rename from backend/src/services/delegated-approval/dispatch/providers/servicenow/index.ts
rename to backend/src/services/delegated-approval/providers/servicenow/index.ts
diff --git a/backend/src/services/delegated-approval/dispatch/providers/servicenow/servicenow-constants.ts b/backend/src/services/delegated-approval/providers/servicenow/servicenow-constants.ts
similarity index 63%
rename from backend/src/services/delegated-approval/dispatch/providers/servicenow/servicenow-constants.ts
rename to backend/src/services/delegated-approval/providers/servicenow/servicenow-constants.ts
index 74e19e5c80..5a2be4ab52 100644
--- a/backend/src/services/delegated-approval/dispatch/providers/servicenow/servicenow-constants.ts
+++ b/backend/src/services/delegated-approval/providers/servicenow/servicenow-constants.ts
@@ -5,3 +5,6 @@ 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;
+
+// The permissions column of the Infisical Approvals ServiceNow application truncates silently past this.
+export const SERVICENOW_PERMISSIONS_MAX_CHARS = 4_000;
diff --git a/backend/src/services/delegated-approval/providers/servicenow/servicenow-enums.ts b/backend/src/services/delegated-approval/providers/servicenow/servicenow-enums.ts
new file mode 100644
index 0000000000..e0252c4090
--- /dev/null
+++ b/backend/src/services/delegated-approval/providers/servicenow/servicenow-enums.ts
@@ -0,0 +1,13 @@
+export enum ServiceNowRequestType {
+ SecretAccess = "secret_access"
+}
+
+export enum ServiceNowDecision {
+ Approved = "approved",
+ Rejected = "rejected"
+}
+
+export enum ServiceNowRequestOperation {
+ Dispatch = "dispatch",
+ Read = "read"
+}
diff --git a/backend/src/services/delegated-approval/dispatch/providers/servicenow/servicenow-fns.test.ts b/backend/src/services/delegated-approval/providers/servicenow/servicenow-fns.test.ts
similarity index 62%
rename from backend/src/services/delegated-approval/dispatch/providers/servicenow/servicenow-fns.test.ts
rename to backend/src/services/delegated-approval/providers/servicenow/servicenow-fns.test.ts
index 94e5c22529..0aa4830b48 100644
--- a/backend/src/services/delegated-approval/dispatch/providers/servicenow/servicenow-fns.test.ts
+++ b/backend/src/services/delegated-approval/providers/servicenow/servicenow-fns.test.ts
@@ -1,19 +1,26 @@
import { AxiosError, AxiosHeaders } from "axios";
import { UnrecoverableError } from "bullmq";
-import { describe, expect, test } from "vitest";
+import { describe, expect, test, vi } 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 { DelegatedApprovalDecision } from "@app/services/delegated-approval-decision/delegated-approval-decision-enums";
-import { TDelegatedApprovalDispatchInput } from "../../delegated-approval-dispatch-types";
-import { ServiceNowRequestType } from "./servicenow-enums";
+import { TDelegatedApprovalDispatchInput } from "../../dispatch/delegated-approval-dispatch-types";
+import { ServiceNowRequestOperation, ServiceNowRequestType } from "./servicenow-enums";
import {
buildServiceNowAccessRequestPayload,
parseServiceNowAccessRequestResponse,
- toServiceNowDispatchError
+ parseServiceNowDecision,
+ toServiceNowRequestError
} from "./servicenow-fns";
+vi.mock("@app/lib/logger", () => ({
+ logger: { info: () => {}, warn: () => {}, error: () => {}, debug: () => {} },
+ initLogger: () => {}
+}));
+
const INSTANCE_URL = "https://acme.service-now.com";
const CALLBACK_TOKEN = "callback-token-plaintext";
@@ -104,6 +111,23 @@ describe("buildServiceNowAccessRequestPayload", () => {
).toThrow(UnrecoverableError);
});
+ test("refuses a permission list longer than the ServiceNow column stores", () => {
+ expect(() =>
+ buildServiceNowAccessRequestPayload(
+ makeInput({
+ details: {
+ policyType: ApprovalPolicyType.SecretAccess,
+ environment: "prod",
+ secretPath: "/",
+ permissions: Array.from({ length: 200 }, (_, i) => `subject-${i}: ${"x".repeat(20)}`),
+ isTemporary: false,
+ temporaryRange: null
+ }
+ })
+ )
+ ).toThrow(/too long for ServiceNow to store/);
+ });
+
test("refuses a temporary range longer than ServiceNow stores", () => {
expect(() =>
buildServiceNowAccessRequestPayload(
@@ -154,7 +178,7 @@ describe("parseServiceNowAccessRequestResponse", () => {
});
});
-describe("toServiceNowDispatchError", () => {
+describe("toServiceNowRequestError", () => {
test.each([
[302, UnrecoverableError, /credentials/],
[401, UnrecoverableError, /credentials/],
@@ -166,15 +190,22 @@ describe("toServiceNowDispatchError", () => {
[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);
+ const error = toServiceNowRequestError(makeAxiosError(status), INSTANCE_URL);
expect(error).toBeInstanceOf(errorClass);
expect(error.message).toMatch(message);
expect(error.message).toContain("acme.service-now.com");
});
+ test("names the missing record when a read returns 404", () => {
+ const error = toServiceNowRequestError(makeAxiosError(404), INSTANCE_URL, ServiceNowRequestOperation.Read);
+
+ expect(error).toBeInstanceOf(UnrecoverableError);
+ expect(error.message).toMatch(/no longer has the record for this request/);
+ });
+
test("includes the detail ServiceNow returned on a validation failure", () => {
- const error = toServiceNowDispatchError(
+ const error = toServiceNowRequestError(
makeAxiosError(400, { result: { error: "Missing required field: environment" } }),
INSTANCE_URL
);
@@ -183,16 +214,79 @@ describe("toServiceNowDispatchError", () => {
});
test("retries when there was no response at all", () => {
- const error = toServiceNowDispatchError(makeAxiosError(undefined, undefined, "ECONNABORTED"), INSTANCE_URL);
+ const error = toServiceNowRequestError(makeAxiosError(undefined, undefined, "ECONNABORTED"), INSTANCE_URL);
expect(error).toBeInstanceOf(BadRequestError);
expect(error.message).toMatch(/could not be reached \(ECONNABORTED\)/);
});
test("never echoes the request path, credentials or token", () => {
- const error = toServiceNowDispatchError(makeAxiosError(401), INSTANCE_URL);
+ const error = toServiceNowRequestError(makeAxiosError(401), INSTANCE_URL);
expect(error.message).not.toContain("x_infis_approvals");
expect(error.message).not.toContain(CALLBACK_TOKEN);
});
});
+
+describe("parseServiceNowDecision", () => {
+ const record = (overrides: Record<string, unknown> = {}) => ({
+ sys_id: "abc",
+ request_id: "request-1",
+ permissions: "secrets: create, read\nsecret-folders: edit",
+ state: "callback_pending",
+ decision: "approved",
+ approved_by: "",
+ decision_date: "2026-10-20 10:15:00",
+ decision_notes: null,
+ ...overrides
+ });
+
+ test("reads an approved record, bare or enveloped", () => {
+ const expected = {
+ status: "decided",
+ decision: DelegatedApprovalDecision.Approved,
+ approvalRequestId: "request-1",
+ permissions: ["secrets: create, read", "secret-folders: edit"],
+ decidedBy: null,
+ decidedAt: "2026-10-20 10:15:00",
+ notes: null
+ };
+
+ expect(parseServiceNowDecision({ success: true, data: record() })).toEqual(expected);
+ expect(parseServiceNowDecision({ result: { success: true, data: record() } })).toEqual(expected);
+ });
+
+ test("reads a rejected record with its notes, whatever the state says", () => {
+ expect(
+ parseServiceNowDecision({
+ result: { success: true, data: record({ decision: " Rejected ", state: "completed", decision_notes: "No." }) }
+ })
+ ).toMatchObject({ status: "decided", decision: DelegatedApprovalDecision.Rejected, notes: "No." });
+ });
+
+ test.each([null, "", " "])("is pending while decision is %j, naming the state", (decision) => {
+ expect(
+ parseServiceNowDecision({ result: { success: true, data: record({ decision, state: "completed" }) } })
+ ).toEqual({
+ status: "pending",
+ reason: "ServiceNow has not recorded a decision for this request yet (state: completed)."
+ });
+ });
+
+ test("gives up on a decision it does not recognise", () => {
+ expect(() => parseServiceNowDecision({ result: { success: true, data: record({ decision: "maybe" }) } })).toThrow(
+ UnrecoverableError
+ );
+ });
+
+ test("gives up when the stored permission list was cut short", () => {
+ expect(() =>
+ parseServiceNowDecision({ result: { success: true, data: record({ permissions: "x".repeat(4000) }) } })
+ ).toThrow(/cut short/);
+ });
+
+ test("retries a response it cannot read", () => {
+ expect(() => parseServiceNowDecision("<html>")).toThrow(BadRequestError);
+ expect(() => parseServiceNowDecision({ result: { success: false, error: "nope" } })).toThrow(BadRequestError);
+ });
+});
diff --git a/backend/src/services/delegated-approval/providers/servicenow/servicenow-fns.ts b/backend/src/services/delegated-approval/providers/servicenow/servicenow-fns.ts
new file mode 100644
index 0000000000..711f9be6fd
--- /dev/null
+++ b/backend/src/services/delegated-approval/providers/servicenow/servicenow-fns.ts
@@ -0,0 +1,355 @@
+import { AxiosError, AxiosRequestConfig } from "axios";
+import { UnrecoverableError } from "bullmq";
+
+import { BadRequestError } from "@app/lib/errors";
+import { logger, sanitizeUrlForLog } from "@app/lib/logger";
+import { safeRequest } from "@app/lib/validator/safe-request";
+import { AppConnection } from "@app/services/app-connection/app-connection-enums";
+import { TAppConnection } from "@app/services/app-connection/app-connection-types";
+import { TServiceNowConnection } from "@app/services/app-connection/servicenow";
+import { ApprovalPolicyType } from "@app/services/approval-policy/approval-policy-enums";
+import { DELEGATED_APPROVAL_CALLBACK_PATH } from "@app/services/delegated-approval-callback/delegated-approval-callback-constants";
+import { DelegatedApprovalCallbackEvent } from "@app/services/delegated-approval-callback/delegated-approval-callback-enums";
+import { DelegatedApprovalDecision } from "@app/services/delegated-approval-decision/delegated-approval-decision-enums";
+import { TDelegatedApprovalDecisionReadResult } from "@app/services/delegated-approval-decision/delegated-approval-decision-types";
+
+import {
+ TDelegatedApprovalDispatchDetails,
+ TDelegatedApprovalDispatchInput,
+ TDelegatedApprovalProvider
+} from "../../dispatch/delegated-approval-dispatch-types";
+import {
+ SERVICENOW_ACCESS_REQUEST_PATH,
+ SERVICENOW_DISPATCH_MAX_CONTENT_LENGTH,
+ SERVICENOW_DISPATCH_TIMEOUT_MS,
+ SERVICENOW_ERROR_DETAIL_MAX_CHARS,
+ SERVICENOW_PERMISSIONS_MAX_CHARS
+} from "./servicenow-constants";
+import { ServiceNowDecision, ServiceNowRequestOperation, ServiceNowRequestType } from "./servicenow-enums";
+import {
+ ServiceNowAccessRequestPayloadSchema,
+ ServiceNowAccessResponseRecordSchema,
+ ServiceNowAccessRequestResponseSchema,
+ ServiceNowErrorResponseSchema
+} from "./servicenow-schemas";
+import {
+ TServiceNowAccessRequestOutcome,
+ TServiceNowAccessRequestPayload,
+ TServiceNowRequestFailureContext
+} from "./servicenow-types";
+
+const describeInstance = (instanceUrl: string) => {
+ try {
+ return new URL(instanceUrl).host;
+ } catch {
+ return "the configured instance";
+ }
+};
+
+function assertServiceNowConnection(connection: TAppConnection): asserts connection is TServiceNowConnection {
+ if (connection.app !== AppConnection.ServiceNow) {
+ throw new UnrecoverableError(`App Connection with ID '${connection.id}' is not a ServiceNow Connection.`);
+ }
+}
+
+const buildServiceNowRequestConfig = (
+ { username, password }: TServiceNowConnection["credentials"],
+ overrides: Partial<AxiosRequestConfig> = {}
+): AxiosRequestConfig => ({
+ auth: { username, password },
+ timeout: SERVICENOW_DISPATCH_TIMEOUT_MS,
+ maxContentLength: SERVICENOW_DISPATCH_MAX_CONTENT_LENGTH,
+ "axios-retry": { retries: 0 },
+ ...overrides,
+ headers: { Accept: "application/json", ...overrides.headers }
+});
+
+// Scripted REST responses may arrive bare or wrapped in the platform's `result` envelope.
+const unwrapServiceNowResult = (data: unknown) =>
+ data && typeof data === "object" && "result" in data ? (data as { result: unknown }).result : data;
+
+const buildRequestTypeFields = (details: TDelegatedApprovalDispatchDetails) => {
+ switch (details.policyType) {
+ case ApprovalPolicyType.SecretAccess:
+ return {
+ event: DelegatedApprovalCallbackEvent.SecretsManagementAccessRequest,
+ request_type: ServiceNowRequestType.SecretAccess,
+ environment: details.environment,
+ secret_path: details.secretPath,
+ permissions: details.permissions,
+ is_temporary: details.isTemporary,
+ ...(details.isTemporary && details.temporaryRange ? { temporary_range: details.temporaryRange } : {})
+ };
+ default: {
+ const { policyType } = details as { policyType: string };
+ throw new UnrecoverableError(`ServiceNow cannot review '${policyType}' requests.`);
+ }
+ }
+};
+
+export const buildServiceNowAccessRequestPayload = (
+ input: TDelegatedApprovalDispatchInput
+): TServiceNowAccessRequestPayload => {
+ const parsed = ServiceNowAccessRequestPayloadSchema.safeParse({
+ request_id: input.approvalRequestId,
+ callback_url: `https://columbus-stretchable-omega.ngrok-free.dev${DELEGATED_APPROVAL_CALLBACK_PATH}`,
+ callback_token: input.callback.token,
+ product_type: input.productType,
+ ...(input.project ? { project_id: input.project.id, project_name: input.project.name } : {}),
+ requestor_email: input.requester.email,
+ ...(input.requester.name ? { requestor_name: input.requester.name } : {}),
+ ...(input.justification ? { justification: input.justification } : {}),
+ ...buildRequestTypeFields(input.details)
+ });
+
+ if (!parsed.success) {
+ const issues = parsed.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join("; ");
+ throw new UnrecoverableError(
+ `The request does not meet what the Infisical Approvals ServiceNow application accepts (${issues}).`
+ );
+ }
+
+ return parsed.data;
+};
+
+export const parseServiceNowAccessRequestResponse = (
+ status: number,
+ data: unknown
+): TServiceNowAccessRequestOutcome => {
+ const parsed = ServiceNowAccessRequestResponseSchema.safeParse(unwrapServiceNowResult(data));
+ const sysId = parsed.success ? parsed.data.sys_id : null;
+
+ if (status === 409) {
+ if (!sysId) {
+ throw new UnrecoverableError(
+ "ServiceNow reported that it already holds this request but did not return the record ID."
+ );
+ }
+ return { sysId, duplicate: true };
+ }
+
+ if (!sysId) {
+ throw new BadRequestError({
+ message: "ServiceNow accepted the request but returned a response without the record ID."
+ });
+ }
+
+ return { sysId, duplicate: false };
+};
+
+const extractErrorDetail = (data: unknown) => {
+ const parsed = ServiceNowErrorResponseSchema.safeParse(unwrapServiceNowResult(data));
+ if (!parsed.success) return null;
+
+ const { error } = parsed.data;
+ if (error === undefined || error === null) return null;
+
+ const detail = typeof error === "string" ? error : JSON.stringify(error);
+ return detail.slice(0, SERVICENOW_ERROR_DETAIL_MAX_CHARS);
+};
+
+// Retryable failures are BadRequestError; anything a retry cannot fix is UnrecoverableError.
+export const toServiceNowRequestError = (
+ err: unknown,
+ instanceUrl: string,
+ operation: ServiceNowRequestOperation = ServiceNowRequestOperation.Dispatch
+) => {
+ const instance = describeInstance(instanceUrl);
+ const unreachable = (code?: string) =>
+ new BadRequestError({
+ message: `ServiceNow instance ${instance} could not be reached${code ? ` (${code})` : ""}. Check the instance URL and that the instance is reachable from Infisical.`
+ });
+
+ if (!(err instanceof AxiosError)) return unreachable();
+
+ const status = err.response?.status;
+ if (!status) return unreachable(err.code);
+
+ // ServiceNow answers an unauthenticated request with a redirect to its login page, and safeRequest
+ // does not follow redirects, so a rejected credential arrives as a 3xx rather than a 401.
+ if ((status >= 300 && status < 400) || status === 401 || status === 403) {
+ return new UnrecoverableError(
+ `ServiceNow instance ${instance} rejected the integration user's credentials (HTTP ${status}). Verify the username and password of the ServiceNow Connection and that the account is active.`
+ );
+ }
+
+ if (status === 404) {
+ return new UnrecoverableError(
+ operation === ServiceNowRequestOperation.Read
+ ? `ServiceNow instance ${instance} no longer has the record for this request (HTTP 404). Create the request again.`
+ : `ServiceNow instance ${instance} has no Infisical Approvals application endpoint (HTTP 404). Install and activate the Infisical Approvals application on the instance.`
+ );
+ }
+
+ if (status === 400 || status === 422) {
+ const detail = extractErrorDetail(err.response?.data);
+ return new UnrecoverableError(
+ `ServiceNow instance ${instance} rejected the request (HTTP ${status})${detail ? `: ${detail}` : ""}.`
+ );
+ }
+
+ if (status === 429) {
+ 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}).`
+ });
+};
+
+// safeRequest's own refusals (private IP, unresolvable host, credentials in the URL) already name
+// what is wrong and pass through. Everything else is logged without the raw error, which carries the
+// password at config.auth.password and, on dispatch, the callback token in config.data.
+const toLoggedServiceNowRequestError = (
+ error: unknown,
+ {
+ instanceUrl,
+ connectionId,
+ operation,
+ action,
+ delegatedRequestId,
+ approvalRequestId
+ }: TServiceNowRequestFailureContext
+) => {
+ if (error instanceof BadRequestError) return error;
+
+ const responseStatus = error instanceof AxiosError ? error.response?.status : undefined;
+ const code = error instanceof AxiosError ? error.code : undefined;
+
+ logger.warn(
+ {
+ status: responseStatus,
+ code,
+ message: (error as Error)?.message,
+ instanceUrl: sanitizeUrlForLog(instanceUrl)
+ },
+ `${action} [delegatedRequestId=${delegatedRequestId}] [approvalRequestId=${approvalRequestId}] [connectionId=${connectionId}] [status=${responseStatus ?? "none"}]`
+ );
+
+ return toServiceNowRequestError(error, instanceUrl, operation);
+};
+
+const dispatchServiceNowRequest: TDelegatedApprovalProvider["dispatch"] = async (input, connection) => {
+ assertServiceNowConnection(connection);
+
+ const { instanceUrl } = connection.credentials;
+ const payload = buildServiceNowAccessRequestPayload(input);
+
+ let status: number;
+ let data: unknown;
+ try {
+ const response = await safeRequest.post<unknown>(
+ `${instanceUrl}${SERVICENOW_ACCESS_REQUEST_PATH}`,
+ payload,
+ buildServiceNowRequestConfig(connection.credentials, {
+ headers: { "Content-Type": "application/json" },
+ validateStatus: (code) => (code >= 200 && code < 300) || code === 409
+ })
+ );
+ status = response.status;
+ data = response.data;
+ } catch (error) {
+ throw toLoggedServiceNowRequestError(error, {
+ instanceUrl,
+ connectionId: connection.id,
+ operation: ServiceNowRequestOperation.Dispatch,
+ action: "Failed to send delegated approval request to ServiceNow",
+ delegatedRequestId: input.delegatedRequestId,
+ approvalRequestId: input.approvalRequestId
+ });
+ }
+
+ const outcome = parseServiceNowAccessRequestResponse(status, data);
+
+ if (outcome.duplicate) {
+ logger.warn(
+ `ServiceNow already held a record for this delegated approval request from an earlier attempt [delegatedRequestId=${input.delegatedRequestId}] [approvalRequestId=${input.approvalRequestId}] [sysId=${outcome.sysId}]`
+ );
+ }
+
+ return { providerRequestId: outcome.sysId };
+};
+
+const toOptionalText = (value: string | null | undefined) => {
+ const text = value?.trim() ?? "";
+ return text || null;
+};
+
+// The application stamps `decision` before it posts the callback and never changes it afterwards,
+// so it alone says whether the request was decided; `state` only describes where the record is.
+export const parseServiceNowDecision = (data: unknown): TDelegatedApprovalDecisionReadResult => {
+ const parsed = ServiceNowAccessResponseRecordSchema.safeParse(unwrapServiceNowResult(data));
+ if (!parsed.success) {
+ throw new BadRequestError({
+ message: "ServiceNow returned the access request in a form Infisical could not read."
+ });
+ }
+
+ const { data: record } = parsed.data;
+ const recorded = toOptionalText(record.decision)?.toLowerCase() ?? null;
+
+ if (!recorded) {
+ return {
+ status: "pending",
+ reason: `ServiceNow has not recorded a decision for this request yet${record.state ? ` (state: ${record.state})` : ""}.`
+ };
+ }
+
+ const decision = {
+ [ServiceNowDecision.Approved]: DelegatedApprovalDecision.Approved,
+ [ServiceNowDecision.Rejected]: DelegatedApprovalDecision.Rejected
+ }[recorded as ServiceNowDecision];
+ if (!decision) {
+ throw new UnrecoverableError(`ServiceNow recorded a decision Infisical does not recognise ('${recorded}').`);
+ }
+
+ const permissions = record.permissions ?? "";
+ if (permissions.length >= SERVICENOW_PERMISSIONS_MAX_CHARS) {
+ throw new UnrecoverableError(
+ "The permission list on the ServiceNow record was cut short, so Infisical cannot verify what was approved. Split the request into smaller ones."
+ );
+ }
+
+ return {
+ status: "decided",
+ decision,
+ approvalRequestId: toOptionalText(record.request_id),
+ permissions: permissions.split(/\r?\n/),
+ decidedBy: toOptionalText(record.approved_by),
+ decidedAt: toOptionalText(record.decision_date),
+ notes: toOptionalText(record.decision_notes)
+ };
+};
+
+const fetchServiceNowDecision: TDelegatedApprovalProvider["fetchDecision"] = async (input, connection) => {
+ assertServiceNowConnection(connection);
+
+ const { instanceUrl } = connection.credentials;
+
+ let data: unknown;
+ try {
+ const response = await safeRequest.get<unknown>(
+ `${instanceUrl}${SERVICENOW_ACCESS_REQUEST_PATH}/${encodeURIComponent(input.providerRequestId)}`,
+ buildServiceNowRequestConfig(connection.credentials)
+ );
+ data = response.data;
+ } catch (error) {
+ throw toLoggedServiceNowRequestError(error, {
+ instanceUrl,
+ connectionId: connection.id,
+ operation: ServiceNowRequestOperation.Read,
+ action: "Failed to read the delegated approval decision from ServiceNow",
+ delegatedRequestId: input.delegatedRequestId,
+ approvalRequestId: input.approvalRequestId
+ });
+ }
+
+ return parseServiceNowDecision(data);
+};
+
+export const serviceNowProvider: TDelegatedApprovalProvider = {
+ dispatch: dispatchServiceNowRequest,
+ fetchDecision: fetchServiceNowDecision
+};
diff --git a/backend/src/services/delegated-approval/dispatch/providers/servicenow/servicenow-schemas.ts b/backend/src/services/delegated-approval/providers/servicenow/servicenow-schemas.ts
similarity index 55%
rename from backend/src/services/delegated-approval/dispatch/providers/servicenow/servicenow-schemas.ts
rename to backend/src/services/delegated-approval/providers/servicenow/servicenow-schemas.ts
index 4b174ae7d1..dabde2463a 100644
--- a/backend/src/services/delegated-approval/dispatch/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 { SERVICENOW_PERMISSIONS_MAX_CHARS } from "./servicenow-constants";
import { ServiceNowRequestType } from "./servicenow-enums";
// Mirrors what the Infisical Approvals ServiceNow application accepts, so a request that would be
@@ -20,7 +21,14 @@ export const ServiceNowAccessRequestPayloadSchema = z.object({
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(),
+ permissions: z
+ .string()
+ .array()
+ .refine(
+ (lines) => lines.join("\n").length <= SERVICENOW_PERMISSIONS_MAX_CHARS,
+ "The permission list is too long for ServiceNow to store. Split it into smaller requests"
+ )
+ .optional(),
requestor_name: z.string().min(1).max(255).optional(),
is_temporary: z.boolean().optional(),
temporary_range: z.string().min(1).max(50).optional(),
@@ -34,3 +42,21 @@ export const ServiceNowAccessRequestResponseSchema = z.object({
export const ServiceNowErrorResponseSchema = z.object({
error: z.unknown().optional()
});
+
+const ServiceNowNullableText = z.string().max(SERVICENOW_PERMISSIONS_MAX_CHARS).nullable().optional();
+
+// The read projection of the Infisical Approvals ServiceNow application. Every field arrives as a
+// string, and an empty field as null.
+export const ServiceNowAccessResponseRecordSchema = z.object({
+ success: z.boolean().optional(),
+ data: z.object({
+ sys_id: ServiceNowNullableText,
+ request_id: ServiceNowNullableText,
+ permissions: ServiceNowNullableText,
+ state: z.string().max(100).nullable().optional(),
+ decision: ServiceNowNullableText,
+ approved_by: ServiceNowNullableText,
+ decision_date: ServiceNowNullableText,
+ decision_notes: ServiceNowNullableText
+ })
+});
diff --git a/backend/src/services/delegated-approval/dispatch/providers/servicenow/servicenow-types.ts b/backend/src/services/delegated-approval/providers/servicenow/servicenow-types.ts
similarity index 51%
rename from backend/src/services/delegated-approval/dispatch/providers/servicenow/servicenow-types.ts
rename to backend/src/services/delegated-approval/providers/servicenow/servicenow-types.ts
index 753884c9ca..7811fb3c77 100644
--- a/backend/src/services/delegated-approval/dispatch/providers/servicenow/servicenow-types.ts
+++ b/backend/src/services/delegated-approval/providers/servicenow/servicenow-types.ts
@@ -1,5 +1,6 @@
import { z } from "zod";
+import { ServiceNowRequestOperation } from "./servicenow-enums";
import { ServiceNowAccessRequestPayloadSchema } from "./servicenow-schemas";
export type TServiceNowAccessRequestPayload = z.infer<typeof ServiceNowAccessRequestPayloadSchema>;
@@ -8,3 +9,12 @@ export type TServiceNowAccessRequestOutcome = {
sysId: string;
duplicate: boolean;
};
+
+export type TServiceNowRequestFailureContext = {
+ instanceUrl: string;
+ connectionId: string;
+ operation: ServiceNowRequestOperation;
+ action: string;
+ delegatedRequestId: string;
+ approvalRequestId: string;
+};
diff --git a/backend/src/services/event-outbox/event-outbox-fns.ts b/backend/src/services/event-outbox/event-outbox-fns.ts
new file mode 100644
index 0000000000..29f5b40f8d
--- /dev/null
+++ b/backend/src/services/event-outbox/event-outbox-fns.ts
@@ -0,0 +1,46 @@
+import { z } from "zod";
+
+import { EventResultStatus, TEvent, TEventConsumerResult } from "./event-outbox-types";
+
+// A payload that fails the consumer's schema is a bug at the emit site, so the event is failed with
+// the issues named rather than retried.
+export const parseEventPayload = <T extends z.ZodTypeAny>(
+ event: TEvent,
+ schema: T,
+ label: string
+): { data: z.infer<T>; failure?: undefined } | { data?: undefined; failure: TEventConsumerResult } => {
+ const parsed = schema.safeParse(event.payload);
+ if (parsed.success) return { data: parsed.data as z.infer<T> };
+
+ return {
+ failure: {
+ id: String(event.id),
+ status: EventResultStatus.Failed,
+ error: `Unreadable ${label} payload: ${parsed.error.issues.map((issue) => issue.message).join(", ")}`
+ }
+ };
+};
+
+// One event at a time, so two events for the same resource never race, and a throw costs only that
+// event a retry instead of the whole batch.
+export const runEventsSerially = async (
+ events: TEvent[],
+ handleEvent: (event: TEvent) => Promise<TEventConsumerResult>
+): Promise<TEventConsumerResult[]> => {
+ const results: TEventConsumerResult[] = [];
+
+ for (const event of events) {
+ try {
+ // eslint-disable-next-line no-await-in-loop -- ordering is the point
+ results.push(await handleEvent(event));
+ } catch (error) {
+ results.push({
+ id: String(event.id),
+ status: EventResultStatus.Retry,
+ error: error instanceof Error ? error.message : "Unknown error"
+ });
+ }
+ }
+
+ return results;
+};
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 557018ed31..9e574d923d 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
@@ -35,6 +35,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 { isApprovalRequestExpired } from "@app/services/delegated-approval/delegated-approval-guards";
import { AccessRequestWebhookAction, WebhookEvents } from "@app/services/webhook/webhook-types";
import { externallyReviewedAccessRequestMessage } from "./secret-access-approval-global-request-bridge-constants";
@@ -54,6 +55,7 @@ import {
TCountSecretAccessApprovalGlobalRequestsDTO,
TCreateSecretAccessApprovalGlobalRequestDTO,
TListSecretAccessApprovalGlobalRequestsDTO,
+ TNotifyDelegatedDecisionDTO,
TRetrySecretAccessApprovalGlobalRequestDispatchDTO,
TReviewSecretAccessApprovalGlobalRequestDTO,
TRevokeSecretAccessApprovalGlobalRequestDTO,
@@ -480,7 +482,7 @@ export const secretAccessApprovalGlobalRequestBridgeServiceFactory = ({
if (request.status !== ApprovalRequestStatus.Pending) {
throw new BadRequestError({ message: "The request has been closed" });
}
- if (request.expiresAt && new Date(request.expiresAt) < new Date()) {
+ if (isApprovalRequestExpired(request)) {
await approvalRequestDAL.updateById(requestId, { status: ApprovalRequestStatus.Expired });
throw new BadRequestError({ message: "This access request has expired and can no longer be reviewed" });
}
@@ -582,7 +584,7 @@ export const secretAccessApprovalGlobalRequestBridgeServiceFactory = ({
if (!locked || locked.status !== ApprovalRequestStatus.Pending) {
throw new BadRequestError({ message: "The request has been closed" });
}
- if (locked.expiresAt && new Date(locked.expiresAt) < new Date()) {
+ if (isApprovalRequestExpired(locked)) {
throw new BadRequestError({ message: "This access request has expired and can no longer be reviewed" });
}
@@ -658,7 +660,7 @@ export const secretAccessApprovalGlobalRequestBridgeServiceFactory = ({
throw new BadRequestError({ message: "The request has been closed" });
}
- if (locked.expiresAt && new Date(locked.expiresAt) < new Date()) {
+ if (isApprovalRequestExpired(locked)) {
throw new BadRequestError({ message: "This access request has expired and can no longer be reviewed" });
}
@@ -908,6 +910,40 @@ export const secretAccessApprovalGlobalRequestBridgeServiceFactory = ({
};
};
+ // Fires the same webhook a reviewer's decision does, for a decision read back from the delegated
+ // approval system. The decision itself is already committed by the time this runs.
+ const notifyDelegatedDecision = async ({ requestId }: TNotifyDelegatedDecisionDTO) => {
+ const request = await $findRequestByIdFromPrimary(requestId);
+ if (!request.policyId || !request.requesterId) {
+ logger.warn(
+ `Skipping access request webhook, policy or requester missing [requestId=${requestId}] [action=${AccessRequestWebhookAction.Reviewed}]`
+ );
+ return;
+ }
+
+ const [policy, project, requestedByUser] = await Promise.all([
+ $findPolicyById(request.policyId, "The policy associated with this access request has been deleted."),
+ projectDAL.findById(request.projectId),
+ userDAL.findById(request.requesterId)
+ ]);
+ if (!project || !requestedByUser) {
+ logger.warn(
+ `Skipping access request webhook, project or requester not found [requestId=${requestId}] [action=${AccessRequestWebhookAction.Reviewed}]`
+ );
+ return;
+ }
+
+ // we need to check this, because I believe this is sending the webhook only, but it does not send any email for the user that created the policy
+ await $queueAccessRequestWebhook({
+ action: AccessRequestWebhookAction.Reviewed,
+ request: toLegacyAccessApprovalRequest(request),
+ project,
+ policy: { ...policy, hasSequencedApprovers: policy.approvers.some((a) => (a.sequence ?? 1) > 1) },
+ requestedByUser,
+ envName: policy.environment.name
+ });
+ };
+
const cancelAccessApprovalRequest = async ({
requestId,
actor,
@@ -967,6 +1003,7 @@ export const secretAccessApprovalGlobalRequestBridgeServiceFactory = ({
reviewAccessApprovalRequest,
revokeAccessApprovalRequest,
retryDelegatedApprovalDispatch,
- cancelAccessApprovalRequest
+ cancelAccessApprovalRequest,
+ notifyDelegatedDecision
};
};
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 cf57c2a628..4bd0d58507 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
@@ -107,3 +107,7 @@ export type TRevokeSecretAccessApprovalGlobalRequestDTO = TRevokeAccessRequestDT
export type TRetrySecretAccessApprovalGlobalRequestDispatchDTO = TRetryDelegatedApprovalDispatchDTO;
export type TCancelSecretAccessApprovalGlobalRequestDTO = TCancelAccessRequestDTO;
+
+export type TNotifyDelegatedDecisionDTO = {
+ requestId: string;
+};
diff --git a/docs/documentation/platform/workflow-integrations/servicenow-integration.mdx b/docs/documentation/platform/workflow-integrations/servicenow-integration.mdx
index 8744bc84ff..cb82a63d38 100644
--- a/docs/documentation/platform/workflow-integrations/servicenow-integration.mdx
+++ b/docs/documentation/platform/workflow-integrations/servicenow-integration.mdx
@@ -157,7 +157,7 @@ Each request becomes one **Infisical Access Request** record, numbered `INFAR<nu
| Infisical Request ID | The Infisical request this record corresponds to. |
| State | Where the request stands, see below. |
-The record is a read-only mirror of the request. Editing the fields in ServiceNow doesn't change what Infisical grants; only the decision sent back matters.
+The record is a mirror of the request. Infisical grants what the request asked for, never what the record says. If the **Permissions** field on the record no longer matches the request when it's approved, Infisical cancels the request instead of granting access.
### States
@@ -186,3 +186,4 @@ Both sides keep their own record. In ServiceNow, the access request record carri
| Callback Failed with HTTP 401 or 403 | The machine identity isn't a member of the project, or is missing the External Review permission on Approval Requests. |
| Callback Failed with a connection error | The ServiceNow instance can't reach your Infisical URL. Check the URL on the alias and any outbound firewall rules on the instance. |
| Request expired before approval | The policy's request expiration elapsed while the request sat in ServiceNow. Extend it, or shorten your approval SLA. |
+| Infisical says the request couldn't be completed in ServiceNow | Infisical couldn't apply the decision. The reason is shown under the request status: the **Permissions** field was changed in ServiceNow, the record was deleted, or ServiceNow rejected the integration user's credentials. Fix the cause and create the request again. |