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 to prevent reusal of tickets for requests
Andrey3c23cda2911e
diff --git a/CLAUDE.md b/CLAUDE.mdindex 2e895e7212..2b2a4d1dcf 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -153,6 +153,8 @@ Auto-approval rules (`approval-policy/auto-approval/`) live on the policy and arprovider to `AUTO_APPROVAL_PROVIDER_REGISTRY`, keyed by its App Connection, not by per-product code. Aresource gates them per request with `allowsAutoApproval`. A policy may have rules and no approvers (nosteps): then a request no rule approves is refused at submission, and only break-glass gets past it. The+engine itself adds a reuse check (`not-used-before`) to every input, answered from the policy's approved+requests' evidence and claimed under an advisory lock in the auto-approve transaction. Thestored evidence holds data fetched from that service, so responses return only its outcome (`autoApproval`),never `autoApprovalEvidence`.diff --git a/backend/src/services/approval-policy/approval-policy-service.ts b/backend/src/services/approval-policy/approval-policy-service.tsindex 2313e7abcf..93a75b8feb 100644--- a/backend/src/services/approval-policy/approval-policy-service.ts+++ b/backend/src/services/approval-policy/approval-policy-service.ts@@ -87,7 +87,13 @@ import {import { createApprovalRequestWithSteps } from "./approval-request-fns";import { getClosestFailedRule, toAutoApprovalOutcome } from "./auto-approval/auto-approval-fns";import { TAutoApprovalServiceFactory } from "./auto-approval/auto-approval-service";-import { TAutoApprovalConfig, TAutoApprovalEvidence } from "./auto-approval/auto-approval-types";+import {+ AUTO_APPROVAL_UNUSED_CONSTRAINT,+ TAutoApprovalConfig,+ TAutoApprovalEvidence,+ TParsedAutoApprovalInput,+ TStoredAutoApproval+} from "./auto-approval/auto-approval-types";type TApprovalPolicyServiceFactoryDep = {approvalPolicyDAL: TApprovalPolicyDALFactory;@@ -1112,6 +1118,68 @@ export const approvalPolicyServiceFactory = ({};};+ // Inputs a rule requires to be unused whose record an earlier approved request on this policy already linked+ const $findUsedInputIds = async (+ policyId: string,+ stored: TStoredAutoApproval,+ parsedInputs: TParsedAutoApprovalInput[]+ ) => {+ const checkedInputIds = new Set(+ stored.rules.flatMap((rule) =>+ rule.conditions+ .filter((condition) => condition.constraint === AUTO_APPROVAL_UNUSED_CONSTRAINT && condition.inputId)+ .map((condition) => condition.inputId as string)+ )+ );+ const used = await Promise.all(+ parsedInputs+ .filter((input) => checkedInputIds.has(input.inputId))+ .map(async (input) =>+ (await approvalRequestDAL.hasApprovedRequestLinkingRecord({+ policyId,+ connectionId: input.connectionId,+ subject: input.subject,+ recordId: input.id+ }))+ ? input.inputId+ : null+ )+ );+ return new Set(used.filter((inputId): inputId is string => Boolean(inputId)));+ };++ // Two requests can pass the reuse check at once, so the approving one locks and rechecks its records+ const $claimUnusedRecords = async (policyId: string, evidence: TAutoApprovalEvidence, tx: Knex) => {+ const rule = evidence.rules.find((candidate) => candidate.id === evidence.approvedByRuleId);+ const claimed = evidence.inputs.filter((input) =>+ rule?.conditions.some(+ (condition) =>+ condition.constraint === AUTO_APPROVAL_UNUSED_CONSTRAINT &&+ condition.connectionId === input.connectionId &&+ condition.subject === input.subject+ )+ );+ if (!claimed.length) return;++ const keys = claimed.map((input) => `auto-approval:${policyId}:${input.connectionId}:${input.subject}:${input.id}`);+ await tx.raw("SELECT pg_advisory_xact_lock(hashtext(key)) FROM unnest(?::text[]) AS key ORDER BY key", [keys]);++ const used = await Promise.all(+ claimed.map(async (input) =>+ (await approvalRequestDAL.hasApprovedRequestLinkingRecord(+ { policyId, connectionId: input.connectionId, subject: input.subject, recordId: input.id },+ tx+ ))+ ? input+ : null+ )+ );+ const taken = used.find(Boolean);+ if (taken) {+ throw new BadRequestError({ message: `${taken.label} ${taken.id} was just used for another request` });+ }+ };+const $createAutoApprovedRequest = async ({projectId,policy,@@ -1138,6 +1206,8 @@ export const approvalPolicyServiceFactory = ({const resource = $resource(policy.type as ApprovalPolicyType);const approved = await approvalRequestDAL.transaction(async (tx) => {+ await $claimUnusedRecords(policy.id, evidence, tx);+const created = await createApprovalRequestWithSteps({projectId,@@ -1293,6 +1363,7 @@ export const approvalPolicyServiceFactory = ({autoApprovalEvidence = await autoApprovalService.evaluate({stored: storedAutoApproval,parsedInputs,+ usedInputIds: await $findUsedInputIds(policy.id, storedAutoApproval, parsedInputs),orgId: actor.orgId,projectId,ctx: {diff --git a/backend/src/services/approval-policy/approval-request-dal.ts b/backend/src/services/approval-policy/approval-request-dal.tsindex ae5520b4f8..1ea55bbb79 100644--- a/backend/src/services/approval-policy/approval-request-dal.ts+++ b/backend/src/services/approval-policy/approval-request-dal.ts@@ -78,6 +78,29 @@ export const approvalRequestDALFactory = (db: TDbClient) => {}};+ // Whether an approved request on the policy already linked this record through auto-approval request information+ const hasApprovedRequestLinkingRecord = async (+ {+ policyId,+ connectionId,+ subject,+ recordId+ }: { policyId: string; connectionId: string; subject: string; recordId: string },+ tx?: Knex+ ) => {+ try {+ const row = await (tx || db.replicaNode())(TableName.ApprovalRequests)+ .where({ policyId, status: ApprovalRequestStatus.Approved })+ .whereRaw(`"autoApprovalEvidence" -> 'inputs' @> ?::jsonb`, [+ JSON.stringify([{ connectionId, subject, id: recordId }])+ ])+ .first("id");+ return Boolean(row);+ } catch (error) {+ throw new DatabaseError({ error, name: "Check approved request linking record" });+ }+ };+const findStepsByRequestId = async (requestId: string, tx?: Knex) => {try {const dbInstance = tx || db.replicaNode();@@ -215,6 +238,7 @@ export const approvalRequestDALFactory = (db: TDbClient) => {...orm,findStepsByRequestId,findStepsByRequestIds,+ hasApprovedRequestLinkingRecord,findByProjectId,findByIdForUpdate,findPendingByPolicyIdForUpdate,diff --git a/backend/src/services/approval-policy/auto-approval/auto-approval-fns.test.ts b/backend/src/services/approval-policy/auto-approval/auto-approval-fns.test.tsindex 1f8b02638c..a705a581fc 100644--- a/backend/src/services/approval-policy/auto-approval/auto-approval-fns.test.ts+++ b/backend/src/services/approval-policy/auto-approval/auto-approval-fns.test.ts@@ -7,6 +7,7 @@ import {} from "./auto-approval-fns";import {AUTO_APPROVAL_REQUESTER_SUBJECT,+ AUTO_APPROVAL_UNUSED_CONSTRAINT,AutoApprovalConstraintValue,TAutoApprovalContext,TAutoApprovalSubject,@@ -117,6 +118,26 @@ describe("evaluateAutoApprovalRules", () => {evaluateAutoApprovalRules([{ id: "rule-1", name: "Empty", conditions: [] }], resolved("Approved"), ctx)).toMatchObject({ approvedByRuleId: null });});++ test("passes the reuse check only for a record no earlier approved request linked", () => {+ const unusedRules = [+ { id: "rule-1", name: "Single use", conditions: [condition("c-1", AUTO_APPROVAL_UNUSED_CONSTRAINT, [])] }+ ];+ const subjects = (previouslyUsed: boolean) =>+ new Map<string, TResolvedAutoApprovalSubject>([+ [+ "input-1",+ { label: "Jira ticket", definition: ticket, facts: {}, error: null, recordId: "PAY-123", previouslyUsed }+ ]+ ]);++ expect(evaluateAutoApprovalRules(unusedRules, subjects(false), ctx).approvedByRuleId).toBe("rule-1");+ expect(evaluateAutoApprovalRules(unusedRules, subjects(true), ctx).rules[0].conditions[0]).toMatchObject({+ description: "Jira ticket hasn't been used before",+ passed: false,+ reason: "Jira ticket PAY-123 was already used for another request"+ });+ });});describe("toAutoApprovalOutcome", () => {diff --git a/backend/src/services/approval-policy/auto-approval/auto-approval-fns.ts b/backend/src/services/approval-policy/auto-approval/auto-approval-fns.tsindex ae1ef008a7..4bddd3026e 100644--- a/backend/src/services/approval-policy/auto-approval/auto-approval-fns.ts+++ b/backend/src/services/approval-policy/auto-approval/auto-approval-fns.ts@@ -2,6 +2,8 @@ import { logger } from "@app/lib/logger";import {AUTO_APPROVAL_REQUESTER_SUBJECT,+ AUTO_APPROVAL_UNUSED_CONSTRAINT,+ AUTO_APPROVAL_UNUSED_CONSTRAINT_LABEL,TAutoApprovalContext,TAutoApprovalEvidence,TAutoApprovalOutcome,@@ -21,6 +23,8 @@ export type TResolvedAutoApprovalSubject = {definition: TAutoApprovalSubject<any, any> | null;facts: unknown;error: string | null;+ recordId?: string | null;+ previouslyUsed?: boolean;};// Every condition in a rule must pass and the first passing rule approves@@ -32,7 +36,9 @@ export const evaluateAutoApprovalRules = (const evaluated = rules.map((rule) => {const conditions = rule.conditions.map((condition) => {const subject = subjects.get(getAutoApprovalSubjectKey(condition));- const constraint = subject?.definition?.constraints[condition.constraint];+ const isUnusedCheck =+ condition.constraint === AUTO_APPROVAL_UNUSED_CONSTRAINT && Boolean(subject?.definition?.input);+ const constraint = isUnusedCheck ? undefined : subject?.definition?.constraints[condition.constraint];const base = {id: condition.id,connectionId: condition.connectionId,@@ -41,13 +47,24 @@ export const evaluateAutoApprovalRules = (values: condition.values,description: describeAutoApprovalCondition(subject?.label ?? condition.subject,- constraint?.label ?? condition.constraint,+ isUnusedCheck ? AUTO_APPROVAL_UNUSED_CONSTRAINT_LABEL : (constraint?.label ?? condition.constraint),condition.values)};- if (!subject || !constraint) return { ...base, passed: false, reason: "This check is no longer available" };+ if (!subject || (!constraint && !isUnusedCheck)) {+ return { ...base, passed: false, reason: "This check is no longer available" };+ }if (subject.error) return { ...base, passed: false, reason: subject.error };+ if (!constraint) {+ return subject.previouslyUsed+ ? {+ ...base,+ passed: false,+ reason: `${subject.label} ${subject.recordId} was already used for another request`+ }+ : { ...base, passed: true, reason: null };+ }try {const result = constraint.test(subject.facts, condition.values, ctx);diff --git a/backend/src/services/approval-policy/auto-approval/auto-approval-service.ts b/backend/src/services/approval-policy/auto-approval/auto-approval-service.tsindex b30e7a7767..18eec1de05 100644--- a/backend/src/services/approval-policy/auto-approval/auto-approval-service.ts+++ b/backend/src/services/approval-policy/auto-approval/auto-approval-service.ts@@ -23,6 +23,8 @@ import {import { AUTO_APPROVAL_APPS, getAutoApprovalProvider } from "./auto-approval-providers";import {AUTO_APPROVAL_REQUESTER_SUBJECT,+ AUTO_APPROVAL_UNUSED_CONSTRAINT,+ AUTO_APPROVAL_UNUSED_CONSTRAINT_LABEL,AutoApprovalConstraintValue,TAutoApprovalConfig,TAutoApprovalContext,@@ -36,6 +38,17 @@ import {const RESOLVE_TIMEOUT_MS = 20_000;+const UNUSED_CONSTRAINT = { label: AUTO_APPROVAL_UNUSED_CONSTRAINT_LABEL, value: AutoApprovalConstraintValue.None };++// A subject the requester links offers the reuse check on top of its provider's own checks+const getConstraintDefinition = (+ subject: { input: unknown; constraints: Record<string, { label: string; value: AutoApprovalConstraintValue }> },+ constraintId: string+) =>+ subject.input && constraintId === AUTO_APPROVAL_UNUSED_CONSTRAINT+ ? UNUSED_CONSTRAINT+ : subject.constraints[constraintId];+type TAutoApprovalServiceFactoryDep = {approvalPolicyAutoApprovalDAL: TApprovalPolicyAutoApprovalDALFactory;appConnectionDAL: Pick<TAppConnectionDALFactory, "findById" | "find">;@@ -159,7 +172,7 @@ export const autoApprovalServiceFactory = ({});}- const constraint = subject.constraints[condition.constraint];+ const constraint = getConstraintDefinition(subject, condition.constraint);if (!constraint) {throw new BadRequestError({message: `Rule '${name}' uses '${condition.constraint}', which is not a check on the ${subject.label}. Use one of: ${Object.keys(@@ -300,12 +313,15 @@ export const autoApprovalServiceFactory = ({const evaluate = async ({stored,parsedInputs,+ usedInputIds,orgId,projectId,ctx}: {stored: TStoredAutoApproval;parsedInputs: TParsedAutoApprovalInput[];+ // Inputs whose linked record an earlier approved request on the policy already used+ usedInputIds: Set<string>;orgId: string;projectId: string;ctx: TAutoApprovalContext;@@ -385,7 +401,18 @@ export const autoApprovalServiceFactory = ({RESOLVE_TIMEOUT_MS,`${getAppName(connection.app)} didn't respond in time`);- return [key, { ...target, label, definition, facts, error: null }];+ return [+ key,+ {+ ...target,+ label,+ definition,+ facts,+ error: null,+ recordId: parsedInput?.id ?? null,+ previouslyUsed: Boolean(target.inputId && usedInputIds.has(target.inputId))+ }+ ];} catch (error) {if (!(error instanceof BadRequestError)) {logger.error(error, `Auto-approval subject resolution failed [connectionId=${target.connectionId}]`);@@ -453,12 +480,17 @@ export const autoApprovalServiceFactory = ({id,label: subject.label,input: subject.input ? { label: subject.input.label, placeholder: subject.input.placeholder } : null,- constraints: Object.entries(subject.constraints).map(([constraintId, constraint]) => ({- id: constraintId,- label: constraint.label,- value: constraint.value,- hasOptions: Boolean(constraint.listOptions)- }))+ constraints: [+ ...Object.entries(subject.constraints).map(([constraintId, constraint]) => ({+ id: constraintId,+ label: constraint.label,+ value: constraint.value,+ hasOptions: Boolean(constraint.listOptions)+ })),+ ...(subject.input+ ? [{ id: AUTO_APPROVAL_UNUSED_CONSTRAINT, ...UNUSED_CONSTRAINT, hasOptions: false }]+ : [])+ ]}))}];diff --git a/backend/src/services/approval-policy/auto-approval/auto-approval-types.ts b/backend/src/services/approval-policy/auto-approval/auto-approval-types.tsindex 9f54f4078a..071e9f361e 100644--- a/backend/src/services/approval-policy/auto-approval/auto-approval-types.ts+++ b/backend/src/services/approval-policy/auto-approval/auto-approval-types.ts@@ -18,6 +18,10 @@ export type TAutoApprovalProviderDeps = {gatewayPoolService: Pick<TGatewayPoolServiceFactory, "resolveEffectiveGatewayId">;};+// Infisical runs this check itself, against its own approved requests, on every record a requester links+export const AUTO_APPROVAL_UNUSED_CONSTRAINT = "not-used-before";+export const AUTO_APPROVAL_UNUSED_CONSTRAINT_LABEL = "hasn't been used before";+export type TAutoApprovalContext = {requester: {email: string | null;diff --git a/docs/documentation/platform/pam/access-requests/auto-approval.mdx b/docs/documentation/platform/pam/access-requests/auto-approval.mdxindex 6a4c852c30..c6b97b1d4b 100644--- a/docs/documentation/platform/pam/access-requests/auto-approval.mdx+++ b/docs/documentation/platform/pam/access-requests/auto-approval.mdx@@ -79,6 +79,8 @@ Each condition runs one check on a linked record, and the checks available depenIf a record has an **is assigned to the requester** check, add that check to every rule that checks the record. Without it, a requester can link a record that belongs to someone else and still pass the rule.</Warning>+Every linked record also has a **hasn't been used before** check. It passes only if no earlier approved request in the folder linked the same record. Use it when one approval in the other service should grant access only once.+### Jira ticket| Check | Passes when |@@ -119,7 +121,7 @@ Infisical checks the rules once, when the request is submitted, by reading each- Later changes in the service don't affect the result, so closing a ticket doesn't revoke access that a rule granted, and a pending request isn't approved when its record passes later- If no record was linked, or Infisical can't read the record (the service doesn't respond or rejects the connection's credentials, the record doesn't exist, or the connection's user can't see it), every condition on that record fails-- A record can be linked to any number of requests, and each request passes as long as the record still passes the rule+- A record can be linked to any number of requests, and each request passes as long as the record still passes the rule (unless the rule also requires that the record **hasn't been used before**)## Next steps