feat(secret-syncs): azure app config & key vault support

This commit is contained in:
Daniel Hougaard
2025-02-08 04:27:17 +04:00
parent 4e41e84491
commit 5cd6a66989
70 changed files with 2065 additions and 204 deletions
@@ -1,123 +0,0 @@
import { useEffect } from "react";
import { useNavigate, useSearch } from "@tanstack/react-router";
import { createNotification } from "@app/components/notifications";
import { ContentLoader } from "@app/components/v2";
import { ROUTE_PATHS } from "@app/const/routes";
import {
GitHubConnectionMethod,
TGitHubConnection,
useCreateAppConnection,
useUpdateAppConnection
} from "@app/hooks/api/appConnections";
import { AppConnection } from "@app/hooks/api/appConnections/enums";
type FormData = Pick<TGitHubConnection, "name" | "method" | "description"> & {
returnUrl?: string;
connectionId?: string;
};
export const GitHubOAuthCallbackPage = () => {
const navigate = useNavigate();
const search = useSearch({
from: ROUTE_PATHS.Organization.AppConnections.GithubOauthCallbackPage.id
});
const updateAppConnection = useUpdateAppConnection();
const createAppConnection = useCreateAppConnection();
const { code, state, installation_id: installationId } = search;
useEffect(() => {
(async () => {
let formData: FormData;
try {
formData = JSON.parse(localStorage.getItem("githubConnectionFormData") ?? "{}") as FormData;
} catch {
createNotification({
type: "error",
text: "Invalid form state, redirecting..."
});
navigate({ to: "/" });
return;
}
// validate state
if (state !== localStorage.getItem("latestCSRFToken")) {
return;
}
localStorage.removeItem("githubConnectionFormData");
localStorage.removeItem("latestCSRFToken");
const { connectionId, name, description, returnUrl } = formData;
try {
if (connectionId) {
await updateAppConnection.mutateAsync({
app: AppConnection.GitHub,
...(installationId
? {
connectionId,
credentials: {
code: code as string,
installationId: installationId as string
}
}
: {
connectionId,
credentials: {
code: code as string
}
})
});
} else {
await createAppConnection.mutateAsync({
app: AppConnection.GitHub,
name,
description,
...(installationId
? {
method: GitHubConnectionMethod.App,
credentials: {
code: code as string,
installationId: installationId as string
}
}
: {
method: GitHubConnectionMethod.OAuth,
credentials: {
code: code as string
}
})
});
}
} catch (e: any) {
createNotification({
title: `Failed to ${connectionId ? "update" : "add"} GitHub Connection`,
text: e.message,
type: "error"
});
navigate({
to: returnUrl ?? "/organization/settings?selectedTab=app-connections"
});
return;
}
createNotification({
text: `Successfully ${connectionId ? "updated" : "added"} GitHub Connection`,
type: "success"
});
navigate({
to: returnUrl ?? "/organization/settings?selectedTab=app-connections"
});
})();
}, []);
return (
<div className="flex h-full w-full items-center justify-center">
<ContentLoader text="Please wait! Authentication in process." />
</div>
);
};
@@ -0,0 +1,240 @@
import { useCallback, useEffect, useState } from "react";
import { useNavigate, useParams, useSearch } from "@tanstack/react-router";
import { createNotification } from "@app/components/notifications";
import { ContentLoader } from "@app/components/v2";
import { ROUTE_PATHS } from "@app/const/routes";
import {
AzureConnectionMethod,
AzureResources,
GitHubConnectionMethod,
TGitHubConnection,
useCreateAppConnection,
useUpdateAppConnection
} from "@app/hooks/api/appConnections";
import { AppConnection } from "@app/hooks/api/appConnections/enums";
type GithubFormData = Pick<TGitHubConnection, "name" | "method" | "description"> & {
returnUrl?: string;
connectionId?: string;
};
type AzureFormData = Pick<TGitHubConnection, "name" | "method" | "description"> & {
returnUrl?: string;
connectionId?: string;
tenantId?: string;
resource: AzureResources;
};
type FormDataMap = {
[AppConnection.GitHub]: GithubFormData & { app: AppConnection.GitHub };
[AppConnection.Azure]: AzureFormData & { app: AppConnection.Azure };
};
const formDataStorageFieldMap: Partial<Record<AppConnection, string>> = {
[AppConnection.GitHub]: "githubConnectionFormData",
[AppConnection.Azure]: "azureConnectionFormData"
};
export const OAuthCallbackPage = () => {
const navigate = useNavigate();
const [isReady, setIsReady] = useState(false);
const search = useSearch({
from: ROUTE_PATHS.Organization.AppConnections.OauthCallbackPage.id
});
const appConnection = useParams({
strict: false,
select: (el) => el?.appConnection as AppConnection
});
const updateAppConnection = useUpdateAppConnection();
const createAppConnection = useCreateAppConnection();
const { code, state, installation_id: installationId } = search;
const clearState = (app: AppConnection) => {
if (state !== localStorage.getItem("latestCSRFToken")) {
throw new Error("Invalid CSRF token");
}
const dataFieldName = formDataStorageFieldMap[app];
localStorage.removeItem(dataFieldName!);
localStorage.removeItem("latestCSRFToken");
};
const getFormData = <T extends keyof FormDataMap>(app: T): FormDataMap[T] | null => {
const dataFieldName = formDataStorageFieldMap[app];
try {
const rawData = JSON.parse(localStorage.getItem(dataFieldName!) ?? "{}");
return {
...rawData,
app
} as FormDataMap[T];
} catch {
createNotification({
type: "error",
text: `Invalid ${app || ""} form state, redirecting...`
});
navigate({ to: "/" });
return null;
}
};
const handleAzure = useCallback(async () => {
const formData = getFormData(AppConnection.Azure);
if (formData === null) return null;
clearState(AppConnection.Azure);
const { connectionId, name, description, returnUrl } = formData;
try {
if (connectionId) {
await updateAppConnection.mutateAsync({
app: AppConnection.Azure,
connectionId,
credentials: {
code: code as string
}
});
} else {
await createAppConnection.mutateAsync({
app: AppConnection.Azure,
name,
description,
method: AzureConnectionMethod.OAuth,
credentials: {
resource: formData.resource,
tenantId: formData.tenantId,
code: code as string
}
});
}
} catch (err: any) {
createNotification({
title: `Failed to ${connectionId ? "update" : "add"} Azure Connection`,
text: err?.message,
type: "error"
});
navigate({
to: returnUrl ?? "/organization/settings?selectedTab=app-connections"
});
}
return {
connectionId,
returnUrl,
appConnectionName: formData.app
};
}, []);
const handleGithub = useCallback(async () => {
const formData = getFormData(AppConnection.GitHub);
if (formData === null) return null;
clearState(AppConnection.GitHub);
const { connectionId, name, description, returnUrl } = formData;
try {
if (connectionId) {
await updateAppConnection.mutateAsync({
app: AppConnection.GitHub,
...(installationId
? {
connectionId,
credentials: {
code: code as string,
installationId: installationId as string
}
}
: {
connectionId,
credentials: {
code: code as string
}
})
});
} else {
await createAppConnection.mutateAsync({
app: AppConnection.GitHub,
name,
description,
...(installationId
? {
method: GitHubConnectionMethod.App,
credentials: {
code: code as string,
installationId: installationId as string
}
}
: {
method: GitHubConnectionMethod.OAuth,
credentials: {
code: code as string
}
})
});
}
} catch (e: any) {
createNotification({
title: `Failed to ${connectionId ? "update" : "add"} GitHub Connection`,
text: e.message,
type: "error"
});
navigate({
to: returnUrl ?? "/organization/settings?selectedTab=app-connections"
});
}
return {
connectionId,
returnUrl,
appConnectionName: formData.app
};
}, []);
// Ensure that the localstorage is ready for use, to avoid the form data being malformed
useEffect(() => {
if (!isReady) {
setIsReady(!!localStorage.length);
}
}, [localStorage.length]);
useEffect(() => {
if (!isReady) return;
(async () => {
let data: { connectionId?: string; returnUrl?: string; appConnectionName?: string } | null =
null;
if (appConnection === AppConnection.GitHub) {
data = await handleGithub();
} else if (appConnection === AppConnection.Azure) {
data = await handleAzure();
}
if (data) {
createNotification({
text: `Successfully ${data.connectionId ? "updated" : "added"} ${data.appConnectionName || ""} Connection`,
type: "success"
});
}
await navigate({
to: data?.returnUrl ?? "/organization/settings?selectedTab=app-connections"
});
})();
}, [isReady]);
return (
<div className="flex h-full w-full items-center justify-center">
<ContentLoader text="Please wait! Authentication in process." />
</div>
);
};
@@ -2,7 +2,7 @@ import { createFileRoute, stripSearchParams } from "@tanstack/react-router";
import { zodValidator } from "@tanstack/zod-adapter";
import { z } from "zod";
import { GitHubOAuthCallbackPage } from "./GithubOauthCallbackPage";
import { OAuthCallbackPage } from "./OauthCallbackPage";
const GitHubOAuthCallbackPageQueryParamsSchema = z.object({
code: z.coerce.string().catch(""),
@@ -11,9 +11,9 @@ const GitHubOAuthCallbackPageQueryParamsSchema = z.object({
});
export const Route = createFileRoute(
"/_authenticate/_inject-org-details/_org-layout/organization/app-connections/github/oauth/callback"
"/_authenticate/_inject-org-details/_org-layout/organization/app-connections/$appConnection/oauth/callback"
)({
component: GitHubOAuthCallbackPage,
component: OAuthCallbackPage,
validateSearch: zodValidator(GitHubOAuthCallbackPageQueryParamsSchema),
search: {
middlewares: [stripSearchParams({ state: "", installation_id: "" })]
@@ -10,6 +10,7 @@ import { DiscriminativePick } from "@app/types";
import { AppConnectionHeader } from "../AppConnectionHeader";
import { AwsConnectionForm } from "./AwsConnectionForm";
import { AzureConnectionForm } from "./AzureConnectionForm";
import { GcpConnectionForm } from "./GcpConnectionForm";
import { GitHubConnectionForm } from "./GitHubConnectionForm";
@@ -53,6 +54,8 @@ const CreateForm = ({ app, onComplete }: CreateFormProps) => {
return <GitHubConnectionForm />;
case AppConnection.GCP:
return <GcpConnectionForm onSubmit={onSubmit} />;
case AppConnection.Azure:
return <AzureConnectionForm />;
default:
throw new Error(`Unhandled App ${app}`);
}
@@ -0,0 +1,208 @@
import crypto from "crypto";
import { useState } from "react";
import { Controller, FormProvider, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { Button, FormControl, Input, ModalClose, Select, SelectItem } from "@app/components/v2";
import { APP_CONNECTION_MAP, getAppConnectionMethodDetails } from "@app/helpers/appConnections";
import { isInfisicalCloud } from "@app/helpers/platform";
import { useGetAppConnectionOption } from "@app/hooks/api/appConnections";
import { AppConnection } from "@app/hooks/api/appConnections/enums";
import {
AzureConnectionMethod,
AzureResources,
TAzureConnection
} from "@app/hooks/api/appConnections/types/azure-connection";
import {
genericAppConnectionFieldsSchema,
GenericAppConnectionsFields
} from "./GenericAppConnectionFields";
type Props = {
appConnection?: TAzureConnection;
};
const resourceScopes: Record<AzureResources, string> = {
[AzureResources.AppConfiguration]: "https://azconfig.io/.default",
[AzureResources.KeyVault]: "https://vault.azure.net/.default"
};
const formSchema = genericAppConnectionFieldsSchema.extend({
app: z.literal(AppConnection.Azure),
method: z.nativeEnum(AzureConnectionMethod),
tenantId: z.string().trim().optional(),
resource: z.nativeEnum(AzureResources)
});
type FormData = z.infer<typeof formSchema>;
export const AzureConnectionForm = ({ appConnection }: Props) => {
const isUpdate = Boolean(appConnection);
const [isRedirecting, setIsRedirecting] = useState(false);
const {
option: { oauthClientId },
isLoading
} = useGetAppConnectionOption(AppConnection.Azure);
const form = useForm<FormData>({
resolver: zodResolver(formSchema),
defaultValues: appConnection ?? {
app: AppConnection.Azure,
method: AzureConnectionMethod.OAuth,
resource: AzureResources.KeyVault
}
});
const {
handleSubmit,
control,
watch,
formState: { isSubmitting, isDirty }
} = form;
const selectedMethod = watch("method");
const onSubmit = (formData: FormData) => {
setIsRedirecting(true);
const state = crypto.randomBytes(16).toString("hex");
localStorage.setItem("latestCSRFToken", state);
localStorage.setItem(
"azureConnectionFormData",
JSON.stringify({ ...formData, connectionId: appConnection?.id })
);
switch (formData.method) {
case AzureConnectionMethod.OAuth:
window.location.assign(
`https://login.microsoftonline.com/${formData.tenantId || "common"}/oauth2/v2.0/authorize?client_id=${oauthClientId}&response_type=code&redirect_uri=${window.location.origin}/organization/app-connections/azure/oauth/callback&response_mode=query&scope=${resourceScopes[formData.resource]}%20openid%20offline_access&state=${state}`
);
break;
default:
throw new Error(`Unhandled Azure Connection method: ${(formData as FormData).method}`);
}
};
let isMissingConfig: boolean;
switch (selectedMethod) {
case AzureConnectionMethod.OAuth:
isMissingConfig = !oauthClientId;
break;
default:
throw new Error(`Unhandled Azure Connection method: ${selectedMethod}`);
}
const methodDetails = getAppConnectionMethodDetails(selectedMethod);
return (
<FormProvider {...form}>
<form onSubmit={handleSubmit(onSubmit)}>
{!isUpdate && <GenericAppConnectionsFields />}
<Controller
name="tenantId"
control={control}
render={({ field, fieldState: { error } }) => (
<FormControl
tooltipText="The Azure Active Directory (Entra ID) Tenant ID. This field cannot be changed after creation."
isError={Boolean(error?.message)}
label="Tenant ID"
isOptional
errorText={error?.message}
>
<Input {...field} placeholder="e4f34ea5-ad23-4291-8585-66d20d603cc8" />
</FormControl>
)}
/>
<Controller
name="resource"
control={control}
render={({ field: { value, onChange }, fieldState: { error } }) => (
<FormControl
tooltipText="Select the Azure resource you would like the app connection to access."
errorText={error?.message}
isError={Boolean(error?.message)}
label="Resource"
>
<Select
isDisabled={isUpdate}
value={value}
onValueChange={(val) => onChange(val)}
className="w-full border border-mineshaft-500"
position="popper"
dropdownContainerClassName="max-w-none"
>
<SelectItem value={AzureResources.KeyVault}>Azure Key Vault</SelectItem>
<SelectItem value={AzureResources.AppConfiguration}>
Azure App Configuration
</SelectItem>
</Select>
</FormControl>
)}
/>
<Controller
name="method"
control={control}
render={({ field: { value, onChange }, fieldState: { error } }) => (
<FormControl
tooltipText={`The method you would like to use to connect with ${
APP_CONNECTION_MAP[AppConnection.Azure].name
}. This field cannot be changed after creation.`}
errorText={
!isLoading && isMissingConfig
? `Environment variables have not been configured. ${
isInfisicalCloud()
? "Please contact Infisical."
: `See documentation to configure Azure ${methodDetails.name} Connections.`
}`
: error?.message
}
isError={Boolean(error?.message) || isMissingConfig}
label="Method"
>
<Select
isDisabled={isUpdate}
value={value}
onValueChange={(val) => onChange(val)}
className="w-full border border-mineshaft-500"
position="popper"
dropdownContainerClassName="max-w-none"
>
{Object.values(AzureConnectionMethod).map((method) => {
return (
<SelectItem value={method} key={method}>
{getAppConnectionMethodDetails(method).name}
</SelectItem>
);
})}
</Select>
</FormControl>
)}
/>
<div className="mt-8 flex items-center">
<Button
className="mr-4"
size="sm"
type="submit"
colorSchema="secondary"
isLoading={isSubmitting || isRedirecting}
isDisabled={isSubmitting || (!isUpdate && !isDirty) || isMissingConfig || isRedirecting}
>
{isUpdate ? "Reconnect to Azure" : "Connect to Azure"}
</Button>
<ModalClose asChild>
<Button colorSchema="secondary" variant="plain">
Cancel
</Button>
</ModalClose>
</div>
</form>
</FormProvider>
);
};
@@ -27,7 +27,8 @@ import { OrgPermissionSubjects } from "@app/context";
import { OrgPermissionAppConnectionActions } from "@app/context/OrgPermissionContext/types";
import { APP_CONNECTION_MAP, getAppConnectionMethodDetails } from "@app/helpers/appConnections";
import { useToggle } from "@app/hooks";
import { TAppConnection } from "@app/hooks/api/appConnections";
import { azureResourcesMap, TAppConnection } from "@app/hooks/api/appConnections";
import { AppConnection } from "@app/hooks/api/appConnections/enums";
type Props = {
appConnection: TAppConnection;
@@ -42,7 +43,7 @@ export const AppConnectionRow = ({
onEditCredentials,
onEditDetails
}: Props) => {
const { id, name, method, app, description } = appConnection;
const { id, name, method, app, description, credentials } = appConnection;
const [isIdCopied, setIsIdCopied] = useToggle(false);
@@ -75,7 +76,10 @@ export const AppConnectionRow = ({
src={`/images/integrations/${APP_CONNECTION_MAP[app].image}`}
className="mr-0.5 h-5 w-5"
/>
<span className="hidden lg:inline">{APP_CONNECTION_MAP[app].name}</span>
<span className="hidden lg:inline">
{APP_CONNECTION_MAP[app].name}
{app === AppConnection.Azure && ` ${azureResourcesMap[credentials.resource]}`}
</span>
</div>
</Td>
<Td className="!min-w-[8rem] max-w-0">
@@ -0,0 +1,14 @@
import { TAzureAppConfigurationSync } from "@app/hooks/api/secretSyncs/types/azure-app-configuration-sync";
import { getSecretSyncDestinationColValues } from "../helpers";
import { SecretSyncTableCell } from "../SecretSyncTableCell";
type Props = {
secretSync: TAzureAppConfigurationSync;
};
export const AzureAppConfigurationDestinationSyncCol = ({ secretSync }: Props) => {
const { primaryText, secondaryText } = getSecretSyncDestinationColValues(secretSync);
return <SecretSyncTableCell primaryText={primaryText} secondaryText={secondaryText} />;
};
@@ -0,0 +1,14 @@
import { TAzureKeyVaultSync } from "@app/hooks/api/secretSyncs/types/azure-key-vault-sync";
import { getSecretSyncDestinationColValues } from "../helpers";
import { SecretSyncTableCell } from "../SecretSyncTableCell";
type Props = {
secretSync: TAzureKeyVaultSync;
};
export const AzureKeyVaultDestinationSyncCol = ({ secretSync }: Props) => {
const { primaryText, secondaryText } = getSecretSyncDestinationColValues(secretSync);
return <SecretSyncTableCell primaryText={primaryText} secondaryText={secondaryText} />;
};
@@ -2,6 +2,8 @@ import { SecretSync, TSecretSync } from "@app/hooks/api/secretSyncs";
import { AwsParameterStoreSyncDestinationCol } from "./AwsParameterStoreSyncDestinationCol";
import { AwsSecretsManagerSyncDestinationCol } from "./AwsSecretsManagerSyncDestinationCol";
import { AzureAppConfigurationDestinationSyncCol } from "./AzureAppConfigurationDestinationSyncCol";
import { AzureKeyVaultDestinationSyncCol } from "./AzureKeyVaultDestinationSyncCol";
import { GcpSyncDestinationCol } from "./GcpSyncDestinationCol";
import { GitHubSyncDestinationCol } from "./GitHubSyncDestinationCol";
@@ -19,6 +21,11 @@ export const SecretSyncDestinationCol = ({ secretSync }: Props) => {
return <GitHubSyncDestinationCol secretSync={secretSync} />;
case SecretSync.GCPSecretManager:
return <GcpSyncDestinationCol secretSync={secretSync} />;
case SecretSync.AzureKeyVault:
return <AzureKeyVaultDestinationSyncCol secretSync={secretSync} />;
case SecretSync.AzureAppConfiguration:
return <AzureAppConfigurationDestinationSyncCol secretSync={secretSync} />;
default:
throw new Error(
`Unhandled Secret Sync Destination Col: ${(secretSync as TSecretSync).destination}`
@@ -47,6 +47,15 @@ export const getSecretSyncDestinationColValues = (secretSync: TSecretSync) => {
primaryText = destinationConfig.projectId;
secondaryText = "Global";
break;
case SecretSync.AzureKeyVault:
primaryText = destinationConfig.vaultBaseUrl;
break;
case SecretSync.AzureAppConfiguration:
primaryText = destinationConfig.configurationUrl;
if (destinationConfig.label) {
secondaryText = `Label - ${destinationConfig.label}`;
}
break;
default:
throw new Error(`Unhandled Destination Col Values ${destination}`);
}
@@ -0,0 +1,21 @@
import { SecretSyncLabel } from "@app/components/secret-syncs";
import { TAzureAppConfigurationSync } from "@app/hooks/api/secretSyncs/types/azure-app-configuration-sync";
type Props = {
secretSync: TAzureAppConfigurationSync;
};
export const AzureAppConfigurationSyncDestinationSection = ({ secretSync }: Props) => {
const {
destinationConfig: { configurationUrl, label }
} = secretSync;
return (
<>
<SecretSyncLabel label="Configuration URL">{configurationUrl}</SecretSyncLabel>
<SecretSyncLabel label="Label">
{label && label.length > 0 ? label : <span className="opacity-40">Not set</span>}
</SecretSyncLabel>
</>
);
};
@@ -0,0 +1,14 @@
import { SecretSyncLabel } from "@app/components/secret-syncs";
import { TAzureKeyVaultSync } from "@app/hooks/api/secretSyncs/types/azure-key-vault-sync";
type Props = {
secretSync: TAzureKeyVaultSync;
};
export const AzureKeyVaultSyncDestinationSection = ({ secretSync }: Props) => {
const {
destinationConfig: { vaultBaseUrl }
} = secretSync;
return <SecretSyncLabel label="Vault URL">{vaultBaseUrl}</SecretSyncLabel>;
};
@@ -13,6 +13,8 @@ import { AwsParameterStoreSyncDestinationSection } from "@app/pages/secret-manag
import { AwsSecretsManagerSyncDestinationSection } from "@app/pages/secret-manager/SecretSyncDetailsByIDPage/components/SecretSyncDestinationSection/AwsSecretsManagerSyncDestinationSection";
import { GitHubSyncDestinationSection } from "@app/pages/secret-manager/SecretSyncDetailsByIDPage/components/SecretSyncDestinationSection/GitHubSyncDestinationSection";
import { AzureAppConfigurationSyncDestinationSection } from "./AzureAppConfigurationSyncDestinationSection";
import { AzureKeyVaultSyncDestinationSection } from "./AzureKeyVaultSyncDestinationSection";
import { GcpSyncDestinationSection } from "./GcpSyncDestinationSection";
type Props = {
@@ -39,6 +41,15 @@ export const SecretSyncDestinationSection = ({ secretSync, onEditDestination }:
case SecretSync.GCPSecretManager:
DestinationComponents = <GcpSyncDestinationSection secretSync={secretSync} />;
break;
case SecretSync.AzureKeyVault:
DestinationComponents = <AzureKeyVaultSyncDestinationSection secretSync={secretSync} />;
break;
case SecretSync.AzureAppConfiguration:
DestinationComponents = (
<AzureAppConfigurationSyncDestinationSection secretSync={secretSync} />
);
break;
default:
throw new Error(`Unhandled Destination Section components: ${destination}`);
}