feat: finished up integration for est config management

This commit is contained in:
Sheen Capadngan
2024-08-14 01:00:31 +08:00
parent f2a49a79f0
commit 1f38b92ec6
10 changed files with 334 additions and 30 deletions
+4 -1
View File
@@ -86,6 +86,7 @@ import { certificateDALFactory } from "@app/services/certificate/certificate-dal
import { certificateServiceFactory } from "@app/services/certificate/certificate-service"; import { certificateServiceFactory } from "@app/services/certificate/certificate-service";
import { certificateAuthorityCertDALFactory } from "@app/services/certificate-authority/certificate-authority-cert-dal"; import { certificateAuthorityCertDALFactory } from "@app/services/certificate-authority/certificate-authority-cert-dal";
import { certificateAuthorityDALFactory } from "@app/services/certificate-authority/certificate-authority-dal"; import { certificateAuthorityDALFactory } from "@app/services/certificate-authority/certificate-authority-dal";
import { certificateAuthorityEstConfigDALFactory } from "@app/services/certificate-authority/certificate-authority-est-config-dal";
import { certificateAuthorityQueueFactory } from "@app/services/certificate-authority/certificate-authority-queue"; import { certificateAuthorityQueueFactory } from "@app/services/certificate-authority/certificate-authority-queue";
import { certificateAuthoritySecretDALFactory } from "@app/services/certificate-authority/certificate-authority-secret-dal"; import { certificateAuthoritySecretDALFactory } from "@app/services/certificate-authority/certificate-authority-secret-dal";
import { certificateAuthorityServiceFactory } from "@app/services/certificate-authority/certificate-authority-service"; import { certificateAuthorityServiceFactory } from "@app/services/certificate-authority/certificate-authority-service";
@@ -585,6 +586,7 @@ export const registerRoutes = async (
const certificateAuthorityCertDAL = certificateAuthorityCertDALFactory(db); const certificateAuthorityCertDAL = certificateAuthorityCertDALFactory(db);
const certificateAuthoritySecretDAL = certificateAuthoritySecretDALFactory(db); const certificateAuthoritySecretDAL = certificateAuthoritySecretDALFactory(db);
const certificateAuthorityCrlDAL = certificateAuthorityCrlDALFactory(db); const certificateAuthorityCrlDAL = certificateAuthorityCrlDALFactory(db);
const certificateAuthorityEstConfigDAL = certificateAuthorityEstConfigDALFactory(db);
const certificateDAL = certificateDALFactory(db); const certificateDAL = certificateDALFactory(db);
const certificateBodyDAL = certificateBodyDALFactory(db); const certificateBodyDAL = certificateBodyDALFactory(db);
@@ -625,7 +627,8 @@ export const registerRoutes = async (
certificateBodyDAL, certificateBodyDAL,
projectDAL, projectDAL,
kmsService, kmsService,
permissionService permissionService,
certificateAuthorityEstConfigDAL
}); });
const certificateAuthorityCrlService = certificateAuthorityCrlServiceFactory({ const certificateAuthorityCrlService = certificateAuthorityCrlServiceFactory({
@@ -2,6 +2,7 @@ import ms from "ms";
import { z } from "zod"; import { z } from "zod";
import { CertificateAuthoritiesSchema } from "@app/db/schemas"; import { CertificateAuthoritiesSchema } from "@app/db/schemas";
import { CertificateAuthorityEstConfigsSchema } from "@app/db/schemas/certificate-authority-est-configs";
import { EventType } from "@app/ee/services/audit-log/audit-log-types"; import { EventType } from "@app/ee/services/audit-log/audit-log-types";
import { CERTIFICATE_AUTHORITIES } from "@app/lib/api-docs"; import { CERTIFICATE_AUTHORITIES } from "@app/lib/api-docs";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter"; import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
@@ -697,4 +698,128 @@ export const registerCaRouter = async (server: FastifyZodProvider) => {
}; };
} }
}); });
server.route({
method: "POST",
url: "/:caId/est-config",
config: {
rateLimit: writeLimit
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
schema: {
description: "Create CA EST configuration",
params: z.object({
caId: z.string().trim()
}),
body: z.object({
caChain: z.string().trim().min(1),
passphrase: z.string().min(1),
isEnabled: z.boolean().default(true)
}),
response: {
200: z.object({
caEstConfig: CertificateAuthorityEstConfigsSchema.pick({
caId: true,
isEnabled: true
})
})
}
},
handler: async (req) => {
const caEstConfig = await server.services.certificateAuthority.createCaEstConfiguration({
caId: req.params.caId,
actor: req.permission.type,
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
...req.body
});
return {
caEstConfig
};
}
});
server.route({
method: "PATCH",
url: "/:caId/est-config",
config: {
rateLimit: writeLimit
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
schema: {
description: "Update CA EST configuration",
params: z.object({
caId: z.string().trim()
}),
body: z.object({
caChain: z.string().trim().min(1).optional(),
passphrase: z.string().min(1).optional(),
isEnabled: z.boolean().optional()
}),
response: {
200: z.object({
caEstConfig: CertificateAuthorityEstConfigsSchema.pick({
caId: true,
isEnabled: true
})
})
}
},
handler: async (req) => {
const caEstConfig = await server.services.certificateAuthority.updateCaEstConfiguration({
caId: req.params.caId,
actor: req.permission.type,
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId,
...req.body
});
return {
caEstConfig
};
}
});
server.route({
method: "GET",
url: "/:caId/est-config",
config: {
rateLimit: readLimit
},
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
schema: {
description: "Get CA EST configuration",
params: z.object({
caId: z.string().trim()
}),
response: {
200: z.object({
caEstConfig: CertificateAuthorityEstConfigsSchema.pick({
caId: true,
isEnabled: true
}).merge(
z.object({
caChain: z.string()
})
)
})
}
},
handler: async (req) => {
const caEstConfig = await server.services.certificateAuthority.getCaEstConfiguration({
caId: req.params.caId,
actor: req.permission.type,
actorId: req.permission.id,
actorAuthMethod: req.permission.authMethod,
actorOrgId: req.permission.orgId
});
return {
caEstConfig
};
}
});
}; };
@@ -42,6 +42,7 @@ import {
TGetCaCertsDTO, TGetCaCertsDTO,
TGetCaCsrDTO, TGetCaCsrDTO,
TGetCaDTO, TGetCaDTO,
TGetCaEstConfigurationDTO,
TImportCertToCaDTO, TImportCertToCaDTO,
TIssueCertFromCaDTO, TIssueCertFromCaDTO,
TRenewCaCertDTO, TRenewCaCertDTO,
@@ -1534,6 +1535,62 @@ export const certificateAuthorityServiceFactory = ({
return estConfig; return estConfig;
}; };
const getCaEstConfiguration = async ({
caId,
actorId,
actorAuthMethod,
actor,
actorOrgId
}: TGetCaEstConfigurationDTO) => {
const ca = await certificateAuthorityDAL.findById(caId);
if (!ca) {
throw new NotFoundError({ message: "CA not found" });
}
const { permission } = await permissionService.getProjectPermission(
actor,
actorId,
ca.projectId,
actorAuthMethod,
actorOrgId
);
ForbiddenError.from(permission).throwUnlessCan(
ProjectPermissionActions.Edit,
ProjectPermissionSub.CertificateAuthorities
);
const caEstConfig = await certificateAuthorityEstConfigDAL.findOne({
caId
});
if (!caEstConfig) {
throw new NotFoundError({
message: "CA EST Config not found"
});
}
const certificateManagerKmsId = await getProjectKmsCertificateKeyId({
projectId: ca.projectId,
projectDAL,
kmsService
});
const kmsDecryptor = await kmsService.decryptWithKmsKey({
kmsId: certificateManagerKmsId
});
const decryptedCaChain = await kmsDecryptor({
cipherTextBlob: caEstConfig.encryptedCaChain
});
return {
caId,
isEnabled: caEstConfig.isEnabled,
caChain: decryptedCaChain.toString()
};
};
return { return {
createCa, createCa,
getCaById, getCaById,
@@ -1548,6 +1605,7 @@ export const certificateAuthorityServiceFactory = ({
issueCertFromCa, issueCertFromCa,
signCertFromCa, signCertFromCa,
createCaEstConfiguration, createCaEstConfiguration,
updateCaEstConfiguration updateCaEstConfiguration,
getCaEstConfiguration
}; };
}; };
@@ -180,3 +180,7 @@ export type TUpdateCaEstConfigurationDTO = {
passphrase?: string; passphrase?: string;
isEnabled?: boolean; isEnabled?: boolean;
} & Omit<TProjectPermission, "projectId">; } & Omit<TProjectPermission, "projectId">;
export type TGetCaEstConfigurationDTO = {
caId: string;
} & Omit<TProjectPermission, "projectId">;
+13 -3
View File
@@ -1,10 +1,20 @@
export { CaRenewalType,CaStatus, CaType } from "./enums"; export { CaRenewalType, CaStatus, CaType } from "./enums";
export { export {
useCreateCa, useCreateCa,
useCreateCaEstConfig,
useCreateCertificate, useCreateCertificate,
useDeleteCa, useDeleteCa,
useImportCaCertificate, useImportCaCertificate,
useRenewCa, useRenewCa,
useSignIntermediate, useSignIntermediate,
useUpdateCa} from "./mutations"; useUpdateCa,
export { useGetCaById, useGetCaCert, useGetCaCerts, useGetCaCrl, useGetCaCsr } from "./queries"; useUpdateCaEstConfig
} from "./mutations";
export {
useGetCaById,
useGetCaCert,
useGetCaCerts,
useGetCaCrl,
useGetCaCsr,
useGetCaEstConfig
} from "./queries";
+30 -1
View File
@@ -7,6 +7,7 @@ import { caKeys } from "./queries";
import { import {
TCertificateAuthority, TCertificateAuthority,
TCreateCaDTO, TCreateCaDTO,
TCreateCaEstConfigDTO,
TCreateCertificateDTO, TCreateCertificateDTO,
TCreateCertificateResponse, TCreateCertificateResponse,
TDeleteCaDTO, TDeleteCaDTO,
@@ -16,7 +17,9 @@ import {
TRenewCaResponse, TRenewCaResponse,
TSignIntermediateDTO, TSignIntermediateDTO,
TSignIntermediateResponse, TSignIntermediateResponse,
TUpdateCaDTO} from "./types"; TUpdateCaDTO,
TUpdateCaEstConfigDTO
} from "./types";
export const useCreateCa = () => { export const useCreateCa = () => {
const queryClient = useQueryClient(); const queryClient = useQueryClient();
@@ -130,3 +133,29 @@ export const useRenewCa = () => {
} }
}); });
}; };
export const useCreateCaEstConfig = () => {
const queryClient = useQueryClient();
return useMutation<{}, {}, TCreateCaEstConfigDTO>({
mutationFn: async (body) => {
const { data } = await apiRequest.post(`/api/v1/pki/ca/${body.caId}/est-config`, body);
return data;
},
onSuccess: (_, { caId }) => {
queryClient.invalidateQueries(caKeys.getCaEstConfig(caId));
}
});
};
export const useUpdateCaEstConfig = () => {
const queryClient = useQueryClient();
return useMutation<{}, {}, TUpdateCaEstConfigDTO>({
mutationFn: async (body) => {
const { data } = await apiRequest.patch(`/api/v1/pki/ca/${body.caId}/est-config`, body);
return data;
},
onSuccess: (_, { caId }) => {
queryClient.invalidateQueries(caKeys.getCaEstConfig(caId));
}
});
};
+19 -2
View File
@@ -2,14 +2,15 @@ import { useQuery } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request"; import { apiRequest } from "@app/config/request";
import { TCertificateAuthority } from "./types"; import { TCaEstConfig, TCertificateAuthority } from "./types";
export const caKeys = { export const caKeys = {
getCaById: (caId: string) => [{ caId }, "ca"], getCaById: (caId: string) => [{ caId }, "ca"],
getCaCerts: (caId: string) => [{ caId }, "ca-cert"], getCaCerts: (caId: string) => [{ caId }, "ca-cert"],
getCaCert: (caId: string) => [{ caId }, "ca-cert"], getCaCert: (caId: string) => [{ caId }, "ca-cert"],
getCaCsr: (caId: string) => [{ caId }, "ca-csr"], getCaCsr: (caId: string) => [{ caId }, "ca-csr"],
getCaCrl: (caId: string) => [{ caId }, "ca-crl"] getCaCrl: (caId: string) => [{ caId }, "ca-crl"],
getCaEstConfig: (caId: string) => [{ caId }, "ca-est-config"]
}; };
export const useGetCaById = (caId: string) => { export const useGetCaById = (caId: string) => {
@@ -87,3 +88,19 @@ export const useGetCaCrl = (caId: string) => {
enabled: Boolean(caId) enabled: Boolean(caId)
}); });
}; };
export const useGetCaEstConfig = (caId: string) => {
return useQuery({
queryKey: caKeys.getCaEstConfig(caId),
queryFn: async () => {
const {
data: { caEstConfig }
} = await apiRequest.get<{
caEstConfig: TCaEstConfig;
}>(`/api/v1/pki/ca/${caId}/est-config`);
return caEstConfig;
},
enabled: Boolean(caId)
});
};
+21 -1
View File
@@ -1,5 +1,5 @@
import { CertKeyAlgorithm } from "../certificates/enums"; import { CertKeyAlgorithm } from "../certificates/enums";
import { CaRenewalType,CaStatus, CaType } from "./enums"; import { CaRenewalType, CaStatus, CaType } from "./enums";
export type TCertificateAuthority = { export type TCertificateAuthority = {
id: string; id: string;
@@ -107,3 +107,23 @@ export type TRenewCaResponse = {
certificateChain: string; certificateChain: string;
serialNumber: string; serialNumber: string;
}; };
export type TCaEstConfig = {
caId: string;
caChain: string;
isEnabled: false;
};
export type TCreateCaEstConfigDTO = {
caId: string;
caChain: string;
passphrase: string;
isEnabled: boolean;
};
export type TUpdateCaEstConfigDTO = {
caId: string;
caChain?: string;
passphrase?: string;
isEnabled?: boolean;
};
@@ -125,7 +125,9 @@ export const CaDetailsSection = ({ caId, handlePopUpOpen }: Props) => {
colorSchema="secondary" colorSchema="secondary"
type="submit" type="submit"
onClick={() => { onClick={() => {
handlePopUpOpen("enrollmentOptions"); handlePopUpOpen("enrollmentOptions", {
caId
});
}} }}
> >
Enrollment Options Enrollment Options
@@ -1,3 +1,4 @@
import { useEffect } from "react";
import { Controller, useForm } from "react-hook-form"; import { Controller, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod"; import { zodResolver } from "@hookform/resolvers/zod";
import z from "zod"; import z from "zod";
@@ -14,6 +15,7 @@ import {
Switch, Switch,
TextArea TextArea
} from "@app/components/v2"; } from "@app/components/v2";
import { useCreateCaEstConfig, useGetCaEstConfig, useUpdateCaEstConfig } from "@app/hooks/api";
import { UsePopUpState } from "@app/hooks/usePopUp"; import { UsePopUpState } from "@app/hooks/usePopUp";
enum EnrollmentMethod { enum EnrollmentMethod {
@@ -28,32 +30,73 @@ type Props = {
) => void; ) => void;
}; };
const schema = z const schema = z.object({
.object({ method: z.nativeEnum(EnrollmentMethod),
method: z.nativeEnum(EnrollmentMethod), caChain: z.string(),
caChain: z.string(), passphrase: z.string().optional(),
passphrase: z.string(), isEnabled: z.boolean()
isEnabled: z.boolean() });
})
.required();
export type FormData = z.infer<typeof schema>; export type FormData = z.infer<typeof schema>;
export const CaEnrollmentModal = ({ popUp, handlePopUpToggle }: Props) => { export const CaEnrollmentModal = ({ popUp, handlePopUpToggle }: Props) => {
const popUpData = popUp?.enrollmentOptions?.data as {
caId: string;
};
const caId = popUpData?.caId;
const { data } = useGetCaEstConfig(caId);
const { const {
control, control,
handleSubmit, handleSubmit,
reset, reset,
setError,
formState: { isSubmitting } formState: { isSubmitting }
} = useForm<FormData>({ } = useForm<FormData>({
resolver: zodResolver(schema), resolver: zodResolver(schema)
defaultValues: {
isEnabled: false
}
}); });
const { mutateAsync: createCaEstConfig } = useCreateCaEstConfig();
const { mutateAsync: updateCaEstConfig } = useUpdateCaEstConfig();
useEffect(() => {
if (data) {
reset({
caChain: data.caChain,
isEnabled: data.isEnabled
});
} else {
reset({
caChain: "",
isEnabled: false
});
}
}, [data]);
const onFormSubmit = async ({ caChain, passphrase, isEnabled }: FormData) => { const onFormSubmit = async ({ caChain, passphrase, isEnabled }: FormData) => {
try { try {
if (data) {
await updateCaEstConfig({
caId,
caChain,
passphrase,
isEnabled
});
} else {
if (!passphrase) {
setError("passphrase", { message: "Passphrase is required to setup EST enrollment." });
return;
}
await createCaEstConfig({
caId,
caChain,
passphrase,
isEnabled
});
}
handlePopUpToggle("enrollmentOptions", false); handlePopUpToggle("enrollmentOptions", false);
createNotification({ createNotification({
@@ -102,7 +145,6 @@ export const CaEnrollmentModal = ({ popUp, handlePopUpToggle }: Props) => {
/> />
<Controller <Controller
control={control} control={control}
defaultValue=""
name="caChain" name="caChain"
render={({ field, fieldState: { error } }) => ( render={({ field, fieldState: { error } }) => (
<FormControl <FormControl
@@ -117,15 +159,9 @@ export const CaEnrollmentModal = ({ popUp, handlePopUpToggle }: Props) => {
/> />
<Controller <Controller
control={control} control={control}
defaultValue=""
name="passphrase" name="passphrase"
render={({ field, fieldState: { error } }) => ( render={({ field, fieldState: { error } }) => (
<FormControl <FormControl label="Passphrase" isError={Boolean(error)} errorText={error?.message}>
label="Passphrase"
isError={Boolean(error)}
errorText={error?.message}
isRequired
>
<Input {...field} type="password" /> <Input {...field} type="password" />
</FormControl> </FormControl>
)} )}