Skip to content

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

Merge remote-tracking branch 'origin/main' into bernie/pki-438-add-google-cloud-dns-as-provider-for-acme

bernie-g09fefbcd0a65
diff --cc backend/src/services/certificate-authority/acme/acme-certificate-authority-enums.ts
index 86bc5c2215,fb38ce1d12..5772753544
--- a/backend/src/services/certificate-authority/acme/acme-certificate-authority-enums.ts
+++ b/backend/src/services/certificate-authority/acme/acme-certificate-authority-enums.ts
@@@ -4,5 -4,5 +4,6 @@@ export enum AcmeDnsProvider
DNSMadeEasy = "dns-made-easy",
AzureDNS = "azure-dns",
PowerDns = "powerdns",
- GcpCloudDns = "gcp-cloud-dns"
++ GcpCloudDns = "gcp-cloud-dns",
+ UltraDNS = "ultradns"
}
diff --cc backend/src/services/certificate-authority/acme/acme-certificate-authority-fns.ts
index b406563bc0,7d87c02902..0b7b8db971
--- a/backend/src/services/certificate-authority/acme/acme-certificate-authority-fns.ts
+++ b/backend/src/services/certificate-authority/acme/acme-certificate-authority-fns.ts
@@@ -26,8 -27,8 +27,9 @@@ import { TAwsConnection } from "@app/se
import { TAzureDnsConnection } from "@app/services/app-connection/azure-dns/azure-dns-connection-types";
import { TCloudflareConnection } from "@app/services/app-connection/cloudflare/cloudflare-connection-types";
import { TDNSMadeEasyConnection } from "@app/services/app-connection/dns-made-easy/dns-made-easy-connection-types";
+import { TGcpConnection } from "@app/services/app-connection/gcp/gcp-connection-types";
import { TPowerDnsConnection } from "@app/services/app-connection/powerdns/powerdns-connection-types";
+ import { TUltraDNSConnection } from "@app/services/app-connection/ultradns/ultradns-connection-types";
import { TCertificateBodyDALFactory } from "@app/services/certificate/certificate-body-dal";
import { TCertificateDALFactory } from "@app/services/certificate/certificate-dal";
import {
@@@ -67,12 -68,8 +69,13 @@@ import
import { azureDnsDeleteTxtRecord, azureDnsInsertTxtRecord } from "./dns-providers/azure-dns";
import { cloudflareDeleteTxtRecord, cloudflareInsertTxtRecord } from "./dns-providers/cloudflare";
import { dnsMadeEasyDeleteTxtRecord, dnsMadeEasyInsertTxtRecord } from "./dns-providers/dns-made-easy";
+import {
+ gcpCloudDnsDeleteTxtRecord,
+ gcpCloudDnsInsertTxtRecord,
+ validateGcpCloudDnsZone
+} from "./dns-providers/gcp-cloud-dns";
import { powerDnsDeleteTxtRecord, powerDnsInsertTxtRecord, TPowerDnsProviderDeps } from "./dns-providers/powerdns";
+ import { ultraDNSDeleteTxtRecord, ultraDNSInsertTxtRecord } from "./dns-providers/ultradns";
const UNCHANGED_CREDENTIAL_SENTINEL = "__INFISICAL_UNCHANGED__";
@@@ -285,6 -282,24 +288,25 @@@ const waitForDnsPropagation = async
}
};
+ const ACME_DNS_PROVIDER_APP_CONNECTION_MAP: Record<AcmeDnsProvider, AppConnection> = {
+ [AcmeDnsProvider.Route53]: AppConnection.AWS,
+ [AcmeDnsProvider.Cloudflare]: AppConnection.Cloudflare,
+ [AcmeDnsProvider.DNSMadeEasy]: AppConnection.DNSMadeEasy,
+ [AcmeDnsProvider.AzureDNS]: AppConnection.AzureDNS,
+ [AcmeDnsProvider.PowerDns]: AppConnection.PowerDns,
++ [AcmeDnsProvider.GcpCloudDns]: AppConnection.GCP,
+ [AcmeDnsProvider.UltraDNS]: AppConnection.UltraDNS
+ };
+
+ const validateDnsProviderAppConnection = (provider: AcmeDnsProvider, dnsAppConnectionId: string, app: string) => {
+ const requiredApp = ACME_DNS_PROVIDER_APP_CONNECTION_MAP[provider];
+ if (app !== requiredApp) {
+ throw new BadRequestError({
+ message: `App connection with ID '${dnsAppConnectionId}' must be ${APP_CONNECTION_NAME_MAP[requiredApp]} for this DNS provider`
+ });
+ }
+ };
+
const getAcmeChallengeRecord = async (
provider: AcmeDnsProvider,
identifierValue: string,
@@@ -517,17 -532,16 +539,27 @@@ export const executeAcmeOrder = async
);
break;
}
+ case AcmeDnsProvider.GcpCloudDns: {
+ await gcpCloudDnsInsertTxtRecord(
+ connection as TGcpConnection,
+ acmeCa.configuration.dnsProviderConfig.hostedZoneId,
+ recordName,
+ recordValue,
+ keyStore,
+ abortSignal
+ );
+ break;
+ }
+ case AcmeDnsProvider.UltraDNS: {
+ await ultraDNSInsertTxtRecord(
+ connection as TUltraDNSConnection,
+ acmeCa.configuration.dnsProviderConfig.hostedZoneId,
+ recordName,
+ recordValue,
+ { keyStore }
+ );
+ break;
+ }
default: {
throw new Error(`Unsupported DNS provider: ${acmeCa.configuration.dnsProviderConfig.provider as string}`);
}
@@@ -598,16 -612,16 +630,26 @@@
);
break;
}
+ case AcmeDnsProvider.GcpCloudDns: {
+ await gcpCloudDnsDeleteTxtRecord(
+ connection as TGcpConnection,
+ acmeCa.configuration.dnsProviderConfig.hostedZoneId,
+ recordName,
+ recordValue,
+ keyStore
+ );
+ break;
+ }
+ case AcmeDnsProvider.UltraDNS: {
+ await ultraDNSDeleteTxtRecord(
+ connection as TUltraDNSConnection,
+ acmeCa.configuration.dnsProviderConfig.hostedZoneId,
+ recordName,
+ recordValue,
+ { keyStore }
+ );
+ break;
+ }
default: {
throw new Error(`Unsupported DNS provider: ${acmeCa.configuration.dnsProviderConfig.provider as string}`);
}
@@@ -754,46 -768,8 +796,12 @@@ export const AcmeCertificateAuthorityFn
throw new NotFoundError({ message: `App connection with ID '${dnsAppConnectionId}' not found` });
}
- if (dnsProviderConfig.provider === AcmeDnsProvider.Route53 && appConnection.app !== AppConnection.AWS) {
- throw new BadRequestError({
- message: `App connection with ID '${dnsAppConnectionId}' is not an AWS connection`
- });
- }
-
- if (dnsProviderConfig.provider === AcmeDnsProvider.Cloudflare && appConnection.app !== AppConnection.Cloudflare) {
- throw new BadRequestError({
- message: `App connection with ID '${dnsAppConnectionId}' is not a Cloudflare connection`
- });
- }
-
- if (dnsProviderConfig.provider === AcmeDnsProvider.DNSMadeEasy && appConnection.app !== AppConnection.DNSMadeEasy) {
- throw new BadRequestError({
- message: `App connection with ID '${dnsAppConnectionId}' is not a DNS Made Easy connection`
- });
- }
-
- if (dnsProviderConfig.provider === AcmeDnsProvider.AzureDNS && appConnection.app !== AppConnection.AzureDNS) {
- throw new BadRequestError({
- message: `App connection with ID '${dnsAppConnectionId}' is not an Azure DNS connection`
- });
- }
-
- if (dnsProviderConfig.provider === AcmeDnsProvider.PowerDns && appConnection.app !== AppConnection.PowerDns) {
- throw new BadRequestError({
- message: `App connection with ID '${dnsAppConnectionId}' is not a PowerDNS connection`
- });
- }
-
- if (dnsProviderConfig.provider === AcmeDnsProvider.GcpCloudDns && appConnection.app !== AppConnection.GCP) {
- throw new BadRequestError({
- message: `App connection with ID '${dnsAppConnectionId}' is not a GCP connection`
- });
- }
+ validateDnsProviderAppConnection(dnsProviderConfig.provider, dnsAppConnectionId, appConnection.app);
+ if (dnsProviderConfig.provider === AcmeDnsProvider.GcpCloudDns) {
+ validateGcpCloudDnsZone(dnsProviderConfig.hostedZoneId);
+ }
+
if (dnsResolver) {
validateDnsResolver(dnsResolver);
}
@@@ -878,52 -854,8 +886,12 @@@
throw new NotFoundError({ message: `App connection with ID '${dnsAppConnectionId}' not found` });
}
- if (dnsProviderConfig.provider === AcmeDnsProvider.Route53 && appConnection.app !== AppConnection.AWS) {
- throw new BadRequestError({
- message: `App connection with ID '${dnsAppConnectionId}' is not an AWS connection`
- });
- }
-
- if (
- dnsProviderConfig.provider === AcmeDnsProvider.Cloudflare &&
- appConnection.app !== AppConnection.Cloudflare
- ) {
- throw new BadRequestError({
- message: `App connection with ID '${dnsAppConnectionId}' is not a Cloudflare connection`
- });
- }
-
- if (
- dnsProviderConfig.provider === AcmeDnsProvider.DNSMadeEasy &&
- appConnection.app !== AppConnection.DNSMadeEasy
- ) {
- throw new BadRequestError({
- message: `App connection with ID '${dnsAppConnectionId}' is not a DNS Made Easy connection`
- });
- }
-
- if (dnsProviderConfig.provider === AcmeDnsProvider.AzureDNS && appConnection.app !== AppConnection.AzureDNS) {
- throw new BadRequestError({
- message: `App connection with ID '${dnsAppConnectionId}' is not an Azure DNS connection`
- });
- }
-
- if (dnsProviderConfig.provider === AcmeDnsProvider.PowerDns && appConnection.app !== AppConnection.PowerDns) {
- throw new BadRequestError({
- message: `App connection with ID '${dnsAppConnectionId}' is not a PowerDNS connection`
- });
- }
-
- if (dnsProviderConfig.provider === AcmeDnsProvider.GcpCloudDns && appConnection.app !== AppConnection.GCP) {
- throw new BadRequestError({
- message: `App connection with ID '${dnsAppConnectionId}' is not a GCP connection`
- });
- }
+ validateDnsProviderAppConnection(dnsProviderConfig.provider, dnsAppConnectionId, appConnection.app);
+ if (dnsProviderConfig.provider === AcmeDnsProvider.GcpCloudDns) {
+ validateGcpCloudDnsZone(dnsProviderConfig.hostedZoneId);
+ }
+
if (dnsResolver) {
validateDnsResolver(dnsResolver);
}
diff --cc backend/src/services/certificate-authority/acme/dns-providers/dns-record-lock.ts
index bd67721eae,4f4d8497ee..fbd3c5b981
--- 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,99 -1,39 +1,76 @@@
import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";
+import { delay } from "@app/lib/delay";
import { logger } from "@app/lib/logger";
+import { throwIfAcmeOrderAborted } from "../acme-certificate-authority-errors";
+
- const RECORD_LOCK_RETRY_DELAY_MS = 2_000;
- const RECORD_LOCK_RETRY_JITTER_MS = 300;
- const RECORD_LOCK_MIN_ATTEMPTS = 50;
+ const DNS_RECORD_LOCK_RETRY_DELAY_MS = 2_000;
+ const DNS_RECORD_LOCK_RETRY_JITTER_MS = 300;
+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> => {
- const pending = pendingRecordOperations.get(key) ?? Promise.resolve();
- const result = pending.then(operation, operation);
- const settled = result.then(
- () => undefined,
- () => undefined
- );
-
- pendingRecordOperations.set(key, settled);
- void settled.then(() => {
- if (pendingRecordOperations.get(key) === settled) pendingRecordOperations.delete(key);
- });
-
- return result;
- };
++type TDnsRecordLock = Awaited<ReturnType<TDnsRecordLockKeyStore["acquireLock"]>>;
+
+// polls one attempt at a time so an aborted order stops waiting instead of taking the lock later
- const acquireRecordLock = async (
++const acquireDnsRecordLock = 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);
++): Promise<TDnsRecordLock | null> => {
++ const maxAttempts = Math.ceil(lockTtlMs / DNS_RECORD_LOCK_RETRY_DELAY_MS) + 6;
+
+ 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));
++ await delay(DNS_RECORD_LOCK_RETRY_DELAY_MS + Math.floor(Math.random() * DNS_RECORD_LOCK_RETRY_JITTER_MS));
+ }
+ }
+ return null;
+};
+
export const withDnsRecordLock = async <T>(
{
+ providerName,
connectionId,
zoneId,
name,
- providerName,
- lockTtlMs
- }: { providerName: string; connectionId: string; zoneId: string; name: string; lockTtlMs: number },
- keyStore: Pick<TKeyStoreFactory, "acquireLock">,
+ lockTtlMs,
+ abortSignal
+ }: {
++ providerName: string;
+ connectionId: string;
+ zoneId: string;
+ name: string;
- providerName: string;
+ lockTtlMs: number;
+ abortSignal?: AbortSignal;
+ },
- keyStore: TDnsRecordLockKeyStore | undefined,
++ keyStore: TDnsRecordLockKeyStore,
operation: () => Promise<T>
- ): Promise<T> =>
- withLocalRecordLock(`${connectionId}|${zoneId}|${name}`, async () => {
- throwIfAcmeOrderAborted(abortSignal);
- if (!keyStore) return operation();
+ ): Promise<T> => {
- const lock = await keyStore
- .acquireLock([KeyStorePrefixes.AcmeDnsRecordLock(connectionId, zoneId, name)], lockTtlMs, {
- retryCount: Math.ceil(lockTtlMs / DNS_RECORD_LOCK_RETRY_DELAY_MS) + 5,
- retryDelay: DNS_RECORD_LOCK_RETRY_DELAY_MS,
- retryJitter: DNS_RECORD_LOCK_RETRY_JITTER_MS
- })
- .catch(() => null);
++ const lock = await acquireDnsRecordLock(
++ keyStore,
++ KeyStorePrefixes.AcmeDnsRecordLock(connectionId, zoneId, name),
++ lockTtlMs,
++ abortSignal
++ );
- const lock = await acquireRecordLock(
- keyStore,
- KeyStorePrefixes.AcmeDnsRecordLock(connectionId, zoneId, name),
- lockTtlMs,
- abortSignal
+ if (!lock) {
+ throw new Error(
+ `Timed out waiting to update the ${providerName} record '${name}'. Another certificate order is still using it.`
);
+ }
- if (!lock) {
- throw new Error(
- `Timed out waiting to update the ${providerName} record '${name}'. Another certificate order is still using it.`
- );
- }
-
- try {
- throwIfAcmeOrderAborted(abortSignal);
- return await operation();
- } finally {
- await lock.release().catch((error) => {
- logger.warn(error, `Failed to release ${providerName} record lock [zoneId=${zoneId}] [name=${name}]`);
- });
- }
- });
+ try {
++ throwIfAcmeOrderAborted(abortSignal);
+ return await operation();
+ } finally {
+ await lock.release().catch((error) => {
+ logger.warn(error, `Failed to release ${providerName} record lock [zoneId=${zoneId}] [name=${name}]`);
+ });
+ }
+ };
diff --cc backend/src/services/certificate-authority/acme/dns-providers/gcp-cloud-dns.test.ts
index fcb7dd62d8,0000000000..deaeafd29b
mode 100644,000000..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
@@@ -1,359 -1,0 +1,331 @@@
+import { AxiosError, AxiosHeaders } from "axios";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { TGcpConnection } from "@app/services/app-connection/gcp/gcp-connection-types";
+
+const { getMock, postMock } = vi.hoisted(() => ({
+ getMock: vi.fn<(url: string, config?: unknown) => Promise<unknown>>(),
+ postMock: vi.fn<(url: string, body?: unknown, config?: unknown) => Promise<unknown>>()
+}));
+
+vi.mock("@app/lib/config/request", () => ({
+ request: { get: getMock, post: postMock }
+}));
+vi.mock("@app/services/app-connection/gcp/gcp-connection-fns", () => ({
+ getGcpConnectionAuthToken: vi.fn().mockResolvedValue("gcp-token")
+}));
+vi.mock("@app/lib/delay", () => ({ delay: vi.fn().mockResolvedValue(undefined) }));
+vi.mock("@app/lib/logger", () => ({
+ logger: { error: vi.fn(), info: vi.fn(), warn: vi.fn(), debug: vi.fn() }
+}));
+
+// eslint-disable-next-line import/first
+import { TDnsRecordLockKeyStore } from "./dns-record-lock";
+// eslint-disable-next-line import/first
+import { gcpCloudDnsDeleteTxtRecord, gcpCloudDnsInsertTxtRecord, validateGcpCloudDnsZone } from "./gcp-cloud-dns";
+
+const connection = { id: "connection-id" } as TGcpConnection;
++const keyStore = {
++ acquireLock: vi.fn().mockResolvedValue({ release: vi.fn().mockResolvedValue(undefined) })
++} as unknown as TDnsRecordLockKeyStore;
+const ZONE = "projects/my-project/managedZones/example-zone";
+const ZONE_URL = `https://dns.googleapis.com/dns/v1/${ZONE}`;
+const RECORD = "_acme-challenge.example.com";
+const FQDN = `${RECORD}.`;
+
+const axiosError = (status: number, message = `status ${status}`, extra: Record<string, unknown> = {}) =>
+ new AxiosError("request failed", String(status), undefined, undefined, {
+ status,
+ statusText: "",
+ headers: {},
+ config: { headers: new AxiosHeaders() },
+ data: { error: { message, ...extra } }
+ });
+
+const existingRecordSet = (rrdatas: string[], ttl = 60) => ({ data: { name: FQDN, type: "TXT", ttl, rrdatas } });
+
+describe("validateGcpCloudDnsZone", () => {
+ it("accepts a managed zone resource name", () => {
+ expect(() => validateGcpCloudDnsZone(ZONE)).not.toThrow();
+ });
+
+ it.each(["example-zone", "projects/my-project/managedZones/", "projects/My_Project/managedZones/zone", `${ZONE}/x`])(
+ "rejects %s",
+ (value) => {
+ expect(() => validateGcpCloudDnsZone(value)).toThrow(/Invalid Google Cloud DNS zone/);
+ }
+ );
+});
+
+describe("gcpCloudDnsInsertTxtRecord", () => {
+ beforeEach(() => {
+ getMock.mockReset();
+ postMock.mockReset().mockResolvedValue({ data: {} });
+ });
+
+ it("creates the record set when none exists", async () => {
+ getMock.mockRejectedValueOnce(axiosError(404));
+
- await gcpCloudDnsInsertTxtRecord(connection, ZONE, RECORD, '"token-a"');
++ await gcpCloudDnsInsertTxtRecord(connection, ZONE, RECORD, '"token-a"', keyStore);
+
+ expect(getMock).toHaveBeenCalledWith(`${ZONE_URL}/rrsets/${encodeURIComponent(FQDN)}/TXT`, expect.anything());
+ expect(postMock).toHaveBeenCalledWith(
+ `${ZONE_URL}/changes`,
+ { additions: [{ name: FQDN, type: "TXT", ttl: 60, rrdatas: ['"token-a"'] }] },
+ expect.anything()
+ );
+ });
+
+ it("appends to an existing record set so concurrent challenges on one name both survive", async () => {
+ getMock.mockResolvedValueOnce(existingRecordSet(['"token-a"']));
+
- await gcpCloudDnsInsertTxtRecord(connection, ZONE, RECORD, '"token-b"');
++ await gcpCloudDnsInsertTxtRecord(connection, ZONE, RECORD, '"token-b"', keyStore);
+
+ expect(postMock).toHaveBeenCalledWith(
+ `${ZONE_URL}/changes`,
+ {
+ deletions: [{ name: FQDN, type: "TXT", ttl: 60, rrdatas: ['"token-a"'] }],
+ additions: [{ name: FQDN, type: "TXT", ttl: 60, rrdatas: ['"token-a"', '"token-b"'] }]
+ },
+ expect.anything()
+ );
+ });
+
+ it("keeps the TTL of a record set it did not create", async () => {
+ getMock.mockResolvedValueOnce(existingRecordSet(['"customer-value"'], 3600));
+
- await gcpCloudDnsInsertTxtRecord(connection, ZONE, RECORD, '"token-a"');
++ await gcpCloudDnsInsertTxtRecord(connection, ZONE, RECORD, '"token-a"', keyStore);
+
+ expect(postMock).toHaveBeenCalledWith(
+ `${ZONE_URL}/changes`,
+ {
+ deletions: [{ name: FQDN, type: "TXT", ttl: 3600, rrdatas: ['"customer-value"'] }],
+ additions: [{ name: FQDN, type: "TXT", ttl: 3600, rrdatas: ['"customer-value"', '"token-a"'] }]
+ },
+ expect.anything()
+ );
+ });
+
+ it("holds a per-record lock while it updates the record set", async () => {
+ const release = vi.fn().mockResolvedValue(undefined);
+ const acquireLock = vi.fn().mockResolvedValue({ release });
+ getMock.mockRejectedValueOnce(axiosError(404));
+
+ await gcpCloudDnsInsertTxtRecord(connection, ZONE, RECORD, '"token-a"', {
+ acquireLock
+ } as unknown as TDnsRecordLockKeyStore);
+
+ expect(acquireLock).toHaveBeenCalledWith(
+ [`acme-dns-record-mutex-connection-id-${ZONE.toLowerCase()}-${FQDN}`],
+ expect.any(Number),
+ expect.anything()
+ );
+ expect(postMock).toHaveBeenCalledTimes(1);
+ expect(release).toHaveBeenCalledTimes(1);
+ });
+
+ it("fails without touching the record when another order holds the lock", 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.");
+ expect(getMock).not.toHaveBeenCalled();
+ 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
- .mockImplementationOnce(
- () =>
- new Promise((resolve) => {
- releaseFirstRead = resolve;
- })
- )
- .mockResolvedValueOnce(existingRecordSet(['"token-a"']));
-
- const first = gcpCloudDnsInsertTxtRecord(connection, ZONE, RECORD, '"token-a"');
- const second = gcpCloudDnsInsertTxtRecord(connection, ZONE, RECORD, '"token-b"');
- await new Promise((resolve) => {
- setImmediate(resolve);
- });
- expect(getMock).toHaveBeenCalledTimes(1);
-
- releaseFirstRead(Promise.reject(axiosError(404)));
- await Promise.all([first, second]);
-
- expect(postMock).toHaveBeenCalledTimes(2);
- expect(postMock).toHaveBeenLastCalledWith(
- `${ZONE_URL}/changes`,
- expect.objectContaining({
- additions: [expect.objectContaining({ rrdatas: ['"token-a"', '"token-b"'] })]
- }),
- expect.anything()
- );
- });
-
+ it("retries as a fresh create when the record set was deleted between read and write", async () => {
+ getMock.mockResolvedValueOnce(existingRecordSet(['"token-a"'])).mockRejectedValueOnce(axiosError(404));
+ postMock.mockRejectedValueOnce(axiosError(404)).mockResolvedValueOnce({ data: {} });
+
- await gcpCloudDnsInsertTxtRecord(connection, ZONE, RECORD, '"token-b"');
++ await gcpCloudDnsInsertTxtRecord(connection, ZONE, RECORD, '"token-b"', keyStore);
+
+ expect(postMock).toHaveBeenCalledTimes(2);
+ expect(postMock).toHaveBeenLastCalledWith(
+ `${ZONE_URL}/changes`,
+ { additions: [{ name: FQDN, type: "TXT", ttl: 60, rrdatas: ['"token-b"'] }] },
+ expect.anything()
+ );
+ });
+
+ it("does not retry a 404 on a plain create", async () => {
+ getMock.mockRejectedValueOnce(axiosError(404));
+ postMock.mockRejectedValueOnce(axiosError(404, "The managed zone does not exist."));
+
- await expect(gcpCloudDnsInsertTxtRecord(connection, ZONE, RECORD, '"token-a"')).rejects.toThrow(
++ await expect(gcpCloudDnsInsertTxtRecord(connection, ZONE, RECORD, '"token-a"', keyStore)).rejects.toThrow(
+ "Failed to update Google Cloud DNS TXT record '_acme-challenge.example.com.' in zone 'example-zone': The managed zone does not exist."
+ );
+ expect(postMock).toHaveBeenCalledTimes(1);
+ });
+
+ it("does nothing when the value is already present", async () => {
+ getMock.mockResolvedValueOnce(existingRecordSet(["token-a"]));
+
- await gcpCloudDnsInsertTxtRecord(connection, ZONE, RECORD, '"token-a"');
++ await gcpCloudDnsInsertTxtRecord(connection, ZONE, RECORD, '"token-a"', keyStore);
+
+ expect(postMock).not.toHaveBeenCalled();
+ });
+
+ it("re-reads and retries when the record set changed underneath it", async () => {
+ getMock.mockRejectedValueOnce(axiosError(404)).mockResolvedValueOnce(existingRecordSet(['"token-a"']));
+ postMock.mockRejectedValueOnce(axiosError(409)).mockResolvedValueOnce({ data: {} });
+
- await gcpCloudDnsInsertTxtRecord(connection, ZONE, RECORD, '"token-b"');
++ await gcpCloudDnsInsertTxtRecord(connection, ZONE, RECORD, '"token-b"', keyStore);
+
+ expect(postMock).toHaveBeenCalledTimes(2);
+ expect(postMock).toHaveBeenLastCalledWith(
+ `${ZONE_URL}/changes`,
+ expect.objectContaining({
+ additions: [expect.objectContaining({ rrdatas: ['"token-a"', '"token-b"'] })]
+ }),
+ expect.anything()
+ );
+ });
+
+ it("tells the user which role to grant when the service account lacks access", async () => {
+ getMock.mockRejectedValueOnce(axiosError(403));
+
- await expect(gcpCloudDnsInsertTxtRecord(connection, ZONE, RECORD, '"token-a"')).rejects.toThrow(
++ await expect(gcpCloudDnsInsertTxtRecord(connection, ZONE, RECORD, '"token-a"', keyStore)).rejects.toThrow(
+ "Grant it the DNS Administrator role (roles/dns.admin) on GCP project 'my-project'"
+ );
+ expect(postMock).not.toHaveBeenCalled();
+ });
+
+ it("tells the user to enable the API when Cloud DNS is disabled on the project", async () => {
+ getMock.mockRejectedValueOnce(
+ axiosError(403, "Cloud DNS API has not been used in project 123456 before or it is disabled.")
+ );
+
- await expect(gcpCloudDnsInsertTxtRecord(connection, ZONE, RECORD, '"token-a"')).rejects.toThrow(
++ await expect(gcpCloudDnsInsertTxtRecord(connection, ZONE, RECORD, '"token-a"', keyStore)).rejects.toThrow(
+ "The Cloud DNS API is not enabled on GCP project 'my-project'"
+ );
+ });
+
+ it("detects a disabled API from Google's error reason, whatever the message says", async () => {
+ getMock.mockRejectedValueOnce(
+ axiosError(403, "Cloud DNS API is disabled.", {
+ details: [{ "@type": "type.googleapis.com/google.rpc.ErrorInfo", reason: "SERVICE_DISABLED" }]
+ })
+ );
+
- await expect(gcpCloudDnsInsertTxtRecord(connection, ZONE, RECORD, '"token-a"')).rejects.toThrow(
++ await expect(gcpCloudDnsInsertTxtRecord(connection, ZONE, RECORD, '"token-a"', keyStore)).rejects.toThrow(
+ "The Cloud DNS API is not enabled on GCP project 'my-project'"
+ );
+ });
+
+ it("does not treat other disabled resources as a disabled API", async () => {
+ getMock.mockRejectedValueOnce(axiosError(403, "The billing account for the project is disabled."));
+
- await expect(gcpCloudDnsInsertTxtRecord(connection, ZONE, RECORD, '"token-a"')).rejects.toThrow(
++ await expect(gcpCloudDnsInsertTxtRecord(connection, ZONE, RECORD, '"token-a"', keyStore)).rejects.toThrow(
+ "Grant it the DNS Administrator role"
+ );
+ });
+
+ it("surfaces the provider message on other failures", async () => {
+ getMock.mockRejectedValueOnce(axiosError(400));
+
- await expect(gcpCloudDnsInsertTxtRecord(connection, ZONE, RECORD, '"token-a"')).rejects.toThrow(
++ await expect(gcpCloudDnsInsertTxtRecord(connection, ZONE, RECORD, '"token-a"', keyStore)).rejects.toThrow(
+ "Failed to update Google Cloud DNS TXT record '_acme-challenge.example.com.' in zone 'example-zone': status 400"
+ );
+ });
+});
+
+describe("gcpCloudDnsDeleteTxtRecord", () => {
+ beforeEach(() => {
+ getMock.mockReset();
+ postMock.mockReset().mockResolvedValue({ data: {} });
+ });
+
+ it("removes only its own value when other values remain", async () => {
+ getMock.mockResolvedValueOnce(existingRecordSet(['"token-a"', '"token-b"']));
+
- await gcpCloudDnsDeleteTxtRecord(connection, ZONE, RECORD, '"token-a"');
++ await gcpCloudDnsDeleteTxtRecord(connection, ZONE, RECORD, '"token-a"', keyStore);
+
+ expect(postMock).toHaveBeenCalledWith(
+ `${ZONE_URL}/changes`,
+ {
+ deletions: [{ name: FQDN, type: "TXT", ttl: 60, rrdatas: ['"token-a"', '"token-b"'] }],
+ additions: [{ name: FQDN, type: "TXT", ttl: 60, rrdatas: ['"token-b"'] }]
+ },
+ expect.anything()
+ );
+ });
+
+ it("deletes the record set when its last value is removed", async () => {
+ getMock.mockResolvedValueOnce(existingRecordSet(['"token-a"']));
+
- await gcpCloudDnsDeleteTxtRecord(connection, ZONE, RECORD, '"token-a"');
++ await gcpCloudDnsDeleteTxtRecord(connection, ZONE, RECORD, '"token-a"', keyStore);
+
+ expect(postMock).toHaveBeenCalledWith(
+ `${ZONE_URL}/changes`,
+ { deletions: [{ name: FQDN, type: "TXT", ttl: 60, rrdatas: ['"token-a"'] }] },
+ expect.anything()
+ );
+ });
+
+ it("re-reads and retries when another challenge removed its value first", async () => {
+ getMock
+ .mockResolvedValueOnce(existingRecordSet(['"token-a"', '"token-b"']))
+ .mockResolvedValueOnce(existingRecordSet(['"token-a"']));
+ postMock.mockRejectedValueOnce(axiosError(412)).mockResolvedValueOnce({ data: {} });
+
- await gcpCloudDnsDeleteTxtRecord(connection, ZONE, RECORD, '"token-a"');
++ await gcpCloudDnsDeleteTxtRecord(connection, ZONE, RECORD, '"token-a"', keyStore);
+
+ expect(postMock).toHaveBeenCalledTimes(2);
+ expect(postMock).toHaveBeenLastCalledWith(
+ `${ZONE_URL}/changes`,
+ { deletions: [{ name: FQDN, type: "TXT", ttl: 60, rrdatas: ['"token-a"'] }] },
+ expect.anything()
+ );
+ });
+
+ it("is a no-op when the record set or value is already gone", async () => {
+ getMock.mockRejectedValueOnce(axiosError(404)).mockResolvedValueOnce(existingRecordSet(['"token-b"']));
+
- await gcpCloudDnsDeleteTxtRecord(connection, ZONE, RECORD, '"token-a"');
- await gcpCloudDnsDeleteTxtRecord(connection, ZONE, RECORD, '"token-a"');
++ await gcpCloudDnsDeleteTxtRecord(connection, ZONE, RECORD, '"token-a"', keyStore);
++ await gcpCloudDnsDeleteTxtRecord(connection, ZONE, RECORD, '"token-a"', keyStore);
+
+ expect(postMock).not.toHaveBeenCalled();
+ });
+});
diff --cc backend/src/services/certificate-authority/acme/dns-providers/gcp-cloud-dns.ts
index 627a2d7c03,0000000000..3c62558815
mode 100644,000000..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
@@@ -1,217 -1,0 +1,217 @@@
+import { isAxiosError } from "axios";
+import RE2 from "re2";
+
+import { request } from "@app/lib/config/request";
+import { delay } from "@app/lib/delay";
+import { BadRequestError } from "@app/lib/errors";
+import { logger } from "@app/lib/logger";
+import { GCP_CLOUD_DNS_ZONE_RESOURCE_PATTERN } from "@app/services/app-connection/gcp/gcp-connection-constants";
+import { isGcpServiceDisabledError, TGoogleApiError } from "@app/services/app-connection/gcp/gcp-connection-errors";
+import { getGcpConnectionAuthToken } from "@app/services/app-connection/gcp/gcp-connection-fns";
+import { TGcpConnection } from "@app/services/app-connection/gcp/gcp-connection-types";
+import { IntegrationUrls } from "@app/services/integration-auth/integration-list";
+
+import { TDnsRecordLockKeyStore, withDnsRecordLock } from "./dns-record-lock";
+
+type TGcpResourceRecordSet = {
+ name: string;
+ type: string;
+ ttl: number;
+ rrdatas: string[];
+};
+
+type TRecordSetChange = { additions?: TGcpResourceRecordSet[]; deletions?: TGcpResourceRecordSet[] };
+
+type TBuildChange = (fqdn: string, existing: TGcpResourceRecordSet | null) => TRecordSetChange | null;
+
+const TXT_RECORD_TTL_SECONDS = 60;
+const MAX_CHANGE_ATTEMPTS = 5;
+const CHANGE_RETRY_DELAY_MS = 1000;
+const REQUEST_TIMEOUT_MS = 30_000;
+const RECORD_LOCK_TTL_MS = MAX_CHANGE_ATTEMPTS * (REQUEST_TIMEOUT_MS * 2 + CHANGE_RETRY_DELAY_MS) + 30_000;
+const QUOTES_REGEX = new RE2('"', "g");
+
+export const validateGcpCloudDnsZone = (hostedZoneId: string) => {
+ if (!GCP_CLOUD_DNS_ZONE_RESOURCE_PATTERN.test(hostedZoneId)) {
+ throw new BadRequestError({
+ message: `Invalid Google Cloud DNS zone '${hostedZoneId}'. Expected format: projects/{projectId}/managedZones/{zoneName}`
+ });
+ }
+};
+
+const getZoneUrl = (hostedZoneId: string) => {
+ validateGcpCloudDnsZone(hostedZoneId);
+ return `${IntegrationUrls.GCP_CLOUD_DNS_URL}/dns/v1/${hostedZoneId}`;
+};
+
+const toFqdn = (recordName: string) => (recordName.endsWith(".") ? recordName : `${recordName}.`);
+
+const normalizeTxtValue = (value: string) => value.replace(QUOTES_REGEX, "");
+
+const toGcpDnsError = (error: unknown, hostedZoneId: string, fqdn: string) => {
+ if (isAxiosError(error)) {
+ const body = error.response?.data as TGoogleApiError | undefined;
+ const message = body?.error?.message || error.message || "Unknown error";
+
+ if (error.response?.status === 403) {
+ const [, gcpProjectId, , zoneName] = hostedZoneId.split("/");
+ if (isGcpServiceDisabledError(body, message)) {
+ return new Error(
+ `The Cloud DNS API is not enabled on GCP project '${gcpProjectId}'. Enable dns.googleapis.com in the Google Cloud console and try again.`
+ );
+ }
+ return new Error(
+ `The GCP connection's service account can't manage records in Google Cloud DNS zone '${zoneName}'. Grant it the DNS Administrator role (roles/dns.admin) on GCP project '${gcpProjectId}' and try again.`
+ );
+ }
+
+ const [, , , zoneName] = hostedZoneId.split("/");
+ return new Error(`Failed to update Google Cloud DNS TXT record '${fqdn}' in zone '${zoneName}': ${message}`);
+ }
+ return error;
+};
+
+// 409 = created concurrently, 412 = changed since read, 404 on a deletion = removed since read
+const isConflictError = (error: unknown, changeHadDeletions: boolean) =>
+ isAxiosError(error) &&
+ (error.response?.status === 409 ||
+ error.response?.status === 412 ||
+ (error.response?.status === 404 && changeHadDeletions));
+
+const getTxtRecordSet = async (zoneUrl: string, accessToken: string, fqdn: string) => {
+ try {
+ const { data } = await request.get<TGcpResourceRecordSet>(`${zoneUrl}/rrsets/${encodeURIComponent(fqdn)}/TXT`, {
+ headers: { Authorization: `Bearer ${accessToken}`, Accept: "application/json" },
+ timeout: REQUEST_TIMEOUT_MS
+ });
+ return data;
+ } catch (error) {
+ if (isAxiosError(error) && error.response?.status === 404) return null;
+ throw error;
+ }
+};
+
+const submitChange = async (zoneUrl: string, accessToken: string, change: TRecordSetChange) => {
+ await request.post(`${zoneUrl}/changes`, change, {
+ headers: { Authorization: `Bearer ${accessToken}`, "Content-Type": "application/json", Accept: "application/json" },
+ timeout: REQUEST_TIMEOUT_MS
+ });
+};
+
+const submitWithRetry = async (
+ connection: TGcpConnection,
+ hostedZoneId: string,
+ zoneUrl: string,
+ fqdn: string,
+ buildChange: TBuildChange
+) => {
+ const accessToken = await getGcpConnectionAuthToken(connection);
+
+ for (let attempt = 1; attempt <= MAX_CHANGE_ATTEMPTS; attempt += 1) {
+ let changeHadDeletions = false;
+ try {
+ // eslint-disable-next-line no-await-in-loop
+ const existing = await getTxtRecordSet(zoneUrl, accessToken, fqdn);
+ const change = buildChange(fqdn, existing);
+ if (!change) return;
+ changeHadDeletions = Boolean(change.deletions?.length);
+
+ // eslint-disable-next-line no-await-in-loop
+ await submitChange(zoneUrl, accessToken, change);
+ return;
+ } catch (error) {
+ if (!isConflictError(error, changeHadDeletions) || attempt === MAX_CHANGE_ATTEMPTS) {
+ throw toGcpDnsError(error, hostedZoneId, fqdn);
+ }
+ // eslint-disable-next-line no-await-in-loop
+ await delay(CHANGE_RETRY_DELAY_MS);
+ }
+ }
+};
+
+const applyTxtRecordChange = async (
+ connection: TGcpConnection,
+ hostedZoneId: string,
+ recordName: string,
+ buildChange: TBuildChange,
- keyStore?: TDnsRecordLockKeyStore,
++ keyStore: TDnsRecordLockKeyStore,
+ abortSignal?: AbortSignal
+) => {
+ const zoneUrl = getZoneUrl(hostedZoneId);
+ const fqdn = toFqdn(recordName);
+
+ await withDnsRecordLock(
+ {
+ connectionId: connection.id,
+ zoneId: hostedZoneId,
+ name: fqdn,
+ providerName: "Google Cloud DNS",
+ lockTtlMs: RECORD_LOCK_TTL_MS,
+ abortSignal
+ },
+ keyStore,
+ () => submitWithRetry(connection, hostedZoneId, zoneUrl, fqdn, buildChange)
+ );
+};
+
+export const gcpCloudDnsInsertTxtRecord = async (
+ connection: TGcpConnection,
+ hostedZoneId: string,
+ recordName: string,
+ value: string,
- keyStore?: TDnsRecordLockKeyStore,
++ keyStore: TDnsRecordLockKeyStore,
+ abortSignal?: AbortSignal
+) => {
+ await applyTxtRecordChange(
+ connection,
+ hostedZoneId,
+ recordName,
+ (fqdn, existing) => {
+ if (!existing) {
+ return { additions: [{ name: fqdn, type: "TXT", ttl: TXT_RECORD_TTL_SECONDS, rrdatas: [value] }] };
+ }
+
+ if (existing.rrdatas.some((rrdata) => normalizeTxtValue(rrdata) === normalizeTxtValue(value))) {
+ return null;
+ }
+
+ return {
+ deletions: [existing],
+ additions: [{ ...existing, rrdatas: [...existing.rrdatas, value] }]
+ };
+ },
+ keyStore,
+ abortSignal
+ );
+};
+
+export const gcpCloudDnsDeleteTxtRecord = async (
+ connection: TGcpConnection,
+ hostedZoneId: string,
+ recordName: string,
+ value: string,
- keyStore?: TDnsRecordLockKeyStore
++ keyStore: TDnsRecordLockKeyStore
+) => {
+ await applyTxtRecordChange(
+ connection,
+ hostedZoneId,
+ recordName,
+ (fqdn, existing) => {
+ const remaining = existing?.rrdatas.filter((rrdata) => normalizeTxtValue(rrdata) !== normalizeTxtValue(value));
+
+ if (!existing || !remaining || remaining.length === existing.rrdatas.length) {
+ logger.warn(
+ { hostedZoneId, recordName: fqdn },
+ `Google Cloud DNS TXT record not found for deletion [hostedZoneId=${hostedZoneId}] [recordName=${fqdn}]`
+ );
+ return null;
+ }
+
+ return {
+ deletions: [existing],
+ ...(remaining.length ? { additions: [{ ...existing, rrdatas: remaining }] } : {})
+ };
+ },
+ keyStore
+ );
+};
diff --cc docs/documentation/platform/pki/ca/acme-ca.mdx
index 848e8f7d2f,56d062f48a..769d3706bd
--- a/docs/documentation/platform/pki/ca/acme-ca.mdx
+++ b/docs/documentation/platform/pki/ca/acme-ca.mdx
@@@ -17,7 -17,7 +17,7 @@@ their **ACME Directory URL** such as
- ZeroSSL: `https://acme.zerossl.com/v2/DV90`.
- SSL.com: `https://acme.ssl.com/sslcom-dv-rsa`.
- When Infisical requests a certificate from an ACME-compatible CA, it creates a TXT record at `_acme-challenge.{your-domain}` in your configured DNS provider (e.g. Route53, Cloudflare, Azure DNS, Google Cloud DNS, DNS Made Easy, PowerDNS, etc.); this TXT record contains the challenge token issued by the ACME-compatible CA to validate domain control for the requested certificate.
-When Infisical requests a certificate from an ACME-compatible CA, it creates a TXT record at `_acme-challenge.{your-domain}` in your configured DNS provider (e.g. Route53, Cloudflare, Azure DNS, DNS Made Easy, PowerDNS, UltraDNS, etc.); this TXT record contains the challenge token issued by the ACME-compatible CA to validate domain control for the requested certificate.
++When Infisical requests a certificate from an ACME-compatible CA, it creates a TXT record at `_acme-challenge.{your-domain}` in your configured DNS provider (e.g. Route53, Cloudflare, Azure DNS, DNS Made Easy, Google Cloud DNS, PowerDNS, UltraDNS, etc.); this TXT record contains the challenge token issued by the ACME-compatible CA to validate domain control for the requested certificate.
The ACME provider checks for the existence of this TXT record to verify domain control before issuing the certificate back to Infisical.
After validation completes successfully, Infisical automatically removes the TXT record from your DNS provider.
@@@ -139,25 -139,19 +139,38 @@@ In the following steps, we explore how
For detailed instructions on setting up a PowerDNS connection, see the [PowerDNS Connection](/integrations/app-connections/powerdns) documentation.
</Tab>
+ <Tab title="UltraDNS">
+ 1. In **Certificate Manager**, go to **Settings → App Connections** and create a new UltraDNS connection.
+
+ 2. Ensure the UltraDNS user can read zones and manage resource records in the zone you want to use for validation. Only primary zones can be used, since secondary zones can't accept record changes.
+
+ <Note>
+ For UltraDNS the zone is identified by its fully qualified name, such as `example.com.`, rather than
+ by an ID. The Infisical UI offers this as a picker, so this only matters if you are creating the CA
+ through the API or Terraform.
+ </Note>
+
+ For detailed instructions on setting up an UltraDNS connection, see the [UltraDNS Connection](/integrations/app-connections/ultradns) documentation.
+ </Tab>
+ <Tab title="Google Cloud DNS">
+ 1. In **Certificate Manager**, go to **Settings → App Connections** and create a new GCP connection. The service account's ID must end with the first two sections of your Infisical organization ID, as described in [Configure service account for Infisical](/integrations/app-connections/gcp#configure-service-account-for-infisical).
+
+ 2. On the Google Cloud project that holds your public managed zone, grant the connection's service account the **DNS Administrator** (`roles/dns.admin`) and **Service Usage Viewer** (`roles/serviceusage.serviceUsageViewer`) roles.
+
+ 3. Enable the Google Cloud APIs that Infisical uses on that same project:
+
+ ```bash
+ gcloud services enable \
+ dns.googleapis.com \
+ cloudresourcemanager.googleapis.com \
+ serviceusage.googleapis.com \
+ --project=PROJECT_ID
+ ```
+
+ When you register the CA, the **GCP Project** list shows only projects with the Cloud DNS API enabled. The **Zone** list shows only public managed zones, since an ACME CA can't look up records in a private zone.
+
+ For detailed instructions on setting up a GCP connection, see the [GCP Connection](/integrations/app-connections/gcp) documentation.
+ </Tab>
</Tabs>
</Step>
<Step title="Register an ACME-compatible CA">
@@@ -241,7 -235,7 +254,7 @@@
<AccordionGroup>
<Accordion title="What DNS validation methods are supported?">
- Currently, Infisical supports DNS-01 validation through AWS Route53, Cloudflare, Azure DNS, Google Cloud DNS, DNS Made Easy, and PowerDNS. The DNS-01 challenge method is preferred for ACME integrations because it:
- Currently, Infisical supports DNS-01 validation through AWS Route53, Cloudflare, Azure DNS, DNS Made Easy, PowerDNS, and UltraDNS. The DNS-01 challenge method is preferred for ACME integrations because it:
++ Currently, Infisical supports DNS-01 validation through AWS Route53, Cloudflare, Azure DNS, Google Cloud DNS, DNS Made Easy, PowerDNS, and UltraDNS. The DNS-01 challenge method is preferred for ACME integrations because it:
- Works with wildcard certificates
- Doesn't require your servers to be publicly accessible
diff --cc frontend/src/hooks/api/ca/constants.tsx
index 6d7ef88c98,9e8243bfd8..ac0a75cf16
--- a/frontend/src/hooks/api/ca/constants.tsx
+++ b/frontend/src/hooks/api/ca/constants.tsx
@@@ -18,7 -18,7 +18,8 @@@ export const ACME_DNS_PROVIDER_NAME_MAP
[AcmeDnsProvider.DNSMadeEasy]: "DNS Made Easy",
[AcmeDnsProvider.AzureDNS]: "Azure DNS",
[AcmeDnsProvider.PowerDns]: "PowerDNS",
- [AcmeDnsProvider.GcpCloudDns]: "Google Cloud DNS"
++ [AcmeDnsProvider.GcpCloudDns]: "Google Cloud DNS",
+ [AcmeDnsProvider.UltraDNS]: "UltraDNS"
};
export const ACME_DNS_PROVIDER_APP_CONNECTION_MAP: Record<AcmeDnsProvider, AppConnection> = {
@@@ -27,7 -27,7 +28,8 @@@
[AcmeDnsProvider.DNSMadeEasy]: AppConnection.DNSMadeEasy,
[AcmeDnsProvider.AzureDNS]: AppConnection.AzureDNS,
[AcmeDnsProvider.PowerDns]: AppConnection.PowerDns,
- [AcmeDnsProvider.GcpCloudDns]: AppConnection.GCP
++ [AcmeDnsProvider.GcpCloudDns]: AppConnection.GCP,
+ [AcmeDnsProvider.UltraDNS]: AppConnection.UltraDNS
};
export const CA_TYPE_CAPABILITIES_MAP: Record<CaType, CaCapability[]> = {
diff --cc frontend/src/hooks/api/ca/enums.tsx
index 65ce496950,ee06231953..ab6021d8e8
--- a/frontend/src/hooks/api/ca/enums.tsx
+++ b/frontend/src/hooks/api/ca/enums.tsx
@@@ -31,7 -31,7 +31,8 @@@ export enum AcmeDnsProvider
DNSMadeEasy = "dns-made-easy",
AzureDNS = "azure-dns",
PowerDns = "powerdns",
- GcpCloudDns = "gcp-cloud-dns"
++ GcpCloudDns = "gcp-cloud-dns",
+ UltraDNS = "ultradns"
}
export enum CaRenewalStatus {
diff --cc frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaFields/AcmeFields.tsx
index 71f3490e09,1186860123..3fbf3696a9
--- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaFields/AcmeFields.tsx
+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaFields/AcmeFields.tsx
@@@ -31,9 -27,10 +27,11 @@@ import
import { AppConnectionSelectField } from "./AppConnectionSelectField";
import { REQUIRED_EAB_DIRECTORIES } from "./constants";
+import { GcpCloudDnsZoneFields } from "./GcpCloudDnsZoneFields";
import { FormData } from "./schema";
+ export type TAcmeDnsZone = { id: string; name: string };
+
type Props = {
control: Control<FormData>;
isExistingCa: boolean;
@@@ -134,125 -119,43 +121,52 @@@ export const AcmeFields = (
)}
/>
)}
- {dnsProvider === AcmeDnsProvider.Cloudflare && (
- <Controller
- name="configuration.dnsProviderConfig.hostedZoneId"
- control={control}
- render={({ field: { value, onChange }, fieldState: { error } }) => (
- <Field className="mb-4">
- <FieldLabel>Zone</FieldLabel>
- <FilterableSelect
- isLoading={isZonesPending && !!dnsAppConnection.id}
- isDisabled={!dnsAppConnection.id}
- value={
- cloudflareZones.find((zone) => zone.id === value) ||
- (value ? { id: value, name: value } : null)
- }
- onChange={(option) => {
- onChange((option as SingleValue<TCloudflareZone>)?.id ?? null);
- }}
- options={cloudflareZones}
- placeholder="Select a zone..."
- getOptionLabel={(option) => option.name}
- getOptionValue={(option) => option.id}
- isError={Boolean(error)}
- />
- <FieldError errors={[error]} />
- </Field>
- )}
- />
- )}
- {dnsProvider === AcmeDnsProvider.DNSMadeEasy && (
- <Controller
- name="configuration.dnsProviderConfig.hostedZoneId"
- control={control}
- render={({ field: { value, onChange }, fieldState: { error } }) => (
- <Field className="mb-4">
- <FieldLabel>Zone</FieldLabel>
- <FilterableSelect
- isLoading={isDNSMadeEasyZonesPending && !!dnsAppConnection.id}
- isDisabled={!dnsAppConnection.id}
- value={
- dnsMadeEasyZones.find((zone) => zone.id === value) ||
- (value ? { id: value, name: value } : null)
- }
- onChange={(option) => {
- onChange((option as SingleValue<TDNSMadeEasyZone>)?.id ?? null);
- }}
- options={dnsMadeEasyZones}
- placeholder="Select a zone..."
- getOptionLabel={(option) => option.name}
- getOptionValue={(option) => option.id}
- isError={Boolean(error)}
- />
- <FieldError errors={[error]} />
- </Field>
- )}
- />
- )}
- {dnsProvider === AcmeDnsProvider.AzureDNS && (
- <Controller
- name="configuration.dnsProviderConfig.hostedZoneId"
- control={control}
- render={({ field: { value, onChange }, fieldState: { error } }) => (
- <Field className="mb-4">
- <FieldLabel>Zone</FieldLabel>
- <FilterableSelect
- isLoading={isAzureDNSZonesPending && !!dnsAppConnection.id}
- isDisabled={!dnsAppConnection.id}
- value={
- azureDnsZones.find((zone) => zone.id === value) ||
- (value ? { id: value, name: value } : null)
- }
- onChange={(option) => {
- onChange((option as SingleValue<TAzureDNSZone>)?.id ?? null);
- }}
- options={azureDnsZones}
- placeholder="Select a zone..."
- getOptionLabel={(option) => option.name}
- getOptionValue={(option) => option.id}
- isError={Boolean(error)}
- />
- <FieldError errors={[error]} />
- </Field>
- )}
- />
- )}
- {dnsProvider === AcmeDnsProvider.PowerDns && (
- {dnsProvider && dnsProvider !== AcmeDnsProvider.ROUTE53 && (
-- <Controller
-- name="configuration.dnsProviderConfig.hostedZoneId"
- control={control}
- render={({ field: { value, onChange }, fieldState: { error } }) => (
- <Field className="mb-4">
- <FieldLabel>
- Zone <span className="text-danger">*</span>
- </FieldLabel>
- <FilterableSelect
- isLoading={isPowerDnsZonesPending && !!dnsAppConnection.id}
- isDisabled={!dnsAppConnection.id}
- value={
- powerDnsZones.find((zone) => zone.id === value) ||
- (value ? { id: value, name: value } : null)
- }
- onChange={(option) => {
- onChange((option as SingleValue<TPowerDnsZone>)?.id ?? null);
- }}
- options={powerDnsZones}
- placeholder="Select a zone..."
- getOptionLabel={(option) => option.name.replace(/\.$/, "")}
- getOptionValue={(option) => option.id}
- isError={Boolean(error)}
- />
- <FieldError errors={[error]} />
- </Field>
- )}
- />
- )}
++ {dnsProvider &&
++ dnsProvider !== AcmeDnsProvider.ROUTE53 &&
++ dnsProvider !== AcmeDnsProvider.GcpCloudDns && (
++ <Controller
++ name="configuration.dnsProviderConfig.hostedZoneId"
++ control={control}
++ render={({ field: { value, onChange }, fieldState: { error } }) => (
++ <Field className="mb-4">
++ <FieldLabel>
++ Zone <span className="text-danger">*</span>
++ <Tooltip>
++ <TooltipTrigger asChild>
++ <Info />
++ </TooltipTrigger>
++ <TooltipContent className="max-w-md">
++ The DNS zone where Infisical creates the challenge TXT records. It must contain
++ the domains you request certificates for.
++ </TooltipContent>
++ </Tooltip>
++ </FieldLabel>
++ <FilterableSelect
++ isLoading={isZonesPending && !!dnsAppConnection.id}
++ isDisabled={!dnsAppConnection.id}
++ value={
++ zones.find((zone) => zone.id === value) ||
++ (value ? { id: value, name: value } : null)
++ }
++ onChange={(option) => {
++ onChange((option as SingleValue<TAcmeDnsZone>)?.id ?? null);
++ }}
++ options={zones}
++ placeholder="Select a zone..."
++ getOptionLabel={(option) => option.name.replace(/\.$/, "")}
++ getOptionValue={(option) => option.id}
++ isError={Boolean(error)}
++ />
++ <FieldError errors={[error]} />
++ </Field>
++ )}
++ />
++ )}
+ {dnsProvider === AcmeDnsProvider.GcpCloudDns && (
+ <GcpCloudDnsZoneFields
+ key={dnsAppConnection.id}
control={control}
- render={({ field: { value, onChange }, fieldState: { error } }) => (
- <Field className="mb-4">
- <FieldLabel>
- Zone <span className="text-danger">*</span>
- <Tooltip>
- <TooltipTrigger asChild>
- <Info />
- </TooltipTrigger>
- <TooltipContent className="max-w-md">
- The DNS zone where Infisical creates the challenge TXT records. It must contain
- the domains you request certificates for.
- </TooltipContent>
- </Tooltip>
- </FieldLabel>
- <FilterableSelect
- isLoading={isZonesPending && !!dnsAppConnection.id}
- isDisabled={!dnsAppConnection.id}
- value={
- zones.find((zone) => zone.id === value) ||
- (value ? { id: value, name: value } : null)
- }
- onChange={(option) => {
- onChange((option as SingleValue<TAcmeDnsZone>)?.id ?? null);
- }}
- options={zones}
- placeholder="Select a zone..."
- getOptionLabel={(option) => option.name.replace(/\.$/, "")}
- getOptionValue={(option) => option.id}
- isError={Boolean(error)}
- />
- <FieldError errors={[error]} />
- </Field>
- )}
+ connectionId={dnsAppConnection.id}
/>
)}
<Controller
diff --cc frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaModal.tsx
index df161d0b76,385165bf26..c835102d17
--- a/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaModal.tsx
+++ b/frontend/src/pages/cert-manager/CertificateAuthoritiesPage/components/ExternalCaModal.tsx
@@@ -401,14 -412,11 +412,19 @@@ export const ExternalCaModal = ({ popUp
enabled: caType === CaType.ACME
});
+ const { data: availableGcpConnections, isPending: isGcpPending } = useListAvailableAppConnections(
+ AppConnection.GCP,
+ currentProject.id,
+ {
+ enabled: caType === CaType.ACME
+ }
+ );
+
+ const { data: availableUltraDNSConnections, isPending: isUltraDNSPending } =
+ useListAvailableAppConnections(AppConnection.UltraDNS, currentProject.id, {
+ enabled: caType === CaType.ACME
+ });
+
const { data: availableAzureConnections, isPending: isAzurePending } =
useListAvailableAppConnections(AppConnection.AzureADCS, currentProject.id, {
enabled: caType === CaType.AZURE_AD_CS
@@@ -467,7 -475,7 +483,8 @@@
...(availableDNSMadeEasyConnections || []),
...(availableAzureDNSConnections || []),
...(availablePowerDnsConnections || []),
- ...(availableGcpConnections || [])
++ ...(availableGcpConnections || []),
+ ...(availableUltraDNSConnections || [])
];
}, [
caType,
@@@ -476,7 -484,7 +493,8 @@@
availableDNSMadeEasyConnections,
availableAzureDNSConnections,
availablePowerDnsConnections,
+ availableGcpConnections,
+ availableUltraDNSConnections,
availableAzureConnections,
availableAdcsConnections,
availableAwsConnections,
@@@ -497,8 -505,8 +515,10 @@@
return availableAzureDNSConnections || [];
case AcmeDnsProvider.PowerDns:
return availablePowerDnsConnections || [];
+ case AcmeDnsProvider.GcpCloudDns:
+ return availableGcpConnections || [];
+ case AcmeDnsProvider.UltraDNS:
+ return availableUltraDNSConnections || [];
default:
return [];
}
@@@ -509,7 -517,7 +529,8 @@@
availableDNSMadeEasyConnections,
availableAzureDNSConnections,
availablePowerDnsConnections,
- availableGcpConnections
++ availableGcpConnections,
+ availableUltraDNSConnections
]);
const isPending =
@@@ -518,7 -526,7 +539,8 @@@
isDNSMadeEasyPending ||
isAzureDNSPending ||
isPowerDnsPending ||
- isGcpPending) &&
++ isGcpPending ||
+ isUltraDNSPending) &&
caType === CaType.ACME) ||
(isAzurePending && caType === CaType.AZURE_AD_CS) ||
(isAdcsPending && caType === CaType.ADCS) ||
@@@ -552,26 -560,30 +574,47 @@@
enabled: dnsProvider === AcmeDnsProvider.PowerDns && !!dnsAppConnection.id
});
+ const { data: ultraDNSZones = [], isPending: isUltraDNSZonesPending } =
+ useUltraDNSConnectionListZones(dnsAppConnection.id, {
+ enabled: dnsProvider === AcmeDnsProvider.UltraDNS && !!dnsAppConnection.id
+ });
+
+ const zonesByDnsProvider: Partial<
+ Record<AcmeDnsProvider, { zones: TAcmeDnsZone[]; isPending: boolean }>
+ > = {
+ [AcmeDnsProvider.Cloudflare]: { zones: cloudflareZones, isPending: isCloudflareZonesPending },
+ [AcmeDnsProvider.DNSMadeEasy]: {
+ zones: dnsMadeEasyZones,
+ isPending: isDNSMadeEasyZonesPending
+ },
+ [AcmeDnsProvider.AzureDNS]: { zones: azureDnsZones, isPending: isAzureDNSZonesPending },
+ [AcmeDnsProvider.PowerDns]: { zones: powerDnsZones, isPending: isPowerDnsZonesPending },
+ [AcmeDnsProvider.UltraDNS]: { zones: ultraDNSZones, isPending: isUltraDNSZonesPending }
+ };
+
+ const { zones = [], isPending: isZonesPending = false } =
+ (dnsProvider && zonesByDnsProvider[dnsProvider]) || {};
+
- // Populate form with CA data when editing
+ const prefilledCaIdRef = useRef<string | null>(null);
+
+ // Prefill once per open: re-running on connection list refreshes would discard unsaved edits
+ useEffect(() => {
+ if (!popUp?.ca?.isOpen) prefilledCaIdRef.current = null;
+ }, [popUp?.ca?.isOpen]);
+
useEffect(() => {
- if (ca && !isCaLoading) {
+ if (
+ ca &&
+ !isCaLoading &&
+ !isPending &&
+ caType === ca.type &&
+ prefilledCaIdRef.current !== ca.id
+ ) {
+ const prefill = (values: Parameters<typeof reset>[0]) => {
+ reset(values);
+ prefilledCaIdRef.current = ca.id;
+ };
+
if (ca.type === CaType.ACME && availableConnections?.length) {
const selectedConnection = availableConnections?.find(
(connection) => connection.id === ca.configuration.dnsAppConnectionId