Skip to content

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

move increment after the claim decision

adilsone9555b4707b7
diff --git a/CLAUDE.md b/CLAUDE.md
index 8610931cb2..fdb3b8f032 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -198,16 +198,18 @@ differs from the one stored for the request; the provider keeps the first token
another, so a mismatch is unrecoverable. The provider calls `POST /api/v1/delegated-approvals/callback` (unauthenticated, IP rate limited)
with the token in the `Infisical-Approval-Token` header and a body naming the event and the provider's record id;
the body carries no decision, which a later worker reads back from the provider. The route finds the row by
-`providerRequestId`, checks the token, and only then counts the callback in `callbackAttempts`; on
-the sixth callback with a valid token it 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. A
+`providerRequestId` and checks the token. Only a callback that starts a read-back counts in `callbackAttempts`,
+so the limit bounds read-backs rather than repeats; on the sixth such callback it sets the row `failed` with a
+readable `statusReason` and cancels the attached approval request in the claim's transaction, so the policy is
+freed and the UI stops offering Cancel. That transaction locks the approval request before it claims, the same
+order the decision consumer and cancel take, or failing the request inside it would invert their lock order. A
refused callback is never counted: the limit closes the request, so counting it would let anyone who knows the
record id cancel the request, and the token is 256 random bits, so there is nothing to brute force. Every other
refusal (no row for the record id, 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, and
only when it wins `claimDecisionRead`: a conditional update of `decisionReadRequestedAt`, in the emit's
transaction, that one of any number of concurrent callbacks wins. A repeat while a read-back is still in
-flight gets the same 200 and emits nothing; a claim older than `DELEGATED_APPROVAL_DECISION_READ_CLAIM_TTL_MS`
+flight gets the same 200, emits nothing and is not counted; a claim older than `DELEGATED_APPROVAL_DECISION_READ_CLAIM_TTL_MS`
(70 minutes, past the outbox's last retry) has expired, so a fresh notification after an earlier read-back
ran out of retries still starts one. `eventType` is the
body's event and `idempotencyKey` is the delegated request id plus the attempt count. The
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 7676c930fd..7973cbd671 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
@@ -17,4 +17,4 @@ export const DELEGATED_APPROVAL_DECISION_READ_CLAIM_TTL_MS = 70 * 60_000;
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.`;
+export const DELEGATED_APPROVAL_CALLBACK_ATTEMPTS_EXHAUSTED_REASON = `The delegated approval system asked Infisical to check for its decision more than ${DELEGATED_APPROVAL_CALLBACK_MAX_ATTEMPTS} times, so Infisical no longer accepts a decision for this request. Create the request again.`;
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 ecaa9142c1..e5241b8b73 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
@@ -219,23 +219,39 @@ describe("handleCallback", () => {
expect(eventEmitter.emit).not.toHaveBeenCalled();
});
- test("counts a callback once its token matches", async () => {
+ test("counts a callback that claims the read-back, in the claim's transaction", async () => {
const { service, delegatedApprovalRequestDAL } = makeCallbackService();
await service.handleCallback(callback());
expect(delegatedApprovalRequestDAL.update).toHaveBeenCalledWith(
{ id: "delegated-1" },
- { $incr: { callbackAttempts: 1 } }
+ { $incr: { callbackAttempts: 1 } },
+ TX
+ );
+ expect(delegatedApprovalRequestDAL.claimDecisionRead.mock.invocationCallOrder[0]).toBeLessThan(
+ delegatedApprovalRequestDAL.update.mock.invocationCallOrder[0]
);
});
- test("rejects a request that is not awaiting a decision", async () => {
- const { service, eventEmitter } = makeCallbackService({
+ test("locks the approval request before claiming the read-back", async () => {
+ const { service, delegatedApprovalRequestDAL, approvalRequestDAL } = makeCallbackService();
+
+ await service.handleCallback(callback());
+
+ expect(approvalRequestDAL.findByIdForUpdate).toHaveBeenCalledWith("request-1", TX);
+ expect(approvalRequestDAL.findByIdForUpdate.mock.invocationCallOrder[0]).toBeLessThan(
+ delegatedApprovalRequestDAL.claimDecisionRead.mock.invocationCallOrder[0]
+ );
+ });
+
+ test("rejects a request that is not awaiting a decision without counting it", async () => {
+ const { service, delegatedApprovalRequestDAL, eventEmitter } = makeCallbackService({
delegatedRequest: makeDelegatedRequest({ status: DelegatedApprovalRequestStatus.Approved })
});
await expect(service.handleCallback(callback())).rejects.toBeInstanceOf(ForbiddenRequestError);
+ expect(delegatedApprovalRequestDAL.update).not.toHaveBeenCalled();
expect(eventEmitter.emit).not.toHaveBeenCalled();
});
@@ -339,6 +355,21 @@ describe("handleCallback", () => {
expect(eventEmitter.emit).not.toHaveBeenCalled();
});
+ test("does not count a repeat while another read-back holds the claim, even at the limit", async () => {
+ const atLimit = makeDelegatedRequest({ callbackAttempts: DELEGATED_APPROVAL_CALLBACK_MAX_ATTEMPTS });
+ const { service, delegatedApprovalRequestDAL, approvalRequestDAL } = makeCallbackService({
+ delegatedRequest: atLimit,
+ attemptsAfterIncrement: DELEGATED_APPROVAL_CALLBACK_MAX_ATTEMPTS + 1
+ });
+ delegatedApprovalRequestDAL.claimDecisionRead.mockResolvedValue(null);
+ delegatedApprovalRequestDAL.findById.mockResolvedValue(atLimit);
+
+ await expect(service.handleCallback(callback())).resolves.toEqual({ delegatedRequestId: "delegated-1" });
+ expect(delegatedApprovalRequestDAL.update).not.toHaveBeenCalled();
+ expect(delegatedApprovalRequestDAL.updateWithDetails).not.toHaveBeenCalled();
+ expect(approvalRequestDAL.updateById).not.toHaveBeenCalled();
+ });
+
test("rejects a callback whose request stopped awaiting a decision before the claim", async () => {
const { service, delegatedApprovalRequestDAL, eventEmitter } = makeCallbackService();
delegatedApprovalRequestDAL.claimDecisionRead.mockResolvedValue(null);
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 b814369d35..1c20c13c5f 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
@@ -84,29 +84,6 @@ export const delegatedApprovalCallbackServiceFactory = ({
throw rejectApprovalCallback("token mismatch", logContext);
}
- // Counted only after the token matches: the limit closes the request, so a refused callback must
- // not count toward it, or anyone who knows the external ID could cancel the request. The token is
- // 256 random bits, so refusals need no counter of their own to stop it being guessed.
- const [counted] = await delegatedApprovalRequestDAL.update(
- { id: delegatedRequest.id },
- { $incr: { callbackAttempts: 1 } }
- );
- const attempts = counted?.callbackAttempts ?? delegatedRequest.callbackAttempts + 1;
- if (attempts > DELEGATED_APPROVAL_CALLBACK_MAX_ATTEMPTS) {
- 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 (delegatedRequest.status !== DelegatedApprovalRequestStatus.WaitingApproval) {
throw rejectApprovalCallback("request is not awaiting a decision", {
...logContext,
@@ -124,25 +101,52 @@ export const delegatedApprovalCallbackServiceFactory = ({
// A read-back already in flight will see the decision this callback announces, so a repeat only
// starts another once that one has had time to finish.
const outcome = await delegatedApprovalRequestDAL.transaction(async (tx) => {
+ await approvalRequestDAL.findByIdForUpdate(delegatedRequest.requestId, tx);
const claimed = await delegatedApprovalRequestDAL.claimDecisionRead(
{ id: delegatedRequest.id, staleBefore: new Date(Date.now() - DELEGATED_APPROVAL_DECISION_READ_CLAIM_TTL_MS) },
tx
);
if (!claimed) {
const current = await delegatedApprovalRequestDAL.findById(delegatedRequest.id, tx);
- return current?.status === DelegatedApprovalRequestStatus.WaitingApproval ? "deduplicated" : "closed";
+ if (current?.status !== DelegatedApprovalRequestStatus.WaitingApproval) return { status: "closed" } as const;
+ return { status: "deduplicated", attempts: current.callbackAttempts } as const;
+ }
+
+ const [counted] = await delegatedApprovalRequestDAL.update(
+ { id: delegatedRequest.id },
+ { $incr: { callbackAttempts: 1 } },
+ tx
+ );
+ const attempts = counted?.callbackAttempts ?? claimed.callbackAttempts + 1;
+ if (attempts > DELEGATED_APPROVAL_CALLBACK_MAX_ATTEMPTS) {
+ await failDelegatedApprovalRequest(
+ {
+ id: delegatedRequest.id,
+ requestId: delegatedRequest.requestId,
+ reason: DELEGATED_APPROVAL_CALLBACK_ATTEMPTS_EXHAUSTED_REASON
+ },
+ { approvalRequestDAL, delegatedApprovalRequestDAL },
+ tx
+ );
+ return { status: "exhausted", attempts } as const;
}
await eventEmitter.emit({ eventType: event, idempotencyKey: `${delegatedRequest.id}:${attempts}`, payload }, tx);
- return "accepted";
+ return { status: "accepted", attempts } as const;
});
- if (outcome === "closed") {
+ if (outcome.status === "closed") {
throw rejectApprovalCallback("request is not awaiting a decision", logContext);
}
+ if (outcome.status === "exhausted") {
+ throw rejectApprovalCallback("callback attempts exhausted", {
+ ...logContext,
+ attempts: String(outcome.attempts)
+ });
+ }
logger.info(
- `Delegated approval callback ${outcome} [delegatedRequestId=${delegatedRequest.id}] [approvalRequestId=${delegatedRequest.requestId}] [event=${event}] [attempt=${attempts}]`
+ `Delegated approval callback ${outcome.status} [delegatedRequestId=${delegatedRequest.id}] [approvalRequestId=${delegatedRequest.requestId}] [event=${event}] [callbackAttempts=${outcome.attempts}]`
);
return { delegatedRequestId: delegatedRequest.id };