Skip to content

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

feat(secret-rotation): enhance transaction handling and add tests for rotation and reconcile processes

Victor Hugo dos Santos998c020872e4
diff --git a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-service.test.ts b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-service.test.ts
index 20ab718cb8..e3bedb0cd0 100644
--- a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-service.test.ts
+++ b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-service.test.ts
@@ -3,6 +3,7 @@ import { beforeEach, describe, expect, test, vi } from "vitest";
import { recordSecretRotationOutcomeMetric, recordSecretRotationStatusChangeMetric } from "@app/lib/telemetry/metrics";
import { ActorType, AuthMethod } from "@app/services/auth/auth-type";
+import { fnSecretBulkUpdate } from "@app/services/secret-v2-bridge/secret-v2-bridge-fns";
import { SecretRotation, SecretRotationStatus } from "./secret-rotation-v2-enums";
import { SecretRotationInProgressError, secretRotationV2ServiceFactory } from "./secret-rotation-v2-service";
@@ -85,6 +86,8 @@ const rotation = (rotationStatus: SecretRotationStatus, type = SecretRotation.St
environment: { id: "env-1", slug: "dev", name: "Development" }
}) as unknown as TSecretRotationV2Raw;
+const TX = { name: "rotation-transaction" };
+
const actor = {
type: ActorType.USER,
id: "user-1",
@@ -129,7 +132,7 @@ const createService = ({
secretValidationRuleService: { findConstraintsForGeneratedSecret: vi.fn(async () => ({ ruleNames: [] })) },
secretRotationV2DAL: {
findById: vi.fn(async () => rotation(stored.rotationStatus, type)),
- transaction: vi.fn(async (callback: (tx: unknown) => Promise<unknown>) => callback({})),
+ transaction: vi.fn(async (callback: (tx: unknown) => Promise<unknown>) => callback(TX)),
// A conditional UPDATE: only a row still matching the filter is changed and returned.
update: vi.fn(async (filter: { rotationStatus?: string }, data: { rotationStatus: SecretRotationStatus }) => {
if (filter.rotationStatus !== stored.rotationStatus) return [];
@@ -200,6 +203,18 @@ describe("rotateGeneratedCredentials metrics", () => {
expect(stored.rotationStatus).toBe(SecretRotationStatus.Failed);
});
+ test("writes the failed status and the run's fields in one transaction", async () => {
+ rotateCredentials.mockRejectedValueOnce(new Error("provider down"));
+ const { service, deps } = createService({ storedStatus: SecretRotationStatus.Success });
+
+ await expect(
+ service.rotateGeneratedCredentials(rotation(SecretRotationStatus.Success), { isFinalAttempt: true })
+ ).rejects.toThrow();
+
+ expect(deps.secretRotationV2DAL.update).toHaveBeenCalledWith(expect.anything(), expect.anything(), TX);
+ expect(deps.secretRotationV2DAL.updateById).toHaveBeenCalledWith("rotation-1", expect.anything(), TX);
+ });
+
test("does not flip again when an already failed rotation fails", async () => {
rotateCredentials.mockRejectedValueOnce(new Error("provider down"));
const { service } = createService({ storedStatus: SecretRotationStatus.Failed });
@@ -246,6 +261,43 @@ describe("rotateGeneratedCredentials metrics", () => {
});
});
+// Rotation and reconcile can run at once on the same rotation (reconcile does not take the rotation lock), so both must
+// lock the secrets before the rotation row or they can deadlock each other.
+describe("row lock order", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ const expectSecretsWrittenBeforeRotationRow = (deps: ReturnType<typeof createService>["deps"]) => {
+ const [secretsWrite] = vi.mocked(fnSecretBulkUpdate).mock.invocationCallOrder;
+ const [rotationRowWrite] = deps.secretRotationV2DAL.update.mock.invocationCallOrder;
+ expect(secretsWrite).toBeLessThan(rotationRowWrite);
+ };
+
+ test("a rotation writes the secrets before the rotation row", async () => {
+ rotateCredentials.mockImplementationOnce(runCallback);
+ const { service, deps } = createService({ storedStatus: SecretRotationStatus.Failed });
+
+ await service.rotateGeneratedCredentials(rotation(SecretRotationStatus.Failed));
+
+ expectSecretsWrittenBeforeRotationRow(deps);
+ });
+
+ test("a reconcile writes the secrets before the rotation row", async () => {
+ const { service, deps } = createService({
+ storedStatus: SecretRotationStatus.Failed,
+ type: SecretRotation.UnixLinuxLocalAccount
+ });
+
+ await service.reconcileLocalAccountRotation(
+ { rotationId: "rotation-1", type: SecretRotation.UnixLinuxLocalAccount },
+ actor as never
+ );
+
+ expectSecretsWrittenBeforeRotationRow(deps);
+ });
+});
+
describe("rotation lock contention", () => {
beforeEach(() => {
vi.clearAllMocks();
diff --git a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-service.ts b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-service.ts
index 6a3f7f5578..509c5249a1 100644
--- a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-service.ts
+++ b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-service.ts
@@ -280,8 +280,6 @@ export const secretRotationV2ServiceFactory = ({
return matched;
};
- // Every writer that can move rotationStatus from Failed to Success goes through this, so recoveries balance failures.
- // The conditional update makes only the run that actually moves it report the change, whatever it loaded earlier.
const $markRotationSucceeded = async (rotationId: string, tx: Knex) =>
(
await secretRotationV2DAL.update(
@@ -1393,8 +1391,6 @@ export const secretRotationV2ServiceFactory = ({
let isRecovery = false;
const rotated = await secretRotationV2DAL.transaction(async (tx) => {
- isRecovery = await $markRotationSucceeded(secretRotation.id, tx);
-
const secretsPayload = rotationFactory.getSecretsPayload(newCredentials);
// update mapped secrets with new credential values
@@ -1433,6 +1429,7 @@ export const secretRotationV2ServiceFactory = ({
const currentTime = new Date();
+ isRecovery = await $markRotationSucceeded(secretRotation.id, tx);
return secretRotationV2DAL.updateById(
secretRotation.id,
{
@@ -1518,20 +1515,28 @@ export const secretRotationV2ServiceFactory = ({
plainText: Buffer.from(errorMessage)
});
- const isStatusChange =
- (
- await secretRotationV2DAL.update(
- { id: secretRotation.id, rotationStatus: SecretRotationStatus.Success },
- { rotationStatus: SecretRotationStatus.Failed }
- )
- ).length > 0;
-
- const updatedRotation = await secretRotationV2DAL.updateById(secretRotation.id, {
- rotationStatus: SecretRotationStatus.Failed,
- lastRotationJobId: jobId,
- lastRotationAttemptedAt: new Date(),
- encryptedLastRotationMessage: encryptedMessage,
- nextRotationAt: getNextUtcRotationInterval(secretRotation.rotateAtUtc as TSecretRotationV2["rotateAtUtc"])
+ let isStatusChange = false;
+ const updatedRotation = await secretRotationV2DAL.transaction(async (tx) => {
+ isStatusChange =
+ (
+ await secretRotationV2DAL.update(
+ { id: secretRotation.id, rotationStatus: SecretRotationStatus.Success },
+ { rotationStatus: SecretRotationStatus.Failed },
+ tx
+ )
+ ).length > 0;
+
+ return secretRotationV2DAL.updateById(
+ secretRotation.id,
+ {
+ rotationStatus: SecretRotationStatus.Failed,
+ lastRotationJobId: jobId,
+ lastRotationAttemptedAt: new Date(),
+ encryptedLastRotationMessage: encryptedMessage,
+ nextRotationAt: getNextUtcRotationInterval(secretRotation.rotateAtUtc as TSecretRotationV2["rotateAtUtc"])
+ },
+ tx
+ );
});
if (isStatusChange) recordSecretRotationStatusChangeMetric({ type, newStatus: "failed" });
diff --git a/backend/src/services/secret-sync/secret-sync-queue.test.ts b/backend/src/services/secret-sync/secret-sync-queue.test.ts
index 567f3143e8..d9b019bd8d 100644
--- a/backend/src/services/secret-sync/secret-sync-queue.test.ts
+++ b/backend/src/services/secret-sync/secret-sync-queue.test.ts
@@ -118,7 +118,7 @@ const createHarness = (initial: TSyncState, { lockFails = false, staleLoad = fal
opts: { attempts: ATTEMPTS }
});
- return { state, runSync };
+ return { state, runSync, secretSyncDAL };
};
const syncSecrets = vi.mocked(SecretSyncFns.syncSecrets);
@@ -258,6 +258,24 @@ describe("secret sync status change", () => {
]);
});
+ test("counts the change once the result commits, even if the rest of the finished-run write fails", async () => {
+ syncSecrets.mockRejectedValue(new Error("upstream 500"));
+ const { runSync, state, secretSyncDAL } = createHarness(healthy);
+ const writeRun = secretSyncDAL.updateById.getMockImplementation()!;
+ secretSyncDAL.updateById.mockImplementation(async (id, data) => {
+ if (data.lastSyncResult !== undefined) throw new Error("connection reset");
+ return writeRun(id, data);
+ });
+
+ await expect(runSync(ATTEMPTS)).rejects.toThrow();
+ expect(state.lastSyncResult).toBe("failed");
+ expect(statusChangeCalls()).toEqual([{ destination: SecretSync.Railway, newStatus: "failed" }]);
+
+ secretSyncDAL.updateById.mockImplementation(writeRun);
+ await expect(runSync(ATTEMPTS)).rejects.toThrow();
+ expect(statusChangeCalls()).toHaveLength(1);
+ });
+
test("reports a breakage once when two jobs loaded the same healthy sync", async () => {
syncSecrets.mockRejectedValue(new Error("upstream 500"));
const { runSync, state } = createHarness(healthy, { staleLoad: true });
diff --git a/backend/src/services/secret-sync/secret-sync-queue.ts b/backend/src/services/secret-sync/secret-sync-queue.ts
index c30ad6636a..ef52e39990 100644
--- a/backend/src/services/secret-sync/secret-sync-queue.ts
+++ b/backend/src/services/secret-sync/secret-sync-queue.ts
@@ -656,6 +656,14 @@ export const secretSyncQueueFactory = ({
)
).length > 0;
+
+ if (isStatusChange) {
+ recordSecretSyncStatusChangeMetric({
+ destination: secretSync.destination,
+ newStatus: isSynced ? "healthy" : "failed"
+ });
+ }
+
const updatedSecretSync = await secretSyncDAL.updateById(secretSync.id, {
syncStatus,
lastSyncJobId: job.id,
@@ -664,13 +672,6 @@ export const secretSyncQueueFactory = ({
lastSyncResult: syncStatus
});
- if (isStatusChange) {
- recordSecretSyncStatusChangeMetric({
- destination: secretSync.destination,
- newStatus: isSynced ? "healthy" : "failed"
- });
- }
-
if (!isSynced) {
void telemetryService
.sendPostHogEvents({