Skip to content

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

check constraints using locked policy

adilsonad2ace4dc5d7
diff --git a/backend/src/services/approval-policy/secret-access/secret-access-policy-fns.ts b/backend/src/services/approval-policy/secret-access/secret-access-policy-fns.ts
index 38df6ecab2..a529b5ea1e 100644
--- a/backend/src/services/approval-policy/secret-access/secret-access-policy-fns.ts
+++ b/backend/src/services/approval-policy/secret-access/secret-access-policy-fns.ts
@@ -82,6 +82,11 @@ const StoredConstraintsSchema = z.object({
constraints: SecretAccessPolicyConstraintsSchema
});
+export const readSecretAccessPolicyConstraints = (constraints: unknown): TSecretAccessPolicyConstraints | null => {
+ const parsed = StoredConstraintsSchema.safeParse(constraints);
+ return parsed.success ? parsed.data.constraints : null;
+};
+
export const getSecretAccessAllowedSelfApprovals = (policy: {
allowedSelfApprovals?: boolean;
constraints?: unknown;
diff --git a/backend/src/services/secret-access-approval-global-request-bridge/secret-access-approval-global-request-bridge-service.test.ts b/backend/src/services/secret-access-approval-global-request-bridge/secret-access-approval-global-request-bridge-service.test.ts
index 9aba3ae5b1..7279a0c6c8 100644
--- a/backend/src/services/secret-access-approval-global-request-bridge/secret-access-approval-global-request-bridge-service.test.ts
+++ b/backend/src/services/secret-access-approval-global-request-bridge/secret-access-approval-global-request-bridge-service.test.ts
@@ -12,6 +12,10 @@ import { DelegatedApprovalRequestStatus } from "@app/services/delegated-approval
import { externallyReviewedAccessRequestMessage } from "./secret-access-approval-global-request-bridge-constants";
import { secretAccessApprovalGlobalRequestBridgeServiceFactory } from "./secret-access-approval-global-request-bridge-service";
+vi.mock("@app/lib/config/env", () => ({
+ getConfig: () => ({ SITE_URL: "https://example.com" })
+}));
+
const pendingRequest = {
id: "req-1",
policyId: "policy-1",
@@ -206,3 +210,127 @@ describe("secretAccessApprovalGlobalRequestBridge.reviewAccessApprovalRequest",
expect(findSecretAccessPolicies).not.toHaveBeenCalled();
});
});
+
+const REQUEST_PERMISSIONS = [["read", "secrets", { environment: "dev", secretPath: { $glob: "/app" } }]];
+
+const snapshotPolicy = {
+ id: "policy-1",
+ name: "Prod access",
+ enforcementLevel: "hard",
+ constraints: {
+ version: 1 as const,
+ constraints: {
+ allowedSelfApprovals: true,
+ requestExpirationTime: "1h",
+ maxTimePeriod: null
+ }
+ }
+};
+
+const lockedConstraints = (requestExpirationTime: string | null, maxTimePeriod: string | null) => ({
+ version: 1 as const,
+ constraints: {
+ allowedSelfApprovals: true,
+ requestExpirationTime,
+ maxTimePeriod
+ }
+});
+
+const createRequestService = ({ constraints = lockedConstraints("2h", null) } = {}) => {
+ const findByIdForShare = vi.fn().mockResolvedValue({ id: "policy-1", constraints });
+ const create = vi.fn().mockResolvedValue({ id: "req-1" });
+ const createRequest = vi.fn().mockResolvedValue({ id: "delegated-1" });
+
+ const service = secretAccessApprovalGlobalRequestBridgeServiceFactory({
+ approvalRequestDAL: {
+ transaction: async (callback: (tx: string) => Promise<unknown>) => callback("tx"),
+ create
+ },
+ approvalRequestStepsDAL: {},
+ approvalRequestStepEligibleApproversDAL: {},
+ approvalPolicyDAL: {
+ findByIdForShare,
+ findStepsByPolicyId: vi.fn().mockResolvedValue([])
+ },
+ delegatedApprovalService: {
+ getPolicyByPolicyId: vi.fn().mockResolvedValue({ policyId: "policy-1" }),
+ createRequest
+ },
+ secretAccessApprovalGlobalResource: {
+ validateConstraints: vi.fn().mockReturnValue({ valid: true }),
+ canAccess: vi.fn().mockResolvedValue(null)
+ },
+ secretAccessApprovalGlobalRequestBridgeDAL: {
+ findPendingRequests: vi.fn().mockResolvedValue([]),
+ findSecretAccessRequestById: vi.fn().mockResolvedValue(pendingRequest)
+ },
+ userDAL: {
+ findById: vi.fn().mockResolvedValue({
+ id: "requester",
+ firstName: "Ada",
+ lastName: "Lovelace",
+ username: "ada",
+ })
+ },
+ projectDAL: { findById: vi.fn().mockResolvedValue({ id: "project-1", name: "Project", orgId: "org-1" }) },
+ queueService: { queue: vi.fn().mockResolvedValue(undefined) }
+ } as never);
+
+ return { service, findByIdForShare, create, createRequest };
+};
+
+const submitAccessRequest = (
+ service: ReturnType<typeof createRequestService>["service"],
+ overrides: Record<string, unknown> = {}
+) =>
+ service.createAccessApprovalRequest({
+ policy: snapshotPolicy,
+ projectId: "project-1",
+ envId: "env-1",
+ envSlug: "dev",
+ envName: "Development",
+ secretPath: "/app",
+ requestedByUserId: "requester",
+ actorOrgId: "org-1",
+ permissions: REQUEST_PERMISSIONS,
+ isTemporary: false,
+ ...overrides
+ } as Parameters<ReturnType<typeof createRequestService>["service"]["createAccessApprovalRequest"]>[0]);
+
+describe("secretAccessApprovalGlobalRequestBridge.createAccessApprovalRequest", () => {
+ test("creates a delegated request using the expiration on the locked policy", async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date("2026-10-28T12:00:00.000Z"));
+ const { service, findByIdForShare, create, createRequest } = createRequestService();
+
+ try {
+ await submitAccessRequest(service);
+
+ expect(findByIdForShare).toHaveBeenCalledWith("policy-1", "tx");
+ expect(findByIdForShare.mock.invocationCallOrder[0]).toBeLessThan(create.mock.invocationCallOrder[0]);
+ expect(create).toHaveBeenCalledWith(
+ expect.objectContaining({ expiresAt: new Date("2026-10-28T14:00:00.000Z") }),
+ "tx"
+ );
+ expect(findByIdForShare.mock.invocationCallOrder[0]).toBeLessThan(createRequest.mock.invocationCallOrder[0]);
+ expect(createRequest).toHaveBeenCalledTimes(1);
+ expect(createRequest.mock.calls[0][1]).toBe("tx");
+ expect(createRequest.mock.calls[0][0]).toMatchObject({ approvalRequest: { id: "req-1" } });
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ test("refuses when the locked max time period is shorter than the requested range", async () => {
+ const { service, create, createRequest } = createRequestService({
+ constraints: lockedConstraints(null, "1h")
+ });
+
+ await expect(submitAccessRequest(service, { isTemporary: true, temporaryRange: "2h" })).rejects.toThrow(
+ "Requested access time range is limited to 1h by policy"
+ );
+ expect(create).not.toHaveBeenCalled();
+ expect(createRequest).not.toHaveBeenCalled();
+ });
+});
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 606332ce87..18b12ccb5e 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
@@ -31,6 +31,7 @@ import {
getSecretAccessRequestData,
hasSameAccessCriteria,
parseSecretAccessRequestData,
+ readSecretAccessPolicyConstraints,
validateSecretAccessConstraints
} from "@app/services/approval-policy/secret-access/secret-access-policy-fns";
import { TSecretAccessRequestData } from "@app/services/approval-policy/secret-access/secret-access-policy-types";
@@ -345,18 +346,32 @@ export const secretAccessApprovalGlobalRequestBridgeServiceFactory = ({
throw new BadRequestError({ message: "You already have a pending access request with the same criteria" });
}
- const { requestExpirationTime } = policy.constraints.constraints;
- const parsedMs = requestExpirationTime ? ms(requestExpirationTime) : null;
- const expiresAt = parsedMs && !Number.isNaN(parsedMs) ? new Date(Date.now() + parsedMs) : null;
-
- // A policy update locks the policy row for update, so sharing it here keeps a request from being
- // created with approver steps the update is replacing with a delegated reviewer, or the reverse.
+ // A policy update locks this row, then rewrites its time limits, approver steps, and delegated reviewer
+ // together. Sharing the row waits that update out, so the limits are read from it before a request is
+ // created against the reviewer the update left in place.
const { approvalRequest: created, policySteps } = await approvalRequestDAL.transaction(async (tx) => {
const lockedPolicy = await approvalPolicyDAL.findByIdForShare(policy.id, tx);
if (!lockedPolicy) {
throw new NotFoundError({ message: `Policy '${policy.name}' was deleted before the request could be created` });
}
+ const lockedConstraints = readSecretAccessPolicyConstraints(lockedPolicy.constraints);
+ if (!lockedConstraints) {
+ throw new BadRequestError({
+ message: `Policy '${policy.name}' could not be read. Submit the request again.`
+ });
+ }
+
+ const lockedConstraintValidation = validateSecretAccessConstraints(lockedConstraints, requestData);
+ if (!lockedConstraintValidation.valid) {
+ throw new BadRequestError({
+ message: lockedConstraintValidation.errors?.join("; ") ?? "Policy constraints not met"
+ });
+ }
+
+ const parsedMs = lockedConstraints.requestExpirationTime ? ms(lockedConstraints.requestExpirationTime) : null;
+ const expiresAt = parsedMs && !Number.isNaN(parsedMs) ? new Date(Date.now() + parsedMs) : null;
+
const currentSteps = await approvalPolicyDAL.findStepsByPolicyId(policy.id, tx);
const delegatedPolicy = currentSteps.length
? null