Skip to content

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

fix(secret-value-tracking): reach every project when a chunk resumes

Calvin87132fa88ee0
diff --git a/backend/src/queue/queue-service.ts b/backend/src/queue/queue-service.ts
index 95e833212f..8f427254f3 100644
--- a/backend/src/queue/queue-service.ts
+++ b/backend/src/queue/queue-service.ts
@@ -622,8 +622,7 @@ export type TQueueJobTypes = {
};
[QueueName.SecretBlindIndexMigration]: {
name: QueueJobs.SecretBlindIndexMigration;
- // `scope` is absent on jobs queued before the org-wide walk shipped, and the handler reads those
- // as project scope so a deploy does not strand them.
+ // `scope` is absent on jobs queued before the org-wide walk shipped.
payload: { scope: "org"; orgId: string } | { scope: "project"; projectId: string } | { projectId: string };
};
[QueueName.UsageEvent]: {
diff --git a/backend/src/services/secret-value-tracking/secret-value-tracking-fns.test.ts b/backend/src/services/secret-value-tracking/secret-value-tracking-fns.test.ts
index 5d503bee62..90dc34bd8e 100644
--- a/backend/src/services/secret-value-tracking/secret-value-tracking-fns.test.ts
+++ b/backend/src/services/secret-value-tracking/secret-value-tracking-fns.test.ts
@@ -1,6 +1,6 @@
import { JobState } from "@app/queue/queue-service";
-import { advanceCursor, needsBackfill, resolveRunStatus } from "./secret-value-tracking-fns";
+import { advanceCursor, isUsableRunState, needsBackfill, resolveRunStatus } from "./secret-value-tracking-fns";
import { TBackfillRunState } from "./secret-value-tracking-types";
const PROJECTS = ["p1", "p2"];
@@ -84,16 +84,30 @@ describe("advanceCursor", () => {
).toEqual({ done: false, cursor: { projectId: "p1", folderId: "f2", key: "", id: "" }, completedProjectId: null });
});
- test("a cursor on a deleted folder resumes at the next folder of that project", () => {
+ // Folder ids are sorted, so resuming past the deleted one keeps the walk moving forward instead of
+ // re-reading everything the run already covered in that project.
+ test("a cursor on a deleted folder resumes at the next folder after it, not at the first", () => {
expect(
advanceCursor({
- cursor: { projectId: "p1", folderId: "gone", key: "M", id: "s5" },
+ cursor: { projectId: "p1", folderId: "f1a", key: "M", id: "s5" },
projectIds: PROJECTS,
folderIdsByProject: FOLDERS,
lastRow: null,
folderExhausted: false
})
- ).toEqual({ done: false, cursor: { projectId: "p1", folderId: "f1", key: "", id: "" }, completedProjectId: null });
+ ).toEqual({ done: false, cursor: { projectId: "p1", folderId: "f2", key: "", id: "" }, completedProjectId: null });
+ });
+
+ test("a cursor on a deleted folder past the project's last one moves to the next project", () => {
+ expect(
+ advanceCursor({
+ cursor: { projectId: "p1", folderId: "zz-gone", key: "M", id: "s5" },
+ projectIds: PROJECTS,
+ folderIdsByProject: FOLDERS,
+ lastRow: null,
+ folderExhausted: false
+ })
+ ).toEqual({ done: false, cursor: { projectId: "p2", folderId: "f3", key: "", id: "" }, completedProjectId: "p1" });
});
test("a cursor on a deleted project resumes at the next project", () => {
@@ -205,3 +219,21 @@ describe("resolveRunStatus", () => {
expect(resolveRunStatus({ ...running(""), lastProgressAt: "not-a-date" }, false, NOW).status).toBe(JobState.Failed);
});
});
+
+describe("run state shape validation", () => {
+ test("a payload with non-numeric counters is rejected rather than yielding NaN", () => {
+ // The status endpoint's response schema rejects NaN, so a payload like this would turn the one
+ // endpoint whose job is to degrade gracefully into a 500.
+ expect(isUsableRunState({ status: "running", lastProgressAt: NOW.toISOString(), projectsDone: "many" })).toBe(
+ false
+ );
+ });
+
+ test("a well formed payload is usable", () => {
+ expect(isUsableRunState(running(minutesAgo(1)))).toBe(true);
+ });
+
+ test("a payload missing its timestamp is rejected", () => {
+ expect(isUsableRunState({ status: "running", projectsTotal: 1, projectsDone: 0, secretsProcessed: 0 })).toBe(false);
+ });
+});
diff --git a/backend/src/services/secret-value-tracking/secret-value-tracking-fns.ts b/backend/src/services/secret-value-tracking/secret-value-tracking-fns.ts
index 446840c609..397292e7d0 100644
--- a/backend/src/services/secret-value-tracking/secret-value-tracking-fns.ts
+++ b/backend/src/services/secret-value-tracking/secret-value-tracking-fns.ts
@@ -55,13 +55,20 @@ export const advanceCursor = ({
const folderIds = folderIdsByProject[cursor.projectId] ?? [];
const folderIndex = folderIds.indexOf(cursor.folderId);
+ // The cursor's folder is gone. Folder ids are sorted, so resuming at the first one past it keeps
+ // the walk moving forward rather than re-reading everything this project already covered.
if (folderIndex === -1) {
- if (folderIds.length) {
- return { done: false, cursor: startOfFolder(cursor.projectId, folderIds[0]), completedProjectId: null };
+ const nextFolderId = folderIds.find((folderId) => folderId > cursor.folderId);
+ if (nextFolderId) {
+ return { done: false, cursor: startOfFolder(cursor.projectId, nextFolderId), completedProjectId: null };
}
const next = firstProjectWithFolders(projectIds, folderIdsByProject, projectIndex + 1);
if (!next) return { done: true };
- return { done: false, cursor: startOfFolder(next.projectId, next.folderId), completedProjectId: null };
+ return {
+ done: false,
+ cursor: startOfFolder(next.projectId, next.folderId),
+ completedProjectId: folderIds.length ? cursor.projectId : null
+ };
}
if (!folderExhausted && lastRow) {
@@ -112,3 +119,17 @@ export const resolveRunStatus = (
return { status: JobState.Pending };
};
+
+// The status endpoint answers from this, so a payload it cannot use has to read as "no run in
+// progress" rather than reach the response schema. The counters matter as much as the timestamp:
+// a non-numeric one becomes NaN, which `z.number()` rejects, turning a graceful degrade into a 500.
+export const isUsableRunState = (value: unknown): value is TBackfillRunState => {
+ const state = value as Partial<TBackfillRunState> | null;
+ if (!state || typeof state !== "object") return false;
+ if (state.status !== "running" && state.status !== "failed") return false;
+ if (typeof state.lastProgressAt !== "string") return false;
+
+ return (["projectsTotal", "projectsDone", "secretsProcessed"] as const).every((field) =>
+ Number.isFinite(state[field])
+ );
+};
diff --git a/backend/src/services/secret-value-tracking/secret-value-tracking-queue.test.ts b/backend/src/services/secret-value-tracking/secret-value-tracking-queue.test.ts
new file mode 100644
index 0000000000..f9758d811f
--- /dev/null
+++ b/backend/src/services/secret-value-tracking/secret-value-tracking-queue.test.ts
@@ -0,0 +1,224 @@
+import { KeyStorePrefixes } from "@app/keystore/keystore";
+import { initLogger } from "@app/lib/logger";
+
+import { secretValueTrackingQueueFactory } from "./secret-value-tracking-queue";
+import { TBackfillRunState } from "./secret-value-tracking-types";
+
+const ORG_ID = "org-1";
+
+type TFakeSecret = { id: string; key: string; folderId: string; hasOrgDigest: boolean };
+
+// Drives the real job handler over in-memory fakes. The e2e suite cannot reach this layer: it runs
+// one project whose secrets fit in a single chunk, so every bug that only shows on a resumed chunk
+// or at a project boundary is invisible to it.
+const makeHarness = ({
+ projectIds,
+ foldersByProject,
+ secrets = []
+}: {
+ projectIds: string[];
+ foldersByProject: Record<string, string[]>;
+ secrets?: TFakeSecret[];
+}) => {
+ const store = new Map<string, string>();
+ const queued: { payload: unknown; opts: Record<string, unknown> }[] = [];
+ const flaggedProjects: string[] = [];
+ const flaggedOrgs: string[] = [];
+ const folderReads: string[] = [];
+ let rows = [...secrets];
+ let handler: (job: { data: unknown }) => Promise<void> = async () => {};
+
+ const keyStore = {
+ getItemPrimary: async (key: string) => store.get(key) ?? null,
+ setItemWithExpiry: async (key: string, _ttl: number | string, value: string | number | Buffer) => {
+ store.set(key, String(value));
+ return "OK" as const;
+ },
+ setItemWithExpiryNX: async (key: string, _ttl: number | string, value: string | number | Buffer) => {
+ if (store.has(key)) return null;
+ store.set(key, String(value));
+ return "OK" as const;
+ },
+ deleteItem: async (key: string) => {
+ store.delete(key);
+ return 1;
+ },
+ deleteItems: async () => 0
+ };
+
+ const queueService = {
+ start: (_name: unknown, jobHandler: (job: { data: unknown }) => Promise<void>) => {
+ handler = jobHandler;
+ },
+ listen: () => {},
+ queue: async (_name: unknown, _job: unknown, payload: unknown, opts: Record<string, unknown>) => {
+ queued.push({ payload, opts });
+ }
+ };
+
+ const factory = secretValueTrackingQueueFactory({
+ queueService: queueService as never,
+ keyStore: keyStore as never,
+ projectDAL: {
+ find: async () => projectIds.map((id) => ({ id, orgId: ORG_ID })) as never,
+ findById: async (id: string) => ({ id, orgId: ORG_ID }) as never,
+ updateById: async (id: string) => {
+ flaggedProjects.push(id);
+ return {} as never;
+ }
+ } as never,
+ orgDAL: {
+ updateById: async (id: string) => {
+ flaggedOrgs.push(id);
+ return {} as never;
+ }
+ } as never,
+ folderDAL: {
+ findByProjectId: async (projectId: string) => {
+ folderReads.push(projectId);
+ return (foldersByProject[projectId] ?? []).map((id) => ({ id })) as never;
+ }
+ } as never,
+ secretV2BridgeDAL: {
+ findSecretsInFolderAfter: async (folderId: string, after: { key: string; id: string }, limit: number) =>
+ rows
+ .filter((row) => row.folderId === folderId)
+ .filter((row) => [row.key, row.id] > [after.key, after.id])
+ .sort((a, b) => (a.key === b.key ? a.id.localeCompare(b.id) : a.key.localeCompare(b.key)))
+ .slice(0, limit)
+ .map((row) => ({
+ id: row.id,
+ key: row.key,
+ encryptedValue: Buffer.from(row.id),
+ secretValueBlindIndex: "project-digest",
+ secretValueOrgBlindIndex: row.hasOrgDigest ? "org-digest" : null
+ })) as never,
+ batchSetBlindIndexes: async (updates: { id: string }[]) => {
+ const filled = new Set(updates.map((u) => u.id));
+ rows = rows.map((row) => (filled.has(row.id) ? { ...row, hasOrgDigest: true } : row));
+ }
+ } as never,
+ kmsService: {
+ createCipherPairWithDataKey: async () => ({
+ decryptor: ({ cipherTextBlob }: { cipherTextBlob: Buffer }) => cipherTextBlob,
+ generateSecretBlindIndex: async (value: Buffer) => `digest-${value.toString()}`
+ })
+ } as never
+ });
+
+ const stateKey = KeyStorePrefixes.SecretValueTrackingBackfill(ORG_ID);
+
+ return {
+ factory,
+ queued,
+ flaggedProjects,
+ flaggedOrgs,
+ folderReads,
+ rowsNow: () => rows,
+ setState: (state: TBackfillRunState) => store.set(stateKey, JSON.stringify(state)),
+ getState: () => {
+ const raw = store.get(stateKey);
+ return raw ? (JSON.parse(raw) as TBackfillRunState) : null;
+ },
+ runChunk: () => handler({ data: { scope: "org", orgId: ORG_ID } })
+ };
+};
+
+const runningState = (cursor: TBackfillRunState["cursor"]): TBackfillRunState => ({
+ status: "running",
+ cursor,
+ projectsTotal: 2,
+ projectsDone: 0,
+ secretsProcessed: 0,
+ lastProgressAt: new Date().toISOString()
+});
+
+describe("the backfill job", () => {
+ // The job logs its own lifecycle, and the unit environment boots no server to initialise it.
+ beforeAll(() => {
+ initLogger();
+ });
+
+ test("a chunk resuming inside one project still reaches the org's other projects", async () => {
+ const harness = makeHarness({
+ projectIds: ["p1", "p2"],
+ foldersByProject: { p1: ["f1"], p2: ["f2"] },
+ secrets: [
+ { id: "s1", key: "A", folderId: "f1", hasOrgDigest: true },
+ { id: "s2", key: "B", folderId: "f2", hasOrgDigest: false }
+ ]
+ });
+
+ // A resumed chunk: the cursor is already inside p1, exactly as the previous chunk left it.
+ harness.setState(runningState({ projectId: "p1", folderId: "f1", key: "A", id: "s1" }));
+
+ await harness.runChunk();
+
+ // The bug this pins: the resumed chunk saw only p1's folders, read every later project as
+ // empty, stopped at the p1 boundary and flagged the org complete with s2 still unindexed.
+ expect(harness.rowsNow().find((row) => row.id === "s2")?.hasOrgDigest).toBe(true);
+ expect(harness.flaggedProjects).toEqual(["p1", "p2"]);
+ // Both projects really are done here, so flagging the org is right.
+ expect(harness.flaggedOrgs).toEqual([ORG_ID]);
+ });
+
+ test("a cursor on a project deleted since the last chunk carries on with the rest", async () => {
+ const harness = makeHarness({
+ projectIds: ["p1", "p2"],
+ foldersByProject: { p1: ["f1"], p2: ["f2"] },
+ secrets: [{ id: "s2", key: "B", folderId: "f2", hasOrgDigest: false }]
+ });
+
+ harness.setState(runningState({ projectId: "gone", folderId: "gone-folder", key: "", id: "" }));
+
+ await harness.runChunk();
+
+ expect(harness.flaggedProjects).not.toContain("gone");
+ expect(harness.rowsNow().find((row) => row.id === "s2")?.hasOrgDigest).toBe(true);
+ });
+
+ test("a project's folders are only read when the walk reaches it", async () => {
+ const harness = makeHarness({
+ projectIds: ["p1", "p2", "p3"],
+ foldersByProject: { p1: ["f1"], p2: ["f2"], p3: ["f3"] },
+ secrets: [{ id: "s1", key: "A", folderId: "f1", hasOrgDigest: false }]
+ });
+
+ harness.setState(runningState({ projectId: "p1", folderId: "f1", key: "", id: "" }));
+ await harness.runChunk();
+
+ // Every project is reached in this run, but each is read once rather than all up front.
+ expect(harness.folderReads.filter((id) => id === "p1")).toHaveLength(1);
+ });
+
+ test("a run over many empty folders checkpoints instead of querying without bound", async () => {
+ const folders = Array.from({ length: 5000 }, (_, i) => `empty-${i}`);
+ const harness = makeHarness({
+ projectIds: ["p1"],
+ foldersByProject: { p1: folders },
+ secrets: []
+ });
+
+ harness.setState(runningState(null));
+ await harness.runChunk();
+
+ // Empty folders read no rows, so a chunk bounded only on rows would walk all 5000 in one job.
+ expect(harness.queued).toHaveLength(1);
+ expect(harness.getState()?.cursor).not.toBeNull();
+ // Work remains, so nothing may claim the org is searchable yet.
+ expect(harness.flaggedOrgs).toEqual([]);
+ });
+
+ test("a queued chunk asks for retries so one transient failure does not kill the chain", async () => {
+ const harness = makeHarness({
+ projectIds: ["p1"],
+ foldersByProject: { p1: Array.from({ length: 5000 }, (_, i) => `empty-${i}`) },
+ secrets: []
+ });
+
+ harness.setState(runningState(null));
+ await harness.runChunk();
+
+ expect(harness.queued[0].opts.attempts).toBeGreaterThan(1);
+ });
+});
diff --git a/backend/src/services/secret-value-tracking/secret-value-tracking-queue.ts b/backend/src/services/secret-value-tracking/secret-value-tracking-queue.ts
index 7c24ae0e82..a1a8279f93 100644
--- a/backend/src/services/secret-value-tracking/secret-value-tracking-queue.ts
+++ b/backend/src/services/secret-value-tracking/secret-value-tracking-queue.ts
@@ -12,13 +12,20 @@ import { createOrgSecretBlindIndexer } from "../secret-v2-bridge/secret-blind-in
import { TSecretV2BridgeDALFactory } from "../secret-v2-bridge/secret-v2-bridge-dal";
import { advanceCursor, needsBackfill } from "./secret-value-tracking-fns";
import { secretValueTrackingStateFactory } from "./secret-value-tracking-state";
-import { TBackfillScope } from "./secret-value-tracking-types";
+import { TBackfillCursor, TBackfillScope } from "./secret-value-tracking-types";
// A chunk is many read batches rather than one, because the per-project data key is resolved once
// per chunk: on an org using external KMS that resolve is a network call, and a chunk per batch
// would pay it five times as often for nothing.
const CHUNK_SIZE = 5000;
const READ_BATCH_SIZE = 1000;
+// A folder that holds nothing still costs a query, so a chunk is bounded on steps as well as rows.
+// Without it a project of tens of thousands of empty folders runs unbounded inside one job.
+const MAX_STEPS_PER_CHUNK = 500;
+// Refreshes lastProgressAt inside a long chunk. Left to the end of the chunk, a slow one reads as
+// stalled and the enable guard lets a second chain take the same scope while this one is still
+// walking it.
+const HEARTBEAT_EVERY_STEPS = 50;
type TSecretValueTrackingQueueFactoryDep = {
queueService: TQueueServiceFactory;
@@ -33,8 +40,10 @@ type TSecretValueTrackingQueueFactoryDep = {
kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
};
-// Jobs queued before the org-wide walk shipped carry only a projectId, so a payload with no scope
-// is read as project scope and a deploy does not strand them.
+// A payload with no scope is one queued before the org-wide walk shipped. It is read as project
+// scope so the shape is understood, but such a job has no run state and the handler stops on that:
+// the old code kept no state, so there is no cursor to resume and nothing to safely assume. The
+// enable button simply comes back for the customer to press again.
const resolveScope = (data: { scope?: "org" | "project"; orgId?: string; projectId?: string }): TBackfillScope => {
if (data.scope === "org" && data.orgId) return { scope: "org", orgId: data.orgId };
return { scope: "project", projectId: data.projectId as string };
@@ -59,6 +68,10 @@ export const secretValueTrackingQueueFactory = ({
queueService.queue(QueueName.SecretBlindIndexMigration, QueueJobs.SecretBlindIndexMigration, scope, {
removeOnComplete: { age: 60 },
removeOnFail: { age: 24 * 3600 },
+ // Without retries one transient database or KMS blip ends the chain and the customer has to
+ // start the backfill again by hand.
+ attempts: 3,
+ backoff: { type: "exponential", delay: 5000 },
jobId: `secret-value-tracking-${scopeIdOf(scope)}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`
});
@@ -133,25 +146,53 @@ export const secretValueTrackingQueueFactory = ({
let { projectsDone } = runState;
let { secretsProcessed } = runState;
let readThisChunk = 0;
+ let steps = 0;
let done = false;
- // Seed the cursor for a run that has not started, and step it past anything deleted since the
- // last chunk, before reading a single row.
- const seedProjects = cursor ? [cursor.projectId] : projectIds;
- await Promise.all(seedProjects.map((projectId) => $foldersOf(projectId)));
- if (!cursor) {
- const seeded = advanceCursor({
- cursor: null,
- projectIds,
- folderIdsByProject: foldersByProject,
- lastRow: null,
- folderExhausted: false
+ const $writeProgress = async (at: TBackfillCursor | null) => {
+ await state.write(scopeId, {
+ status: "running",
+ cursor: at,
+ projectsTotal: runState.projectsTotal,
+ projectsDone,
+ secretsProcessed,
+ lastProgressAt: new Date().toISOString()
});
+ };
+
+ // advanceCursor only sees the projects whose folders are loaded, and reads an unloaded one as a
+ // project with none, so it would declare the walk finished at the first project boundary. Load
+ // the next unseeded project and ask again before accepting the end.
+ const $advance = async (
+ from: TBackfillCursor | null,
+ lastRow: { key: string; id: string } | null,
+ folderExhausted: boolean
+ ) => {
+ for (;;) {
+ const next = advanceCursor({
+ cursor: from,
+ projectIds,
+ folderIdsByProject: foldersByProject,
+ lastRow,
+ folderExhausted
+ });
+ if (!next.done) return next;
+
+ const unseeded = projectIds.find((projectId) => !(projectId in foldersByProject));
+ if (!unseeded) return next;
+ // eslint-disable-next-line no-await-in-loop
+ await $foldersOf(unseeded);
+ }
+ };
+
+ if (!cursor) {
+ const seeded = await $advance(null, null, false);
if (seeded.done) done = true;
else cursor = seeded.cursor;
}
- while (!done && cursor && readThisChunk < CHUNK_SIZE) {
+ while (!done && cursor && readThisChunk < CHUNK_SIZE && steps < MAX_STEPS_PER_CHUNK) {
+ steps += 1;
// eslint-disable-next-line no-await-in-loop
await $foldersOf(cursor.projectId);
@@ -184,20 +225,18 @@ export const secretValueTrackingQueueFactory = ({
}
const lastRow = rows.length ? { key: rows[rows.length - 1].key, id: rows[rows.length - 1].id } : null;
- const next = advanceCursor({
- cursor,
- projectIds,
- folderIdsByProject: foldersByProject,
- lastRow,
- folderExhausted: rows.length < READ_BATCH_SIZE
- });
+ // eslint-disable-next-line no-await-in-loop
+ const next = await $advance(cursor, lastRow, rows.length < READ_BATCH_SIZE);
if (next.done) {
// The walk ends inside the project it was working, so that project's own flag is set here
- // rather than from a completedProjectId the `done` branch never carries.
- // eslint-disable-next-line no-await-in-loop
- await $markProjectComplete(cursor.projectId);
- projectsDone += 1;
+ // rather than from a completedProjectId the `done` branch never carries. A cursor left on a
+ // project that has since been deleted is not a project to flag.
+ if (projectIds.includes(cursor.projectId)) {
+ // eslint-disable-next-line no-await-in-loop
+ await $markProjectComplete(cursor.projectId);
+ projectsDone += 1;
+ }
done = true;
break;
}
@@ -208,6 +247,11 @@ export const secretValueTrackingQueueFactory = ({
projectsDone += 1;
}
cursor = next.cursor;
+
+ if (steps % HEARTBEAT_EVERY_STEPS === 0) {
+ // eslint-disable-next-line no-await-in-loop
+ await $writeProgress(cursor);
+ }
}
if (done) {
@@ -219,14 +263,7 @@ export const secretValueTrackingQueueFactory = ({
return;
}
- await state.write(scopeId, {
- status: "running",
- cursor,
- projectsTotal: runState.projectsTotal,
- projectsDone,
- secretsProcessed,
- lastProgressAt: new Date().toISOString()
- });
+ await $writeProgress(cursor);
await queueChunk(scope);
};
diff --git a/backend/src/services/secret-value-tracking/secret-value-tracking-service.ts b/backend/src/services/secret-value-tracking/secret-value-tracking-service.ts
index de4b416b5d..ca87aaff89 100644
--- a/backend/src/services/secret-value-tracking/secret-value-tracking-service.ts
+++ b/backend/src/services/secret-value-tracking/secret-value-tracking-service.ts
@@ -70,7 +70,14 @@ export const secretValueTrackingServiceFactory = ({
});
}
- await secretValueTrackingQueue.startBackfill({ scope: "org", orgId: actor.orgId });
+ // Releasing the claim matters: without it a failed enqueue leaves the organization holding a
+ // claim it is not using, and the guard refuses every retry until the staleness window passes.
+ try {
+ await secretValueTrackingQueue.startBackfill({ scope: "org", orgId: actor.orgId });
+ } catch (error) {
+ await state.clear(actor.orgId);
+ throw error;
+ }
return { projectsTotal };
};
@@ -131,7 +138,12 @@ export const secretValueTrackingServiceFactory = ({
throw new BadRequestError({ message: "A secret value tracking backfill is already running for this project" });
}
- await secretValueTrackingQueue.startBackfill({ scope: "project", projectId: project.id });
+ try {
+ await secretValueTrackingQueue.startBackfill({ scope: "project", projectId: project.id });
+ } catch (error) {
+ await state.clear(project.id);
+ throw error;
+ }
};
const getProjectStatus = async (dto: TProjectPermission) => {
diff --git a/backend/src/services/secret-value-tracking/secret-value-tracking-state.ts b/backend/src/services/secret-value-tracking/secret-value-tracking-state.ts
index 1ddf04242c..e72699473d 100644
--- a/backend/src/services/secret-value-tracking/secret-value-tracking-state.ts
+++ b/backend/src/services/secret-value-tracking/secret-value-tracking-state.ts
@@ -1,7 +1,7 @@
import { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/keystore";
import { logger } from "@app/lib/logger";
-import { BACKFILL_STALE_AFTER_MS } from "./secret-value-tracking-fns";
+import { BACKFILL_STALE_AFTER_MS, isUsableRunState } from "./secret-value-tracking-fns";
import { TBackfillRunState } from "./secret-value-tracking-types";
type TSecretValueTrackingStateFactoryDep = {
@@ -16,11 +16,10 @@ export const secretValueTrackingStateFactory = ({ keyStore }: TSecretValueTracki
if (!raw) return null;
try {
- const parsed = JSON.parse(raw) as TBackfillRunState;
// An unreadable key means no run in progress, which the status endpoint can answer, rather
// than an exception it cannot.
- if (typeof parsed?.lastProgressAt !== "string" || typeof parsed?.status !== "string") return null;
- return parsed;
+ const parsed: unknown = JSON.parse(raw);
+ return isUsableRunState(parsed) ? parsed : null;
} catch (error) {
logger.warn(error, `Secret value tracking backfill state unreadable [scopeId=${scopeId}]`);
return null;