Skip to content

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

move computation to fns file

adilson4aa86a1f66a6
diff --git a/backend/e2e-test/routes/v1/secret-approval-request.spec.ts b/backend/e2e-test/routes/v1/secret-approval-request.spec.ts
new file mode 100644
index 0000000000..0acae56829
--- /dev/null
+++ b/backend/e2e-test/routes/v1/secret-approval-request.spec.ts
@@ -0,0 +1,136 @@
+import { SecretType } from "@app/db/schemas";
+import { seedData1 } from "@app/db/seed-data";
+import { ApproverType } from "@app/ee/services/access-approval-policy/access-approval-policy-types";
+
+const workspaceId = seedData1.projectV3.id;
+const environment = seedData1.environment.slug;
+
+const createRawSecret = async (secretKey: string) => {
+ const res = await testServer.inject({
+ method: "POST",
+ url: `/api/v3/secrets/raw/${secretKey}`,
+ headers: {
+ authorization: `Bearer ${jwtAuthToken}`
+ },
+ body: {
+ workspaceId,
+ environment,
+ type: SecretType.Shared,
+ secretPath: "/",
+ secretKey,
+ secretValue: "value"
+ }
+ });
+ expect(res.statusCode).toBe(200);
+};
+
+const deleteRawSecret = async (secretKey: string) => {
+ const res = await testServer.inject({
+ method: "DELETE",
+ url: `/api/v3/secrets/raw/${secretKey}`,
+ headers: {
+ authorization: `Bearer ${jwtAuthToken}`
+ },
+ body: {
+ workspaceId,
+ environment,
+ secretPath: "/"
+ }
+ });
+ expect(res.statusCode).toBe(200);
+};
+
+const requestRename = (secretKey: string, newSecretName: string) =>
+ testServer.inject({
+ method: "PATCH",
+ url: `/api/v3/secrets/raw/${secretKey}`,
+ headers: {
+ authorization: `Bearer ${jwtAuthToken}`
+ },
+ body: {
+ workspaceId,
+ environment,
+ secretPath: "/",
+ type: SecretType.Shared,
+ newSecretName
+ }
+ });
+
+describe("Secret approval request for a rename", () => {
+ const sourceSecretKey = "RENAME-SRC";
+ const takenSecretKey = "RENAME-TAKEN";
+ let policyId = "";
+
+ beforeAll(async () => {
+ // secrets must exist before the policy does, or their creation would route through approval too
+ await createRawSecret(sourceSecretKey);
+ await createRawSecret(takenSecretKey);
+
+ const res = await testServer.inject({
+ method: "POST",
+ url: `/api/v1/secret-approvals`,
+ headers: {
+ authorization: `Bearer ${jwtAuthToken}`
+ },
+ body: {
+ workspaceId,
+ environment,
+ name: "rename-policy",
+ secretPath: "/",
+ approvers: [{ type: ApproverType.User, id: seedData1.id }],
+ approvals: 1
+ }
+ });
+ expect(res.statusCode).toBe(200);
+ policyId = res.json().approval.id;
+ });
+
+ afterAll(async () => {
+ const res = await testServer.inject({
+ method: "DELETE",
+ url: `/api/v1/secret-approvals/${policyId}`,
+ headers: {
+ authorization: `Bearer ${jwtAuthToken}`
+ }
+ });
+ expect(res.statusCode).toBe(200);
+
+ await deleteRawSecret(sourceSecretKey);
+ await deleteRawSecret(takenSecretKey);
+ });
+
+ test("rename request stores an update commit carrying the new key and the source secret id", async () => {
+ const res = await requestRename(sourceSecretKey, "RENAME-DST");
+ expect(res.statusCode).toBe(200);
+ const payload = JSON.parse(res.payload);
+ expect(payload).toHaveProperty("approval");
+
+ const detailRes = await testServer.inject({
+ method: "GET",
+ url: `/api/v1/secret-approval-requests/${payload.approval.id}`,
+ headers: {
+ authorization: `Bearer ${jwtAuthToken}`
+ }
+ });
+ expect(detailRes.statusCode).toBe(200);
+ const { approval } = detailRes.json();
+
+ // the merge path applies the commit's key by secret id, so both must be present and correct
+ expect(approval.commits).toHaveLength(1);
+ expect(approval.commits[0]).toEqual(
+ expect.objectContaining({
+ op: "update",
+ secretKey: "RENAME-DST",
+ secret: expect.objectContaining({
+ id: expect.any(String),
+ secretKey: sourceSecretKey
+ })
+ })
+ );
+ });
+
+ test("rename request targeting an existing secret name is rejected", async () => {
+ const res = await requestRename(sourceSecretKey, takenSecretKey);
+ expect(res.statusCode).toBe(400);
+ });
+});
diff --git a/backend/src/ee/services/secret-approval-request/secret-approval-request-fns.test.ts b/backend/src/ee/services/secret-approval-request/secret-approval-request-fns.test.ts
new file mode 100644
index 0000000000..9e83b7f74f
--- /dev/null
+++ b/backend/src/ee/services/secret-approval-request/secret-approval-request-fns.test.ts
@@ -0,0 +1,63 @@
+import { describe, expect, test } from "vitest";
+
+import { hasSecretUpdateCommitConflict, TSecretUpdateCommitCandidate } from "./secret-approval-request-fns";
+
+const SECRET_ID = "secret-1";
+const OTHER_SECRET_ID = "secret-2";
+
+// a commit as created for an update of secret FOO: references the secret and the version it was reviewed against
+const buildCommit = (overrides: Partial<TSecretUpdateCommitCandidate> = {}): TSecretUpdateCommitCandidate => ({
+ key: "FOO",
+ secretId: SECRET_ID,
+ secret: { id: SECRET_ID, key: "FOO" },
+ secretVersion: { key: "FOO" },
+ ...overrides
+});
+
+describe("hasSecretUpdateCommitConflict", () => {
+ test("plain update of an untouched secret does not conflict", () => {
+ expect(hasSecretUpdateCommitConflict(buildCommit(), { id: SECRET_ID })).toBe(false);
+ });
+
+ // regression: renames were unconditionally flagged as conflicts because the new key has no owner yet
+ test("rename to a free key does not conflict", () => {
+ expect(hasSecretUpdateCommitConflict(buildCommit({ key: "BAR" }), undefined)).toBe(false);
+ });
+
+ test("rename to a key already taken by another secret conflicts", () => {
+ expect(hasSecretUpdateCommitConflict(buildCommit({ key: "BAR" }), { id: OTHER_SECRET_ID })).toBe(true);
+ });
+
+ test("commit whose referenced secret was deleted conflicts", () => {
+ expect(hasSecretUpdateCommitConflict(buildCommit({ secretId: null, secret: null }), undefined)).toBe(true);
+ });
+
+ test("commit whose key is now owned by a recreated secret conflicts", () => {
+ expect(hasSecretUpdateCommitConflict(buildCommit(), { id: OTHER_SECRET_ID })).toBe(true);
+ });
+
+ test("second rename request applies last-writer-wins once the first rename has merged", () => {
+ // reviewed against FOO, the secret is already renamed to BAR; this commit renames it on to BAZ
+ const commit = buildCommit({ key: "BAZ", secret: { id: SECRET_ID, key: "BAR" } });
+ expect(hasSecretUpdateCommitConflict(commit, undefined)).toBe(false);
+ });
+
+ test("plain update conflicts when the secret was renamed externally", () => {
+ const commit = buildCommit({ secret: { id: SECRET_ID, key: "BAR" } });
+ expect(hasSecretUpdateCommitConflict(commit, undefined)).toBe(true);
+ });
+
+ test("plain update whose key vanished from the folder conflicts", () => {
+ expect(hasSecretUpdateCommitConflict(buildCommit(), undefined)).toBe(true);
+ });
+
+ test("plain update still applies when the reviewed version was pruned", () => {
+ const commit = buildCommit({ secretVersion: null });
+ expect(hasSecretUpdateCommitConflict(commit, { id: SECRET_ID })).toBe(false);
+ });
+
+ test("key change without the reviewed version falls back to the live key and applies as a rename", () => {
+ const commit = buildCommit({ key: "BAR", secretVersion: null });
+ expect(hasSecretUpdateCommitConflict(commit, undefined)).toBe(false);
+ });
+});
diff --git a/backend/src/ee/services/secret-approval-request/secret-approval-request-fns.ts b/backend/src/ee/services/secret-approval-request/secret-approval-request-fns.ts
index 211ef02984..f26e132edd 100644
--- a/backend/src/ee/services/secret-approval-request/secret-approval-request-fns.ts
+++ b/backend/src/ee/services/secret-approval-request/secret-approval-request-fns.ts
@@ -57,3 +57,32 @@ export const sendApprovalEmailsFn = async ({
});
}
};
+
+export type TSecretUpdateCommitCandidate = {
+ key: string;
+ secretId?: string | null;
+ secret?: { id: string; key: string } | null;
+ secretVersion?: { key: string } | null;
+};
+
+/**
+ * Decides whether an update commit of a secret approval request can no longer be applied at merge time.
+ * `commit.secret` is the referenced secret in its current DB state (nullish if since deleted) and
+ * `secretWithSameKey` is the folder secret currently holding the commit's key, if any.
+ *
+ * Updates apply last-writer-wins by secret identity: a rename still applies even if the secret was
+ * renamed by another merge in the meantime.
+ */
+export const hasSecretUpdateCommitConflict = (
+ commit: TSecretUpdateCommitCandidate,
+ secretWithSameKey?: { id: string }
+): boolean => {
+ if (!commit.secretId || !commit.secret) return true; // referenced secret was deleted (or recreated)
+ // whoever currently holds the commit's key must be the referenced secret itself
+ if (secretWithSameKey) return secretWithSameKey.id !== commit.secretId;
+ // the key is free: only a rename may claim it. rename intent is read from the secret version the
+ // commit was based on (falling back to the live key if that version was pruned), so a plain update
+ // whose secret was renamed externally stays a conflict instead of dragging the old name back
+ const reviewedKey = commit.secretVersion?.key ?? commit.secret.key;
+ return commit.key === reviewedKey;
+};
diff --git a/backend/src/ee/services/secret-approval-request/secret-approval-request-service.ts b/backend/src/ee/services/secret-approval-request/secret-approval-request-service.ts
index b8b133a745..47d7d6b540 100644
--- a/backend/src/ee/services/secret-approval-request/secret-approval-request-service.ts
+++ b/backend/src/ee/services/secret-approval-request/secret-approval-request-service.ts
@@ -89,7 +89,7 @@ import { TSecretApprovalPolicyDALFactory } from "../secret-approval-policy/secre
import { scanSecretPolicyViolations } from "../secret-scanning-v2/secret-scanning-v2-fns";
import { TSecretSnapshotServiceFactory } from "../secret-snapshot/secret-snapshot-service";
import { TSecretApprovalRequestDALFactory } from "./secret-approval-request-dal";
-import { sendApprovalEmailsFn } from "./secret-approval-request-fns";
+import { hasSecretUpdateCommitConflict, sendApprovalEmailsFn } from "./secret-approval-request-fns";
import { TSecretApprovalRequestReviewerDALFactory } from "./secret-approval-request-reviewer-dal";
import { TSecretApprovalRequestSecretDALFactory } from "./secret-approval-request-secret-dal";
import {
@@ -734,21 +734,8 @@ export const secretApprovalRequestServiceFactory = ({
}))
);
const updationSecretsGroupByKey = groupBy(secrets, (i) => i.key);
- // el.secret is the commit's referenced secret in its current DB state (undefined if since deleted)
- const hasUpdateConflict = (el: (typeof secretUpdationCommits)[number]) => {
- if (!el.secretId || !el.secret) return true; // referenced secret was deleted (or recreated)
- // the key the request was created (and reviewed) against; undefined if that secret version was pruned
- const reviewedKey = el.secretVersion?.key;
- // the referenced secret was renamed after the request was created: the approved change no longer applies
- if (reviewedKey && el.secret.key !== reviewedKey) return true;
- // whoever currently holds the commit's key must be the referenced secret itself
- const secretWithSameKey = updationSecretsGroupByKey[el.key]?.[0];
- if (secretWithSameKey) return secretWithSameKey.id !== el.secretId;
- // the key is free: only a rename (commit key differs from the reviewed key) may claim it.
- // without the reviewed key we cannot tell a rename from external drift, so treat it as a conflict
- if (!reviewedKey) return true;
- return el.key === reviewedKey;
- };
+ const hasUpdateConflict = (el: (typeof secretUpdationCommits)[number]) =>
+ hasSecretUpdateCommitConflict(el, updationSecretsGroupByKey[el.key]?.[0]);
secretUpdationCommits.filter(hasUpdateConflict).forEach((el) => {
conflicts.push({ op: SecretOperations.Update, secretId: el.id });