Skip to content

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

feat: refactor for simplicity

adilson4b4c3c9c6da7
diff --git a/CLAUDE.md b/CLAUDE.md
index 0c2516f13a..8f5f1fe0f6 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -159,9 +159,8 @@ policies may opt in today: `assertPolicyTypeSupportsDelegatedApproval` refuses t
policies return it as a 400 rather than dropping the field.
Delivery to the delegated system is asynchronous and lives in `delegated-approval/dispatch/`. The request
-bridge creates the `delegated_approval_requests` row inside the request's own transaction (through the
-`onCreated` hook of `createApprovalRequestWithSteps`) and enqueues the `DelegatedApprovalDispatch` job after
-commit; the worker moves the row `pending_dispatch` → `waiting_approval` (storing the provider's record id in
+bridge creates the `delegated_approval_requests` row inside the request's own transaction and enqueues the
+`DelegatedApprovalDispatch` job after commit; the worker moves the row `pending_dispatch` → `waiting_approval` (storing the provider's record id in
`providerRequestId`) or `failed_dispatch` with a `statusReason` a user can read, and BullMQ retries put it back
to `pending_dispatch`. Every provider implements `TDelegatedApprovalProvider` against the same
`TDelegatedApprovalDispatchInput` and registers in `DELEGATED_APPROVAL_PROVIDER_MAP`
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index acd3b8f1d9..68ca86b958 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -356,7 +356,6 @@ import { delegatedApprovalPolicyDALFactory } from "@app/services/delegated-appro
import { delegatedApprovalRequestDALFactory } from "@app/services/delegated-approval/delegated-approval-request-dal";
import { delegatedApprovalServiceFactory } from "@app/services/delegated-approval/delegated-approval-service";
import { delegatedApprovalDispatchQueueFactory } from "@app/services/delegated-approval/dispatch/delegated-approval-dispatch-queue";
-import { delegatedApprovalCallbackDALFactory } from "@app/services/delegated-approval-callback/delegated-approval-callback-dal";
import { delegatedApprovalCallbackServiceFactory } from "@app/services/delegated-approval-callback/delegated-approval-callback-service";
import { encryptionKeyRotationServiceFactory } from "@app/services/encryption-key-rotation/encryption-key-rotation-service";
import { acmeEnrollmentConfigDALFactory } from "@app/services/enrollment-config/acme-enrollment-config-dal";
@@ -865,7 +864,6 @@ export const registerRoutes = async (
const approvalRequestDAL = approvalRequestDALFactory(db);
const delegatedApprovalPolicyDAL = delegatedApprovalPolicyDALFactory(db);
const delegatedApprovalRequestDAL = delegatedApprovalRequestDALFactory(db);
- const delegatedApprovalCallbackDAL = delegatedApprovalCallbackDALFactory(db);
const secretChangeGlobalPolicyBridgeDAL = secretChangeGlobalPolicyBridgeDALFactory(db);
const roleDAL = roleDALFactory(db);
const pkiAlertHistoryDAL = pkiAlertHistoryDALFactory(db);
@@ -3252,6 +3250,70 @@ export const registerRoutes = async (
appConnectionService
});
+ const delegatedApprovalCallbackService = delegatedApprovalCallbackServiceFactory({
+ delegatedApprovalRequestDAL,
+ kmsService
+ });
+
+ const delegatedApprovalDispatchQueue = delegatedApprovalDispatchQueueFactory({
+ delegatedApprovalRequestDAL,
+ delegatedApprovalPolicyDAL,
+ delegatedApprovalCallbackService,
+ approvalRequestDAL,
+ projectDAL,
+ appConnectionDAL,
+ kmsService,
+ queueService
+ });
+
+ const secretAccessApprovalGlobalRequestBridgeService = secretAccessApprovalGlobalRequestBridgeServiceFactory({
+ projectDAL,
+ projectEnvDAL,
+ permissionService,
+ userDAL,
+ userGroupMembershipDAL,
+ approvalRequestDAL,
+ approvalRequestStepsDAL,
+ approvalRequestStepEligibleApproversDAL,
+ approvalRequestApprovalsDAL,
+ approvalRequestGrantsDAL,
+ additionalPrivilegeDAL,
+ secretAccessApprovalGlobalPolicyBridgeDAL,
+ secretAccessApprovalGlobalRequestBridgeDAL,
+ delegatedApprovalService,
+ delegatedApprovalDispatchQueue,
+ smtpService,
+ notificationService,
+ kmsService,
+ projectSlackConfigDAL,
+ microsoftTeamsService,
+ projectMicrosoftTeamsConfigDAL,
+ queueService,
+ secretAccessApprovalGlobalResource
+ });
+
+ const accessApprovalRequestService = accessApprovalRequestServiceFactory({
+ projectDAL,
+ permissionService,
+ accessApprovalRequestReviewerDAL,
+ accessApprovalPolicyDAL,
+ secretAccessApprovalGlobalResource,
+ secretAccessApprovalGlobalRequestBridge: secretAccessApprovalGlobalRequestBridgeService,
+ accessApprovalRequestDAL,
+ projectEnvDAL,
+ userDAL,
+ smtpService,
+ accessApprovalPolicyApproverDAL,
+ projectSlackConfigDAL,
+ kmsService,
+ groupDAL,
+ microsoftTeamsService,
+ projectMicrosoftTeamsConfigDAL,
+ notificationService,
+ additionalPrivilegeDAL,
+ queueService
+ });
+
const secretAccessApprovalGlobalPolicyBridgeService = secretAccessApprovalGlobalPolicyBridgeServiceFactory({
projectDAL,
permissionService,
@@ -3913,69 +3975,6 @@ export const registerRoutes = async (
resources: approvalResources
});
- const delegatedApprovalCallbackService = delegatedApprovalCallbackServiceFactory({
- delegatedApprovalCallbackDAL,
- kmsService
- });
-
- const delegatedApprovalDispatchQueue = delegatedApprovalDispatchQueueFactory({
- delegatedApprovalRequestDAL,
- delegatedApprovalPolicyDAL,
- delegatedApprovalCallbackService,
- approvalPolicyService,
- projectService,
- appConnectionService,
- queueService
- });
-
- const secretAccessApprovalGlobalRequestBridgeService = secretAccessApprovalGlobalRequestBridgeServiceFactory({
- projectDAL,
- projectEnvDAL,
- permissionService,
- userDAL,
- userGroupMembershipDAL,
- approvalRequestDAL,
- approvalRequestStepsDAL,
- approvalRequestStepEligibleApproversDAL,
- approvalRequestApprovalsDAL,
- approvalRequestGrantsDAL,
- additionalPrivilegeDAL,
- secretAccessApprovalGlobalPolicyBridgeDAL,
- secretAccessApprovalGlobalRequestBridgeDAL,
- delegatedApprovalService,
- delegatedApprovalDispatchQueue,
- smtpService,
- notificationService,
- kmsService,
- projectSlackConfigDAL,
- microsoftTeamsService,
- projectMicrosoftTeamsConfigDAL,
- queueService,
- secretAccessApprovalGlobalResource
- });
-
- const accessApprovalRequestService = accessApprovalRequestServiceFactory({
- projectDAL,
- permissionService,
- accessApprovalRequestReviewerDAL,
- accessApprovalPolicyDAL,
- secretAccessApprovalGlobalResource,
- secretAccessApprovalGlobalRequestBridge: secretAccessApprovalGlobalRequestBridgeService,
- accessApprovalRequestDAL,
- projectEnvDAL,
- userDAL,
- smtpService,
- accessApprovalPolicyApproverDAL,
- projectSlackConfigDAL,
- kmsService,
- groupDAL,
- microsoftTeamsService,
- projectMicrosoftTeamsConfigDAL,
- notificationService,
- additionalPrivilegeDAL,
- queueService
- });
-
const pkiApplicationEnrollmentService = pkiApplicationEnrollmentServiceFactory({
pkiApplicationDAL,
pkiApplicationProfileDAL,
diff --git a/backend/src/services/app-connection/app-connection-service.ts b/backend/src/services/app-connection/app-connection-service.ts
index d2d471df4a..7b5b7cdf05 100644
--- a/backend/src/services/app-connection/app-connection-service.ts
+++ b/backend/src/services/app-connection/app-connection-service.ts
@@ -464,15 +464,6 @@ export const appConnectionServiceFactory = ({
return decryptAppConnection(appConnection, kmsService);
};
- // For background work that has no actor. It performs no authorization or scope check, so it must not
- // back a route, and the caller still has to check the connection's org and app.
- const findDecryptedAppConnectionById = async (connectionId: string) => {
- const appConnection = await appConnectionDAL.findById(connectionId);
- if (!appConnection) return null;
-
- return decryptAppConnection(appConnection, kmsService);
- };
-
const findAppConnectionByName = async (
app: AppConnection,
{ connectionName, projectId }: TGetAppConnectionByNameDTO,
@@ -1443,7 +1434,6 @@ export const appConnectionServiceFactory = ({
listAppConnections,
findAppConnectionById,
findAppConnectionByName,
- findDecryptedAppConnectionById,
createAppConnection,
updateAppConnection,
deleteAppConnection,
diff --git a/backend/src/services/approval-policy/approval-policy-service.ts b/backend/src/services/approval-policy/approval-policy-service.ts
index bc2e00b6a2..10da716c92 100644
--- a/backend/src/services/approval-policy/approval-policy-service.ts
+++ b/backend/src/services/approval-policy/approval-policy-service.ts
@@ -1166,9 +1166,6 @@ export const approvalPolicyServiceFactory = ({
actorAuthMethod: actor.authMethod
});
- // For background work that has no actor. It performs no authorization, so it must not back a route.
- const findRequestById = (requestId: string, tx?: Knex) => approvalRequestDAL.findById(requestId, tx);
-
const getRequestById = async (requestId: string, actor: TApprovalActor) => {
const request = await approvalRequestDAL.findById(requestId);
if (!request) {
@@ -2462,7 +2459,6 @@ export const approvalPolicyServiceFactory = ({
createRequest,
createRequestFromPolicy,
listRequests,
- findRequestById,
getRequestById,
approveRequest,
rejectRequest,
diff --git a/backend/src/services/delegated-approval-callback/delegated-approval-callback-dal.ts b/backend/src/services/delegated-approval-callback/delegated-approval-callback-dal.ts
deleted file mode 100644
index 435a2cacdf..0000000000
--- a/backend/src/services/delegated-approval-callback/delegated-approval-callback-dal.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-import { TDbClient } from "@app/db";
-import { TableName } from "@app/db/schemas";
-import { ormify } from "@app/lib/knex";
-
-export type TDelegatedApprovalCallbackDALFactory = ReturnType<typeof delegatedApprovalCallbackDALFactory>;
-
-export const delegatedApprovalCallbackDALFactory = (db: TDbClient) => ormify(db, TableName.DelegatedApprovalRequests);
diff --git a/backend/src/services/delegated-approval-callback/delegated-approval-callback-fns.test.ts b/backend/src/services/delegated-approval-callback/delegated-approval-callback-fns.test.ts
index 486562f25d..4799c95f89 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
@@ -1,10 +1,6 @@
import { describe, expect, test } from "vitest";
-import { DELEGATED_APPROVAL_CALLBACK_PATH } from "./delegated-approval-callback-constants";
-import {
- buildDelegatedApprovalCallbackUrl,
- generateDelegatedApprovalCallbackToken
-} from "./delegated-approval-callback-fns";
+import { generateDelegatedApprovalCallbackToken } from "./delegated-approval-callback-fns";
describe("generateDelegatedApprovalCallbackToken", () => {
test("returns a fresh base64url token of 32 random bytes", () => {
@@ -15,14 +11,3 @@ describe("generateDelegatedApprovalCallbackToken", () => {
expect(generateDelegatedApprovalCallbackToken()).not.toBe(token);
});
});
-
-describe("buildDelegatedApprovalCallbackUrl", () => {
- test("joins the site URL and the callback path", () => {
- expect(buildDelegatedApprovalCallbackUrl("https://app.infisical.com")).toBe(
- `https://app.infisical.com${DELEGATED_APPROVAL_CALLBACK_PATH}`
- );
- expect(buildDelegatedApprovalCallbackUrl("https://app.infisical.com/")).toBe(
- `https://app.infisical.com${DELEGATED_APPROVAL_CALLBACK_PATH}`
- );
- });
-});
diff --git a/backend/src/services/delegated-approval-callback/delegated-approval-callback-fns.ts b/backend/src/services/delegated-approval-callback/delegated-approval-callback-fns.ts
index a868398a69..90bab219d7 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,13 +1,6 @@
import { crypto } from "@app/lib/crypto/cryptography";
-import { removeTrailingSlash } from "@app/lib/fn";
-import {
- DELEGATED_APPROVAL_CALLBACK_PATH,
- DELEGATED_APPROVAL_CALLBACK_TOKEN_BYTES
-} from "./delegated-approval-callback-constants";
+import { DELEGATED_APPROVAL_CALLBACK_TOKEN_BYTES } from "./delegated-approval-callback-constants";
export const generateDelegatedApprovalCallbackToken = () =>
crypto.randomBytes(DELEGATED_APPROVAL_CALLBACK_TOKEN_BYTES).toString("base64url");
-
-export const buildDelegatedApprovalCallbackUrl = (siteUrl: string) =>
- `${removeTrailingSlash(siteUrl)}${DELEGATED_APPROVAL_CALLBACK_PATH}`;
diff --git a/backend/src/services/delegated-approval-callback/delegated-approval-callback-service.test.ts b/backend/src/services/delegated-approval-callback/delegated-approval-callback-service.test.ts
index 0e2eb2c23a..58f77f0c56 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
@@ -21,9 +21,9 @@ const makeService = ({
stored = true,
currentRow = null
}: { stored?: boolean; currentRow?: { encryptedCallbackToken: Buffer | null } | null } = {}) => {
- const delegatedApprovalCallbackDAL = {
+ const delegatedApprovalRequestDAL = {
update: vi.fn(async () => (stored ? [{ id: "delegated-1" }] : [])),
- transaction: vi.fn(async (cb: (tx: unknown) => Promise<unknown>) => cb({})),
+ primaryNode: vi.fn(() => ({})),
findById: vi.fn(async () => currentRow)
};
const kmsService = {
@@ -34,11 +34,11 @@ const makeService = ({
};
const service = delegatedApprovalCallbackServiceFactory({
- delegatedApprovalCallbackDAL: delegatedApprovalCallbackDAL as never,
+ delegatedApprovalRequestDAL: delegatedApprovalRequestDAL as never,
kmsService: kmsService as never
});
- return { service, delegatedApprovalCallbackDAL, kmsService };
+ return { service, delegatedApprovalRequestDAL, kmsService };
};
describe("getCallbackUrl", () => {
@@ -51,7 +51,7 @@ describe("getCallbackUrl", () => {
describe("getOrIssueCallbackToken", () => {
test("issues a token once and stores it encrypted under the org key", async () => {
- const { service, delegatedApprovalCallbackDAL, kmsService } = makeService();
+ const { service, delegatedApprovalRequestDAL, kmsService } = makeService();
const token = await service.getOrIssueCallbackToken({
delegatedRequest: { id: "delegated-1", encryptedCallbackToken: null },
@@ -63,14 +63,14 @@ describe("getOrIssueCallbackToken", () => {
type: KmsDataKey.Organization,
orgId: "org-1"
});
- expect(delegatedApprovalCallbackDAL.update).toHaveBeenCalledWith(
+ expect(delegatedApprovalRequestDAL.update).toHaveBeenCalledWith(
{ id: "delegated-1", encryptedCallbackToken: null },
{ encryptedCallbackToken: encrypt(Buffer.from(token as string)) }
);
});
test("resends the token the request already holds instead of issuing another", async () => {
- const { service, delegatedApprovalCallbackDAL } = makeService();
+ const { service, delegatedApprovalRequestDAL } = makeService();
const token = await service.getOrIssueCallbackToken({
delegatedRequest: { id: "delegated-1", encryptedCallbackToken: encrypt(Buffer.from("first-token")) },
@@ -78,7 +78,7 @@ describe("getOrIssueCallbackToken", () => {
});
expect(token).toBe("first-token");
- expect(delegatedApprovalCallbackDAL.update).not.toHaveBeenCalled();
+ expect(delegatedApprovalRequestDAL.update).not.toHaveBeenCalled();
});
test("falls back to the token a concurrent attempt stored first", async () => {
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 46e99bc663..59b919649e 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
@@ -1,10 +1,8 @@
import { getConfig } from "@app/lib/config/env";
import { KmsDataKey } from "@app/services/kms/kms-types";
-import {
- buildDelegatedApprovalCallbackUrl,
- generateDelegatedApprovalCallbackToken
-} from "./delegated-approval-callback-fns";
+import { DELEGATED_APPROVAL_CALLBACK_PATH } from "./delegated-approval-callback-constants";
+import { generateDelegatedApprovalCallbackToken } from "./delegated-approval-callback-fns";
import {
TDelegatedApprovalCallbackServiceFactoryDep,
TGetOrIssueCallbackTokenDTO
@@ -13,12 +11,12 @@ import {
export type TDelegatedApprovalCallbackServiceFactory = ReturnType<typeof delegatedApprovalCallbackServiceFactory>;
export const delegatedApprovalCallbackServiceFactory = ({
- delegatedApprovalCallbackDAL,
+ delegatedApprovalRequestDAL,
kmsService
}: TDelegatedApprovalCallbackServiceFactoryDep) => {
const getCallbackUrl = () => {
const { SITE_URL } = getConfig();
- return SITE_URL ? buildDelegatedApprovalCallbackUrl(SITE_URL) : null;
+ return SITE_URL ? `${SITE_URL}${DELEGATED_APPROVAL_CALLBACK_PATH}` : null;
};
const getOrIssueCallbackToken = async ({ delegatedRequest, orgId }: TGetOrIssueCallbackTokenDTO) => {
@@ -32,14 +30,15 @@ export const delegatedApprovalCallbackServiceFactory = ({
}
const token = generateDelegatedApprovalCallbackToken();
- const [issued] = await delegatedApprovalCallbackDAL.update(
+ const [issued] = await delegatedApprovalRequestDAL.update(
{ id: delegatedRequest.id, encryptedCallbackToken: null },
{ encryptedCallbackToken: encryptor({ plainText: Buffer.from(token) }).cipherTextBlob }
);
if (issued) return token;
- const current = await delegatedApprovalCallbackDAL.transaction((tx) =>
- delegatedApprovalCallbackDAL.findById(delegatedRequest.id, tx)
+ const current = await delegatedApprovalRequestDAL.findById(
+ delegatedRequest.id,
+ delegatedApprovalRequestDAL.primaryNode()
);
if (!current?.encryptedCallbackToken) return null;
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 2081e748b1..643d2e29c0 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
@@ -1,10 +1,9 @@
import { TDelegatedApprovalRequests } from "@app/db/schemas";
+import { TDelegatedApprovalRequestDALFactory } from "@app/services/delegated-approval/delegated-approval-request-dal";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
-import { TDelegatedApprovalCallbackDALFactory } from "./delegated-approval-callback-dal";
-
export type TDelegatedApprovalCallbackServiceFactoryDep = {
- delegatedApprovalCallbackDAL: Pick<TDelegatedApprovalCallbackDALFactory, "findById" | "transaction" | "update">;
+ delegatedApprovalRequestDAL: Pick<TDelegatedApprovalRequestDALFactory, "findById" | "primaryNode" | "update">;
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
};
diff --git a/backend/src/services/delegated-approval/delegated-approval-maps.ts b/backend/src/services/delegated-approval/delegated-approval-maps.ts
index cc3089e34c..e6ae8c04ca 100644
--- a/backend/src/services/delegated-approval/delegated-approval-maps.ts
+++ b/backend/src/services/delegated-approval/delegated-approval-maps.ts
@@ -11,7 +11,7 @@ export const DELEGATED_APPROVAL_CONNECTION_MAP: Record<DelegatedApprovalPolicyTy
[DelegatedApprovalPolicyType.ServiceNow]: AppConnection.ServiceNow
};
-export const DELEGATED_APPROVAL_SUPPORTED_POLICY_TYPES = [ApprovalPolicyType.SecretAccess] as const;
+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 343998172b..b03168321c 100644
--- a/backend/src/services/delegated-approval/delegated-approval-request-dal.ts
+++ b/backend/src/services/delegated-approval/delegated-approval-request-dal.ts
@@ -4,4 +4,10 @@ import { ormify } from "@app/lib/knex";
export type TDelegatedApprovalRequestDALFactory = ReturnType<typeof delegatedApprovalRequestDALFactory>;
-export const delegatedApprovalRequestDALFactory = (db: TDbClient) => ormify(db, TableName.DelegatedApprovalRequests);
+export const delegatedApprovalRequestDALFactory = (db: TDbClient) => {
+ const orm = ormify(db, TableName.DelegatedApprovalRequests);
+
+ const primaryNode = () => db.primaryNode();
+
+ return { ...orm, primaryNode };
+};
diff --git a/backend/src/services/delegated-approval/delegated-approval-service.ts b/backend/src/services/delegated-approval/delegated-approval-service.ts
index 1a33be4ed8..c4f164dedd 100644
--- a/backend/src/services/delegated-approval/delegated-approval-service.ts
+++ b/backend/src/services/delegated-approval/delegated-approval-service.ts
@@ -1,7 +1,8 @@
import { Knex } from "knex";
import { DatabaseErrorCode } from "@app/lib/error-codes";
-import { BadRequestError, DatabaseError, NotFoundError } from "@app/lib/errors";
+import { BadRequestError, NotFoundError } from "@app/lib/errors";
+import { hasPostgresErrorCode } from "@app/lib/errors/postgres";
import { OrgServiceActor } from "@app/lib/types";
import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
@@ -34,13 +35,6 @@ type TDelegatedApprovalServiceFactoryDep = {
export type TDelegatedApprovalServiceFactory = ReturnType<typeof delegatedApprovalServiceFactory>;
-const getDatabaseErrorCode = (err: unknown) =>
- err instanceof DatabaseError ? (err.error as { code?: string })?.code : undefined;
-
-const isUniqueViolation = (err: unknown) => getDatabaseErrorCode(err) === DatabaseErrorCode.UniqueViolation;
-
-const isForeignKeyViolation = (err: unknown) => getDatabaseErrorCode(err) === DatabaseErrorCode.ForeignKeyViolation;
-
export const delegatedApprovalServiceFactory = ({
delegatedApprovalPolicyDAL,
delegatedApprovalRequestDAL,
@@ -96,7 +90,7 @@ export const delegatedApprovalServiceFactory = ({
const policy = await delegatedApprovalPolicyDAL.create({ policyId, type, connectionId }, tx);
return policy as TDelegatedApprovalPolicy;
} catch (err) {
- if (isUniqueViolation(err)) {
+ if (hasPostgresErrorCode(err, DatabaseErrorCode.UniqueViolation)) {
throw new BadRequestError({
message: `Approval policy with ID '${policyId}' already has a delegated approver configured`
});
@@ -166,12 +160,12 @@ export const delegatedApprovalServiceFactory = ({
);
return request as TDelegatedApprovalRequest;
} catch (err) {
- if (isUniqueViolation(err)) {
+ if (hasPostgresErrorCode(err, DatabaseErrorCode.UniqueViolation)) {
throw new BadRequestError({
message: `Approval request with ID '${approvalRequest.id}' already has a delegated approval request`
});
}
- if (isForeignKeyViolation(err)) {
+ if (hasPostgresErrorCode(err, DatabaseErrorCode.ForeignKeyViolation)) {
throw new NotFoundError({ message: `Approval request with ID '${approvalRequest.id}' not found` });
}
throw err;
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 5e1e86f162..2eda92f61d 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
@@ -7,10 +7,10 @@ import {
TDelegatedApprovalDispatchDetailsBuilder,
TDelegatedApprovalProvider
} from "./delegated-approval-dispatch-types";
-import { servicenowProviderFactory } from "./providers/servicenow";
+import { serviceNowProvider } from "./providers/servicenow";
export const DELEGATED_APPROVAL_PROVIDER_MAP: Record<DelegatedApprovalPolicyType, TDelegatedApprovalProvider> = {
- [DelegatedApprovalPolicyType.ServiceNow]: servicenowProviderFactory()
+ [DelegatedApprovalPolicyType.ServiceNow]: serviceNowProvider
};
export const DELEGATED_APPROVAL_DISPATCH_DETAILS_BUILDER_MAP: Record<
diff --git a/backend/src/services/delegated-approval/dispatch/delegated-approval-dispatch-queue.ts b/backend/src/services/delegated-approval/dispatch/delegated-approval-dispatch-queue.ts
index adb20bb05d..4b7800ccce 100644
--- a/backend/src/services/delegated-approval/dispatch/delegated-approval-dispatch-queue.ts
+++ b/backend/src/services/delegated-approval/dispatch/delegated-approval-dispatch-queue.ts
@@ -3,16 +3,17 @@ import { UnrecoverableError } from "bullmq";
import { ProjectType } from "@app/db/schemas";
import { logger } from "@app/lib/logger";
import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
-import { AppConnection } from "@app/services/app-connection/app-connection-enums";
+import { 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 { TAppConnectionServiceFactory } from "@app/services/app-connection/app-connection-service";
import { ApprovalRequestStatus } from "@app/services/approval-policy/approval-policy-enums";
-import { TApprovalPolicyServiceFactory } from "@app/services/approval-policy/approval-policy-service";
+import { TApprovalRequestDALFactory } from "@app/services/approval-policy/approval-request-dal";
import { TDelegatedApprovalCallbackServiceFactory } from "@app/services/delegated-approval-callback/delegated-approval-callback-service";
-import { TProjectServiceFactory } from "@app/services/project/project-service";
+import { TKmsServiceFactory } from "@app/services/kms/kms-service";
+import { TProjectDALFactory } from "@app/services/project/project-dal";
-import { DelegatedApprovalRequestStatus } from "../delegated-approval-enums";
-import { DELEGATED_APPROVAL_NAME_MAP } from "../delegated-approval-maps";
+import { DelegatedApprovalPolicyType, DelegatedApprovalRequestStatus } from "../delegated-approval-enums";
+import { DELEGATED_APPROVAL_CONNECTION_MAP } from "../delegated-approval-maps";
import { TDelegatedApprovalPolicyDALFactory } from "../delegated-approval-policy-dal";
import { TDelegatedApprovalRequestDALFactory } from "../delegated-approval-request-dal";
import {
@@ -33,16 +34,17 @@ import {
type TDelegatedApprovalDispatchQueueFactoryDep = {
delegatedApprovalRequestDAL: Pick<
TDelegatedApprovalRequestDALFactory,
- "findById" | "transaction" | "update" | "updateById"
+ "findById" | "primaryNode" | "update" | "updateById"
>;
delegatedApprovalPolicyDAL: Pick<TDelegatedApprovalPolicyDALFactory, "findOne">;
delegatedApprovalCallbackService: Pick<
TDelegatedApprovalCallbackServiceFactory,
"getCallbackUrl" | "getOrIssueCallbackToken"
>;
- approvalPolicyService: Pick<TApprovalPolicyServiceFactory, "findRequestById">;
- projectService: Pick<TProjectServiceFactory, "findProjectById">;
- appConnectionService: Pick<TAppConnectionServiceFactory, "findDecryptedAppConnectionById">;
+ approvalRequestDAL: Pick<TApprovalRequestDALFactory, "findById">;
+ projectDAL: Pick<TProjectDALFactory, "findById">;
+ appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">;
+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
queueService: Pick<TQueueServiceFactory, "queue" | "start">;
};
@@ -52,9 +54,10 @@ export const delegatedApprovalDispatchQueueFactory = ({
delegatedApprovalRequestDAL,
delegatedApprovalPolicyDAL,
delegatedApprovalCallbackService,
- approvalPolicyService,
- projectService,
- appConnectionService,
+ approvalRequestDAL,
+ projectDAL,
+ appConnectionDAL,
+ kmsService,
queueService
}: TDelegatedApprovalDispatchQueueFactoryDep) => {
const $markDispatchFailed = async (delegatedRequestId: string, statusReason: string) => {
@@ -98,18 +101,19 @@ export const delegatedApprovalDispatchQueueFactory = ({
};
// Both rows were committed together moments before the job runs, so they are read from the primary.
- const $loadRequests = (delegatedRequestId: string) =>
- delegatedApprovalRequestDAL.transaction(async (tx) => {
- const delegatedRequest = await delegatedApprovalRequestDAL.findById(delegatedRequestId, tx);
- if (!delegatedRequest) return null;
+ const $loadRequests = async (delegatedRequestId: string) => {
+ const primary = delegatedApprovalRequestDAL.primaryNode();
- const approvalRequest = await approvalPolicyService.findRequestById(delegatedRequest.requestId, tx);
- const delegatedPolicy = approvalRequest?.policyId
- ? await delegatedApprovalPolicyDAL.findOne({ policyId: approvalRequest.policyId }, tx)
- : null;
+ const delegatedRequest = await delegatedApprovalRequestDAL.findById(delegatedRequestId, primary);
+ if (!delegatedRequest) return null;
- return { delegatedRequest, approvalRequest, delegatedPolicy };
- });
+ 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 init = () => {
queueService.start(
@@ -147,10 +151,12 @@ export const delegatedApprovalDispatchQueueFactory = ({
return;
}
- await delegatedApprovalRequestDAL.updateById(delegatedRequestId, {
- status: DelegatedApprovalRequestStatus.PendingDispatch,
- statusReason: null
- });
+ if (delegatedRequest.status === DelegatedApprovalRequestStatus.FailedDispatch) {
+ await delegatedApprovalRequestDAL.update(
+ { id: delegatedRequestId, status: DelegatedApprovalRequestStatus.FailedDispatch },
+ { status: DelegatedApprovalRequestStatus.PendingDispatch, statusReason: null }
+ );
+ }
try {
if (!approvalRequest) {
@@ -158,7 +164,7 @@ export const delegatedApprovalDispatchQueueFactory = ({
}
if (approvalRequest.status !== ApprovalRequestStatus.Pending) {
throw new UnrecoverableError(
- "The access request is no longer pending, so it was not sent to the delegated approval system."
+ "The approval request is no longer pending, so it was not sent to the delegated approval system."
);
}
if (!delegatedPolicy) {
@@ -168,32 +174,33 @@ export const delegatedApprovalDispatchQueueFactory = ({
}
const provider = getDelegatedApprovalProvider(delegatedPolicy.type);
- const providerName = DELEGATED_APPROVAL_NAME_MAP[provider.type];
-
- const project = await projectService.findProjectById(approvalRequest.projectId);
- if (!project) {
- throw new UnrecoverableError("The project of the access request no longer exists.");
- }
+ const details = getDelegatedApprovalDispatchDetailsBuilder(approvalRequest.type)(approvalRequest);
- const connection = await appConnectionService.findDecryptedAppConnectionById(delegatedPolicy.connectionId);
- if (!connection || connection.orgId !== approvalRequest.organizationId) {
- throw new UnrecoverableError(
- `App Connection with ID '${delegatedPolicy.connectionId}' was not found. Select a ${APP_CONNECTION_NAME_MAP[provider.app]} Connection on the policy and create the request again.`
- );
- }
- if (connection.app !== provider.app) {
+ const callbackUrl = delegatedApprovalCallbackService.getCallbackUrl();
+ if (!callbackUrl) {
throw new UnrecoverableError(
- `${APP_CONNECTION_NAME_MAP[connection.app as AppConnection]} Connection with ID '${connection.id}' cannot be used as a ${providerName} delegated approver. Select a ${APP_CONNECTION_NAME_MAP[provider.app]} Connection on the policy instead.`
+ "SITE_URL must be configured so the delegated approval system can call Infisical back."
);
}
- const callbackUrl = delegatedApprovalCallbackService.getCallbackUrl();
- if (!callbackUrl) {
+ const primary = delegatedApprovalRequestDAL.primaryNode();
+ const [project, rawConnection] = await Promise.all([
+ projectDAL.findById(approvalRequest.projectId, primary),
+ appConnectionDAL.findById(delegatedPolicy.connectionId, primary)
+ ]);
+ 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(
- "SITE_URL must be configured so the delegated approval system can call Infisical back."
+ `App Connection with ID '${delegatedPolicy.connectionId}' was not found. Select a ${APP_CONNECTION_NAME_MAP[connectionApp]} Connection on the policy and create the request again.`
);
}
+ const connection = await decryptAppConnection(rawConnection, kmsService);
+
const callbackToken = await delegatedApprovalCallbackService.getOrIssueCallbackToken({
delegatedRequest,
orgId: approvalRequest.organizationId
@@ -204,8 +211,6 @@ export const delegatedApprovalDispatchQueueFactory = ({
);
}
- const buildDetails = getDelegatedApprovalDispatchDetailsBuilder(approvalRequest.type);
-
const input: TDelegatedApprovalDispatchInput = {
delegatedRequestId,
approvalRequestId: approvalRequest.id,
@@ -215,7 +220,7 @@ export const delegatedApprovalDispatchQueueFactory = ({
requester: { name: approvalRequest.requesterName, email: approvalRequest.requesterEmail },
justification: approvalRequest.justification ?? null,
callback: { url: callbackUrl, token: callbackToken },
- details: buildDetails(approvalRequest)
+ details
};
const { providerRequestId } = await provider.dispatch(input, connection);
@@ -232,7 +237,7 @@ export const delegatedApprovalDispatchQueueFactory = ({
}
logger.info(
- `Delegated approval request delivered [delegatedRequestId=${delegatedRequestId}] [approvalRequestId=${approvalRequest.id}] [provider=${provider.type}] [providerRequestId=${providerRequestId}]`
+ `Delegated approval request delivered [delegatedRequestId=${delegatedRequestId}] [approvalRequestId=${approvalRequest.id}] [provider=${delegatedPolicy.type}] [providerRequestId=${providerRequestId}]`
);
} catch (error) {
const isTerminal = isFinalAttempt || error instanceof UnrecoverableError;
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 7c3b4d3460..15861ade66 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,10 +1,7 @@
import { ProjectType, TApprovalRequests } from "@app/db/schemas";
-import { AppConnection } from "@app/services/app-connection/app-connection-enums";
import { TAppConnection } from "@app/services/app-connection/app-connection-types";
import { ApprovalPolicyType } from "@app/services/approval-policy/approval-policy-enums";
-import { DelegatedApprovalPolicyType } from "../delegated-approval-enums";
-
export type TSecretAccessDispatchDetails = {
policyType: ApprovalPolicyType.SecretAccess;
environment: string;
@@ -33,14 +30,9 @@ export type TDelegatedApprovalDispatchInput = {
export type TDelegatedApprovalDispatchResult = {
providerRequestId: string;
- // The provider already held this request from an earlier attempt whose response was lost. Safe to treat
- // as delivered because every attempt sends the same callback token.
- duplicate: boolean;
};
export type TDelegatedApprovalProvider = {
- type: DelegatedApprovalPolicyType;
- app: AppConnection;
dispatch: (
input: TDelegatedApprovalDispatchInput,
connection: TAppConnection
diff --git a/backend/src/services/delegated-approval/dispatch/providers/servicenow/servicenow-constants.ts b/backend/src/services/delegated-approval/dispatch/providers/servicenow/servicenow-constants.ts
index c52ad968cc..74e19e5c80 100644
--- a/backend/src/services/delegated-approval/dispatch/providers/servicenow/servicenow-constants.ts
+++ b/backend/src/services/delegated-approval/dispatch/providers/servicenow/servicenow-constants.ts
@@ -1,8 +1,3 @@
-import { ApprovalPolicyType } from "@app/services/approval-policy/approval-policy-enums";
-
-import { DelegatedApprovalSupportedPolicyType } from "../../../delegated-approval-maps";
-import { ServiceNowRequestType } from "./servicenow-enums";
-
export const SERVICENOW_ACCESS_REQUEST_PATH = "/api/x_infis_approvals/v1/infisical/access_request";
export const SERVICENOW_DISPATCH_TIMEOUT_MS = 15_000;
@@ -10,13 +5,3 @@ export const SERVICENOW_DISPATCH_TIMEOUT_MS = 15_000;
export const SERVICENOW_DISPATCH_MAX_CONTENT_LENGTH = 64 * 1024;
export const SERVICENOW_ERROR_DETAIL_MAX_CHARS = 200;
-
-export const SERVICENOW_EVENT_MAP: Record<
- DelegatedApprovalSupportedPolicyType,
- { event: string; requestType: ServiceNowRequestType }
-> = {
- [ApprovalPolicyType.SecretAccess]: {
- event: "secrets_management.access_request",
- requestType: ServiceNowRequestType.SecretAccess
- }
-};
diff --git a/backend/src/services/delegated-approval/dispatch/providers/servicenow/servicenow-fns.ts b/backend/src/services/delegated-approval/dispatch/providers/servicenow/servicenow-fns.ts
index 3247f3cc8f..e23437d012 100644
--- a/backend/src/services/delegated-approval/dispatch/providers/servicenow/servicenow-fns.ts
+++ b/backend/src/services/delegated-approval/dispatch/providers/servicenow/servicenow-fns.ts
@@ -9,7 +9,6 @@ import { TAppConnection } from "@app/services/app-connection/app-connection-type
import { TServiceNowConnection } from "@app/services/app-connection/servicenow";
import { ApprovalPolicyType } from "@app/services/approval-policy/approval-policy-enums";
-import { DelegatedApprovalPolicyType } from "../../../delegated-approval-enums";
import {
TDelegatedApprovalDispatchDetails,
TDelegatedApprovalDispatchInput,
@@ -19,19 +18,15 @@ import {
SERVICENOW_ACCESS_REQUEST_PATH,
SERVICENOW_DISPATCH_MAX_CONTENT_LENGTH,
SERVICENOW_DISPATCH_TIMEOUT_MS,
- SERVICENOW_ERROR_DETAIL_MAX_CHARS,
- SERVICENOW_EVENT_MAP
+ SERVICENOW_ERROR_DETAIL_MAX_CHARS
} from "./servicenow-constants";
+import { ServiceNowRequestType } from "./servicenow-enums";
import {
ServiceNowAccessRequestPayloadSchema,
ServiceNowAccessRequestResponseSchema,
ServiceNowErrorResponseSchema
} from "./servicenow-schemas";
-import {
- TServiceNowAccessRequestOutcome,
- TServiceNowAccessRequestPayload,
- TServiceNowAccessRequestRecord
-} from "./servicenow-types";
+import { TServiceNowAccessRequestOutcome, TServiceNowAccessRequestPayload } from "./servicenow-types";
const describeInstance = (instanceUrl: string) => {
try {
@@ -44,10 +39,16 @@ const describeInstance = (instanceUrl: string) => {
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: "secrets_management.access_request",
+ request_type: ServiceNowRequestType.SecretAccess,
environment: details.environment,
secret_path: details.secretPath,
permissions: details.permissions,
@@ -64,14 +65,10 @@ const buildRequestTypeFields = (details: TDelegatedApprovalDispatchDetails) => {
export const buildServiceNowAccessRequestPayload = (
input: TDelegatedApprovalDispatchInput
): TServiceNowAccessRequestPayload => {
- const { event, requestType } = SERVICENOW_EVENT_MAP[input.details.policyType];
-
const parsed = ServiceNowAccessRequestPayloadSchema.safeParse({
request_id: input.approvalRequestId,
callback_url: input.callback.url,
callback_token: input.callback.token,
- event,
- request_type: requestType,
product_type: input.productType,
...(input.project ? { project_id: input.project.id, project_name: input.project.name } : {}),
requestor_email: input.requester.email,
@@ -94,35 +91,32 @@ export const parseServiceNowAccessRequestResponse = (
status: number,
data: unknown
): TServiceNowAccessRequestOutcome => {
- const parsed = ServiceNowAccessRequestResponseSchema.safeParse(data);
- let record: TServiceNowAccessRequestRecord | null = null;
- if (parsed.success) {
- record = "result" in parsed.data ? parsed.data.result : parsed.data;
- }
+ const parsed = ServiceNowAccessRequestResponseSchema.safeParse(unwrapServiceNowResult(data));
+ const sysId = parsed.success ? parsed.data.sys_id : null;
if (status === 409) {
- if (!record) {
+ if (!sysId) {
throw new UnrecoverableError(
"ServiceNow reported that it already holds this request but did not return the record ID."
);
}
- return { sysId: record.sys_id, duplicate: true };
+ return { sysId, duplicate: true };
}
- if (!record) {
+ if (!sysId) {
throw new BadRequestError({
message: "ServiceNow accepted the request but returned a response without the record ID."
});
}
- return { sysId: record.sys_id, duplicate: false };
+ return { sysId, duplicate: false };
};
const extractErrorDetail = (data: unknown) => {
- const parsed = ServiceNowErrorResponseSchema.safeParse(data);
+ const parsed = ServiceNowErrorResponseSchema.safeParse(unwrapServiceNowResult(data));
if (!parsed.success) return null;
- const error = "result" in parsed.data ? parsed.data.result.error : parsed.data.error;
+ const { error } = parsed.data;
if (error === undefined || error === null) return null;
const detail = typeof error === "string" ? error : JSON.stringify(error);
@@ -174,65 +168,59 @@ export const toServiceNowDispatchError = (err: unknown, instanceUrl: string) =>
});
};
-export const servicenowProviderFactory = (): TDelegatedApprovalProvider => {
- const dispatch: TDelegatedApprovalProvider["dispatch"] = async (input, connection) => {
- if (!isServiceNowConnection(connection)) {
- throw new UnrecoverableError(`App Connection with ID '${connection.id}' is not a ServiceNow Connection.`);
- }
+const 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"}]`
- );
+ const { instanceUrl, username, password } = connection.credentials;
+ const payload = buildServiceNowAccessRequestPayload(input);
- throw toServiceNowDispatchError(error, instanceUrl);
- }
+ 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"}]`
+ );
- const outcome = parseServiceNowAccessRequestResponse(status, data);
+ throw toServiceNowDispatchError(error, instanceUrl);
+ }
- 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}]`
- );
- }
+ const outcome = parseServiceNowAccessRequestResponse(status, data);
- return { providerRequestId: outcome.sysId, duplicate: outcome.duplicate };
- };
+ 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 {
- type: DelegatedApprovalPolicyType.ServiceNow,
- app: AppConnection.ServiceNow,
- dispatch
- };
+ return { providerRequestId: outcome.sysId };
};
+
+export const serviceNowProvider: TDelegatedApprovalProvider = { dispatch: dispatchServiceNowRequest };
diff --git a/backend/src/services/delegated-approval/dispatch/providers/servicenow/servicenow-schemas.ts b/backend/src/services/delegated-approval/dispatch/providers/servicenow/servicenow-schemas.ts
index 15fa827999..4b174ae7d1 100644
--- a/backend/src/services/delegated-approval/dispatch/providers/servicenow/servicenow-schemas.ts
+++ b/backend/src/services/delegated-approval/dispatch/providers/servicenow/servicenow-schemas.ts
@@ -27,20 +27,10 @@ export const ServiceNowAccessRequestPayloadSchema = z.object({
justification: z.string().optional()
});
-export const ServiceNowAccessRequestRecordSchema = z.object({
- success: z.boolean().optional(),
- request_number: z.string().nullish(),
- sys_id: z.string().min(1),
- error: z.unknown().optional()
+export const ServiceNowAccessRequestResponseSchema = z.object({
+ sys_id: z.string().min(1)
});
-// Scripted REST responses may arrive bare or wrapped in the platform's `result` envelope.
-export const ServiceNowAccessRequestResponseSchema = z.union([
- z.object({ result: ServiceNowAccessRequestRecordSchema }),
- ServiceNowAccessRequestRecordSchema
-]);
-
-export const ServiceNowErrorResponseSchema = z.union([
- z.object({ result: z.object({ error: z.unknown().optional() }) }),
- z.object({ error: z.unknown().optional() })
-]);
+export const ServiceNowErrorResponseSchema = z.object({
+ error: z.unknown().optional()
+});
diff --git a/backend/src/services/delegated-approval/dispatch/providers/servicenow/servicenow-types.ts b/backend/src/services/delegated-approval/dispatch/providers/servicenow/servicenow-types.ts
index 331ed62fea..753884c9ca 100644
--- a/backend/src/services/delegated-approval/dispatch/providers/servicenow/servicenow-types.ts
+++ b/backend/src/services/delegated-approval/dispatch/providers/servicenow/servicenow-types.ts
@@ -1,11 +1,9 @@
import { z } from "zod";
-import { ServiceNowAccessRequestPayloadSchema, ServiceNowAccessRequestRecordSchema } from "./servicenow-schemas";
+import { ServiceNowAccessRequestPayloadSchema } from "./servicenow-schemas";
export type TServiceNowAccessRequestPayload = z.infer<typeof ServiceNowAccessRequestPayloadSchema>;
-export type TServiceNowAccessRequestRecord = z.infer<typeof ServiceNowAccessRequestRecordSchema>;
-
export type TServiceNowAccessRequestOutcome = {
sysId: string;
duplicate: boolean;
diff --git a/backend/src/services/project/project-service.ts b/backend/src/services/project/project-service.ts
index e1d450fa2c..bccf3e83b6 100644
--- a/backend/src/services/project/project-service.ts
+++ b/backend/src/services/project/project-service.ts
@@ -971,9 +971,6 @@ export const projectServiceFactory = ({
return projects.map(({ id, orgId, name, slug, type }) => ({ id, orgId, name, slug, type }));
};
- // For background work that has no actor. It performs no authorization, so it must not back a route.
- const findProjectById = (projectId: string) => projectDAL.findById(projectId);
-
const getAProject = async ({ actorId, actorOrgId, actorAuthMethod, filter, actor }: TGetProjectDTO) => {
const project = await projectDAL.findProjectByFilter(filter);
@@ -2379,7 +2376,6 @@ export const projectServiceFactory = ({
getAccessibleProjectsWithSubOrgs,
updateProject,
getProjectUpgradeStatus,
- findProjectById,
getAProject,
toggleAutoCapitalization,
toggleDeleteProtection,
diff --git a/backend/src/services/secret-access-approval-global-request-bridge/secret-access-approval-global-request-bridge-service.ts b/backend/src/services/secret-access-approval-global-request-bridge/secret-access-approval-global-request-bridge-service.ts
index 52299a149a..156c50c690 100644
--- a/backend/src/services/secret-access-approval-global-request-bridge/secret-access-approval-global-request-bridge-service.ts
+++ b/backend/src/services/secret-access-approval-global-request-bridge/secret-access-approval-global-request-bridge-service.ts
@@ -30,7 +30,6 @@ import {
} from "@app/services/approval-policy/secret-access/secret-access-policy-fns";
import { TSecretAccessRequestData } from "@app/services/approval-policy/secret-access/secret-access-policy-types";
import { ActorType } from "@app/services/auth/auth-type";
-import { TDelegatedApprovalRequest } from "@app/services/delegated-approval/delegated-approval-types";
import { AccessRequestWebhookAction, WebhookEvents } from "@app/services/webhook/webhook-types";
import {
@@ -288,13 +287,13 @@ export const secretAccessApprovalGlobalRequestBridgeServiceFactory = ({
throw new BadRequestError({ message: constraintValidation.errors?.join("; ") ?? "Policy constraints not met" });
}
- const [requestedByUser, project] = await Promise.all([
+ const [requestedByUser, project, delegatedPolicy] = await Promise.all([
userDAL.findById(requestedByUserId),
- projectDAL.findById(projectId)
+ projectDAL.findById(projectId),
+ policy.steps.length ? null : delegatedApprovalService.getPolicyByPolicyId(policy.id)
]);
if (!requestedByUser) throw new ForbiddenRequestError({ message: "User not found" });
if (!project) throw new NotFoundError({ message: `Project with ID '${projectId}' not found` });
- const delegatedPolicy = policy.steps.length ? null : await delegatedApprovalService.getPolicyByPolicyId(policy.id);
if (!policy.steps.length && !delegatedPolicy) {
throw new BadRequestError({ message: `Policy '${policy.name}' has no approvers configured` });
}
@@ -324,9 +323,8 @@ export const secretAccessApprovalGlobalRequestBridgeServiceFactory = ({
const parsedMs = requestExpirationTime ? ms(requestExpirationTime) : null;
const expiresAt = parsedMs && !Number.isNaN(parsedMs) ? new Date(Date.now() + parsedMs) : null;
- let delegatedRequest: TDelegatedApprovalRequest | undefined;
- const created = await approvalRequestDAL.transaction((tx) =>
- createApprovalRequestWithSteps(
+ const { created, delegatedRequest } = await approvalRequestDAL.transaction(async (tx) => {
+ const approvalRequest = await createApprovalRequestWithSteps(
{
projectId,
organizationId: actorOrgId,
@@ -342,14 +340,13 @@ export const secretAccessApprovalGlobalRequestBridgeServiceFactory = ({
requesterEmail: requestedByUser.email || requestedByUser.username
},
{ approvalRequestDAL, approvalRequestStepsDAL, approvalRequestStepEligibleApproversDAL },
- tx,
- delegatedPolicy
- ? async (approvalRequest, trx) => {
- delegatedRequest = await delegatedApprovalService.createRequest({ approvalRequest }, trx);
- }
- : undefined
- )
- );
+ tx
+ );
+ return {
+ created: approvalRequest,
+ delegatedRequest: delegatedPolicy ? await delegatedApprovalService.createRequest({ approvalRequest }, tx) : null
+ };
+ });
if (delegatedRequest) {
await delegatedApprovalDispatchQueue.queueDispatch({ delegatedRequestId: delegatedRequest.id });