Skip to content

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

refac for simplicity

adilson677706c69c6d
diff --git a/backend/src/db/migrations/20261019120000_delegated-approval-callback-attempts.ts b/backend/src/db/migrations/20261019120000_delegated-approval-callback-attempts.ts
index 50bcd4cdbc..dff69a8251 100644
--- a/backend/src/db/migrations/20261019120000_delegated-approval-callback-attempts.ts
+++ b/backend/src/db/migrations/20261019120000_delegated-approval-callback-attempts.ts
@@ -3,23 +3,17 @@ import { Knex } from "knex";
import { TableName } from "../schemas";
export async function up(knex: Knex): Promise<void> {
- const hasCallbackAttempts = await knex.schema.hasColumn(TableName.DelegatedApprovalRequests, "callbackAttempts");
-
- await knex.schema.alterTable(TableName.DelegatedApprovalRequests, (t) => {
- if (!hasCallbackAttempts) {
+ if (!(await knex.schema.hasColumn(TableName.DelegatedApprovalRequests, "callbackAttempts"))) {
+ await knex.schema.alterTable(TableName.DelegatedApprovalRequests, (t) => {
t.integer("callbackAttempts").notNullable().defaultTo(0);
- }
- t.index(["providerRequestId"], "delegated_approval_requests_provider_request_id_idx");
- });
+ });
+ }
}
export async function down(knex: Knex): Promise<void> {
- const hasCallbackAttempts = await knex.schema.hasColumn(TableName.DelegatedApprovalRequests, "callbackAttempts");
-
- await knex.schema.alterTable(TableName.DelegatedApprovalRequests, (t) => {
- t.dropIndex(["providerRequestId"], "delegated_approval_requests_provider_request_id_idx");
- if (hasCallbackAttempts) {
+ if (await knex.schema.hasColumn(TableName.DelegatedApprovalRequests, "callbackAttempts")) {
+ await knex.schema.alterTable(TableName.DelegatedApprovalRequests, (t) => {
t.dropColumn("callbackAttempts");
- }
- });
+ });
+ }
}
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
index cdb053f3b1..8f195ac8b9 100644
--- a/backend/src/services/delegated-approval-callback/delegated-approval-callback-events.ts
+++ b/backend/src/services/delegated-approval-callback/delegated-approval-callback-events.ts
@@ -14,5 +14,7 @@ export const DelegatedApprovalCallbackEventPayloadSchema = z.object({
export type TDelegatedApprovalCallbackEventPayload = z.infer<typeof DelegatedApprovalCallbackEventPayloadSchema>;
+const DELEGATED_APPROVAL_CALLBACK_EVENTS = new Set<string>(Object.values(DelegatedApprovalCallbackEvent));
+
export const isDelegatedApprovalCallbackEvent = (eventType: string): eventType is DelegatedApprovalCallbackEvent =>
- (Object.values(DelegatedApprovalCallbackEvent) as string[]).includes(eventType);
+ DELEGATED_APPROVAL_CALLBACK_EVENTS.has(eventType);
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 c13aff00f5..888bc1f665 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
@@ -35,6 +35,7 @@ const encrypt = (plainText: Buffer) => Buffer.concat([CIPHER_PREFIX, plainText])
const decrypt = (cipherTextBlob: Buffer) => cipherTextBlob.subarray(CIPHER_PREFIX.length);
const TX = { isTx: true };
+const PRIMARY = { isPrimary: true };
const makeService = ({
stored = true,
@@ -43,6 +44,7 @@ const makeService = ({
const delegatedApprovalRequestDAL = {
update: vi.fn(async (_filter: unknown, patch: object) => (stored ? [{ id: "delegated-1", ...patch }] : [])),
transaction: vi.fn(async (cb: (tx: unknown) => Promise<unknown>) => cb(TX)),
+ primaryNode: vi.fn(() => PRIMARY),
findById: vi.fn(async (): Promise<unknown> => currentRow),
findByProviderRequestId: vi.fn(async (): Promise<unknown> => null),
claimDecisionRead: vi.fn(async (): Promise<unknown> => ({ id: "delegated-1" }))
@@ -94,8 +96,7 @@ describe("getOrIssueCallbackToken", () => {
});
expect(delegatedApprovalRequestDAL.update).toHaveBeenCalledWith(
{ id: "delegated-1", encryptedCallbackToken: null },
- { encryptedCallbackToken: encrypt(Buffer.from(token as string)) },
- TX
+ { encryptedCallbackToken: encrypt(Buffer.from(token as string)) }
);
});
@@ -111,8 +112,8 @@ describe("getOrIssueCallbackToken", () => {
expect(delegatedApprovalRequestDAL.update).not.toHaveBeenCalled();
});
- test("falls back to the token a concurrent attempt stored first", async () => {
- const { service } = makeService({
+ test("falls back to the token a concurrent attempt stored first, read from the primary", async () => {
+ const { service, delegatedApprovalRequestDAL } = makeService({
stored: false,
currentRow: { encryptedCallbackToken: encrypt(Buffer.from("winner-token")) }
});
@@ -123,6 +124,7 @@ describe("getOrIssueCallbackToken", () => {
});
expect(token).toBe("winner-token");
+ expect(delegatedApprovalRequestDAL.findById).toHaveBeenCalledWith("delegated-1", PRIMARY);
});
test("returns null when the request vanished before a token could be stored", async () => {
@@ -150,7 +152,6 @@ describe("handleCallback", () => {
providerRequestId: EXTERNAL_ID,
callbackAttempts: 0,
approvalRequestOrganizationId: "org-1",
- approvalRequestStatus: ApprovalRequestStatus.Pending,
...overrides
});
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 8688e8271e..43c0a61787 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
@@ -45,14 +45,16 @@ export const delegatedApprovalCallbackServiceFactory = ({
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);
- });
+ const [issued] = await delegatedApprovalRequestDAL.update(
+ { id: delegatedRequest.id, encryptedCallbackToken: null },
+ { encryptedCallbackToken }
+ );
+ if (issued) return token;
+
+ const current = await delegatedApprovalRequestDAL.findById(
+ delegatedRequest.id,
+ delegatedApprovalRequestDAL.primaryNode()
+ );
if (!current?.encryptedCallbackToken) return null;
return decryptor({ cipherTextBlob: current.encryptedCallbackToken }).toString();
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 8e886542a3..3a12bb94d4 100644
--- a/backend/src/services/delegated-approval-callback/delegated-approval-callback-types.ts
+++ b/backend/src/services/delegated-approval-callback/delegated-approval-callback-types.ts
@@ -9,7 +9,7 @@ import { DelegatedApprovalCallbackEvent } from "./delegated-approval-callback-en
export type TDelegatedApprovalCallbackServiceFactoryDep = {
delegatedApprovalRequestDAL: Pick<
TDelegatedApprovalRequestDALFactory,
- "claimDecisionRead" | "findById" | "findByProviderRequestId" | "transaction" | "update"
+ "claimDecisionRead" | "findById" | "findByProviderRequestId" | "primaryNode" | "transaction" | "update"
>;
approvalRequestDAL: Pick<TApprovalRequestDALFactory, "transaction" | "findByIdForUpdate" | "updateById">;
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
diff --git a/backend/src/services/delegated-approval-decision/delegated-approval-decision-consumer.test.ts b/backend/src/services/delegated-approval-decision/delegated-approval-decision-consumer.test.ts
index 752a8f7d70..7d7eaf25f7 100644
--- a/backend/src/services/delegated-approval-decision/delegated-approval-decision-consumer.test.ts
+++ b/backend/src/services/delegated-approval-decision/delegated-approval-decision-consumer.test.ts
@@ -50,6 +50,7 @@ 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 PRIMARY = { primary: true } as never;
const waitingDelegatedRequest = {
id: DELEGATED_REQUEST_ID,
requestId: APPROVAL_REQUEST_ID,
@@ -122,7 +123,7 @@ const buildConsumer = ({
const delegatedApprovalDecisionService = delegatedApprovalDecisionServiceFactory({
delegatedApprovalRequestDAL: {
findById: vi.fn(async () => row),
- transaction: async (cb: (tx: never) => Promise<unknown>) => cb(TX),
+ primaryNode: () => PRIMARY,
update
},
delegatedApprovalPolicyDAL: { findOne: vi.fn().mockResolvedValue(policy) },
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
index 83d80ad577..c4716958f9 100644
--- a/backend/src/services/delegated-approval-decision/delegated-approval-decision-fns.ts
+++ b/backend/src/services/delegated-approval-decision/delegated-approval-decision-fns.ts
@@ -1,15 +1,3 @@
-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();
@@ -69,40 +57,3 @@ export const describeDelegatedApprovalPermissions = (normalized: string[]) => {
.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
index fae3e2b659..3a07e789b8 100644
--- a/backend/src/services/delegated-approval-decision/delegated-approval-decision-service.ts
+++ b/backend/src/services/delegated-approval-decision/delegated-approval-decision-service.ts
@@ -11,8 +11,8 @@ import {
DelegatedApprovalRequestStatus
} from "@app/services/delegated-approval/delegated-approval-enums";
import {
- getDelegatedApprovalConnectionError,
- isApprovalRequestExpired
+ isApprovalRequestExpired,
+ requireDelegatedApprovalConnection
} from "@app/services/delegated-approval/delegated-approval-guards";
import {
DELEGATED_APPROVAL_FINAL_STATE,
@@ -36,8 +36,7 @@ import { DelegatedApprovalDecision, DelegatedApprovalDecisionOutcome } from "./d
import {
describeDelegatedApprovalPermissions,
haveSameDelegatedApprovalPermissions,
- normalizeDelegatedApprovalPermissions,
- recordDelegatedApprovalDecisionOutcome
+ normalizeDelegatedApprovalPermissions
} from "./delegated-approval-decision-fns";
import {
TApplyDelegatedApprovalDecisionDTO,
@@ -112,7 +111,10 @@ export const delegatedApprovalDecisionServiceFactory = ({
}
};
- const $fail = async (context: TDelegatedApprovalDecisionContext, reason: string) => {
+ const $terminal = async (
+ context: TDelegatedApprovalDecisionContext,
+ reason: string
+ ): Promise<TApplyDelegatedApprovalDecisionResult> => {
try {
await failDelegatedApprovalRequest(
{ id: context.delegatedRequestId, requestId: context.approvalRequest.id, reason },
@@ -125,16 +127,17 @@ export const delegatedApprovalDecisionServiceFactory = ({
);
}
await $audit(context, { outcome: DelegatedApprovalDecisionOutcome.Failed, reason });
+ logger.error(
+ `Delegated approval decision failed [delegatedRequestId=${context.delegatedRequestId}] [approvalRequestId=${context.approvalRequest.id}] [reason=${reason}]`
+ );
+ return { status: EventResultStatus.Failed, error: reason };
};
const $finalize = async (
context: TDelegatedApprovalDecisionContext,
decided: TDecidedDelegatedApprovalReadResult,
postApprovalTxRoutine: TApprovalResource["postApprovalTxRoutine"]
- ): Promise<{
- outcome: TDelegatedApprovalFinalizeOutcome;
- result: TApplyDelegatedApprovalDecisionResult;
- }> => {
+ ): Promise<TDelegatedApprovalFinalizeOutcome> => {
const outcome = await approvalRequestDAL.transaction(async (tx): Promise<TDelegatedApprovalFinalizeOutcome> => {
const locked = await approvalRequestDAL.findByIdForUpdate(context.approvalRequest.id, tx);
if (!locked) return { kind: "gone" };
@@ -163,28 +166,34 @@ export const delegatedApprovalDecisionServiceFactory = ({
);
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);
- }
+ await approvalRequestDAL.updateById(
+ locked.id,
+ { status: isApproved ? ApprovalRequestStatus.Approved : ApprovalRequestStatus.Rejected },
+ tx
+ );
+ if (isApproved) await postApprovalTxRoutine?.(locked as TApprovalRequest, 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 };
+ 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}]`
+ );
+ break;
+ 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}]`
+ );
+ break;
+ default:
+ logger.info(
+ `Delegated approval request was finalized while its decision was being read, skipping [delegatedRequestId=${context.delegatedRequestId}] [outcome=${outcome.kind}]`
+ );
+ }
+ return outcome;
};
// Reads the decision back from the delegated approval system and finalizes the request. Retry
@@ -261,21 +270,21 @@ export const delegatedApprovalDecisionServiceFactory = ({
}
const rawConnection = await appConnectionDAL.findById(delegatedPolicy.connectionId);
- const connectionError = getDelegatedApprovalConnectionError({
- rawConnection,
- delegatedPolicy,
- organizationId: approvalRequest.organizationId
- });
- if (connectionError || !rawConnection) {
- return $terminal(context, connectionError ?? "The policy's App Connection was not found.");
- }
+ const postApprovalTxRoutine = isDelegatedApprovalSupportedPolicyType(approvalRequest.type)
+ ? approvalResources[approvalRequest.type]?.postApprovalTxRoutine
+ : undefined;
- 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 connection = await decryptAppConnection(
+ requireDelegatedApprovalConnection({
+ rawConnection,
+ delegatedPolicy,
+ organizationId: approvalRequest.organizationId
+ }),
+ kmsService
+ );
const result = await provider.fetchDecision(
{ delegatedRequestId, approvalRequestId: approvalRequest.id, providerRequestId: context.providerRequestId },
connection
@@ -291,7 +300,7 @@ export const delegatedApprovalDecisionServiceFactory = ({
if (result.approvalRequestId && result.approvalRequestId !== approvalRequest.id) {
throw new UnrecoverableError(
- `${providerName} returned the record of a different request ('${result.approvalRequestId}'). Create the request again.`
+ `${delegatedApprovalName} returned the record of a different request ('${result.approvalRequestId}'). Create the request again.`
);
}
@@ -301,16 +310,13 @@ export const delegatedApprovalDecisionServiceFactory = ({
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.`
+ `${delegatedApprovalName} approved different permissions than this request asked for. Requested: ${describeDelegatedApprovalPermissions(requested)}. Approved in ${delegatedApprovalName}: ${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}.`
+ `Requests of type '${approvalRequest.type}' cannot be granted from a decision made in ${delegatedApprovalName}.`
);
}
}
@@ -328,7 +334,7 @@ export const delegatedApprovalDecisionServiceFactory = ({
return { status: EventResultStatus.Retry, error: message };
}
- const { outcome: finalized, result } = await $finalize(context, decided, postApprovalTxRoutine);
+ const finalized = await $finalize(context, decided, postApprovalTxRoutine);
if (finalized.kind === "applied") {
const notify = isDelegatedApprovalSupportedPolicyType(approvalRequest.type)
? decisionNotifiers[approvalRequest.type]
@@ -344,7 +350,7 @@ export const delegatedApprovalDecisionServiceFactory = ({
}
}
}
- return result;
+ return { status: EventResultStatus.Delivered };
};
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
index ecd33d5174..022336abb5 100644
--- a/backend/src/services/delegated-approval-decision/delegated-approval-decision-types.ts
+++ b/backend/src/services/delegated-approval-decision/delegated-approval-decision-types.ts
@@ -46,7 +46,7 @@ export type TDelegatedApprovalDecisionAuditMetadata = {
};
export type TDelegatedApprovalDecisionServiceFactoryDep = {
- delegatedApprovalRequestDAL: Pick<TDelegatedApprovalRequestDALFactory, "findById" | "transaction" | "update">;
+ delegatedApprovalRequestDAL: Pick<TDelegatedApprovalRequestDALFactory, "findById" | "primaryNode" | "update">;
delegatedApprovalPolicyDAL: Pick<TDelegatedApprovalPolicyDALFactory, "findOne">;
approvalRequestDAL: Pick<TApprovalRequestDALFactory, "findById" | "findByIdForUpdate" | "updateById" | "transaction">;
appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">;
diff --git a/backend/src/services/delegated-approval/delegated-approval-guards.test.ts b/backend/src/services/delegated-approval/delegated-approval-guards.test.ts
index 4c7dc59eb3..f87e7d1cd6 100644
--- a/backend/src/services/delegated-approval/delegated-approval-guards.test.ts
+++ b/backend/src/services/delegated-approval/delegated-approval-guards.test.ts
@@ -1,3 +1,4 @@
+import { UnrecoverableError } from "bullmq";
import { describe, expect, test } from "vitest";
import { ApprovalRequestStatus } from "@app/services/approval-policy/approval-policy-enums";
@@ -5,9 +6,9 @@ import { ApprovalRequestStatus } from "@app/services/approval-policy/approval-po
import { DelegatedApprovalPolicyType } from "./delegated-approval-enums";
import {
DelegatedApprovalRequestBlocker,
- getDelegatedApprovalConnectionError,
getDelegatedApprovalRequestBlocker,
- isApprovalRequestExpired
+ isApprovalRequestExpired,
+ requireDelegatedApprovalConnection
} from "./delegated-approval-guards";
const pending = { status: ApprovalRequestStatus.Pending, expiresAt: null as Date | null };
@@ -40,28 +41,24 @@ describe("getDelegatedApprovalRequestBlocker", () => {
});
});
-describe("getDelegatedApprovalConnectionError", () => {
- test("accepts the policy's connection in the request's org", () => {
+describe("requireDelegatedApprovalConnection", () => {
+ test("returns the policy's connection when it is in the request's org", () => {
+ const rawConnection = { orgId: "org-1" };
+
expect(
- getDelegatedApprovalConnectionError({
- rawConnection: { orgId: "org-1" },
- delegatedPolicy: policy,
- organizationId: "org-1"
- })
- ).toBeNull();
+ requireDelegatedApprovalConnection({ rawConnection, delegatedPolicy: policy, organizationId: "org-1" })
+ ).toBe(rawConnection);
});
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"
- });
+ const requireConnection = () =>
+ requireDelegatedApprovalConnection({ rawConnection, delegatedPolicy: policy, organizationId: "org-1" });
- expect(error).toContain("App Connection with ID 'connection-1' was not found");
- expect(error).toContain("ServiceNow Connection");
+ expect(requireConnection).toThrow(UnrecoverableError);
+ expect(requireConnection).toThrow("App Connection with ID 'connection-1' was not found");
+ expect(requireConnection).toThrow("ServiceNow Connection");
});
});
diff --git a/backend/src/services/delegated-approval/delegated-approval-guards.ts b/backend/src/services/delegated-approval/delegated-approval-guards.ts
index c3d1c75f35..71024b4fc7 100644
--- a/backend/src/services/delegated-approval/delegated-approval-guards.ts
+++ b/backend/src/services/delegated-approval/delegated-approval-guards.ts
@@ -1,10 +1,12 @@
-import { TApprovalRequests } from "@app/db/schemas";
+import { UnrecoverableError } from "bullmq";
+
+import { TAppConnections, 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";
+import { TApprovalRequestExpiry, TRequireDelegatedApprovalConnectionDTO } 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 =>
@@ -32,13 +34,15 @@ export const getDelegatedApprovalRequestBlocker = (
// 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 = ({
+export const requireDelegatedApprovalConnection = <T extends Pick<TAppConnections, "orgId">>({
rawConnection,
delegatedPolicy,
organizationId
-}: TGetDelegatedApprovalConnectionErrorDTO): string | null => {
- if (rawConnection && rawConnection.orgId === organizationId) return null;
+}: TRequireDelegatedApprovalConnectionDTO<T>): T => {
+ if (rawConnection && rawConnection.orgId === organizationId) return rawConnection;
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.`;
+ 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.`
+ );
};
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 c5bbec4cdd..5b54e20bac 100644
--- a/backend/src/services/delegated-approval/delegated-approval-request-dal.ts
+++ b/backend/src/services/delegated-approval/delegated-approval-request-dal.ts
@@ -11,12 +11,13 @@ export type TDelegatedApprovalRequestDALFactory = ReturnType<typeof delegatedApp
export type TDelegatedApprovalRequestWithApprovalRequest = TDelegatedApprovalRequests & {
approvalRequestOrganizationId: string;
- approvalRequestStatus: string;
};
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
@@ -28,10 +29,7 @@ export const delegatedApprovalRequestDALFactory = (db: TDbClient) => {
)
.where(`${TableName.DelegatedApprovalRequests}.providerRequestId`, providerRequestId)
.select(selectAllTableCols(TableName.DelegatedApprovalRequests))
- .select(
- db.ref("organizationId").withSchema(TableName.ApprovalRequests).as("approvalRequestOrganizationId"),
- db.ref("status").withSchema(TableName.ApprovalRequests).as("approvalRequestStatus")
- )
+ .select(db.ref("organizationId").withSchema(TableName.ApprovalRequests).as("approvalRequestOrganizationId"))
.first();
return (row as TDelegatedApprovalRequestWithApprovalRequest | undefined) ?? null;
} catch (error) {
@@ -56,5 +54,5 @@ export const delegatedApprovalRequestDALFactory = (db: TDbClient) => {
}
};
- return { ...orm, findByProviderRequestId, claimDecisionRead };
+ return { ...orm, primaryNode, findByProviderRequestId, claimDecisionRead };
};
diff --git a/backend/src/services/delegated-approval/delegated-approval-request-fns.ts b/backend/src/services/delegated-approval/delegated-approval-request-fns.ts
index 025c259fa2..dff4e0f6f0 100644
--- a/backend/src/services/delegated-approval/delegated-approval-request-fns.ts
+++ b/backend/src/services/delegated-approval/delegated-approval-request-fns.ts
@@ -49,21 +49,21 @@ export const failDelegatedApprovalRequest = (
return tx ? run(tx) : approvalRequestDAL.transaction(run);
};
+// 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.
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 primary = delegatedApprovalRequestDAL.primaryNode();
- const approvalRequest = await approvalRequestDAL.findById(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 };
};
diff --git a/backend/src/services/delegated-approval/delegated-approval-types.ts b/backend/src/services/delegated-approval/delegated-approval-types.ts
index 343617cd21..6b9691133a 100644
--- a/backend/src/services/delegated-approval/delegated-approval-types.ts
+++ b/backend/src/services/delegated-approval/delegated-approval-types.ts
@@ -64,13 +64,13 @@ export type TUpdateDelegatedApprovalRequestDTO = {
export type TApprovalRequestExpiry = { expiresAt?: Date | string | null };
export type TLoadDelegatedApprovalContextDeps = {
- delegatedApprovalRequestDAL: Pick<TDelegatedApprovalRequestDALFactory, "findById" | "transaction">;
+ delegatedApprovalRequestDAL: Pick<TDelegatedApprovalRequestDALFactory, "findById" | "primaryNode">;
approvalRequestDAL: Pick<TApprovalRequestDALFactory, "findById">;
delegatedApprovalPolicyDAL: Pick<TDelegatedApprovalPolicyDALFactory, "findOne">;
};
-export type TGetDelegatedApprovalConnectionErrorDTO = {
- rawConnection: Pick<TAppConnections, "orgId"> | null | undefined;
+export type TRequireDelegatedApprovalConnectionDTO<T extends Pick<TAppConnections, "orgId">> = {
+ rawConnection: T | null | undefined;
delegatedPolicy: Pick<TDelegatedApprovalPolicies, "type" | "connectionId">;
organizationId: string;
};
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 e5592bab52..0018143764 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),
- transaction: async (cb: (tx: never) => Promise<unknown>) => cb(PRIMARY),
+ primaryNode: () => 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 26a8dc7713..c42ef3c7e0 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
@@ -24,8 +24,8 @@ import {
} from "../delegated-approval-events";
import {
DelegatedApprovalRequestBlocker,
- getDelegatedApprovalConnectionError,
- getDelegatedApprovalRequestBlocker
+ getDelegatedApprovalRequestBlocker,
+ requireDelegatedApprovalConnection
} from "../delegated-approval-guards";
import { TDelegatedApprovalPolicyDALFactory } from "../delegated-approval-policy-dal";
import { TDelegatedApprovalRequestDALFactory } from "../delegated-approval-request-dal";
@@ -56,7 +56,7 @@ const BLOCKER_MESSAGES: Record<DelegatedApprovalRequestBlocker, string> = {
type TDelegatedApprovalDispatchConsumerDep = {
delegatedApprovalRequestDAL: Pick<
TDelegatedApprovalRequestDALFactory,
- "findById" | "transaction" | "update" | "updateById"
+ "findById" | "primaryNode" | "update" | "updateById"
>;
delegatedApprovalPolicyDAL: Pick<TDelegatedApprovalPolicyDALFactory, "findOne">;
delegatedApprovalCallbackService: Pick<
@@ -154,23 +154,23 @@ export const delegatedApprovalDispatchConsumerFactory = ({
);
}
+ const primary = delegatedApprovalRequestDAL.primaryNode();
const [project, rawConnection] = await Promise.all([
- projectDAL.findById(approvalRequest.projectId),
- appConnectionDAL.findById(delegatedPolicy.connectionId)
+ projectDAL.findById(approvalRequest.projectId, primary),
+ appConnectionDAL.findById(delegatedPolicy.connectionId, primary)
]);
if (!project) {
throw new UnrecoverableError("The project of the approval request no longer exists.");
}
- 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);
+ const connection = await decryptAppConnection(
+ requireDelegatedApprovalConnection({
+ rawConnection,
+ delegatedPolicy,
+ organizationId: approvalRequest.organizationId
+ }),
+ kmsService
+ );
const callbackToken = await delegatedApprovalCallbackService.getOrIssueCallbackToken({
delegatedRequest,