Skip to content

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

fix(acme): stop waiting for DNS record locks once the order times out

bernie-g077ffcc589be
diff --git a/backend/src/services/certificate-authority/acme/acme-certificate-authority-fns.ts b/backend/src/services/certificate-authority/acme/acme-certificate-authority-fns.ts
index 11424e18b4..b406563bc0 100644
--- a/backend/src/services/certificate-authority/acme/acme-certificate-authority-fns.ts
+++ b/backend/src/services/certificate-authority/acme/acme-certificate-authority-fns.ts
@@ -523,7 +523,8 @@ export const executeAcmeOrder = async (
acmeCa.configuration.dnsProviderConfig.hostedZoneId,
recordName,
recordValue,
- keyStore
+ keyStore,
+ abortSignal
);
break;
}
diff --git a/backend/src/services/certificate-authority/acme/dns-providers/dns-record-lock.ts b/backend/src/services/certificate-authority/acme/dns-providers/dns-record-lock.ts
index ad7701c7ec..bd67721eae 100644
--- a/backend/src/services/certificate-authority/acme/dns-providers/dns-record-lock.ts
+++ b/backend/src/services/certificate-authority/acme/dns-providers/dns-record-lock.ts
@@ -1,18 +1,17 @@
import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";
+import { delay } from "@app/lib/delay";
import { logger } from "@app/lib/logger";
-const RECORD_LOCK_RETRY_DELAY_MS = 2_000;
-const RECORD_LOCK_MIN_RETRY_COUNT = 50;
+import { throwIfAcmeOrderAborted } from "../acme-certificate-authority-errors";
-// a waiter must outlast the holder's lock TTL, or it gives up while the holder is still within bounds
-const getLockRetrySettings = (lockTtlMs: number) => ({
- retryCount: Math.max(RECORD_LOCK_MIN_RETRY_COUNT, Math.ceil(lockTtlMs / RECORD_LOCK_RETRY_DELAY_MS)),
- retryDelay: RECORD_LOCK_RETRY_DELAY_MS,
- retryJitter: 300
-});
+const RECORD_LOCK_RETRY_DELAY_MS = 2_000;
+const RECORD_LOCK_RETRY_JITTER_MS = 300;
+const RECORD_LOCK_MIN_ATTEMPTS = 50;
export type TDnsRecordLockKeyStore = Pick<TKeyStoreFactory, "acquireLock">;
+type TRecordLock = Awaited<ReturnType<TDnsRecordLockKeyStore["acquireLock"]>>;
+
const pendingRecordOperations = new Map<string, Promise<void>>();
const withLocalRecordLock = async <T>(key: string, operation: () => Promise<T>): Promise<T> => {
@@ -31,27 +30,57 @@ const withLocalRecordLock = async <T>(key: string, operation: () => Promise<T>):
return result;
};
+// polls one attempt at a time so an aborted order stops waiting instead of taking the lock later
+const acquireRecordLock = async (
+ keyStore: TDnsRecordLockKeyStore,
+ resource: string,
+ lockTtlMs: number,
+ abortSignal?: AbortSignal
+): Promise<TRecordLock | null> => {
+ const maxAttempts = Math.max(RECORD_LOCK_MIN_ATTEMPTS, Math.ceil(lockTtlMs / RECORD_LOCK_RETRY_DELAY_MS) + 1);
+
+ for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
+ throwIfAcmeOrderAborted(abortSignal);
+ // eslint-disable-next-line no-await-in-loop
+ const lock = await keyStore.acquireLock([resource], lockTtlMs, { retryCount: 0 }).catch(() => null);
+ if (lock) return lock;
+ if (attempt < maxAttempts) {
+ // eslint-disable-next-line no-await-in-loop
+ await delay(RECORD_LOCK_RETRY_DELAY_MS + Math.floor(Math.random() * RECORD_LOCK_RETRY_JITTER_MS));
+ }
+ }
+ return null;
+};
+
export const withDnsRecordLock = async <T>(
{
connectionId,
zoneId,
name,
providerName,
- lockTtlMs
- }: { connectionId: string; zoneId: string; name: string; providerName: string; lockTtlMs: number },
+ lockTtlMs,
+ abortSignal
+ }: {
+ connectionId: string;
+ zoneId: string;
+ name: string;
+ providerName: string;
+ lockTtlMs: number;
+ abortSignal?: AbortSignal;
+ },
keyStore: TDnsRecordLockKeyStore | undefined,
operation: () => Promise<T>
): Promise<T> =>
withLocalRecordLock(`${connectionId}|${zoneId}|${name}`, async () => {
+ throwIfAcmeOrderAborted(abortSignal);
if (!keyStore) return operation();
- const lock = await keyStore
- .acquireLock(
- [KeyStorePrefixes.AcmeDnsRecordLock(connectionId, zoneId, name)],
- lockTtlMs,
- getLockRetrySettings(lockTtlMs)
- )
- .catch(() => null);
+ const lock = await acquireRecordLock(
+ keyStore,
+ KeyStorePrefixes.AcmeDnsRecordLock(connectionId, zoneId, name),
+ lockTtlMs,
+ abortSignal
+ );
if (!lock) {
throw new Error(
@@ -60,6 +89,7 @@ export const withDnsRecordLock = async <T>(
}
try {
+ throwIfAcmeOrderAborted(abortSignal);
return await operation();
} finally {
await lock.release().catch((error) => {
diff --git a/backend/src/services/certificate-authority/acme/dns-providers/gcp-cloud-dns.test.ts b/backend/src/services/certificate-authority/acme/dns-providers/gcp-cloud-dns.test.ts
index d0ec3cee14..fcb7dd62d8 100644
--- a/backend/src/services/certificate-authority/acme/dns-providers/gcp-cloud-dns.test.ts
+++ b/backend/src/services/certificate-authority/acme/dns-providers/gcp-cloud-dns.test.ts
@@ -117,12 +117,6 @@ describe("gcpCloudDnsInsertTxtRecord", () => {
expect.any(Number),
expect.anything()
);
- const [, lockTtlMs, retry] = acquireLock.mock.calls[0] as [
- string[],
- number,
- { retryCount: number; retryDelay: number }
- ];
- expect(retry.retryCount * retry.retryDelay).toBeGreaterThanOrEqual(lockTtlMs);
expect(postMock).toHaveBeenCalledTimes(1);
expect(release).toHaveBeenCalledTimes(1);
});
@@ -139,6 +133,45 @@ describe("gcpCloudDnsInsertTxtRecord", () => {
expect(postMock).not.toHaveBeenCalled();
});
+ it("keeps trying for at least as long as the holder's lock can live", async () => {
+ const acquireLock = vi.fn().mockRejectedValue(new Error("lock busy"));
+
+ await expect(
+ gcpCloudDnsInsertTxtRecord(connection, ZONE, RECORD, '"token-a"', {
+ acquireLock
+ } as unknown as TDnsRecordLockKeyStore)
+ ).rejects.toThrow("Another certificate order is still using it.");
+
+ const lockTtlMs = acquireLock.mock.calls[0][1] as number;
+ expect(acquireLock.mock.calls.length * 2_000).toBeGreaterThanOrEqual(lockTtlMs);
+ });
+
+ it("stops waiting for the lock once the order is aborted", async () => {
+ const controller = new AbortController();
+ const release = vi.fn().mockResolvedValue(undefined);
+ const acquireLock = vi
+ .fn()
+ .mockImplementationOnce(() => {
+ controller.abort();
+ return Promise.reject(new Error("lock busy"));
+ })
+ .mockResolvedValue({ release });
+
+ await expect(
+ gcpCloudDnsInsertTxtRecord(
+ connection,
+ ZONE,
+ RECORD,
+ '"token-a"',
+ { acquireLock } as unknown as TDnsRecordLockKeyStore,
+ controller.signal
+ )
+ ).rejects.toThrow("ACME order aborted after timeout");
+ expect(acquireLock).toHaveBeenCalledTimes(1);
+ expect(getMock).not.toHaveBeenCalled();
+ expect(postMock).not.toHaveBeenCalled();
+ });
+
it("serializes concurrent updates to the same record in one process", async () => {
let releaseFirstRead: (value: unknown) => void = () => {};
getMock
diff --git a/backend/src/services/certificate-authority/acme/dns-providers/gcp-cloud-dns.ts b/backend/src/services/certificate-authority/acme/dns-providers/gcp-cloud-dns.ts
index d28d45622a..627a2d7c03 100644
--- a/backend/src/services/certificate-authority/acme/dns-providers/gcp-cloud-dns.ts
+++ b/backend/src/services/certificate-authority/acme/dns-providers/gcp-cloud-dns.ts
@@ -134,7 +134,8 @@ const applyTxtRecordChange = async (
hostedZoneId: string,
recordName: string,
buildChange: TBuildChange,
- keyStore?: TDnsRecordLockKeyStore
+ keyStore?: TDnsRecordLockKeyStore,
+ abortSignal?: AbortSignal
) => {
const zoneUrl = getZoneUrl(hostedZoneId);
const fqdn = toFqdn(recordName);
@@ -145,7 +146,8 @@ const applyTxtRecordChange = async (
zoneId: hostedZoneId,
name: fqdn,
providerName: "Google Cloud DNS",
- lockTtlMs: RECORD_LOCK_TTL_MS
+ lockTtlMs: RECORD_LOCK_TTL_MS,
+ abortSignal
},
keyStore,
() => submitWithRetry(connection, hostedZoneId, zoneUrl, fqdn, buildChange)
@@ -157,7 +159,8 @@ export const gcpCloudDnsInsertTxtRecord = async (
hostedZoneId: string,
recordName: string,
value: string,
- keyStore?: TDnsRecordLockKeyStore
+ keyStore?: TDnsRecordLockKeyStore,
+ abortSignal?: AbortSignal
) => {
await applyTxtRecordChange(
connection,
@@ -177,7 +180,8 @@ export const gcpCloudDnsInsertTxtRecord = async (
additions: [{ ...existing, rrdatas: [...existing.rrdatas, value] }]
};
},
- keyStore
+ keyStore,
+ abortSignal
);
};