Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
Address PR comments
Carlos Monastyrski0279b6b8074a
diff --git a/backend/src/ee/services/pki-scep/challenge/scep-intune-handler.ts b/backend/src/ee/services/pki-scep/challenge/scep-intune-handler.tsindex cfcb8cc992..fc07f41d57 100644--- a/backend/src/ee/services/pki-scep/challenge/scep-intune-handler.ts+++ b/backend/src/ee/services/pki-scep/challenge/scep-intune-handler.ts@@ -1,8 +1,8 @@import * as x509 from "@peculiar/x509";import { KeyStorePrefixes } from "@app/keystore/keystore";-import { withCache } from "@app/lib/cache/with-cache";import { BadRequestError } from "@app/lib/errors";+import { logger } from "@app/lib/logger";import { AppConnection } from "@app/services/app-connection/app-connection-enums";import { decryptAppConnectionCredentials } from "@app/services/app-connection/app-connection-fns";import {@@ -14,6 +14,7 @@ import {MicrosoftEntraTokenResource,TMicrosoftIntuneConnectionCredentials} from "@app/services/app-connection/microsoft-intune";+import { KmsDataKey } from "@app/services/kms/kms-types";import { IScepValidationHandler, TScepValidationHandlerDeps } from "./scep-validation-handler-types";@@ -47,33 +48,66 @@ export const intuneDelegatedHandler = (deps: TScepValidationHandlerDeps): IScepVconst inFlight = intuneAccessInFlight.get(cacheKey);if (inFlight) return inFlight;- const acquisition = withCache<TIntuneAccess>({- keyStore: deps.keyStore,- key: cacheKey,- ttlSeconds: intuneAccessTtlSeconds,- fetcher: async () => {- const credentials = (await decryptAppConnectionCredentials({- orgId: connection.orgId,- projectId: connection.projectId,- encryptedCredentials: connection.encryptedCredentials,- kmsService: deps.kmsService- })) as TMicrosoftIntuneConnectionCredentials;-- const graphToken = await getMicrosoftEntraToken(credentials, MicrosoftEntraTokenResource.Graph);- const serviceUri = await discoverScepValidationServiceUri(graphToken.accessToken);- const intuneToken = await getMicrosoftEntraToken(credentials, MicrosoftEntraTokenResource.Intune);-- return { serviceUri, intuneToken: intuneToken.accessToken, expiresAt: intuneToken.expiresAt };+ const remember = (access: TIntuneAccess) => {+ for (const key of intuneAccessCache.keys()) {+ if (key !== cacheKey && key.startsWith(connectionKeyPrefix)) intuneAccessCache.delete(key);}- })- .then((access) => {- for (const key of intuneAccessCache.keys()) {- if (key !== cacheKey && key.startsWith(connectionKeyPrefix)) intuneAccessCache.delete(key);+ intuneAccessCache.set(cacheKey, access);+ };++ const acquisition = (async (): Promise<TIntuneAccess> => {+ const { encryptor, decryptor } = await deps.kmsService.createCipherPairWithDataKey(+ connection.projectId+ ? { type: KmsDataKey.SecretManager, projectId: connection.projectId }+ : { type: KmsDataKey.Organization, orgId: connection.orgId }+ );++ const cachedCipherText = await deps.keyStore.getItem(cacheKey).catch((err: unknown) => {+ logger.warn({ err }, `Intune access cache read failed [cacheKey=${cacheKey}]`);+ return null;+ });+ if (cachedCipherText) {+ try {+ const shared = JSON.parse(+ decryptor({ cipherTextBlob: Buffer.from(cachedCipherText, "base64") }).toString("utf8")+ ) as TIntuneAccess;+ if (shared.expiresAt > Date.now()) {+ remember(shared);+ return shared;+ }+ } catch (err) {+ logger.warn({ err }, `Intune access cache decrypt failed, re-acquiring [cacheKey=${cacheKey}]`);}- intuneAccessCache.set(cacheKey, access);- return access;- })- .finally(() => intuneAccessInFlight.delete(cacheKey));+ }++ const credentials = (await decryptAppConnectionCredentials({+ orgId: connection.orgId,+ projectId: connection.projectId,+ encryptedCredentials: connection.encryptedCredentials,+ kmsService: deps.kmsService+ })) as TMicrosoftIntuneConnectionCredentials;++ const graphToken = await getMicrosoftEntraToken(credentials, MicrosoftEntraTokenResource.Graph);+ const serviceUri = await discoverScepValidationServiceUri(graphToken.accessToken);+ const intuneToken = await getMicrosoftEntraToken(credentials, MicrosoftEntraTokenResource.Intune);++ const access: TIntuneAccess = {+ serviceUri,+ intuneToken: intuneToken.accessToken,+ expiresAt: intuneToken.expiresAt+ };++ await deps.keyStore+ .setItemWithExpiry(+ cacheKey,+ intuneAccessTtlSeconds(access),+ encryptor({ plainText: Buffer.from(JSON.stringify(access)) }).cipherTextBlob.toString("base64")+ )+ .catch((err: unknown) => logger.warn({ err }, `Intune access cache write failed [cacheKey=${cacheKey}]`));++ remember(access);+ return access;+ })().finally(() => intuneAccessInFlight.delete(cacheKey));intuneAccessInFlight.set(cacheKey, acquisition);return acquisition;diff --git a/backend/src/ee/services/pki-scep/pki-scep-fns.ts b/backend/src/ee/services/pki-scep/pki-scep-fns.tsindex f749f9ba09..d3adb52082 100644--- a/backend/src/ee/services/pki-scep/pki-scep-fns.ts+++ b/backend/src/ee/services/pki-scep/pki-scep-fns.ts@@ -143,6 +143,14 @@ export const SCEP_RA_CA_SIGNING_SUPPORTED_BY_CA_TYPE: Record<CaType, boolean> =export const isScepRaCaSigningSupported = (caType: CaType): boolean =>SCEP_RA_CA_SIGNING_SUPPORTED_BY_CA_TYPE[caType] ?? false;+export const resolveCaType = async (+ caId: string | null | undefined,+ certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findByIdWithAssociatedCa">+): Promise<CaType> => {+ const ca = caId ? await certificateAuthorityDAL.findByIdWithAssociatedCa(caId) : null;+ return (ca?.externalCa?.type as CaType) ?? CaType.INTERNAL;+};+export const resolveScepRaSigning = async ({caId,requestedSignRaWithCa,@@ -151,16 +159,15 @@ export const resolveScepRaSigning = async ({caId?: string | null;requestedSignRaWithCa?: boolean;certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findByIdWithAssociatedCa">;-}): Promise<{ signRaWithCa: boolean; raCaSigningSupported: boolean; caType: CaType }> => {- const ca = caId ? await certificateAuthorityDAL.findByIdWithAssociatedCa(caId) : null;- const caType = (ca?.externalCa?.type as CaType) ?? CaType.INTERNAL;+}): Promise<{ signRaWithCa: boolean; raCaSigningSupported: boolean }> => {+ const caType = await resolveCaType(caId, certificateAuthorityDAL);const raCaSigningSupported = isScepRaCaSigningSupported(caType);if (requestedSignRaWithCa === true && !raCaSigningSupported) {throw new BadRequestError({message: `CA-signed SCEP RA certificates are not supported for '${caType}' certificate authorities.`});}- return { signRaWithCa: requestedSignRaWithCa ?? false, raCaSigningSupported, caType };+ return { signRaWithCa: requestedSignRaWithCa ?? false, raCaSigningSupported };};const buildCaSignedRaCertificate = async (slug: string, caId: string, deps: TGenerateScepRaCertificateDeps) => {diff --git a/backend/src/services/app-connection/microsoft-intune/microsoft-intune-connection-fns.ts b/backend/src/services/app-connection/microsoft-intune/microsoft-intune-connection-fns.tsindex 859cf7eaec..96f6976e48 100644--- a/backend/src/services/app-connection/microsoft-intune/microsoft-intune-connection-fns.ts+++ b/backend/src/services/app-connection/microsoft-intune/microsoft-intune-connection-fns.ts@@ -155,6 +155,14 @@ export const intuneValidateScepRequest = async ({}};+const assertIntuneNotificationAccepted = (data: TIntuneScepValidationResponse | undefined, action: string) => {+ if (data?.code && data.code.toLowerCase() !== INTUNE_SUCCESS_CODE) {+ throw new BadRequestError({+ message: `Microsoft Intune rejected the SCEP ${action}: ${data.errorDescription || data.code}`+ });+ }+};+export const intuneSendSuccessNotification = async ({intuneAccessToken,serviceUri,@@ -171,11 +179,13 @@ export const intuneSendSuccessNotification = async ({issuingCertificateAuthority: string;};}) => {- await safeRequest.post(+ const { data } = await safeRequest.post<TIntuneScepValidationResponse>(`${serviceUri}/ScepActions/successNotification`,{ notification: { ...notification, callerInfo: INTUNE_CALLER_INFO } },{ headers: intuneScepActionHeaders(intuneAccessToken) });++ assertIntuneNotificationAccepted(data, "success notification");};export const intuneSendFailureNotification = async ({@@ -192,11 +202,13 @@ export const intuneSendFailureNotification = async ({errorDescription: string;};}) => {- await safeRequest.post(+ const { data } = await safeRequest.post<TIntuneScepValidationResponse>(`${serviceUri}/ScepActions/failureNotification`,{ notification: { ...notification, callerInfo: INTUNE_CALLER_INFO } },{ headers: intuneScepActionHeaders(intuneAccessToken) });++ assertIntuneNotificationAccepted(data, "failure notification");};export const validateMicrosoftIntuneConnectionCredentials = async (config: TMicrosoftIntuneConnectionConfig) => {diff --git a/backend/src/services/pki-application/pki-application-enrollment-service.ts b/backend/src/services/pki-application/pki-application-enrollment-service.tsindex 9606441d1d..2b5cb76b27 100644--- a/backend/src/services/pki-application/pki-application-enrollment-service.ts+++ b/backend/src/services/pki-application/pki-application-enrollment-service.ts@@ -8,7 +8,11 @@ import {ResourcePermissionSub} from "@app/ee/services/permission/resource-permission";import { ScepChallengeType } from "@app/ee/services/pki-scep/challenge";-import { generateAndEncryptScepRaCertificate, resolveScepRaSigning } from "@app/ee/services/pki-scep/pki-scep-fns";+import {+ generateAndEncryptScepRaCertificate,+ resolveCaType,+ resolveScepRaSigning+} from "@app/ee/services/pki-scep/pki-scep-fns";import { getConfig } from "@app/lib/config/env";import { crypto } from "@app/lib/crypto";import { BadRequestError, NotFoundError } from "@app/lib/errors";@@ -217,10 +221,7 @@ export const pkiApplicationEnrollmentServiceFactory = ({const scepConfig = junction.scepConfigId ? await scepEnrollmentConfigDAL.findById(junction.scepConfigId) : null;const profile = await certificateProfileDAL.findById(profileId);- const { caType } = await resolveScepRaSigning({- caId: profile?.caId,- certificateAuthorityDAL- });+ const caType = await resolveCaType(profile?.caId, certificateAuthorityDAL);const siteUrl = getConfig().SITE_URL ?? "";const appProfilePath = `applications/${applicationId}/profiles/${profileId}`;@@ -709,11 +710,7 @@ export const pkiApplicationEnrollmentServiceFactory = ({const raSlug = `app-${applicationId}-${profileId}`;const profile = await certificateProfileDAL.findById(profileId);- const { signRaWithCa, caType } = await resolveScepRaSigning({- caId: profile?.caId,- requestedSignRaWithCa: config.signRaWithCa,- certificateAuthorityDAL- });+ const caType = await resolveCaType(profile?.caId, certificateAuthorityDAL);// External CAs always issue asynchronously and Intune has no pending state, so every enrollment// would be reported to Intune as a failure.@@ -723,9 +720,23 @@ export const pkiApplicationEnrollmentServiceFactory = ({});}+ const { signRaWithCa } = await resolveScepRaSigning({+ caId: profile?.caId,+ requestedSignRaWithCa: config.signRaWithCa,+ certificateAuthorityDAL+ });+const existingScepConfig = junction.scepConfigId? await scepEnrollmentConfigDAL.findById(junction.scepConfigId): null;++ if (isIntune && !signRaWithCa) {+ throw new BadRequestError({+ message:+ "Microsoft Intune validation requires the RA certificate to be signed with the CA. Enable 'Sign RA certificate with the CA' on this SCEP enrollment."+ });+ }+// Changing this regenerates the RA certificate, which breaks devices already trusting the current one.if (existingScepConfig && existingScepConfig.signRaWithCa !== signRaWithCa) {throw new BadRequestError({diff --git a/docs/documentation/platform/pki/guides/applications/microsoft-intune-scep.mdx b/docs/documentation/platform/pki/guides/applications/microsoft-intune-scep.mdxindex e0c967fd42..5df3b8f4a0 100644--- a/docs/documentation/platform/pki/guides/applications/microsoft-intune-scep.mdx+++ b/docs/documentation/platform/pki/guides/applications/microsoft-intune-scep.mdx@@ -8,9 +8,9 @@ Issue certificates to devices managed by [Microsoft Intune](https://learn.micros## How It Works-Intune generates a unique, single-use challenge for each device and seals it inside the SCEP request. Infisical does not store a shared password for these enrollments. Instead it calls the Intune SCEP validation service to confirm the challenge, issues the certificate, and reports the outcome back to Intune so the certificate appears against the device record.+Intune generates a unique, single-use challenge for each device and seals it inside the SCEP request. Infisical calls the Intune SCEP validation service to confirm the challenge, issues the certificate, and reports the outcome back to Intune so the certificate appears against the device record.-The result is a request flow of: device asks Intune for a profile, device sends the SCEP request to Infisical, Infisical asks Intune whether the challenge is valid, Infisical issues the certificate and notifies Intune.+The request flow is: the device retrieves its profile from Intune, submits the SCEP request to Infisical, Infisical validates the challenge with Intune, then Infisical issues the certificate and reports the result.## Prerequisites@@ -20,14 +20,14 @@ The result is a request flow of: device asks Intune for a profile, device sends- One or more devices enrolled in Intune<Warning>- Microsoft Intune validation requires that the profile must not have an approval policy attached. Intune issues synchronously and has no pending state, so any issuance that cannot complete inside the request is reported to Intune as a failure.+ Microsoft Intune validation requires a profile with no [approval policy](/documentation/platform/pki/applications/approvals) attached. Intune issues synchronously and has no pending state, so any issuance that cannot complete inside the request is reported to Intune as a failure.</Warning>## Guide<Steps><Step title="Register an application in Microsoft Entra ID">- Infisical authenticates to Intune with a client secret and needs two application permissions.+ Infisical authenticates to Intune with a client secret and requires two application permissions.Follow [Setup Azure application](/integrations/app-connections/microsoft-intune#setup-azure-application) to register the application, assign the permissions below, grant admin consent, and collect the credentials.@@ -65,24 +65,34 @@ The result is a request flow of: device asks Intune for a profile, device sends<Warning>- **Enable Sign RA certificate with the CA.** With a self-signed RA, Intune fails to build a chain to a trusted root and rejects the response. Signing the RA with your CA makes it chain to the root you deploy in the next steps. This option cannot be changed once SCEP enrollment exists, so set it now rather than later.+ **Sign RA certificate with the CA is required for Intune.** It makes the RA chain to the CA certificates you deploy in the next steps. Without it the RA is self-signed, and Intune rejects the `GetCACert` response before it ever submits a certificate request, so Infisical refuses the combination. This option cannot be changed once SCEP enrollment exists, so set it before saving.</Warning>- Certificate-based renewal is not available with Intune validation, because a renewal skips the challenge and would bypass Intune's per-request validation. Infisical rejects the combination.-- Copy the **SCEP URL** shown on the enrollment.+ Copy the **SCEP endpoint URL** shown on the enrollment.</Step>- <Step title="Download the CA certificate">- Intune needs your CA certificate so devices trust the certificates Infisical issues.+ <Step title="Download the CA certificates">+ Devices must trust your certificate authority before they accept the certificates Infisical issues.++ Navigate to **Certificate Authorities**, open the CA behind your profile, and in the **CA Certificates** section select **Download CA Certificate**. If that CA is an intermediate, also select **Download CA Certificate Chain** to obtain its issuers.++ <Note>+ Infisical exports PEM files (`cert.pem` and `chain.pem`). Intune requires DER-encoded `.cer` files, so convert each certificate before uploading it:- Navigate to **Certificate Authorities**, open the CA behind your profile, and in the **Certificates** section choose **Download CA Certificate**. If your CA is an intermediate, download the full chain and repeat the next step for each certificate in it.+ ```bash+ openssl x509 -in cert.pem -outform der -out ca-root.cer+ ```++ `chain.pem` holds one PEM block per issuer. Separate it into individual files and convert each one, because a trusted certificate profile accepts a single certificate.+ </Note></Step>- <Step title="Create a Trusted certificate profile in Intune">- This profile installs your CA into each device's trusted root store. It must exist before the SCEP profile, because the SCEP profile references it.+ <Step title="Create the Trusted certificate profiles in Intune">+ These profiles install your CA certificates onto each device. They must exist before the SCEP profile, because the SCEP profile references one of them.++ A profile carries a single certificate, so create one profile per certificate: one for the root, plus one for each intermediate or issuing CA. Also create a separate set per device platform you support.1. In the [Microsoft Intune admin center](https://intune.microsoft.com), go to **Devices** > **Configuration** and click **Create** > **New Policy**.@@ -93,14 +103,20 @@ The result is a request flow of: device asks Intune for a profile, device sends3. Give the profile a name, for example `Infisical Root CA`.- 4. Upload the CA certificate file downloaded in the previous step.- 5. Assign the profile to the device or user groups that will receive certificates, then create it.+ 4. On Apple platforms, set **Deployment Channel**. Select **Device Channel** to install the certificate for every user on the device, and **User Channel** only where the certificate must be scoped to a single user. Microsoft's requirement is that this profile be assigned to the same groups as the SCEP profile, so align the assignments rather than the channels.+ 5. Upload one of the `.cer` files from the previous step.+ 6. Assign the profile to the device or user groups that will receive certificates, then create it.+ 7. Repeat for each remaining certificate in the chain.<Note>- Windows profiles add a **Destination Store** field. Choose **Computer certificate store - Root** when uploading a root CA, or **Computer certificate store - Intermediate** when uploading an intermediate.+ Windows profiles have no Deployment Channel. They add a **Destination Store** field instead, offering **Computer certificate store - Root**, **Computer certificate store - Intermediate**, and **User certificate store - Intermediate**. Choose the Root store for a root CA and an Intermediate store for an intermediate.</Note>++ <Note>+ The SCEP RA certificate needs no profile of its own. Because it is signed by your CA, these profiles already establish trust for it.+ </Note></Step><Step title="Create the SCEP certificate profile in Intune">@@ -113,8 +129,8 @@ The result is a request flow of: device asks Intune for a profile, device sends| Setting | Value ||---------|-------|- | **Root Certificate** | The Trusted certificate profile created above |- | **SCEP Server URLs** | The **SCEP URL** copied from Infisical |+ | **Root Certificate** | The Trusted certificate profile holding the **root** CA. For a multi-tier PKI, Microsoft says to select the top level root profile that validates the issuing CA, not the intermediate's profile |+ | **SCEP Server URLs** | The **SCEP endpoint URL** copied from Infisical |The remaining fields, such as certificate type, subject name format, subject alternative name, validity period, key usage, key size, extended key usage, and renewal threshold, depend on what your devices and workloads require.@@ -122,6 +138,10 @@ The result is a request flow of: device asks Intune for a profile, device sendsField names vary slightly by platform. Apple profiles include **Deployment Channel**, while Windows profiles include **Hash algorithm** and a **Key storage provider**.</Note>+ <Warning>+ On Apple platforms, pair **Deployment Channel** with **Certificate type**: use Device Channel for device certificates, which stores them in the system keychain, and User Channel for user certificates, which stores them in the user keychain. Under User Channel, Certificate type can only be **User**. The channel cannot be edited after the profile is deployed, so a change means creating a new profile.+ </Warning>+<Warning>@@ -130,7 +150,7 @@ The result is a request flow of: device asks Intune for a profile, device sends</Step><Step title="Assign and create the profile">- Assign the SCEP profile to the same groups as the Trusted certificate profile, then review and create it.+ Assign the SCEP profile to the same groups as the Trusted certificate profiles, then review and create it.</Step>@@ -160,7 +180,7 @@ The result is a request flow of: device asks Intune for a profile, device sendsCheck the audit log in Infisical for the SCEP enrollment event, which records the reason reported by Intune.</Accordion><Accordion title="Enrollment returns a failure even though the challenge was accepted">- The challenge passed but issuance did not complete. Either the requested certificate violates the certificate policy, or the profile is attached to an approval policy so issuance is waiting on a human.+ The challenge passed but issuance did not complete. Either the requested certificate violates the certificate policy, or the profile is attached to an approval policy and issuance is pending review.Intune has no pending state, so Infisical reports these to Intune as failures rather than leaving the device polling. Use a profile with no approval policy for Intune validation.</Accordion>diff --git a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ConfigureEnrollmentModal.tsx b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ConfigureEnrollmentModal.tsxindex ec3d762f80..04b3ac88da 100644--- a/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ConfigureEnrollmentModal.tsx+++ b/frontend/src/pages/cert-manager/ApplicationDetailsByIDPage/components/ConfigureEnrollmentModal.tsx@@ -832,6 +832,10 @@ const ScepPanel = ({ProjectPermissionSub.AppConnections);+ useEffect(() => {+ if (isIntune && !isScepConfigured && raCaSigningSupported) setValue("signRaWithCa", true);+ }, [isIntune, isScepConfigured, raCaSigningSupported, setValue]);+const { data: intuneConnections, isPending: isIntuneConnectionsLoading } =useListAvailableAppConnections(AppConnection.MicrosoftIntune, currentProject.id, {enabled: isIntune@@ -1104,9 +1108,10 @@ const ScepPanel = ({<div><FieldLabel>Sign RA certificate with the CA</FieldLabel><p className="text-xs text-accent">- Issue the SCEP RA certificate from this profile's CA so it chains to the CA- root. Strict clients such as Apple and Microsoft Intune require this. Only- available for internal certificate authorities.+ Issue the SCEP RA certificate from this profile's CA so clients can build a+ chain to a CA they already trust. Required by strict clients such as Apple and+ Microsoft Intune, which reject a self-signed RA. Only available for internal+ certificate authorities.</p></div>{raCaSigningSupported && !isScepConfigured ? (