Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
check token before incrementing
adilson074d20a0fce2
diff --git a/CLAUDE.md b/CLAUDE.mdindex ac724ad2c5..dd5fb0b40b 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -190,10 +190,12 @@ request; the provider keeps the first token it was given and cannot be told anotunrecoverable. 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` (404 when none), counts the callback in `callbackAttempts` before checking anything else so a-wrong token for a known record still burns the request, and on the sixth callback sets the row `failed` with a-readable `statusReason` and cancels the attached approval request in the same transaction, so the policy is freed-and the UI stops offering Cancel. Every other refusal (bad or missing token, request not `waiting_approval`)+`providerRequestId` (404 when none), 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+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 (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, andonly when it wins `claimDecisionRead`: a conditional update of `decisionReadRequestedAt`, in the emit'stransaction, that one of any number of concurrent callbacks wins. A repeat while a read-back is still indiff --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.tsindex cf741939c9..23897fff85 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@@ -192,30 +192,34 @@ describe("handleCallback", () => {expect(eventEmitter.emit).not.toHaveBeenCalled();});- test("counts the callback before checking the token", async () => {- const { service, delegatedApprovalRequestDAL, eventEmitter } = makeCallbackService();-- await expect(service.handleCallback(callback({ token: "inf_ext_wrong" }))).rejects.toBeInstanceOf(- ForbiddenRequestError- );- expect(delegatedApprovalRequestDAL.update).toHaveBeenCalledWith(- { id: "delegated-1" },- { $incr: { callbackAttempts: 1 } }- );- expect(eventEmitter.emit).not.toHaveBeenCalled();- });-test.each([["missing", undefined],["unprefixed", "stored-token"],["mismatched", "inf_ext_other-token"]- ])("rejects a %s token with 403 and no event", async (_label, token) => {- const { service, eventEmitter } = makeCallbackService();+ ])("rejects a %s token without counting it, even when it would pass the limit", async (_label, token) => {+ const { service, delegatedApprovalRequestDAL, approvalRequestDAL, eventEmitter } = makeCallbackService({+ delegatedRequest: makeDelegatedRequest({ callbackAttempts: DELEGATED_APPROVAL_CALLBACK_MAX_ATTEMPTS }),+ attemptsAfterIncrement: DELEGATED_APPROVAL_CALLBACK_MAX_ATTEMPTS + 1+ });await expect(service.handleCallback(callback({ token }))).rejects.toBeInstanceOf(ForbiddenRequestError);+ expect(delegatedApprovalRequestDAL.update).not.toHaveBeenCalled();+ expect(delegatedApprovalRequestDAL.updateWithDetails).not.toHaveBeenCalled();+ expect(approvalRequestDAL.updateById).not.toHaveBeenCalled();expect(eventEmitter.emit).not.toHaveBeenCalled();});+ test("counts a callback once its token matches", async () => {+ const { service, delegatedApprovalRequestDAL } = makeCallbackService();++ await service.handleCallback(callback());++ expect(delegatedApprovalRequestDAL.update).toHaveBeenCalledWith(+ { id: "delegated-1" },+ { $incr: { callbackAttempts: 1 } }+ );+ });+test("rejects a request that is not awaiting a decision", async () => {const { service, eventEmitter } = makeCallbackService({delegatedRequest: makeDelegatedRequest({ status: DelegatedApprovalRequestStatus.Approved })@@ -226,7 +230,7 @@ describe("handleCallback", () => {});test("fails the request and cancels its approval request on the callback past the limit", async () => {- const { service, delegatedApprovalRequestDAL, approvalRequestDAL, eventEmitter, kmsService } = makeCallbackService({+ const { service, delegatedApprovalRequestDAL, approvalRequestDAL, eventEmitter } = makeCallbackService({attemptsAfterIncrement: DELEGATED_APPROVAL_CALLBACK_MAX_ATTEMPTS + 1});@@ -247,7 +251,6 @@ describe("handleCallback", () => {expect(patch.status).toBe(DelegatedApprovalRequestStatus.Failed);expect(patch.details.statusReason).toContain(`more than ${DELEGATED_APPROVAL_CALLBACK_MAX_ATTEMPTS} times`);expect(tx).toBe(TX);- expect(kmsService.createCipherPairWithDataKey).not.toHaveBeenCalled();expect(eventEmitter.emit).not.toHaveBeenCalled();});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.tsindex 43c0a61787..550ebfb462 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@@ -70,8 +70,25 @@ export const delegatedApprovalCallbackServiceFactory = ({const logContext = { delegatedRequestId: delegatedRequest.id, externalId };- // Counted before the token is checked, so a wrong token for a known external ID still burns the- // request and the token cannot be brute-forced.+ if (!token || !token.startsWith(DELEGATED_APPROVAL_CALLBACK_TOKEN_PREFIX)) {+ throw rejectApprovalCallback("missing or malformed token", logContext);+ }+ if (!delegatedRequest.encryptedCallbackToken) {+ throw rejectApprovalCallback("request has no callback token", logContext);+ }++ const { decryptor } = await kmsService.createCipherPairWithDataKey({+ type: KmsDataKey.Organization,+ orgId: delegatedRequest.approvalRequestOrganizationId+ });+ const storedToken = decryptor({ cipherTextBlob: delegatedRequest.encryptedCallbackToken }).toString();+ if (!isTokenMatch(token, storedToken)) {+ 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 } }@@ -92,22 +109,6 @@ export const delegatedApprovalCallbackServiceFactory = ({});}- if (!token || !token.startsWith(DELEGATED_APPROVAL_CALLBACK_TOKEN_PREFIX)) {- throw rejectApprovalCallback("missing or malformed token", logContext);- }- if (!delegatedRequest.encryptedCallbackToken) {- throw rejectApprovalCallback("request has no callback token", logContext);- }-- const { decryptor } = await kmsService.createCipherPairWithDataKey({- type: KmsDataKey.Organization,- orgId: delegatedRequest.approvalRequestOrganizationId- });- const storedToken = decryptor({ cipherTextBlob: delegatedRequest.encryptedCallbackToken }).toString();- if (!isTokenMatch(token, storedToken)) {- throw rejectApprovalCallback("token mismatch", logContext);- }-if (delegatedRequest.status !== DelegatedApprovalRequestStatus.WaitingApproval) {throw rejectApprovalCallback("request is not awaiting a decision", {...logContext,diff --git a/tests/suites/secretmanager/approvals/delegated_access_request_test.go b/tests/suites/secretmanager/approvals/delegated_access_request_test.goindex 0dbc3d30da..d9a30e36b8 100644--- a/tests/suites/secretmanager/approvals/delegated_access_request_test.go+++ b/tests/suites/secretmanager/approvals/delegated_access_request_test.go@@ -158,6 +158,41 @@ func TestDelegatedAccessRequest_CallbackLimit(t *testing.T) {require.False(t, req.current(t).granted)require.Equal(t, http.StatusForbidden, req.readSecret(t))})++ t.Run("should keep the request open when a sixth callback arrives without a token", func(t *testing.T) {+ t.Parallel()++ // Setup+ req := newWaitingDelegatedRequest(t)+ for range 5 {+ require.Equal(t, http.StatusForbidden, req.callback(t, ""))+ }++ // Action+ code := req.callback(t, "")++ // Assert+ require.Equal(t, http.StatusForbidden, code)+ require.Equal(t, delegatedState{status: "pending", delegated: "waiting_approval"}, req.current(t))+ })++ t.Run("should grant access when ServiceNow approves after six callbacks without a token", func(t *testing.T) {+ t.Parallel()++ // Setup+ req := newWaitingDelegatedRequest(t)+ for range 6 {+ require.Equal(t, http.StatusForbidden, req.callback(t, ""))+ }+ req.sn.Seed(t, servicenow.Approved(req.record.SysID))++ // Action+ code := req.callback(t, req.record.CallbackToken)++ // Assert+ require.Equal(t, http.StatusOK, code)+ require.Equal(t, delegatedState{status: "approved", delegated: "approved", granted: true}, req.await(t, "approved"))+ })}func TestDelegatedAccessRequest_CallbackToken(t *testing.T) {