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
feat(database): enhance dynamic secret and secret sync schemas, and improve revocation handling
Victor Hugo dos Santos32f96dd3edeb
diff --git a/backend/e2e-test/mocks/keystore.ts b/backend/e2e-test/mocks/keystore.tsindex 9ae56053b1..e68c7e26a0 100644--- a/backend/e2e-test/mocks/keystore.ts+++ b/backend/e2e-test/mocks/keystore.ts@@ -30,11 +30,6 @@ export const mockKeyStore = (): TKeyStoreFactory => {store[key] = value;return "OK";},- setItemWithExpiryReturningPrevious: async (key, _expiryInSeconds, value) => {- const previous = store[key];- store[key] = value;- return previous === undefined ? null : previous.toString();- },deleteItem: async (key) => {delete store[key];delete hashStore[key];diff --git a/backend/src/db/migrations/20261026172627_secrets-last-result-columns.ts b/backend/src/db/migrations/20261026172627_secrets-last-result-columns.tsnew file mode 100644index 0000000000..6dd6f94f7b--- /dev/null+++ b/backend/src/db/migrations/20261026172627_secrets-last-result-columns.ts@@ -0,0 +1,53 @@+import { Knex } from "knex";++import { TableName } from "../schemas";++export async function up(knex: Knex): Promise<void> {+ const hasLastSyncResult = await knex.schema.hasColumn(TableName.SecretSync, "lastSyncResult");+ if (!hasLastSyncResult) {+ await knex.schema.alterTable(TableName.SecretSync, (t) => {+ t.string("lastSyncResult").nullable();+ });++ await knex.raw(`ALTER TABLE ${TableName.SecretSync} DISABLE TRIGGER "${TableName.SecretSync}_updatedAt"`);+ await knex(TableName.SecretSync)+ .where((qb) => {+ void qb+ .whereIn("syncStatus", ["succeeded", "failed"])+ .orWhereNotNull("lastSyncMessage")+ .orWhereNotNull("lastSyncedAt");+ })+ .update({+ // @ts-expect-error lastSyncResult is typed as a string; a raw CASE expression is expected here+ lastSyncResult: knex.raw(`+ CASE+ WHEN "syncStatus" = 'succeeded' THEN 'succeeded'+ WHEN "syncStatus" = 'failed' THEN 'failed'+ WHEN "lastSyncMessage" IS NOT NULL THEN 'failed'+ ELSE 'succeeded'+ END+ `)+ });+ await knex.raw(`ALTER TABLE ${TableName.SecretSync} ENABLE TRIGGER "${TableName.SecretSync}_updatedAt"`);+ }++ if (!(await knex.schema.hasColumn(TableName.DynamicSecret, "revocationFailing"))) {+ await knex.schema.alterTable(TableName.DynamicSecret, (t) => {+ t.boolean("revocationFailing").notNullable().defaultTo(false);+ });+ }+}++export async function down(knex: Knex): Promise<void> {+ if (await knex.schema.hasColumn(TableName.SecretSync, "lastSyncResult")) {+ await knex.schema.alterTable(TableName.SecretSync, (t) => {+ t.dropColumn("lastSyncResult");+ });+ }++ if (await knex.schema.hasColumn(TableName.DynamicSecret, "revocationFailing")) {+ await knex.schema.alterTable(TableName.DynamicSecret, (t) => {+ t.dropColumn("revocationFailing");+ });+ }+}diff --git a/backend/src/db/schemas/dynamic-secrets.ts b/backend/src/db/schemas/dynamic-secrets.tsindex 73a8eea7d8..e4083e15a6 100644--- a/backend/src/db/schemas/dynamic-secrets.ts+++ b/backend/src/db/schemas/dynamic-secrets.ts@@ -31,7 +31,8 @@ export const DynamicSecretsSchema = z.object({gatewayId: z.string().uuid().nullable().optional(),usernameTemplate: z.string().nullable().optional(),gatewayV2Id: z.string().uuid().nullable().optional(),- gatewayPoolId: z.string().uuid().nullable().optional()+ gatewayPoolId: z.string().uuid().nullable().optional(),+ revocationFailing: z.boolean().default(false)});export type TDynamicSecrets = z.infer<typeof DynamicSecretsSchema>;diff --git a/backend/src/db/schemas/secret-syncs.ts b/backend/src/db/schemas/secret-syncs.tsindex 0e0728e874..8816f41a4c 100644--- a/backend/src/db/schemas/secret-syncs.ts+++ b/backend/src/db/schemas/secret-syncs.ts@@ -32,7 +32,8 @@ export const SecretSyncsSchema = z.object({removeStatus: z.string().nullable().optional(),lastRemoveJobId: z.string().nullable().optional(),lastRemoveMessage: z.string().nullable().optional(),- lastRemovedAt: z.date().nullable().optional()+ lastRemovedAt: z.date().nullable().optional(),+ lastSyncResult: z.string().nullable().optional()});export type TSecretSyncs = z.infer<typeof SecretSyncsSchema>;diff --git a/backend/src/ee/services/dynamic-secret-lease/dynamic-secret-lease-dal.ts b/backend/src/ee/services/dynamic-secret-lease/dynamic-secret-lease-dal.tsindex f8f873f44c..16dd180b94 100644--- a/backend/src/ee/services/dynamic-secret-lease/dynamic-secret-lease-dal.ts+++ b/backend/src/ee/services/dynamic-secret-lease/dynamic-secret-lease-dal.ts@@ -24,6 +24,7 @@ export interface TDynamicSecretLeaseDALFactory extends Omit<TOrmify<TableName.DyfolderId: string;status: string | null | undefined;statusDetails: string | null | undefined;+ revocationFailing: boolean;createdAt: Date;updatedAt: Date;};@@ -107,6 +108,7 @@ export const dynamicSecretLeaseDALFactory = (db: TDbClient) => {db.ref("folderId").withSchema(TableName.DynamicSecret).as("dynFolderId"),db.ref("status").withSchema(TableName.DynamicSecret).as("dynStatus"),db.ref("statusDetails").withSchema(TableName.DynamicSecret).as("dynStatusDetails"),+ db.ref("revocationFailing").withSchema(TableName.DynamicSecret).as("dynRevocationFailing"),db.ref("createdAt").withSchema(TableName.DynamicSecret).as("dynCreatedAt"),db.ref("updatedAt").withSchema(TableName.DynamicSecret).as("dynUpdatedAt"));@@ -125,6 +127,7 @@ export const dynamicSecretLeaseDALFactory = (db: TDbClient) => {folderId: doc.dynFolderId,status: doc.dynStatus,statusDetails: doc.dynStatusDetails,+ revocationFailing: doc.dynRevocationFailing as boolean,createdAt: doc.dynCreatedAt,updatedAt: doc.dynUpdatedAt}diff --git a/backend/src/ee/services/dynamic-secret-lease/dynamic-secret-lease-fns.ts b/backend/src/ee/services/dynamic-secret-lease/dynamic-secret-lease-fns.tsindex 855910b6ba..958d700dd9 100644--- a/backend/src/ee/services/dynamic-secret-lease/dynamic-secret-lease-fns.ts+++ b/backend/src/ee/services/dynamic-secret-lease/dynamic-secret-lease-fns.ts@@ -1,5 +1,10 @@import { z } from "zod";+import { logger } from "@app/lib/logger";+import { recordDynamicSecretStatusChangeMetric } from "@app/lib/telemetry/metrics";++import { TDynamicSecretDALFactory } from "../dynamic-secret/dynamic-secret-dal";+const LeaseDataSchema = z.record(z.string());export const pickPersistedLeaseData = (data: unknown, fields: string[]): Record<string, string> => {@@ -21,3 +26,35 @@ export const decryptLeaseData = (JSON.parse(decryptor({ cipherTextBlob: Buffer.from(encryptedLeaseData) }).toString()) as unknown);};++export const recordDynamicSecretRevocationResult = async ({+ dynamicSecretDAL,+ dynamicSecretId,+ provider,+ isRevoked,+ wasFailing+}: {+ dynamicSecretDAL: Pick<TDynamicSecretDALFactory, "update">;+ dynamicSecretId: string;+ provider: string;+ isRevoked: boolean;+ wasFailing: boolean;+}) => {+ const isFailing = !isRevoked;+ if (wasFailing === isFailing) return;++ try {+ const flipped = await dynamicSecretDAL.update(+ { id: dynamicSecretId, revocationFailing: !isFailing },+ { revocationFailing: isFailing }+ );+ if (flipped.length) {+ recordDynamicSecretStatusChangeMetric({ provider, newStatus: isFailing ? "failed" : "healthy" });+ }+ } catch (error) {+ logger.warn(+ error,+ `Failed to record dynamic secret revocation result [dynamicSecretId=${dynamicSecretId}] [provider=${provider}]`+ );+ }+};diff --git a/backend/src/ee/services/dynamic-secret-lease/dynamic-secret-lease-queue.test.ts b/backend/src/ee/services/dynamic-secret-lease/dynamic-secret-lease-queue.test.tsindex 7c4665f664..26dd9c75ba 100644--- a/backend/src/ee/services/dynamic-secret-lease/dynamic-secret-lease-queue.test.ts+++ b/backend/src/ee/services/dynamic-secret-lease/dynamic-secret-lease-queue.test.ts@@ -1,10 +1,7 @@import { beforeEach, describe, expect, test, vi } from "vitest";-import { KeyStorePrefixes } from "@app/keystore/keystore";-import { inMemoryKeyStore } from "@app/keystore/memory";import { logger } from "@app/lib/logger";import {- isTelemetryEnabled,recordDynamicSecretOrphanedLeaseMetric,recordDynamicSecretRevocationOutcomeMetric,recordDynamicSecretStatusChangeMetric@@ -26,7 +23,6 @@ vi.mock("@app/lib/logger", () => ({vi.mock("@app/lib/telemetry/metrics", async (importOriginal) => ({...(await importOriginal<typeof import("@app/lib/telemetry/metrics")>()),- isTelemetryEnabled: vi.fn(() => true),recordDynamicSecretOrphanedLeaseMetric: vi.fn(),recordDynamicSecretRevocationOutcomeMetric: vi.fn(),recordDynamicSecretStatusChangeMetric: vi.fn()@@ -41,7 +37,8 @@ const dynamicSecretCfg = {type: PROVIDER,folderId: "folder-1",encryptedInput: Buffer.from("{}"),- status: DynamicSecretStatus.Deleting+ status: DynamicSecretStatus.Deleting,+ revocationFailing: false};const lease = (id: string) => ({@@ -49,42 +46,50 @@ const lease = (id: string) => ({dynamicSecretId: CONFIG_ID,externalEntityId: `entity-${id}`,config: {},- encryptedLeaseData: null,- dynamicSecret: dynamicSecretCfg+ encryptedLeaseData: null});type THandler = (job: unknown) => Promise<void>;-const createHarness = () => {+// staleFlag: the revocationFailing value every lease load returns, standing in for a snapshot taken before another+// lease of the same config flipped the row.+const createHarness = ({ staleFlag }: { staleFlag?: boolean } = {}) => {const handlers = new Map<string, THandler>();const queueService = {start: vi.fn((name: string, fn: THandler) => {handlers.set(name, fn);}),queue: vi.fn(async () => undefined),- stopJobById: vi.fn(async () => undefined)+ stopJobById: vi.fn<(queue: string, jobId: string) => Promise<void>>(async () => undefined)};+ const cfg = { ...dynamicSecretCfg };const leases = new Map<string, ReturnType<typeof lease>>();const dynamicSecretLeaseDAL = {- findById: vi.fn(async (id: string) => leases.get(id)),+ findById: vi.fn(async (id: string) => {+ const found = leases.get(id);+ if (!found) return undefined;+ return { ...found, dynamicSecret: { ...cfg, revocationFailing: staleFlag ?? cfg.revocationFailing } };+ }),deleteById: vi.fn(async (id: string) => {leases.delete(id);}),find: vi.fn(async () => [...leases.values()]),updateById: vi.fn(async () => ({}))};- const cfg = { ...dynamicSecretCfg };const dynamicSecretDAL = {findById: vi.fn(async () => cfg),deleteById: vi.fn(async () => cfg),- updateById: vi.fn(async (_id: string, data: Partial<typeof cfg>) => Object.assign(cfg, data))+ updateById: vi.fn(async (_id: string, data: Partial<typeof cfg>) => Object.assign(cfg, data)),+ // A conditional UPDATE: only a row still matching the filter is changed and returned.+ update: vi.fn(async (filter: Partial<typeof cfg>, data: Partial<typeof cfg>) => {+ const matches = Object.entries(filter).every(([key, value]) => cfg[key as keyof typeof cfg] === value);+ return matches ? [Object.assign(cfg, data)] : [];+ })};const revoke = vi.fn<(inputs: unknown, entityId: string) => Promise<{ entityId: string }>>(async (_inputs, entityId) => ({ entityId }));- const keyStore = inMemoryKeyStore();-dynamicSecretLeaseQueueServiceFactory({queueService: queueService as never,dynamicSecretLeaseDAL: dynamicSecretLeaseDAL as never,@@ -94,7 +99,6 @@ const createHarness = () => {kmsService: {createCipherPairWithDataKey: vi.fn(async () => ({ decryptor: () => Buffer.from("{}") }))} as never,- keyStore,smtpService: {} as never,userDAL: {} as never,identityDAL: {} as never,@@ -137,7 +141,17 @@ const createHarness = () => {const addLease = (id: string) => leases.set(id, lease(id));- return { queueService, revoke, keyStore, addLease, runScheduled, runRetry, runPruning };+ return {+ queueService,+ revoke,+ cfg,+ dynamicSecretDAL,+ dynamicSecretLeaseDAL,+ addLease,+ runScheduled,+ runRetry,+ runPruning+ };};const outcomeCalls = () => vi.mocked(recordDynamicSecretRevocationOutcomeMetric).mock.calls.map(([params]) => params);@@ -146,15 +160,12 @@ const orphanedCalls = () => vi.mocked(recordDynamicSecretOrphanedLeaseMetric).moconst retryQueued = (queue: ReturnType<typeof createHarness>["queueService"]["queue"]) =>queue.mock.calls.filter((call) => (call as unknown[])[1] === QueueJobs.DynamicSecretRevocation);-const failingKey = KeyStorePrefixes.DynamicSecretRevocationFailing(CONFIG_ID);-describe("dynamic secret lease revocation metrics", () => {beforeEach(() => {vi.clearAllMocks();- vi.mocked(isTelemetryEnabled).mockReturnValue(true);});- describe("scheduled phase", () => {+ describe("scheduled revocation", () => {test("records one success and no status change for a healthy config", async () => {const harness = createHarness();harness.addLease("lease-1");@@ -162,7 +173,7 @@ describe("dynamic secret lease revocation metrics", () => {await harness.runScheduled("lease-1");expect(outcomeCalls()).toEqual([- { provider: PROVIDER, phase: "scheduled", outcome: "success", attemptsExhausted: false }+ { provider: PROVIDER, trigger: "scheduled", outcome: "success", attemptsExhausted: false }]);expect(statusChangeCalls()).toEqual([]);});@@ -180,7 +191,7 @@ describe("dynamic secret lease revocation metrics", () => {await expect(harness.runScheduled("lease-1", 3)).rejects.toThrow("connection refused");expect(outcomeCalls()).toEqual([- { provider: PROVIDER, phase: "scheduled", outcome: "failure", attemptsExhausted: true }+ { provider: PROVIDER, trigger: "scheduled", outcome: "failure", attemptsExhausted: true }]);expect(retryQueued(harness.queueService.queue)).toHaveLength(1);});@@ -194,7 +205,7 @@ describe("dynamic secret lease revocation metrics", () => {await harness.runScheduled("lease-1", 2);expect(outcomeCalls()).toEqual([- { provider: PROVIDER, phase: "scheduled", outcome: "success", attemptsExhausted: false }+ { provider: PROVIDER, trigger: "scheduled", outcome: "success", attemptsExhausted: false }]);});@@ -207,8 +218,8 @@ describe("dynamic secret lease revocation metrics", () => {await expect(harness.runScheduled("lease-1", MAX_ATTEMPTS)).rejects.toThrow();await expect(harness.runScheduled("lease-2", MAX_ATTEMPTS)).rejects.toThrow();- expect(statusChangeCalls()).toEqual([{ provider: PROVIDER, to: "failed" }]);- expect(await harness.keyStore.getItem(failingKey)).toBe("1");+ expect(statusChangeCalls()).toEqual([{ provider: PROVIDER, newStatus: "failed" }]);+ expect(harness.cfg.revocationFailing).toBe(true);});test("flips to healthy once when a failing config revokes again", async () => {@@ -223,41 +234,72 @@ describe("dynamic secret lease revocation metrics", () => {await harness.runScheduled("lease-3");expect(statusChangeCalls()).toEqual([- { provider: PROVIDER, to: "failed" },- { provider: PROVIDER, to: "healthy" }+ { provider: PROVIDER, newStatus: "failed" },+ { provider: PROVIDER, newStatus: "healthy" }]);- expect(await harness.keyStore.getItem(failingKey)).toBeNull();+ expect(harness.cfg.revocationFailing).toBe(false);});- test("does not let a Redis error fail or change the revocation", async () => {+ test("does not let a failed flag update fail or change the revocation", async () => {const harness = createHarness();harness.addLease("lease-1");harness.addLease("lease-2");- const redisError = new Error("redis unavailable");- vi.spyOn(harness.keyStore, "getItem").mockRejectedValue(redisError);- vi.spyOn(harness.keyStore, "setItemWithExpiryReturningPrevious").mockRejectedValue(redisError);+ harness.dynamicSecretDAL.update.mockRejectedValue(new Error("db pool timeout"));+ harness.revoke.mockRejectedValueOnce(new Error("connection refused"));- await expect(harness.runScheduled("lease-1")).resolves.toBeUndefined();+ await expect(harness.runScheduled("lease-1", MAX_ATTEMPTS)).rejects.toThrow("connection refused");+ expect(retryQueued(harness.queueService.queue)).toHaveLength(1);- harness.revoke.mockRejectedValueOnce(new Error("connection refused"));- await expect(harness.runScheduled("lease-2", MAX_ATTEMPTS)).rejects.toThrow("connection refused");+ harness.cfg.revocationFailing = true;+ await expect(harness.runScheduled("lease-2")).resolves.toBeUndefined();expect(statusChangeCalls()).toEqual([]);- expect(outcomeCalls().map(({ outcome }) => outcome)).toEqual(["success", "failure"]);- expect(retryQueued(harness.queueService.queue)).toHaveLength(1);+ expect(outcomeCalls().map(({ outcome }) => outcome)).toEqual(["failure", "success"]);expect(vi.mocked(logger.warn)).toHaveBeenCalledTimes(2);});- test("skips the status change entirely while telemetry is disabled", async () => {- vi.mocked(isTelemetryEnabled).mockReturnValue(false);- const harness = createHarness();+ test("reports a flip once even when every lease loaded the config before it flipped", async () => {+ const harness = createHarness({ staleFlag: false });harness.addLease("lease-1");- const setPrevious = vi.spyOn(harness.keyStore, "setItemWithExpiryReturningPrevious");+ harness.addLease("lease-2");harness.revoke.mockRejectedValue(new Error("connection refused"));await expect(harness.runScheduled("lease-1", MAX_ATTEMPTS)).rejects.toThrow();+ await expect(harness.runScheduled("lease-2", MAX_ATTEMPTS)).rejects.toThrow();++ expect(statusChangeCalls()).toEqual([{ provider: PROVIDER, newStatus: "failed" }]);+ });- expect(setPrevious).not.toHaveBeenCalled();+ test("picks up a recovery a stale load skipped on the config's next revocation", async () => {+ const harness = createHarness();+ harness.addLease("lease-1");+ harness.addLease("lease-2");+ harness.cfg.revocationFailing = true;++ const stale = createHarness({ staleFlag: false });+ stale.addLease("lease-1");+ stale.cfg.revocationFailing = true;+ await stale.runScheduled("lease-1");+ expect(statusChangeCalls()).toEqual([]);+ expect(stale.cfg.revocationFailing).toBe(true);++ await harness.runScheduled("lease-2");+ expect(statusChangeCalls()).toEqual([{ provider: PROVIDER, newStatus: "healthy" }]);+ });++ test("hands off to the retry queue even when marking the lease failed throws", async () => {+ const harness = createHarness();+ harness.addLease("lease-1");+ harness.revoke.mockRejectedValue(new Error("connection refused"));+ harness.dynamicSecretLeaseDAL.updateById.mockRejectedValue(new Error("db pool timeout"));++ await expect(harness.runScheduled("lease-1", MAX_ATTEMPTS)).rejects.toThrow("connection refused");++ expect(retryQueued(harness.queueService.queue)).toHaveLength(1);+ expect(vi.mocked(logger.error)).toHaveBeenCalledWith(+ expect.objectContaining({ message: "db pool timeout" }),+ expect.stringContaining("lease-1")+ );});test("records nothing when the lease no longer exists", async () => {@@ -270,7 +312,18 @@ describe("dynamic secret lease revocation metrics", () => {});});- describe("retry phase", () => {+ describe("retry revocation", () => {+ test("clears a failing config's flag and records the recovery when a retry succeeds", async () => {+ const harness = createHarness();+ harness.addLease("lease-1");+ harness.cfg.revocationFailing = true;++ await harness.runRetry("lease-1", 2);++ expect(harness.cfg.revocationFailing).toBe(false);+ expect(statusChangeCalls()).toEqual([{ provider: PROVIDER, newStatus: "healthy" }]);+ });+test("records every attempt, exhausted only on the last, and orphans the lease there", async () => {const harness = createHarness();harness.addLease("lease-1");@@ -282,13 +335,29 @@ describe("dynamic secret lease revocation metrics", () => {}expect(outcomeCalls()).toEqual([- { provider: PROVIDER, phase: "retry", outcome: "failure", attemptsExhausted: false },- { provider: PROVIDER, phase: "retry", outcome: "failure", attemptsExhausted: false },- { provider: PROVIDER, phase: "retry", outcome: "failure", attemptsExhausted: true }+ { provider: PROVIDER, trigger: "retry", outcome: "failure", attemptsExhausted: false },+ { provider: PROVIDER, trigger: "retry", outcome: "failure", attemptsExhausted: false },+ { provider: PROVIDER, trigger: "retry", outcome: "failure", attemptsExhausted: true }]);expect(orphanedCalls()).toEqual([{ provider: PROVIDER }]);expect(statusChangeCalls()).toEqual([]);});++ test("still orphans the lease and emails admins when marking the lease failed throws", async () => {+ const harness = createHarness();+ harness.addLease("lease-1");+ harness.revoke.mockRejectedValue(new Error("connection refused"));+ harness.dynamicSecretLeaseDAL.updateById.mockRejectedValue(new Error("db pool timeout"));++ await expect(harness.runRetry("lease-1", MAX_ATTEMPTS)).rejects.toThrow("connection refused");++ expect(orphanedCalls()).toEqual([{ provider: PROVIDER }]);+ expect(+ harness.queueService.queue.mock.calls.filter(+ (call) => (call as unknown[])[1] === QueueJobs.DynamicSecretLeaseRevocationFailedEmail+ )+ ).toHaveLength(1);+ });});describe("pruning", () => {@@ -308,14 +377,36 @@ describe("dynamic secret lease revocation metrics", () => {await harness.runPruning(3);expect(outcomeCalls()).toEqual([- { provider: PROVIDER, phase: "pruning", outcome: "success", attemptsExhausted: true },- { provider: PROVIDER, phase: "pruning", outcome: "failure", attemptsExhausted: true },- { provider: PROVIDER, phase: "pruning", outcome: "success", attemptsExhausted: true }+ { provider: PROVIDER, trigger: "pruning", outcome: "success", attemptsExhausted: true },+ { provider: PROVIDER, trigger: "pruning", outcome: "failure", attemptsExhausted: true },+ { provider: PROVIDER, trigger: "pruning", outcome: "success", attemptsExhausted: true }]);expect(orphanedCalls()).toEqual([{ provider: PROVIDER, count: 1 }]);expect(harness.revoke).toHaveBeenCalledTimes(3);});+ test("still revokes and counts every lease when cancelling a scheduled job fails partway", async () => {+ const harness = createHarness();+ harness.addLease("lease-1");+ harness.addLease("lease-2");+ harness.queueService.stopJobById.mockImplementation(async (_queue: string, jobId: string) => {+ if (jobId === "lease-2") throw new Error("redis timeout");+ });+ harness.revoke.mockImplementation(async (_inputs, entityId) => {+ if (entityId === "entity-lease-1") throw new Error("permission denied");+ return { entityId };+ });++ await expect(harness.runPruning(1)).rejects.toThrow("permission denied");++ expect(harness.revoke).toHaveBeenCalledTimes(2);+ expect(outcomeCalls()).toEqual([+ { provider: PROVIDER, trigger: "pruning", outcome: "failure", attemptsExhausted: true },+ { provider: PROVIDER, trigger: "pruning", outcome: "success", attemptsExhausted: true }+ ]);+ expect(orphanedCalls()).toEqual([{ provider: PROVIDER, count: 1 }]);+ });+test("records a success per lease when every revoke succeeds", async () => {const harness = createHarness();harness.addLease("lease-1");@@ -324,8 +415,8 @@ describe("dynamic secret lease revocation metrics", () => {await harness.runPruning(1);expect(outcomeCalls()).toEqual([- { provider: PROVIDER, phase: "pruning", outcome: "success", attemptsExhausted: false },- { provider: PROVIDER, phase: "pruning", outcome: "success", attemptsExhausted: false }+ { provider: PROVIDER, trigger: "pruning", outcome: "success", attemptsExhausted: false },+ { provider: PROVIDER, trigger: "pruning", outcome: "success", attemptsExhausted: false }]);expect(orphanedCalls()).toEqual([]);});diff --git a/backend/src/ee/services/dynamic-secret-lease/dynamic-secret-lease-queue.ts b/backend/src/ee/services/dynamic-secret-lease/dynamic-secret-lease-queue.tsindex b653314668..89af57b098 100644--- a/backend/src/ee/services/dynamic-secret-lease/dynamic-secret-lease-queue.ts+++ b/backend/src/ee/services/dynamic-secret-lease/dynamic-secret-lease-queue.ts@@ -1,14 +1,11 @@import { ProjectMembershipRole } from "@app/db/schemas";-import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";import { getConfig } from "@app/lib/config/env";import { applyJitter } from "@app/lib/delay";import { DisableRotationErrors, NotFoundError } from "@app/lib/errors";import { logger } from "@app/lib/logger";import {- isTelemetryEnabled,recordDynamicSecretOrphanedLeaseMetric,- recordDynamicSecretRevocationOutcomeMetric,- recordDynamicSecretStatusChangeMetric+ recordDynamicSecretRevocationOutcomeMetric} from "@app/lib/telemetry/metrics";import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";import { TIdentityDALFactory } from "@app/services/identity/identity-dal";@@ -24,7 +21,7 @@ import { TDynamicSecretDALFactory } from "../dynamic-secret/dynamic-secret-dal";import { DynamicSecretStatus } from "../dynamic-secret/dynamic-secret-types";import { DynamicSecretProviders, TDynamicProviderFns } from "../dynamic-secret/providers/models";import { TDynamicSecretLeaseDALFactory } from "./dynamic-secret-lease-dal";-import { decryptLeaseData } from "./dynamic-secret-lease-fns";+import { decryptLeaseData, recordDynamicSecretRevocationResult } from "./dynamic-secret-lease-fns";import { TDynamicSecretLeaseConfig } from "./dynamic-secret-lease-types";type TDynamicSecretLeaseQueueServiceFactoryDep = {@@ -33,13 +30,12 @@ type TDynamicSecretLeaseQueueServiceFactoryDep = {smtpService: Pick<TSmtpService, "sendMail">;userDAL: Pick<TUserDALFactory, "findById">;identityDAL: TIdentityDALFactory;- dynamicSecretDAL: Pick<TDynamicSecretDALFactory, "findById" | "deleteById" | "updateById" | "findOne">;+ dynamicSecretDAL: Pick<TDynamicSecretDALFactory, "findById" | "deleteById" | "updateById" | "update" | "findOne">;projectMembershipDAL: Pick<TProjectMembershipDALFactory, "findAllProjectMembers">;projectDAL: Pick<TProjectDALFactory, "findById">;dynamicSecretProviders: Record<DynamicSecretProviders, TDynamicProviderFns>;kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;folderDAL: Pick<TSecretFolderDALFactory, "findById" | "findSecretPathByFolderIds">;- keyStore: Pick<TKeyStoreFactory, "getItem" | "deleteItem" | "setItemWithExpiryReturningPrevious">;};export type TDynamicSecretLeaseQueueServiceFactory = {@@ -50,7 +46,6 @@ export type TDynamicSecretLeaseQueueServiceFactory = {};const MAX_REVOCATION_RETRY_COUNT = 3;-const REVOCATION_FAILING_STATUS_EXPIRY_SECONDS = 7 * 24 * 60 * 60;export const dynamicSecretLeaseQueueServiceFactory = ({queueService,@@ -61,8 +56,7 @@ export const dynamicSecretLeaseQueueServiceFactory = ({folderDAL,projectMembershipDAL,projectDAL,- smtpService,- keyStore+ smtpService}: TDynamicSecretLeaseQueueServiceFactoryDep): TDynamicSecretLeaseQueueServiceFactory => {const pruneDynamicSecret = async (dynamicSecretCfgId: string) => {await queueService.queue(@@ -146,48 +140,11 @@ export const dynamicSecretLeaseQueueServiceFactory = ({);};- // Dynamic secret configs have no revocation status column, so whether a config's scheduled revocations are- // failing is kept in Redis. This only feeds a metric and must never fail or retry the revocation job.- const $recordScheduledRevocationStatusChange = async ({- dynamicSecretId,- provider,- isRevoked- }: {- dynamicSecretId: string;- provider: string;- isRevoked: boolean;- }) => {- if (!isTelemetryEnabled()) return;-- const key = KeyStorePrefixes.DynamicSecretRevocationFailing(dynamicSecretId);- try {- if (isRevoked) {- if (!(await keyStore.getItem(key))) return;- // Only the caller that actually deleted the key reports the recovery.- const deleted = await keyStore.deleteItem(key);- if (deleted > 0) recordDynamicSecretStatusChangeMetric({ provider, to: "healthy" });- return;- }-- const previous = await keyStore.setItemWithExpiryReturningPrevious(- key,- REVOCATION_FAILING_STATUS_EXPIRY_SECONDS,- "1"- );- if (!previous) recordDynamicSecretStatusChangeMetric({ provider, to: "failed" });- } catch (error) {- logger.warn(- error,- `Failed to record dynamic secret revocation status change [dynamicSecretId=${dynamicSecretId}] [provider=${provider}]`- );- }- };-const $recordPruningOutcomes = (provider: string, revoked: boolean[], attemptsExhausted: boolean) => {revoked.forEach((isRevoked) =>recordDynamicSecretRevocationOutcomeMetric({provider,- phase: "pruning",+ trigger: "pruning",outcome: isRevoked ? "success" : "failure",attemptsExhausted})@@ -203,6 +160,7 @@ export const dynamicSecretLeaseQueueServiceFactory = ({): Promise<void> => {let providerType: string | undefined;let configId: string | undefined;+ let wasFailing = false;const isFinalAttempt = retryCount !== undefined && retryCount >= maxAttempts;// Per-lease revoke results of this pruning run, so a failed run reports each lease once.let pruningRevoked: boolean[] | undefined;@@ -219,6 +177,7 @@ export const dynamicSecretLeaseQueueServiceFactory = ({const dynamicSecretCfg = dynamicSecretLease.dynamicSecret;providerType = dynamicSecretCfg.type;configId = dynamicSecretCfg.id;+ wasFailing = dynamicSecretCfg.revocationFailing;const folder = await folderDAL.findById(dynamicSecretCfg.folderId);if (!folder) {@@ -249,17 +208,17 @@ export const dynamicSecretLeaseQueueServiceFactory = ({recordDynamicSecretRevocationOutcomeMetric({provider: providerType,- phase: isRetry ? "retry" : "scheduled",+ trigger: isRetry ? "retry" : "scheduled",outcome: "success",attemptsExhausted: isFinalAttempt});- if (!isRetry) {- await $recordScheduledRevocationStatusChange({- dynamicSecretId: configId,- provider: providerType,- isRevoked: true- });- }+ await recordDynamicSecretRevocationResult({+ dynamicSecretDAL,+ dynamicSecretId: configId,+ provider: providerType,+ isRevoked: true,+ wasFailing+ });return;}@@ -295,7 +254,17 @@ export const dynamicSecretLeaseQueueServiceFactory = ({secretManagerDecryptor({ cipherTextBlob: dynamicSecretCfg.encryptedInput }).toString()) as object;- await Promise.all(dynamicSecretLeases.map(({ id }) => unsetLeaseRevocation(id)));+ // Best-effort: stopping partway must not skip the revokes below, or leases whose scheduled job was already+ // removed would be left unrevoked and uncounted. A lease whose job survives is revoked here anyway.+ const cancellations = await Promise.allSettled(dynamicSecretLeases.map(({ id }) => unsetLeaseRevocation(id)));+ cancellations.forEach((cancellation, index) => {+ if (cancellation.status === "rejected") {+ logger.warn(+ cancellation.reason,+ `Failed to cancel scheduled revocation while pruning [leaseId=${dynamicSecretLeases[index].id}]`+ );+ }+ });const revocations = await Promise.allSettled(dynamicSecretLeases.map(async ({ externalEntityId, config, encryptedLeaseData }) =>selectedProvider.revoke(@@ -353,35 +322,36 @@ export const dynamicSecretLeaseQueueServiceFactory = ({if (providerType && isRevocationFailure && (isRetry || isFinalAttempt)) {recordDynamicSecretRevocationOutcomeMetric({provider: providerType,- phase: isRetry ? "retry" : "scheduled",+ trigger: isRetry ? "retry" : "scheduled",outcome: "failure",attemptsExhausted: isFinalAttempt});if (!isRetry && configId) {- await $recordScheduledRevocationStatusChange({+ await recordDynamicSecretRevocationResult({+ dynamicSecretDAL,dynamicSecretId: configId,provider: providerType,- isRevoked: false+ isRevoked: false,+ wasFailing});}}- await dynamicSecretLeaseDAL.updateById(leaseId, {- status: DynamicSecretStatus.FailedDeletion,- statusDetails: `${(error as Error)?.message?.slice(0, 255)} - Retrying automatically`- });+ if (!isRetry && isRevocationFailure && isFinalAttempt) {+ await queueFailedRevocation(leaseId, dynamicSecretId);+ }- // only add to retry queue if this is not a retry, and if the error is not a DisableRotationErrors error- if (!isRetry && isRevocationFailure) {- // BullMQ retries the scheduled job (it cannot be removed while active), so hand off to the slower retry- // queue only once its attempts are used up. Handing off earlier lets the retry job revoke the lease between- // scheduled attempts, leaving the lease with no scheduled outcome.- if (isFinalAttempt) {- await queueFailedRevocation(leaseId, dynamicSecretId);- }+ try {+ await dynamicSecretLeaseDAL.updateById(leaseId, {+ status: DynamicSecretStatus.FailedDeletion,+ statusDetails: `${(error as Error)?.message?.slice(0, 255)} - Retrying automatically`+ });+ } catch (statusError) {+ logger.error(statusError, `Failed to mark dynamic secret lease as failed to revoke [leaseId=${leaseId}]`);+ }- // if its the last attempt, and the error isn't a DisableRotationErrors error, send an email to the project admins (debounced)- } else if (isRetry && isRevocationFailure) {+ // if its the last attempt, and the error isn't a DisableRotationErrors error, send an email to the project admins (debounced)+ if (isRetry && isRevocationFailure) {if (isFinalAttempt) {// if all retries fail, we should also stop the automatic revocation job.// the ID of the revocation job is set to the leaseId, so we can use that to stop the jobdiff --git a/backend/src/ee/services/dynamic-secret-lease/dynamic-secret-lease-service.test.ts b/backend/src/ee/services/dynamic-secret-lease/dynamic-secret-lease-service.test.tsindex 9058abfb98..7c21260a37 100644--- a/backend/src/ee/services/dynamic-secret-lease/dynamic-secret-lease-service.test.ts+++ b/backend/src/ee/services/dynamic-secret-lease/dynamic-secret-lease-service.test.ts@@ -3,6 +3,7 @@ import { beforeEach, describe, expect, test, vi } from "vitest";import {recordDynamicSecretRevocationOutcomeMetric,+ recordDynamicSecretStatusChangeMetric,recordDynamicSecretUnrecordedCredentialMetric} from "@app/lib/telemetry/metrics";import { ActorType, AuthMethod } from "@app/services/auth/auth-type";@@ -22,6 +23,7 @@ vi.mock("@app/lib/logger", () => ({vi.mock("@app/lib/telemetry/metrics", async (importOriginal) => ({...(await importOriginal<typeof import("@app/lib/telemetry/metrics")>()),recordDynamicSecretRevocationOutcomeMetric: vi.fn(),+ recordDynamicSecretStatusChangeMetric: vi.fn(),recordDynamicSecretUnrecordedCredentialMetric: vi.fn()}));@@ -38,7 +40,8 @@ const dynamicSecretCfg = {metadata: []};-const createService = () => {+const createService = ({ revocationFailing = false } = {}) => {+ const cfg = { ...dynamicSecretCfg, revocationFailing };const provider = {create: vi.fn(async () => ({ entityId: "entity-1", data: {} })),revoke: vi.fn(async () => ({ entityId: "entity-1" }))@@ -52,7 +55,7 @@ const createService = () => {externalEntityId: "entity-1",config: {},encryptedLeaseData: null,- dynamicSecret: dynamicSecretCfg+ dynamicSecret: cfg})),updateById: vi.fn(async () => ({})),deleteById: vi.fn(async () => ({}))@@ -60,7 +63,13 @@ const createService = () => {const service = dynamicSecretLeaseServiceFactory({dynamicSecretLeaseDAL: dynamicSecretLeaseDAL as never,- dynamicSecretDAL: { findOne: vi.fn(async () => dynamicSecretCfg) } as never,+ dynamicSecretDAL: {+ findOne: vi.fn(async () => ({ ...cfg })),+ update: vi.fn(async (filter: { revocationFailing: boolean }, data: { revocationFailing: boolean }) => {+ if (filter.revocationFailing !== cfg.revocationFailing) return [];+ return [Object.assign(cfg, data)];+ })+ } as never,dynamicSecretProviders: { [PROVIDER]: provider } as never,dynamicSecretQueueService: {setLeaseRevocation: vi.fn(async () => undefined),@@ -86,7 +95,7 @@ const createService = () => {secretValidationRuleService: { findConstraintsForGeneratedSecret: vi.fn(async () => ({ ruleNames: [] })) } as never});- return { service, provider, dynamicSecretLeaseDAL };+ return { service, provider, dynamicSecretLeaseDAL, cfg };};const actor = {@@ -113,7 +122,7 @@ describe("dynamic secret lease service metrics", () => {await service.revokeLease({ ...actor, leaseId: "lease-1" });expect(outcomeCalls()).toEqual([- { provider: PROVIDER, phase: "manual", outcome: "success", attemptsExhausted: true }+ { provider: PROVIDER, trigger: "manual", outcome: "success", attemptsExhausted: true }]);});@@ -124,7 +133,7 @@ describe("dynamic secret lease service metrics", () => {await service.revokeLease({ ...actor, leaseId: "lease-1" });expect(outcomeCalls()).toEqual([- { provider: PROVIDER, phase: "manual", outcome: "failure", attemptsExhausted: true }+ { provider: PROVIDER, trigger: "manual", outcome: "failure", attemptsExhausted: true }]);});@@ -137,13 +146,34 @@ describe("dynamic secret lease service metrics", () => {expect(outcomeCalls()).toEqual([]);});+ test("clears a failing config's flag and records the recovery when a manual revoke succeeds", async () => {+ const { service, cfg } = createService({ revocationFailing: true });++ await service.revokeLease({ ...actor, leaseId: "lease-1" });++ expect(cfg.revocationFailing).toBe(false);+ expect(vi.mocked(recordDynamicSecretStatusChangeMetric).mock.calls).toEqual([+ [{ provider: PROVIDER, newStatus: "healthy" }]+ ]);+ });++ test("leaves a failing config's flag when a forced revoke swallowed the upstream error", async () => {+ const { service, provider, cfg } = createService({ revocationFailing: true });+ provider.revoke.mockRejectedValueOnce(new Error("connection refused"));++ await service.revokeLease({ ...actor, leaseId: "lease-1", isForced: true });++ expect(cfg.revocationFailing).toBe(true);+ expect(vi.mocked(recordDynamicSecretStatusChangeMetric)).not.toHaveBeenCalled();+ });+test("records a forced revoke that succeeded upstream", async () => {const { service } = createService();await service.revokeLease({ ...actor, leaseId: "lease-1", isForced: true });expect(outcomeCalls()).toEqual([- { provider: PROVIDER, phase: "manual", outcome: "success", attemptsExhausted: true }+ { provider: PROVIDER, trigger: "manual", outcome: "success", attemptsExhausted: true }]);});});diff --git a/backend/src/ee/services/dynamic-secret-lease/dynamic-secret-lease-service.ts b/backend/src/ee/services/dynamic-secret-lease/dynamic-secret-lease-service.tsindex 6c1096ba0f..9f8823dd42 100644--- a/backend/src/ee/services/dynamic-secret-lease/dynamic-secret-lease-service.ts+++ b/backend/src/ee/services/dynamic-secret-lease/dynamic-secret-lease-service.ts@@ -33,7 +33,11 @@ import { TDynamicSecretDALFactory } from "../dynamic-secret/dynamic-secret-dal";import { DynamicSecretProviders, TDynamicProviderFns } from "../dynamic-secret/providers/models";import { toSafeUsername } from "../dynamic-secret/providers/templateUtils";import { TDynamicSecretLeaseDALFactory } from "./dynamic-secret-lease-dal";-import { decryptLeaseData, pickPersistedLeaseData } from "./dynamic-secret-lease-fns";+import {+ decryptLeaseData,+ pickPersistedLeaseData,+ recordDynamicSecretRevocationResult+} from "./dynamic-secret-lease-fns";import { TDynamicSecretLeaseQueueServiceFactory } from "./dynamic-secret-lease-queue";import {DynamicSecretLeaseStatus,@@ -43,7 +47,7 @@ import {type TDynamicSecretLeaseServiceFactoryDep = {dynamicSecretLeaseDAL: TDynamicSecretLeaseDALFactory;- dynamicSecretDAL: Pick<TDynamicSecretDALFactory, "findOne">;+ dynamicSecretDAL: Pick<TDynamicSecretDALFactory, "findOne" | "update">;dynamicSecretProviders: Record<DynamicSecretProviders, TDynamicProviderFns>;dynamicSecretQueueService: TDynamicSecretLeaseQueueServiceFactory;licenseService: Pick<TLicenseServiceFactory, "getPlan">;@@ -432,7 +436,7 @@ export const dynamicSecretLeaseServiceFactory = ({if (!isRevokeErrorSwallowed) {recordDynamicSecretRevocationOutcomeMetric({provider: dynamicSecretCfg.type,- phase: "manual",+ trigger: "manual",outcome: (revokeResponse as { error?: Error })?.error ? "failure" : "success",attemptsExhausted: true});@@ -456,6 +460,16 @@ export const dynamicSecretLeaseServiceFactory = ({};}+ if (!isRevokeErrorSwallowed) {+ await recordDynamicSecretRevocationResult({+ dynamicSecretDAL,+ dynamicSecretId: dynamicSecretCfg.id,+ provider: dynamicSecretCfg.type,+ isRevoked: true,+ wasFailing: dynamicSecretCfg.revocationFailing+ });+ }+await dynamicSecretQueueService.unsetLeaseRevocation(dynamicSecretLease.id);const deletedDynamicSecretLease = await dynamicSecretLeaseDAL.deleteById(dynamicSecretLease.id);return {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.tsindex 417be0fb30..20ab718cb8 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@@ -1,12 +1,18 @@+import { createMongoAbility } from "@casl/ability";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 { SecretRotation, SecretRotationStatus } from "./secret-rotation-v2-enums";-import { secretRotationV2ServiceFactory } from "./secret-rotation-v2-service";+import { SecretRotationInProgressError, secretRotationV2ServiceFactory } from "./secret-rotation-v2-service";import { TSecretRotationV2Raw } from "./secret-rotation-v2-types";+import { UnixLinuxLocalAccountRotationMethod } from "./unix-linux-local-account-rotation/unix-linux-local-account-rotation-schemas";-const rotateCredentials = vi.fn<() => Promise<unknown>>();+type TRotationCallback = (newCredentials: unknown) => Promise<unknown>;+const rotateCredentials = vi.fn<(inactive: unknown, callback: TRotationCallback) => Promise<unknown>>();+// What a provider does on success: issue new credentials and hand them to the service to persist.+const runCallback = async (_inactive: unknown, callback: TRotationCallback) => callback({});vi.mock("@app/lib/config/env", async (importOriginal) => ({...(await importOriginal<typeof import("@app/lib/config/env")>()),@@ -28,19 +34,82 @@ vi.mock("@app/services/app-connection/app-connection-fns", async (importOriginaldecryptAppConnection: vi.fn(async () => ({}))}));+vi.mock("@app/services/secret-v2-bridge/secret-blind-index-fns", () => ({+ createSecretBlindIndexer: vi.fn(async () => ({ generateBlindIndexes: vi.fn(async () => []) }))+}));++vi.mock("@app/services/secret-v2-bridge/secret-v2-bridge-fns", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@app/services/secret-v2-bridge/secret-v2-bridge-fns")>()),+ fnSecretBulkUpdate: vi.fn(async () => [])+}));+vi.mock("@app/ee/services/secret-rotation-v2/secret-rotation-v2-fns", async (importOriginal) => ({...(await importOriginal<typeof import("@app/ee/services/secret-rotation-v2/secret-rotation-v2-fns")>()),- decryptSecretRotationCredentials: vi.fn(async () => [{}, {}])+ decryptSecretRotationCredentials: vi.fn(async () => [{ username: "app", password: "old" }, {}]),+ encryptSecretRotationCredentials: vi.fn(async () => Buffer.from("encrypted")),+ expandSecretRotation: vi.fn(async (rotation: unknown) => rotation)}));vi.mock("./stripe-api-key/stripe-api-key-rotation-fns", () => ({- stripeApiKeyRotationFactory: () => ({ rotateCredentials })+ stripeApiKeyRotationFactory: () => ({ rotateCredentials, getSecretsPayload: () => [] })}));-const createService = ({ lockFails = false } = {}) => {+vi.mock("./unix-linux-local-account-rotation/unix-linux-local-account-rotation-fns", () => ({+ unixLinuxLocalAccountRotationFactory: () => ({+ issueCredentials: async (callback: TRotationCallback) => callback({ username: "app", password: "reconciled" })+ })+}));++const rotation = (rotationStatus: SecretRotationStatus, type = SecretRotation.StripeApiKey) =>+ ({+ id: "rotation-1",+ name: "rotation",+ type,+ rotationStatus,+ projectId: "project-1",+ folderId: "folder-1",+ activeIndex: 0,+ encryptedGeneratedCredentials: Buffer.from(""),+ rotateAtUtc: { hours: 0, minutes: 0 },+ rotationInterval: 1,+ isAutoRotationEnabled: false,+ lastRotatedAt: new Date("2026-10-01T00:00:00.000Z"),+ parameters: { rotationMethod: UnixLinuxLocalAccountRotationMethod.LoginAsTarget },+ secretsMapping: { username: "APP_USER", password: "APP_PASS" },+ connection: {+ id: "connection-1",+ orgId: "org-1",+ app: type === SecretRotation.StripeApiKey ? "stripe" : "ssh"+ },+ folder: { id: "folder-1", path: "/" },+ environment: { id: "env-1", slug: "dev", name: "Development" }+ }) as unknown as TSecretRotationV2Raw;++const actor = {+ type: ActorType.USER,+ id: "user-1",+ orgId: "org-1",+ authMethod: AuthMethod.EMAIL,+ rootOrgId: "org-1",+ parentOrgId: "org-1"+};++// storedStatus is the rotation row in the database; the object passed to rotateGeneratedCredentials is what the+// job loaded, which can be older.+const createService = ({+ storedStatus,+ lockFails = false,+ type = SecretRotation.StripeApiKey+}: {+ storedStatus: SecretRotationStatus;+ lockFails?: boolean;+ type?: SecretRotation;+}) => {+ const stored = { rotationStatus: storedStatus };const release = vi.fn(async () => undefined);const deps = {keyStore: {+ getItem: vi.fn(async () => null),acquireLock: vi.fn(async () => {if (lockFails) throw new Error("locked");return { release };@@ -51,7 +120,27 @@ const createService = ({ lockFails = false } = {}) => {encryptor: () => ({ cipherTextBlob: Buffer.from("encrypted") })}))},- secretRotationV2DAL: { updateById: vi.fn(async () => ({})) },+ licenseService: { getPlan: vi.fn(async () => ({ secretRotation: true })) },+ permissionService: {+ getProjectPermission: vi.fn(async () => ({+ permission: createMongoAbility([{ action: "manage", subject: "all" }])+ }))+ },+ 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({})),+ // 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 [];+ Object.assign(stored, data);+ return [{ ...stored }];+ }),+ updateById: vi.fn(async (_id: string, data: Partial<typeof stored>) => ({+ ...rotation(stored.rotationStatus, type),+ ...Object.assign(stored, data)+ }))+ },auditLogService: { createAuditLog: vi.fn(async () => undefined) },secretV2BridgeDAL: { invalidateSecretCacheByProjectId: vi.fn(async () => undefined) },secretQueueService: { syncSecrets: vi.fn(async () => undefined) },@@ -59,27 +148,9 @@ const createService = ({ lockFails = false } = {}) => {queueService: { queue: vi.fn(async () => undefined) }};- return secretRotationV2ServiceFactory(deps as never);+ return { service: secretRotationV2ServiceFactory(deps as never), stored, deps };};-const rotation = (rotationStatus: SecretRotationStatus) =>- ({- id: "rotation-1",- name: "rotation",- type: SecretRotation.StripeApiKey,- rotationStatus,- projectId: "project-1",- folderId: "folder-1",- activeIndex: 0,- encryptedGeneratedCredentials: Buffer.from(""),- rotateAtUtc: { hours: 0, minutes: 0 },- parameters: {},- secretsMapping: {},- connection: { id: "connection-1", orgId: "org-1", app: "stripe" },- folder: { id: "folder-1", path: "/" },- environment: { id: "env-1", slug: "dev", name: "Development" }- }) as unknown as TSecretRotationV2Raw;-const outcomeCalls = () => vi.mocked(recordSecretRotationOutcomeMetric).mock.calls.map(([params]) => params);const statusChangeCalls = () => vi.mocked(recordSecretRotationStatusChangeMetric).mock.calls.map(([params]) => params);@@ -89,8 +160,8 @@ describe("rotateGeneratedCredentials metrics", () => {});test("reports a manual rotation as exhausted, since it is never retried", async () => {- rotateCredentials.mockResolvedValueOnce({});- const service = createService();+ rotateCredentials.mockImplementationOnce(runCallback);+ const { service } = createService({ storedStatus: SecretRotationStatus.Success });await service.rotateGeneratedCredentials(rotation(SecretRotationStatus.Success), { isManualRotation: true });@@ -101,7 +172,7 @@ describe("rotateGeneratedCredentials metrics", () => {test("reports an intermediate failed attempt as not exhausted and does not flip the status", async () => {rotateCredentials.mockRejectedValueOnce(new Error("provider down"));- const service = createService();+ const { service, stored } = createService({ storedStatus: SecretRotationStatus.Success });await expect(service.rotateGeneratedCredentials(rotation(SecretRotationStatus.Success), { isFinalAttempt: false })@@ -111,11 +182,12 @@ describe("rotateGeneratedCredentials metrics", () => {{ type: SecretRotation.StripeApiKey, outcome: "failure", attemptsExhausted: false }]);expect(statusChangeCalls()).toEqual([]);+ expect(stored.rotationStatus).toBe(SecretRotationStatus.Success);});test("flips to failed when the final attempt fails after a previous success", async () => {rotateCredentials.mockRejectedValueOnce(new Error("provider down"));- const service = createService();+ const { service, stored } = createService({ storedStatus: SecretRotationStatus.Success });await expect(service.rotateGeneratedCredentials(rotation(SecretRotationStatus.Success), { isFinalAttempt: true })@@ -124,12 +196,13 @@ describe("rotateGeneratedCredentials metrics", () => {expect(outcomeCalls()).toEqual([{ type: SecretRotation.StripeApiKey, outcome: "failure", attemptsExhausted: true }]);- expect(statusChangeCalls()).toEqual([{ type: SecretRotation.StripeApiKey, to: "failed" }]);+ expect(statusChangeCalls()).toEqual([{ type: SecretRotation.StripeApiKey, newStatus: "failed" }]);+ expect(stored.rotationStatus).toBe(SecretRotationStatus.Failed);});test("does not flip again when an already failed rotation fails", async () => {rotateCredentials.mockRejectedValueOnce(new Error("provider down"));- const service = createService();+ const { service } = createService({ storedStatus: SecretRotationStatus.Failed });await expect(service.rotateGeneratedCredentials(rotation(SecretRotationStatus.Failed), { isFinalAttempt: true })@@ -138,37 +211,108 @@ describe("rotateGeneratedCredentials metrics", () => {expect(statusChangeCalls()).toEqual([]);});+ test("reports a breakage once when two runs loaded the same healthy rotation", async () => {+ rotateCredentials.mockRejectedValue(new Error("provider down"));+ const { service } = createService({ storedStatus: SecretRotationStatus.Success });+ const loadedBeforeEitherRan = rotation(SecretRotationStatus.Success);++ await expect(service.rotateGeneratedCredentials(loadedBeforeEitherRan, { isFinalAttempt: true })).rejects.toThrow();+ await expect(service.rotateGeneratedCredentials(loadedBeforeEitherRan, { isFinalAttempt: true })).rejects.toThrow();++ expect(statusChangeCalls()).toEqual([{ type: SecretRotation.StripeApiKey, newStatus: "failed" }]);+ rotateCredentials.mockReset();+ });+test("flips to healthy when a previously failed rotation succeeds", async () => {- rotateCredentials.mockResolvedValueOnce({});- const service = createService();+ rotateCredentials.mockImplementationOnce(runCallback);+ const { service, stored } = createService({ storedStatus: SecretRotationStatus.Failed });await service.rotateGeneratedCredentials(rotation(SecretRotationStatus.Failed), { isFinalAttempt: false });expect(outcomeCalls()).toEqual([{ type: SecretRotation.StripeApiKey, outcome: "success", attemptsExhausted: false }]);- expect(statusChangeCalls()).toEqual([{ type: SecretRotation.StripeApiKey, to: "healthy" }]);+ expect(statusChangeCalls()).toEqual([{ type: SecretRotation.StripeApiKey, newStatus: "healthy" }]);+ expect(stored.rotationStatus).toBe(SecretRotationStatus.Success);});test("does not flip to healthy when a healthy rotation succeeds", async () => {- rotateCredentials.mockResolvedValueOnce({});- const service = createService();+ rotateCredentials.mockImplementationOnce(runCallback);+ const { service } = createService({ storedStatus: SecretRotationStatus.Success });await service.rotateGeneratedCredentials(rotation(SecretRotationStatus.Success));expect(statusChangeCalls()).toEqual([]);});+});++describe("rotation lock contention", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });- test("does not count lock contention as the rotation breaking", async () => {- const service = createService({ lockFails: true });+ test("skips a run that cannot take the lock: no outcome, status write, notification or status change", async () => {+ const { service, stored, deps } = createService({ storedStatus: SecretRotationStatus.Success, lockFails: true });await expect(- service.rotateGeneratedCredentials(rotation(SecretRotationStatus.Success), { isFinalAttempt: true })- ).rejects.toThrow();+ service.rotateGeneratedCredentials(rotation(SecretRotationStatus.Success), {+ isFinalAttempt: true,+ shouldSendNotification: true+ })+ ).rejects.toBeInstanceOf(SecretRotationInProgressError);++ expect(outcomeCalls()).toEqual([]);+ expect(statusChangeCalls()).toEqual([]);+ expect(stored.rotationStatus).toBe(SecretRotationStatus.Success);+ expect(deps.secretRotationV2DAL.updateById).not.toHaveBeenCalled();+ expect(deps.queueService.queue).not.toHaveBeenCalled();+ expect(deps.telemetryService.sendPostHogEvents).not.toHaveBeenCalled();+ expect(deps.auditLogService.createAuditLog).not.toHaveBeenCalled();+ });++ test("answers a manual rotation that loses the lock race with the in-progress error, not a server error", async () => {+ const { service } = createService({ storedStatus: SecretRotationStatus.Success, lockFails: true });++ await expect(+ service.rotateSecretRotation(+ { rotationId: "rotation-1", type: SecretRotation.StripeApiKey, auditLogInfo: {} as never },+ actor as never+ )+ ).rejects.toBeInstanceOf(SecretRotationInProgressError);+ });+});++describe("reconcile", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ test("records the recovery when it fixes a failed local-account rotation", async () => {+ const { service, stored } = createService({+ storedStatus: SecretRotationStatus.Failed,+ type: SecretRotation.UnixLinuxLocalAccount+ });++ await service.reconcileLocalAccountRotation(+ { rotationId: "rotation-1", type: SecretRotation.UnixLinuxLocalAccount },+ actor as never+ );++ expect(stored.rotationStatus).toBe(SecretRotationStatus.Success);+ expect(statusChangeCalls()).toEqual([{ type: SecretRotation.UnixLinuxLocalAccount, newStatus: "healthy" }]);+ });++ test("records nothing when it reconciles a rotation that was not failing", async () => {+ const { service } = createService({+ storedStatus: SecretRotationStatus.Success,+ type: SecretRotation.UnixLinuxLocalAccount+ });++ await service.reconcileLocalAccountRotation(+ { rotationId: "rotation-1", type: SecretRotation.UnixLinuxLocalAccount },+ actor as never+ );- expect(outcomeCalls()).toEqual([- { type: SecretRotation.StripeApiKey, outcome: "failure", attemptsExhausted: true }- ]);expect(statusChangeCalls()).toEqual([]);});});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.tsindex d89d898746..6a3f7f5578 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@@ -225,6 +225,12 @@ const SECRET_ROTATION_FACTORY_MAP: Record<SecretRotation, TRotationFactoryImplem[SecretRotation.GcpServiceAccountKey]: gcpServiceAccountKeyRotationFactory as TRotationFactoryImplementation};+export class SecretRotationInProgressError extends BadRequestError {+ constructor() {+ super({ message: "A rotation is already in progress. Please try again shortly." });+ }+}+export const secretRotationV2ServiceFactory = ({secretRotationV2DAL,folderDAL,@@ -274,6 +280,17 @@ 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(+ { id: rotationId, rotationStatus: SecretRotationStatus.Failed },+ { rotationStatus: SecretRotationStatus.Success },+ tx+ )+ ).length > 0;+const $queueSendSecretRotationStatusNotification = async (secretRotation: TSecretRotationV2Raw) => {const appCfg = getConfig();if (!appCfg.isSmtpConfigured) return; // comment out if testing email sending@@ -1313,18 +1330,14 @@ export const secretRotationV2ServiceFactory = ({secretsMapping} = secretRotation;- let lock: Awaited<ReturnType<typeof keyStore.acquireLock>> | undefined;- const previousRotationStatus = secretRotation.rotationStatus as SecretRotationStatus;-+ let lock: Awaited<ReturnType<typeof keyStore.acquireLock>>;try {- try {- lock = await keyStore.acquireLock([KeyStorePrefixes.SecretRotationLock(rotationId)], 60 * 1000);- } catch (e) {- throw new InternalServerError({- message: "Failed to acquire rotation lock."- });- }+ lock = await keyStore.acquireLock([KeyStorePrefixes.SecretRotationLock(rotationId)], 60 * 1000);+ } catch (e) {+ throw new SecretRotationInProgressError();+ }+ try {const appConnection = await decryptAppConnection(connection, kmsService);const generatedCredentials = await decryptSecretRotationCredentials({@@ -1378,7 +1391,10 @@ export const secretRotationV2ServiceFactory = ({});const blindIndexer = await createSecretBlindIndexer({ projectId, orgId: connection.orgId, kmsService });- return secretRotationV2DAL.transaction(async (tx) => {+ 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@@ -1438,6 +1454,9 @@ export const secretRotationV2ServiceFactory = ({tx);});++ if (isRecovery) recordSecretRotationStatusChangeMetric({ type, newStatus: "healthy" });+ return rotated;},activeCredentials);@@ -1478,9 +1497,6 @@ export const secretRotationV2ServiceFactory = ({});recordSecretRotationOutcomeMetric({ type, outcome: "success", attemptsExhausted: isFinalAttempt });- if (previousRotationStatus === SecretRotationStatus.Failed) {- recordSecretRotationStatusChangeMetric({ type, to: "healthy" });- }return updatedRotation;} catch (error) {@@ -1502,6 +1518,14 @@ 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,@@ -1510,10 +1534,7 @@ export const secretRotationV2ServiceFactory = ({nextRotationAt: getNextUtcRotationInterval(secretRotation.rotateAtUtc as TSecretRotationV2["rotateAtUtc"])});- // Without the lock another run of this rotation was in progress, which says nothing about the provider.- if (previousRotationStatus === SecretRotationStatus.Success && lock) {- recordSecretRotationStatusChangeMetric({ type, to: "failed" });- }+ if (isStatusChange) recordSecretRotationStatusChangeMetric({ type, newStatus: "failed" });if (shouldSendNotification) {await $queueSendSecretRotationStatusNotification(updatedRotation);@@ -1561,7 +1582,7 @@ export const secretRotationV2ServiceFactory = ({throw new BadRequestError({ message: errorMessage });} finally {- await lock?.release();+ await lock.release();}};@@ -1618,6 +1639,7 @@ export const secretRotationV2ServiceFactory = ({return await expandSecretRotation(updatedRotation, kmsService);} catch (err) {+ if (err instanceof SecretRotationInProgressError) throw err;throw new InternalServerError({message: (err as Error).message ?? "Failed to rotate secrets: check Rotation status for details."});@@ -2116,7 +2138,8 @@ export const secretRotationV2ServiceFactory = ({});const blindIndexer = await createSecretBlindIndexer({ projectId, orgId: actor.orgId, kmsService });- return secretRotationV2DAL.transaction(async (tx) => {+ let isRecovery = false;+ const reconciled = await secretRotationV2DAL.transaction(async (tx) => {// Update the password secret with the new valueconst secretsMapping = secretRotation.secretsMapping as TLocalAccountRotation["secretsMapping"];const passwordBuffer = Buffer.from(localAccountCredentials.password);@@ -2150,6 +2173,7 @@ export const secretRotationV2ServiceFactory = ({resourceMetadataDAL});+ isRecovery = await $markRotationSucceeded(rotationId, tx);return secretRotationV2DAL.updateById(rotationId,{@@ -2160,6 +2184,8 @@ export const secretRotationV2ServiceFactory = ({tx);});+ if (isRecovery) recordSecretRotationStatusChangeMetric({ type, newStatus: "healthy" });+ return reconciled;},{ password: activeCredentials.password });diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.tsindex 00048aae60..a963ba652e 100644--- a/backend/src/keystore/keystore.ts+++ b/backend/src/keystore/keystore.ts@@ -195,9 +195,6 @@ export const KeyStorePrefixes = {// Braces are a Redis Cluster hash tag: the index zset and every member's payload key must land on// one slot for the multi-key upsert/delete scripts.- DynamicSecretRevocationFailing: (dynamicSecretId: string) =>- `dynamic-secret-revocation-failing:${dynamicSecretId}` as const,-WorkerHeartbeatIndex: (workerType: string) => `worker-heartbeat:{${workerType}}` as const,WorkerHeartbeat: (workerType: string, instanceId: string) =>`worker-heartbeat:{${workerType}}:${instanceId}` as const,@@ -357,11 +354,6 @@ export type TKeyStoreFactory = {value: string | number | Buffer,prefix?: string) => Promise<"OK" | null>;- setItemWithExpiryReturningPrevious: (- key: string,- expiryInSeconds: number,- value: string | number- ) => Promise<string | null>;deleteItem: (key: string) => Promise<number>;deleteItemsByKeyIn: (keys: string[]) => Promise<number>;deleteItems: (arg: TDeleteItems) => Promise<number>;@@ -500,9 +492,6 @@ export const keyStoreFactory = (prefix?: string) => primaryRedis.set(prefix ? `${prefix}:${key}` : key, value, "EX", expiryInSeconds, "NX");- const setItemWithExpiryReturningPrevious = async (key: string, expiryInSeconds: number, value: string | number) =>- primaryRedis.set(key, value, "EX", expiryInSeconds, "GET");-const deleteItem = async (key: string) => primaryRedis.del(key);const deleteItemsByKeyIn = async (keys: string[]) => {@@ -948,7 +937,6 @@ export const keyStoreFactory = (ttl,setItemWithExpiry,setItemWithExpiryNX,- setItemWithExpiryReturningPrevious,deleteItem,deleteItems,incrementBy,diff --git a/backend/src/keystore/memory.ts b/backend/src/keystore/memory.tsindex 9709a75e60..ea55f8d22a 100644--- a/backend/src/keystore/memory.ts+++ b/backend/src/keystore/memory.ts@@ -32,11 +32,6 @@ export const inMemoryKeyStore = (): TKeyStoreFactory => {store[key] = value;return "OK";},- setItemWithExpiryReturningPrevious: async (key, _expiryInSeconds, value) => {- const previous = store[key];- store[key] = value;- return previous === undefined ? null : previous.toString();- },deleteItem: async (key) => {delete store[key];delete hashStore[key];diff --git a/backend/src/lib/telemetry/metrics.ts b/backend/src/lib/telemetry/metrics.tsindex b5f3b5d24f..4aac46b61e 100644--- a/backend/src/lib/telemetry/metrics.ts+++ b/backend/src/lib/telemetry/metrics.ts@@ -733,11 +733,14 @@ export const secretSyncStatusChangeCounter = infisicalCoreMeter.createCounter(});-export const recordSecretSyncStatusChangeMetric = (params: { destination: string; to: "failed" | "healthy" }) => {+export const recordSecretSyncStatusChangeMetric = (params: {+ destination: string;+ newStatus: "failed" | "healthy";+}) => {if (!isTelemetryEnabled()) return;secretSyncStatusChangeCounter.add(1, {destination: params.destination,- to: params.to+ new_status: params.newStatus});};@@ -773,11 +776,11 @@ export const secretRotationStatusChangeCounter = infisicalCoreMeter.createCounte});-export const recordSecretRotationStatusChangeMetric = (params: { type: string; to: "failed" | "healthy" }) => {+export const recordSecretRotationStatusChangeMetric = (params: { type: string; newStatus: "failed" | "healthy" }) => {if (!isTelemetryEnabled()) return;secretRotationStatusChangeCounter.add(1, {type: params.type,- to: params.to+ new_status: params.newStatus});};@@ -802,21 +805,21 @@ export const dynamicSecretRevocationOutcomeCounter = infisicalCoreMeter.createCo"infisical.dynamic_secret.revocation.outcome.count",{description:- "Dynamic secret lease revocations by provider, phase, and outcome. The scheduled phase records exactly one outcome per expired lease; retry records every attempt, with attempts.exhausted=true on the last.",+ "Dynamic secret lease revocations by provider, trigger, and outcome. A scheduled revocation (lease expiry) records exactly one outcome per lease; retry records every attempt, with attempts.exhausted=true on the last.",unit: "{revocation}"});export const recordDynamicSecretRevocationOutcomeMetric = (params: {provider: string;- phase: "scheduled" | "retry" | "manual" | "pruning";+ trigger: "scheduled" | "retry" | "manual" | "pruning";outcome: "success" | "failure";attemptsExhausted: boolean;}) => {if (!isTelemetryEnabled()) return;dynamicSecretRevocationOutcomeCounter.add(1, {provider: params.provider,- phase: params.phase,+ trigger: params.trigger,outcome: params.outcome,"attempts.exhausted": String(params.attemptsExhausted)});@@ -826,16 +829,19 @@ export const dynamicSecretStatusChangeCounter = infisicalCoreMeter.createCounter"infisical.dynamic_secret.status_change.count",{description:- "Dynamic secret configs whose scheduled lease revocations flipped between healthy and failed, by provider. Counts distinct configs breaking without a per-config label.",+ "Dynamic secret configs whose lease revocations flipped between working and failing, by provider: failed when a scheduled revocation fails for good, healthy when any revocation succeeds again. Counts distinct configs breaking without a per-config label.",unit: "{change}"});-export const recordDynamicSecretStatusChangeMetric = (params: { provider: string; to: "failed" | "healthy" }) => {+export const recordDynamicSecretStatusChangeMetric = (params: {+ provider: string;+ newStatus: "failed" | "healthy";+}) => {if (!isTelemetryEnabled()) return;dynamicSecretStatusChangeCounter.add(1, {provider: params.provider,- to: params.to+ new_status: params.newStatus});};diff --git a/backend/src/lib/telemetry/telemetry-attributes.ts b/backend/src/lib/telemetry/telemetry-attributes.tsindex cbb70efc6e..4087a82890 100644--- a/backend/src/lib/telemetry/telemetry-attributes.ts+++ b/backend/src/lib/telemetry/telemetry-attributes.ts@@ -50,8 +50,8 @@ export const INFISICAL_CORE_METER_ATTRIBUTES = ["type","operation",// Closed enums on the secrets status_change and revocation outcome counters.- "to",- "phase",+ "new_status",+ "trigger",// Build info gauge labels — single-value per deploy, no cardinality concern"service.version","git.commit.sha",diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 00855401db..1582f3cf54 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -3106,8 +3106,7 @@ export const registerRoutes = async (userDAL,identityDAL,projectMembershipDAL,- projectDAL,- keyStore+ projectDAL});const dynamicSecretService = dynamicSecretServiceFactory({orgDAL,diff --git a/backend/src/services/secret-sync/secret-sync-queue.test.ts b/backend/src/services/secret-sync/secret-sync-queue.test.tsindex 0c29bd15af..567f3143e8 100644--- a/backend/src/services/secret-sync/secret-sync-queue.test.ts+++ b/backend/src/services/secret-sync/secret-sync-queue.test.ts@@ -47,10 +47,12 @@ const ATTEMPTS = 5;const REQUEUE_LIMIT = 120;const LAST_SYNCED_AT = new Date("2026-10-01T00:00:00.000Z");-type TSyncState = { lastSyncedAt: Date | null; lastSyncMessage: string | null };+type TSyncState = { lastSyncedAt: Date | null; lastSyncMessage: string | null; lastSyncResult: string | null };type THandler = (job: unknown) => Promise<void>;-const createHarness = (initial: TSyncState, { lockFails = false } = {}) => {+// staleLoad: every attempt loads the sync as it was before the test, standing in for a job that read the row+// before another job for the same sync finished.+const createHarness = (initial: TSyncState, { lockFails = false, staleLoad = false } = {}) => {const handlers = new Map<string, THandler>();const queueService = {start: vi.fn((name: string, fn: THandler) => {@@ -73,9 +75,15 @@ const createHarness = (initial: TSyncState, { lockFails = false } = {}) => {destinationConfig: {},...initial};+ const snapshot = { ...state };const secretSyncDAL = {// Every attempt reloads the sync, as the real handler does.- findById: vi.fn(async () => ({ ...state })),+ findById: vi.fn(async () => (staleLoad ? { ...snapshot } : { ...state })),+ // A conditional UPDATE: only a row still matching the filter is changed and returned.+ update: vi.fn(async (filter: Partial<typeof state>, data: Partial<typeof state>) => {+ const matches = Object.entries(filter).every(([key, value]) => state[key as keyof typeof state] === value);+ return matches ? [Object.assign(state, data)] : [];+ }),updateById: vi.fn(async (_id: string, data: Partial<typeof state>) => {Object.entries(data).forEach(([key, value]) => {if (value !== undefined) Object.assign(state, { [key]: value });@@ -116,10 +124,14 @@ const createHarness = (initial: TSyncState, { lockFails = false } = {}) => {const syncSecrets = vi.mocked(SecretSyncFns.syncSecrets);const statusChangeCalls = () => vi.mocked(recordSecretSyncStatusChangeMetric).mock.calls.map(([params]) => params);-const healthy: TSyncState = { lastSyncedAt: LAST_SYNCED_AT, lastSyncMessage: null };-const failed: TSyncState = { lastSyncedAt: LAST_SYNCED_AT, lastSyncMessage: "Railway disabled updates" };-const neverSucceeded: TSyncState = { lastSyncedAt: null, lastSyncMessage: "Invalid token" };-const brandNew: TSyncState = { lastSyncedAt: null, lastSyncMessage: null };+const healthy: TSyncState = { lastSyncedAt: LAST_SYNCED_AT, lastSyncMessage: null, lastSyncResult: "succeeded" };+const failed: TSyncState = {+ lastSyncedAt: LAST_SYNCED_AT,+ lastSyncMessage: "Railway disabled updates",+ lastSyncResult: "failed"+};+const neverSucceeded: TSyncState = { lastSyncedAt: null, lastSyncMessage: "Invalid token", lastSyncResult: "failed" };+const brandNew: TSyncState = { lastSyncedAt: null, lastSyncMessage: null, lastSyncResult: null };describe("secret sync status change", () => {beforeEach(() => {@@ -132,7 +144,7 @@ describe("secret sync status change", () => {await expect(runSync(ATTEMPTS)).rejects.toThrow("upstream 500");- expect(statusChangeCalls()).toEqual([{ destination: SecretSync.Railway, to: "failed" }]);+ expect(statusChangeCalls()).toEqual([{ destination: SecretSync.Railway, newStatus: "failed" }]);});test("uses the result before the job, not the Running status, across retries", async () => {@@ -147,7 +159,7 @@ describe("secret sync status change", () => {expect(vi.mocked(recordSecretSyncOutcomeMetric)).toHaveBeenCalledTimes(ATTEMPTS - 1);await expect(runSync(ATTEMPTS)).rejects.toThrow();- expect(statusChangeCalls()).toEqual([{ destination: SecretSync.Railway, to: "failed" }]);+ expect(statusChangeCalls()).toEqual([{ destination: SecretSync.Railway, newStatus: "failed" }]);});test("flips to failed when a non-retryable error ends a healthy sync early", async () => {@@ -156,7 +168,7 @@ describe("secret sync status change", () => {await runSync(1);- expect(statusChangeCalls()).toEqual([{ destination: SecretSync.Railway, to: "failed" }]);+ expect(statusChangeCalls()).toEqual([{ destination: SecretSync.Railway, newStatus: "failed" }]);});test("does not count a sync that has never succeeded", async () => {@@ -184,7 +196,7 @@ describe("secret sync status change", () => {await runSync(1);await runSync(1);- expect(statusChangeCalls()).toEqual([{ destination: SecretSync.Railway, to: "healthy" }]);+ expect(statusChangeCalls()).toEqual([{ destination: SecretSync.Railway, newStatus: "healthy" }]);});test("does not flip to healthy when a healthy sync succeeds", async () => {@@ -212,10 +224,48 @@ describe("secret sync status change", () => {syncSecrets.mockRejectedValue(new Error("upstream 500"));const afterContention = createHarness({lastSyncedAt: contended.state.lastSyncedAt,- lastSyncMessage: contended.state.lastSyncMessage+ lastSyncMessage: contended.state.lastSyncMessage,+ lastSyncResult: contended.state.lastSyncResult});await expect(afterContention.runSync(ATTEMPTS)).rejects.toThrow();- expect(statusChangeCalls()).toEqual([{ destination: SecretSync.Railway, to: "failed" }]);+ expect(statusChangeCalls()).toEqual([{ destination: SecretSync.Railway, newStatus: "failed" }]);+ });++ test("keeps a provider failure through later lock contention, so its recovery is still counted", async () => {+ syncSecrets.mockRejectedValue(new Error("upstream 500"));+ const broken = createHarness(healthy);+ await expect(broken.runSync(ATTEMPTS)).rejects.toThrow();++ const contended = createHarness(+ { lastSyncedAt: broken.state.lastSyncedAt, lastSyncMessage: null, lastSyncResult: broken.state.lastSyncResult },+ { lockFails: true }+ );+ await contended.runSync(1, { failedToAcquireLockCount: REQUEUE_LIMIT });+ expect(contended.state.lastSyncResult).toBe("failed");++ syncSecrets.mockResolvedValue({} as never);+ const recovered = createHarness({+ lastSyncedAt: contended.state.lastSyncedAt,+ lastSyncMessage: contended.state.lastSyncMessage,+ lastSyncResult: contended.state.lastSyncResult+ });+ await recovered.runSync(1);++ expect(statusChangeCalls()).toEqual([+ { destination: SecretSync.Railway, newStatus: "failed" },+ { destination: SecretSync.Railway, newStatus: "healthy" }+ ]);+ });++ 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 });++ await expect(runSync(ATTEMPTS)).rejects.toThrow();+ await expect(runSync(ATTEMPTS)).rejects.toThrow();++ expect(state.lastSyncResult).toBe("failed");+ expect(statusChangeCalls()).toEqual([{ destination: SecretSync.Railway, newStatus: "failed" }]);});});diff --git a/backend/src/services/secret-sync/secret-sync-queue.ts b/backend/src/services/secret-sync/secret-sync-queue.tsindex 07959e5e7c..c30ad6636a 100644--- a/backend/src/services/secret-sync/secret-sync-queue.ts+++ b/backend/src/services/secret-sync/secret-sync-queue.ts@@ -90,20 +90,6 @@ const DEFAULT_SECRET_SYNC_RETRY_CONFIG = {backoff: { type: "exponential" as const, delay: 3000 }};-const LOCK_FAILURE_MESSAGE =- "Failed to run job. This typically happens when a sync is already in progress. Please try again.";--// syncStatus can't tell us how the previous run ended: every attempt overwrites it with Running first. lastSyncedAt-// is only written on success, and lastSyncMessage is cleared on success and set on a final failure, so together they-// hold the last finished result across retries. A lock-contention message says nothing about the destination.-const getLastSyncResult = ({- lastSyncedAt,- lastSyncMessage-}: Pick<TSecretSyncRaw, "lastSyncedAt" | "lastSyncMessage">): "succeeded" | "failed" | null => {- if (lastSyncMessage && lastSyncMessage !== LOCK_FAILURE_MESSAGE) return "failed";- return lastSyncedAt ? "succeeded" : null;-};-export type TSecretSyncQueueFactory = ReturnType<typeof secretSyncQueueFactory>;type TSecretSyncQueueFactoryDep = {@@ -655,19 +641,34 @@ export const secretSyncQueueFactory = ({});if (isSynced || isFinalAttempt) {+ // lastSyncResult is written only here, so lock and admission failures cannot overwrite the provider's result.+ // The conditional update makes only the run that actually changes it report the change, whatever state this+ // job loaded before taking the lock. A sync that never succeeded (null) failing is a new misconfiguration, not+ // a breakage, so it is not counted.+ const isStatusChange =+ (+ await secretSyncDAL.update(+ {+ id: secretSync.id,+ lastSyncResult: isSynced ? SecretSyncStatus.Failed : SecretSyncStatus.Succeeded+ },+ { lastSyncResult: syncStatus }+ )+ ).length > 0;+const updatedSecretSync = await secretSyncDAL.updateById(secretSync.id, {syncStatus,lastSyncJobId: job.id,lastSyncMessage: syncMessage,- lastSyncedAt: isSynced ? ranAt : undefined+ lastSyncedAt: isSynced ? ranAt : undefined,+ lastSyncResult: syncStatus});- const lastSyncResult = getLastSyncResult(secretSync);- if (isSynced && lastSyncResult === "failed") {- recordSecretSyncStatusChangeMetric({ destination: secretSync.destination, to: "healthy" });- } else if (!isSynced && lastSyncResult === "succeeded") {- // A sync that has never succeeded is a new misconfiguration, not a breakage, so it is not counted.- recordSecretSyncStatusChangeMetric({ destination: secretSync.destination, to: "failed" });+ if (isStatusChange) {+ recordSecretSyncStatusChangeMetric({+ destination: secretSync.destination,+ newStatus: isSynced ? "healthy" : "failed"+ });}if (!isSynced) {@@ -1135,7 +1136,8 @@ export const secretSyncQueueFactory = ({const secretSync = await secretSyncDAL.updateById(syncId, {syncStatus: SecretSyncStatus.Failed,- lastSyncMessage: LOCK_FAILURE_MESSAGE,+ lastSyncMessage:+ "Failed to run job. This typically happens when a sync is already in progress. Please try again.",lastSyncJobId: job.id});@@ -1158,7 +1160,8 @@ export const secretSyncQueueFactory = ({case QueueJobs.SecretSyncImportSecrets: {const secretSync = await secretSyncDAL.updateById(syncId, {importStatus: SecretSyncStatus.Failed,- lastImportMessage: LOCK_FAILURE_MESSAGE,+ lastImportMessage:+ "Failed to run job. This typically happens when a sync is already in progress. Please try again.",lastImportJobId: job.id});@@ -1180,7 +1183,8 @@ export const secretSyncQueueFactory = ({case QueueJobs.SecretSyncRemoveSecrets: {const secretSync = await secretSyncDAL.updateById(syncId, {removeStatus: SecretSyncStatus.Failed,- lastRemoveMessage: LOCK_FAILURE_MESSAGE,+ lastRemoveMessage:+ "Failed to run job. This typically happens when a sync is already in progress. Please try again.",lastRemoveJobId: job.id});