Skip to content

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

fix(pki): validate Venafi and Azure AD CS signing connections like ADCS (#8446)

Saif Ur Rahmanc08b151dd3ef
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index a24ada3397..4273694f34 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -3487,7 +3487,6 @@ export const registerRoutes = async (
internalCertificateAuthorityDAL,
permissionService,
licenseService,
- appConnectionDAL,
appConnectionService,
caAutoRenewalQueue
});
diff --git a/backend/src/services/app-connection/app-connection-service.test.ts b/backend/src/services/app-connection/app-connection-service.test.ts
new file mode 100644
index 0000000000..a716aef5a1
--- /dev/null
+++ b/backend/src/services/app-connection/app-connection-service.test.ts
@@ -0,0 +1,205 @@
+import { createMongoAbility, ForbiddenError } from "@casl/ability";
+import { describe, expect, test, vi } from "vitest";
+
+import { OrgPermissionAppConnectionActions, OrgPermissionSubjects } from "@app/ee/services/permission/org-permission";
+import {
+ ProjectPermissionAppConnectionActions,
+ ProjectPermissionSub
+} from "@app/ee/services/permission/project-permission";
+import { BadRequestError, NotFoundError } from "@app/lib/errors";
+import { ActorType, AuthMethod } from "@app/services/auth/auth-type";
+
+import { AppConnection } from "./app-connection-enums";
+import { appConnectionServiceFactory } from "./app-connection-service";
+
+const ACTOR_ORG_ID = "org-1";
+const CONNECTION_ID = "conn-1";
+
+const actor = {
+ type: ActorType.USER,
+ id: "user-1",
+ authMethod: AuthMethod.EMAIL,
+ orgId: ACTOR_ORG_ID,
+ rootOrgId: ACTOR_ORG_ID,
+ parentOrgId: ACTOR_ORG_ID
+};
+
+class PermissionReached extends Error {}
+
+const buildService = (
+ connection: { orgId: string; projectId: string | null; app?: AppConnection },
+ abilities: { org?: unknown; project?: unknown } = {}
+) => {
+ const permissionService = {
+ getOrgPermission: vi.fn(async () => {
+ if (!abilities.org) throw new PermissionReached();
+ return { permission: abilities.org };
+ }),
+ getProjectPermission: vi.fn(async () => {
+ if (!abilities.project) throw new PermissionReached();
+ return { permission: abilities.project };
+ })
+ };
+
+ const overrides: Record<string, unknown> = {
+ appConnectionDAL: {
+ findById: vi.fn(async () => ({
+ id: CONNECTION_ID,
+ app: AppConnection.AWS,
+ encryptedCredentials: Buffer.from("{}"),
+ ...connection
+ }))
+ },
+ projectDAL: { findProjectById: vi.fn(async (id: string) => ({ id, type: "cert-manager" })) },
+ kmsService: {
+ createCipherPairWithDataKey: vi.fn(async () => ({
+ decryptor: ({ cipherTextBlob }: { cipherTextBlob: Buffer }) => cipherTextBlob
+ }))
+ },
+ permissionService,
+ licenseService: { getPlan: vi.fn(async () => ({})) }
+ };
+
+ const deps = new Proxy(overrides, {
+ get: (target, key: string) => (key in target ? target[key] : new Proxy({}, { get: () => vi.fn() }))
+ });
+
+ const service = appConnectionServiceFactory(deps as unknown as Parameters<typeof appConnectionServiceFactory>[0]);
+ return { service, permissionService };
+};
+
+type TService = ReturnType<typeof buildService>["service"];
+
+const CALLS: [string, (service: TService) => Promise<unknown>][] = [
+ ["findAppConnectionById", (s) => s.findAppConnectionById(AppConnection.AWS, CONNECTION_ID, actor)],
+ ["updateAppConnection", (s) => s.updateAppConnection(AppConnection.AWS, { connectionId: CONNECTION_ID }, actor)],
+ ["deleteAppConnection", (s) => s.deleteAppConnection(AppConnection.AWS, CONNECTION_ID, actor)],
+ ["connectAppConnectionById", (s) => s.connectAppConnectionById(AppConnection.AWS, CONNECTION_ID, actor)],
+ [
+ "validateAppConnectionUsageById",
+ (s) =>
+ s.validateAppConnectionUsageById(AppConnection.AWS, { connectionId: CONNECTION_ID, projectId: "proj-1" }, actor)
+ ],
+ ["findAppConnectionUsageById", (s) => s.findAppConnectionUsageById(AppConnection.AWS, CONNECTION_ID, actor)],
+ [
+ "triggerCredentialRotation",
+ (s) => s.triggerCredentialRotation({ app: AppConnection.AWS, connectionId: CONNECTION_ID }, actor)
+ ]
+];
+
+describe("app connection in another org reads as missing", () => {
+ test.each(CALLS)("%s: org-level connection in another org", async (_, call) => {
+ const { service, permissionService } = buildService({ orgId: "org-2", projectId: null });
+
+ const result = call(service);
+ await expect(result).rejects.toBeInstanceOf(NotFoundError);
+ await expect(result).rejects.toThrow(`Could not find App Connection with ID ${CONNECTION_ID}`);
+ expect(permissionService.getOrgPermission).not.toHaveBeenCalled();
+ expect(permissionService.getProjectPermission).not.toHaveBeenCalled();
+ });
+
+ test.each(CALLS)("%s: project connection in another org", async (_, call) => {
+ const { service, permissionService } = buildService({ orgId: "org-2", projectId: "proj-2" });
+
+ await expect(call(service)).rejects.toBeInstanceOf(NotFoundError);
+ expect(permissionService.getOrgPermission).not.toHaveBeenCalled();
+ expect(permissionService.getProjectPermission).not.toHaveBeenCalled();
+ });
+
+ test.each(CALLS)("%s: connection in the caller's org still reaches the permission check", async (_, call) => {
+ const { service } = buildService({ orgId: ACTOR_ORG_ID, projectId: null });
+
+ await expect(call(service)).rejects.toBeInstanceOf(PermissionReached);
+ });
+});
+
+describe("validateAppConnectionUsageById refuses connections the caller cannot use", () => {
+ const canConnectOrg = createMongoAbility([
+ { action: OrgPermissionAppConnectionActions.Connect, subject: OrgPermissionSubjects.AppConnections }
+ ]);
+ const canConnectProject = createMongoAbility([
+ { action: ProjectPermissionAppConnectionActions.Connect, subject: ProjectPermissionSub.AppConnections }
+ ]);
+
+ test("org connection without Connect permission", async () => {
+ const { service } = buildService({ orgId: ACTOR_ORG_ID, projectId: null }, { org: createMongoAbility([]) });
+
+ await expect(
+ service.validateAppConnectionUsageById(
+ AppConnection.AWS,
+ { connectionId: CONNECTION_ID, projectId: "proj-1" },
+ actor
+ )
+ ).rejects.toBeInstanceOf(ForbiddenError);
+ });
+
+ test("project connection without Connect permission", async () => {
+ const { service } = buildService({ orgId: ACTOR_ORG_ID, projectId: "proj-1" }, { project: createMongoAbility([]) });
+
+ await expect(
+ service.validateAppConnectionUsageById(
+ AppConnection.AWS,
+ { connectionId: CONNECTION_ID, projectId: "proj-1" },
+ actor
+ )
+ ).rejects.toBeInstanceOf(ForbiddenError);
+ });
+
+ test("project connection from another project, even with Connect there", async () => {
+ const { service } = buildService({ orgId: ACTOR_ORG_ID, projectId: "proj-2" }, { project: canConnectProject });
+
+ await expect(
+ service.validateAppConnectionUsageById(
+ AppConnection.AWS,
+ { connectionId: CONNECTION_ID, projectId: "proj-1" },
+ actor
+ )
+ ).rejects.toThrow(BadRequestError);
+ await expect(
+ service.validateAppConnectionUsageById(
+ AppConnection.AWS,
+ { connectionId: CONNECTION_ID, projectId: "proj-1" },
+ actor
+ )
+ ).rejects.toThrow(/from project with ID "proj-2" to project with ID "proj-1"/);
+ });
+
+ test("project connection in the same project with Connect passes", async () => {
+ const { service } = buildService({ orgId: ACTOR_ORG_ID, projectId: "proj-1" }, { project: canConnectProject });
+
+ await expect(
+ service.validateAppConnectionUsageById(
+ AppConnection.AWS,
+ { connectionId: CONNECTION_ID, projectId: "proj-1" },
+ actor
+ )
+ ).resolves.toMatchObject({ id: CONNECTION_ID, projectId: "proj-1" });
+ });
+
+ test("org connection with Connect passes", async () => {
+ const { service } = buildService({ orgId: ACTOR_ORG_ID, projectId: null }, { org: canConnectOrg });
+
+ await expect(
+ service.validateAppConnectionUsageById(
+ AppConnection.AWS,
+ { connectionId: CONNECTION_ID, projectId: "proj-1" },
+ actor
+ )
+ ).resolves.toMatchObject({ id: CONNECTION_ID });
+ });
+
+ test("connection of the wrong type, even with Connect", async () => {
+ const { service } = buildService(
+ { orgId: ACTOR_ORG_ID, projectId: null, app: AppConnection.AWS },
+ { org: canConnectOrg }
+ );
+
+ await expect(
+ service.validateAppConnectionUsageById(
+ AppConnection.Venafi,
+ { connectionId: CONNECTION_ID, projectId: "proj-1" },
+ actor
+ )
+ ).rejects.toThrow(BadRequestError);
+ });
+});
diff --git a/backend/src/services/app-connection/app-connection-service.ts b/backend/src/services/app-connection/app-connection-service.ts
index ae2af5aff4..1c1ef18aa5 100644
--- a/backend/src/services/app-connection/app-connection-service.ts
+++ b/backend/src/services/app-connection/app-connection-service.ts
@@ -409,7 +409,7 @@ export const appConnectionServiceFactory = ({
const appConnection = await appConnectionDAL.findById(connectionId);
// Checked before any permission or app check, so a connection outside the scope reads exactly like a missing one.
- if (!appConnection || (scope && appConnection.projectId !== scope.projectId))
+ if (!appConnection || appConnection.orgId !== actor.orgId || (scope && appConnection.projectId !== scope.projectId))
throw new NotFoundError({ message: `Could not find App Connection with ID ${connectionId}` });
if (appConnection.projectId) {
@@ -773,7 +773,7 @@ export const appConnectionServiceFactory = ({
const appConnection = await appConnectionDAL.findById(connectionId);
- if (!appConnection || (scope && appConnection.projectId !== scope.projectId))
+ if (!appConnection || appConnection.orgId !== actor.orgId || (scope && appConnection.projectId !== scope.projectId))
throw new NotFoundError({ message: `Could not find App Connection with ID ${connectionId}` });
await enterpriseAppCheck(
@@ -1139,7 +1139,7 @@ export const appConnectionServiceFactory = ({
) => {
const appConnection = await appConnectionDAL.findById(connectionId);
- if (!appConnection || (scope && appConnection.projectId !== scope.projectId))
+ if (!appConnection || appConnection.orgId !== actor.orgId || (scope && appConnection.projectId !== scope.projectId))
throw new NotFoundError({ message: `Could not find App Connection with ID ${connectionId}` });
if (appConnection.projectId) {
@@ -1208,7 +1208,8 @@ export const appConnectionServiceFactory = ({
const allowedApps = Array.isArray(app) ? app : [app];
const appConnection = await appConnectionDAL.findById(connectionId);
- if (!appConnection) throw new NotFoundError({ message: `Could not find App Connection with ID ${connectionId}` });
+ if (!appConnection || appConnection.orgId !== actor.orgId)
+ throw new NotFoundError({ message: `Could not find App Connection with ID ${connectionId}` });
const connectionApp = appConnection.app as AppConnection;
@@ -1341,7 +1342,8 @@ export const appConnectionServiceFactory = ({
const findAppConnectionUsageById = async (app: AppConnection, connectionId: string, actor: OrgServiceActor) => {
const appConnection = await appConnectionDAL.findById(connectionId);
- if (!appConnection) throw new NotFoundError({ message: `Could not find App Connection with ID ${connectionId}` });
+ if (!appConnection || appConnection.orgId !== actor.orgId)
+ throw new NotFoundError({ message: `Could not find App Connection with ID ${connectionId}` });
const { permission } = await permissionService.getOrgPermission({
actorId: actor.id,
@@ -1372,7 +1374,7 @@ export const appConnectionServiceFactory = ({
) => {
const appConnection = await appConnectionDAL.findById(connectionId);
- if (!appConnection || (scope && appConnection.projectId !== scope.projectId))
+ if (!appConnection || appConnection.orgId !== actor.orgId || (scope && appConnection.projectId !== scope.projectId))
throw new NotFoundError({ message: `Could not find App Connection with ID ${connectionId}` });
if (appConnection.app !== app)
diff --git a/backend/src/services/certificate-authority/ca-signing-config/ca-signing-config-service.test.ts b/backend/src/services/certificate-authority/ca-signing-config/ca-signing-config-service.test.ts
new file mode 100644
index 0000000000..f7a83eb522
--- /dev/null
+++ b/backend/src/services/certificate-authority/ca-signing-config/ca-signing-config-service.test.ts
@@ -0,0 +1,268 @@
+import { createMongoAbility } from "@casl/ability";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+
+import {
+ ProjectPermissionCertificateAuthorityActions,
+ ProjectPermissionSub
+} from "@app/ee/services/permission/project-permission";
+import { ForbiddenRequestError } from "@app/lib/errors";
+import { AppConnection } from "@app/services/app-connection/app-connection-enums";
+import { ActorType, AuthMethod } from "@app/services/auth/auth-type";
+
+import { InternalCaType } from "../certificate-authority-enums";
+import { CaSigningConfigType } from "./ca-signing-config-enums";
+import { caSigningConfigServiceFactory } from "./ca-signing-config-service";
+
+const CA_PROJECT_ID = "ca-project";
+const ACTOR_ORG_ID = "org-1";
+const CONNECTION_ID = "conn-1";
+
+const permissionActor = {
+ type: ActorType.USER,
+ id: "user-1",
+ authMethod: AuthMethod.EMAIL,
+ orgId: ACTOR_ORG_ID,
+ rootOrgId: ACTOR_ORG_ID,
+ parentOrgId: ACTOR_ORG_ID
+};
+
+const actorFields = {
+ actor: ActorType.USER,
+ actorId: "user-1",
+ actorAuthMethod: AuthMethod.EMAIL,
+ actorOrgId: ACTOR_ORG_ID,
+ permissionActor
+};
+
+const DESTINATION: Record<string, Record<string, unknown>> = {
+ [CaSigningConfigType.Venafi]: {
+ applicationId: "6f1c7a52-6c55-4a9f-9a57-0d3c1a3f8f11",
+ issuingTemplateId: "0b7e2c1d-9f3a-4c2e-8d1b-5a6f7e8d9c00"
+ },
+ [CaSigningConfigType.AzureAdCs]: { template: "SubCA" },
+ [CaSigningConfigType.Adcs]: { template: "SubCA", caName: "corp-ca" }
+};
+
+const EXPECTED_APP: Record<string, AppConnection> = {
+ [CaSigningConfigType.Venafi]: AppConnection.Venafi,
+ [CaSigningConfigType.AzureAdCs]: AppConnection.AzureADCS,
+ [CaSigningConfigType.Adcs]: AppConnection.ADCS
+};
+
+const EXTERNAL_TYPES = [CaSigningConfigType.Venafi, CaSigningConfigType.AzureAdCs, CaSigningConfigType.Adcs];
+
+const buildService = ({
+ existing = null as null | { id: string; type: string },
+ validatorThrows = false,
+ plan = { pkiEnterpriseCaIntegrations: true }
+} = {}) => {
+ const caSigningConfigDAL = {
+ create: vi.fn(async (data: Record<string, unknown>) => ({ id: "cfg-new", ...data })),
+ findByCaId: vi.fn(async () => existing),
+ updateById: vi.fn(async (id: string, data: Record<string, unknown>) => ({ id, ...existing, ...data })),
+ deleteById: vi.fn(async () => undefined),
+ findOne: vi.fn(),
+ transaction: vi.fn(async (cb: (tx: unknown) => unknown) => cb({}))
+ };
+
+ const appConnectionService = {
+ validateAppConnectionUsageById: vi.fn(async () => {
+ if (validatorThrows) throw new ForbiddenRequestError({ message: "no connect" });
+ return {};
+ })
+ };
+
+ const licenseService = { getPlan: vi.fn(async () => plan) };
+
+ const deps = {
+ caSigningConfigDAL,
+ certificateAuthorityDAL: {
+ findById: vi.fn(),
+ findByIdWithAssociatedCa: vi.fn(async () => ({
+ id: "ca-1",
+ name: "intermediate",
+ projectId: CA_PROJECT_ID,
+ internalCa: { id: "internal-ca-1", dn: "CN=intermediate" }
+ }))
+ },
+ internalCertificateAuthorityDAL: {
+ findOne: vi.fn(async () => ({ id: "internal-ca-1", type: InternalCaType.INTERMEDIATE })),
+ updateById: vi.fn()
+ },
+ permissionService: {
+ getProjectPermission: vi.fn(async () => ({
+ permission: createMongoAbility([
+ {
+ action: ProjectPermissionCertificateAuthorityActions.Edit,
+ subject: ProjectPermissionSub.CertificateAuthorities
+ }
+ ])
+ }))
+ },
+ licenseService,
+ appConnectionService,
+ caAutoRenewalQueue: {
+ queueVenafiInstall: vi.fn(),
+ queueAdcsInstall: vi.fn(),
+ queueNativeAdcsInstall: vi.fn()
+ }
+ };
+
+ const service = caSigningConfigServiceFactory(deps as unknown as Parameters<typeof caSigningConfigServiceFactory>[0]);
+ return { service, caSigningConfigDAL, appConnectionService, licenseService };
+};
+
+describe("createSigningConfig connection checks", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ test.each(EXTERNAL_TYPES)("%s checks the connection for the CA's project and the caller", async (type) => {
+ const { service, appConnectionService, caSigningConfigDAL } = buildService();
+
+ await service.createSigningConfig({
+ caId: "ca-1",
+ type,
+ appConnectionId: CONNECTION_ID,
+ destinationConfig: DESTINATION[type] as never,
+ ...actorFields
+ });
+
+ expect(appConnectionService.validateAppConnectionUsageById).toHaveBeenCalledTimes(1);
+ expect(appConnectionService.validateAppConnectionUsageById).toHaveBeenCalledWith(
+ EXPECTED_APP[type],
+ { connectionId: CONNECTION_ID, projectId: CA_PROJECT_ID },
+ permissionActor
+ );
+ expect(caSigningConfigDAL.create).toHaveBeenCalledWith(
+ expect.objectContaining({ type, appConnectionId: CONNECTION_ID, destinationConfig: DESTINATION[type] }),
+ expect.anything()
+ );
+ });
+
+ test.each(EXTERNAL_TYPES)("%s writes nothing when the connection check fails", async (type) => {
+ const { service, caSigningConfigDAL } = buildService({ validatorThrows: true });
+
+ await expect(
+ service.createSigningConfig({
+ caId: "ca-1",
+ type,
+ appConnectionId: CONNECTION_ID,
+ destinationConfig: DESTINATION[type] as never,
+ ...actorFields
+ })
+ ).rejects.toBeInstanceOf(ForbiddenRequestError);
+
+ expect(caSigningConfigDAL.create).not.toHaveBeenCalled();
+ expect(caSigningConfigDAL.deleteById).not.toHaveBeenCalled();
+ });
+
+ test.each(EXTERNAL_TYPES)("%s still requires the CA integrations licence", async (type) => {
+ const { service, caSigningConfigDAL, licenseService } = buildService({
+ plan: { pkiEnterpriseCaIntegrations: false }
+ });
+
+ await expect(
+ service.createSigningConfig({
+ caId: "ca-1",
+ type,
+ appConnectionId: CONNECTION_ID,
+ destinationConfig: DESTINATION[type] as never,
+ ...actorFields
+ })
+ ).rejects.toThrow(/plan restriction/);
+
+ expect(licenseService.getPlan).toHaveBeenCalled();
+ expect(caSigningConfigDAL.create).not.toHaveBeenCalled();
+ });
+
+ test("switching between external types skips the licence check", async () => {
+ const { service, licenseService } = buildService({
+ existing: { id: "cfg-old", type: CaSigningConfigType.Venafi },
+ plan: { pkiEnterpriseCaIntegrations: false }
+ });
+
+ await service.createSigningConfig({
+ caId: "ca-1",
+ type: CaSigningConfigType.AzureAdCs,
+ appConnectionId: CONNECTION_ID,
+ destinationConfig: DESTINATION[CaSigningConfigType.AzureAdCs] as never,
+ ...actorFields
+ });
+
+ expect(licenseService.getPlan).not.toHaveBeenCalled();
+ });
+
+ test.each([CaSigningConfigType.Internal, CaSigningConfigType.Manual])(
+ "%s does not check a connection or the licence",
+ async (type) => {
+ const { service, appConnectionService, licenseService, caSigningConfigDAL } = buildService();
+
+ await service.createSigningConfig({
+ caId: "ca-1",
+ type,
+ parentCaId: type === CaSigningConfigType.Internal ? "parent-ca" : undefined,
+ ...actorFields
+ });
+
+ expect(appConnectionService.validateAppConnectionUsageById).not.toHaveBeenCalled();
+ expect(licenseService.getPlan).not.toHaveBeenCalled();
+ expect(caSigningConfigDAL.create).toHaveBeenCalledWith(
+ expect.objectContaining({ type, appConnectionId: undefined, destinationConfig: undefined }),
+ expect.anything()
+ );
+ }
+ );
+});
+
+describe("updateSigningConfig connection checks", () => {
+ beforeEach(() => vi.clearAllMocks());
+
+ test.each(EXTERNAL_TYPES)("%s checks a new connection for the CA's project and the caller", async (type) => {
+ const { service, appConnectionService, caSigningConfigDAL } = buildService({
+ existing: { id: "cfg-1", type }
+ });
+
+ await service.updateSigningConfig({ caId: "ca-1", appConnectionId: CONNECTION_ID, ...actorFields });
+
+ expect(appConnectionService.validateAppConnectionUsageById).toHaveBeenCalledTimes(1);
+ expect(appConnectionService.validateAppConnectionUsageById).toHaveBeenCalledWith(
+ EXPECTED_APP[type],
+ { connectionId: CONNECTION_ID, projectId: CA_PROJECT_ID },
+ permissionActor
+ );
+ expect(caSigningConfigDAL.updateById).toHaveBeenCalledWith(
+ "cfg-1",
+ expect.objectContaining({ appConnectionId: CONNECTION_ID })
+ );
+ });
+
+ test.each(EXTERNAL_TYPES)("%s writes nothing when the connection check fails", async (type) => {
+ const { service, caSigningConfigDAL } = buildService({
+ existing: { id: "cfg-1", type },
+ validatorThrows: true
+ });
+
+ await expect(
+ service.updateSigningConfig({ caId: "ca-1", appConnectionId: CONNECTION_ID, ...actorFields })
+ ).rejects.toBeInstanceOf(ForbiddenRequestError);
+
+ expect(caSigningConfigDAL.updateById).not.toHaveBeenCalled();
+ });
+
+ test.each(EXTERNAL_TYPES)("%s does not check the connection when none is sent", async (type) => {
+ const { service, appConnectionService, caSigningConfigDAL } = buildService({
+ existing: { id: "cfg-1", type }
+ });
+
+ await service.updateSigningConfig({
+ caId: "ca-1",
+ destinationConfig: DESTINATION[type] as never,
+ ...actorFields
+ });
+
+ expect(appConnectionService.validateAppConnectionUsageById).not.toHaveBeenCalled();
+ expect(caSigningConfigDAL.updateById).toHaveBeenCalledWith(
+ "cfg-1",
+ expect.objectContaining({ destinationConfig: DESTINATION[type] })
+ );
+ });
+});
diff --git a/backend/src/services/certificate-authority/ca-signing-config/ca-signing-config-service.ts b/backend/src/services/certificate-authority/ca-signing-config/ca-signing-config-service.ts
index fc44d13f14..873f2dd008 100644
--- a/backend/src/services/certificate-authority/ca-signing-config/ca-signing-config-service.ts
+++ b/backend/src/services/certificate-authority/ca-signing-config/ca-signing-config-service.ts
@@ -9,7 +9,6 @@ import {
} from "@app/ee/services/permission/project-permission";
import { BadRequestError, NotFoundError } from "@app/lib/errors";
import { OrgServiceActor } from "@app/lib/types";
-import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";
import { AppConnection } from "@app/services/app-connection/app-connection-enums";
import { TAppConnectionServiceFactory } from "@app/services/app-connection/app-connection-service";
import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";
@@ -32,12 +31,14 @@ import {
VenafiDestinationConfigSchema
} from "./ca-signing-config-types";
+const CA_SIGNING_CONFIG_CONNECTION_MAP: Partial<Record<CaSigningConfigType, AppConnection>> = {
+ [CaSigningConfigType.Venafi]: AppConnection.Venafi,
+ [CaSigningConfigType.AzureAdCs]: AppConnection.AzureADCS,
+ [CaSigningConfigType.Adcs]: AppConnection.ADCS
+};
+
// Signing through a third-party provider is the same capability as connecting one as an external CA.
-const EXTERNAL_SIGNING_TYPES: string[] = [
- CaSigningConfigType.Venafi,
- CaSigningConfigType.AzureAdCs,
- CaSigningConfigType.Adcs
-];
+const EXTERNAL_SIGNING_TYPES: string[] = Object.keys(CA_SIGNING_CONFIG_CONNECTION_MAP);
type TCaSigningConfigServiceFactoryDep = {
caSigningConfigDAL: Pick<
@@ -48,7 +49,6 @@ type TCaSigningConfigServiceFactoryDep = {
internalCertificateAuthorityDAL: Pick<TInternalCertificateAuthorityDALFactory, "findOne" | "updateById">;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
licenseService: Pick<TLicenseServiceFactory, "getPlan">;
- appConnectionDAL: Pick<TAppConnectionDALFactory, "findById">;
appConnectionService: Pick<TAppConnectionServiceFactory, "validateAppConnectionUsageById">;
caAutoRenewalQueue: Pick<
TCaAutoRenewalQueueFactory,
@@ -64,21 +64,9 @@ export const caSigningConfigServiceFactory = ({
internalCertificateAuthorityDAL,
permissionService,
licenseService,
- appConnectionDAL,
appConnectionService,
caAutoRenewalQueue
}: TCaSigningConfigServiceFactoryDep) => {
- const validateAppConnectionOrg = async (connectionId: string, actorOrgId: string) => {
- const appConnection = await appConnectionDAL.findById(connectionId);
- if (!appConnection || appConnection.orgId !== actorOrgId) {
- throw new BadRequestError({ message: "App connection not found or does not belong to your organization" });
- }
- };
-
- const validateAdcsAppConnectionUsage = async (connectionId: string, projectId: string, actor: OrgServiceActor) => {
- await appConnectionService.validateAppConnectionUsageById(AppConnection.ADCS, { connectionId, projectId }, actor);
- };
-
const getSigningConfigByCaId = async (internalCaId: string) => {
const config = await caSigningConfigDAL.findByCaId(internalCaId);
if (!config) {
@@ -87,6 +75,18 @@ export const caSigningConfigServiceFactory = ({
return config;
};
+ const validateSigningAppConnection = async (
+ type: CaSigningConfigType,
+ connectionId: string | undefined,
+ projectId: string,
+ actor: OrgServiceActor
+ ) => {
+ const app = CA_SIGNING_CONFIG_CONNECTION_MAP[type];
+ if (!app || connectionId === undefined) return;
+
+ await appConnectionService.validateAppConnectionUsageById(app, { connectionId, projectId }, actor);
+ };
+
const createSigningConfig = async ({
caId,
type,
@@ -144,7 +144,6 @@ export const caSigningConfigServiceFactory = ({
throw new BadRequestError({ message: "Destination config is required for Venafi signing" });
}
VenafiDestinationConfigSchema.parse(destinationConfig);
- await validateAppConnectionOrg(appConnectionId, actorOrgId);
}
// Azure AD CS requires appConnectionId and destinationConfig
@@ -156,7 +155,6 @@ export const caSigningConfigServiceFactory = ({
throw new BadRequestError({ message: "Destination config is required for Azure AD CS signing" });
}
AzureAdCsDestinationConfigSchema.parse(destinationConfig);
- await validateAppConnectionOrg(appConnectionId, actorOrgId);
}
if (type === CaSigningConfigType.Adcs) {
@@ -167,9 +165,10 @@ export const caSigningConfigServiceFactory = ({
throw new BadRequestError({ message: "Destination config is required for ADCS signing" });
}
AdcsDestinationConfigSchema.parse(destinationConfig);
- await validateAdcsAppConnectionUsage(appConnectionId, ca.projectId, permissionActor);
}
+ await validateSigningAppConnection(type, appConnectionId, ca.projectId, permissionActor);
+
const isExternalCa = EXTERNAL_SIGNING_TYPES.includes(type);
// An org already signing through a provider can re-save or switch between them; only introducing
@@ -294,13 +293,19 @@ export const caSigningConfigServiceFactory = ({
lastExternalCertificateId?: string;
} = {};
+ await validateSigningAppConnection(
+ existing.type as CaSigningConfigType,
+ appConnectionId,
+ ca.projectId,
+ permissionActor
+ );
+
if (existing.type === CaSigningConfigType.Internal && parentCaId !== undefined) {
updateData.parentCaId = parentCaId;
}
if (existing.type === CaSigningConfigType.Venafi) {
if (appConnectionId !== undefined) {
- await validateAppConnectionOrg(appConnectionId, actorOrgId);
updateData.appConnectionId = appConnectionId;
}
if (destinationConfig !== undefined) {
@@ -312,7 +317,6 @@ export const caSigningConfigServiceFactory = ({
if (existing.type === CaSigningConfigType.AzureAdCs) {
if (appConnectionId !== undefined) {
- await validateAppConnectionOrg(appConnectionId, actorOrgId);
updateData.appConnectionId = appConnectionId;
}
if (destinationConfig !== undefined) {
@@ -323,7 +327,6 @@ export const caSigningConfigServiceFactory = ({
if (existing.type === CaSigningConfigType.Adcs) {
if (appConnectionId !== undefined) {
- await validateAdcsAppConnectionUsage(appConnectionId, ca.projectId, permissionActor);
updateData.appConnectionId = appConnectionId;
}
if (destinationConfig !== undefined) {