requested changes

This commit is contained in:
Daniel Hougaard
2025-02-08 04:27:17 +04:00
parent ba42ea736b
commit a67badf660
55 changed files with 872 additions and 428 deletions
@@ -5,9 +5,10 @@ import { createNotification } from "@app/components/notifications";
import { ContentLoader } from "@app/components/v2";
import { ROUTE_PATHS } from "@app/const/routes";
import {
AzureConnectionMethod,
AzureResources,
AzureAppConfigurationConnectionMethod,
AzureKeyVaultConnectionMethod,
GitHubConnectionMethod,
TAzureKeyVaultConnection,
TGitHubConnection,
useCreateAppConnection,
useUpdateAppConnection
@@ -22,18 +23,20 @@ type GithubFormData = Pick<TGitHubConnection, "name" | "method" | "description">
type AzureFormData = Pick<TGitHubConnection, "name" | "method" | "description"> & {
returnUrl?: string;
connectionId?: string;
tenantId?: string;
resource: AzureResources;
};
} & Pick<TAzureKeyVaultConnection["credentials"], "tenantId">;
type FormDataMap = {
[AppConnection.GitHub]: GithubFormData & { app: AppConnection.GitHub };
[AppConnection.Azure]: AzureFormData & { app: AppConnection.Azure };
[AppConnection.AzureKeyVault]: AzureFormData & { app: AppConnection.AzureKeyVault };
[AppConnection.AzureAppConfiguration]: AzureFormData & {
app: AppConnection.AzureAppConfiguration;
};
};
const formDataStorageFieldMap: Partial<Record<AppConnection, string>> = {
[AppConnection.GitHub]: "githubConnectionFormData",
[AppConnection.Azure]: "azureConnectionFormData"
[AppConnection.AzureKeyVault]: "azureKeyVaultConnectionFormData",
[AppConnection.AzureAppConfiguration]: "azureAppConfigurationConnectionFormData"
};
export const OAuthCallbackPage = () => {
@@ -44,7 +47,7 @@ export const OAuthCallbackPage = () => {
from: ROUTE_PATHS.Organization.AppConnections.OauthCallbackPage.id
});
const appConnection = useParams({
const rawAppConnection = useParams({
strict: false,
select: (el) => el?.appConnection as AppConnection
});
@@ -52,7 +55,10 @@ export const OAuthCallbackPage = () => {
const updateAppConnection = useUpdateAppConnection();
const createAppConnection = useCreateAppConnection();
const { code, state, installation_id: installationId } = search;
const { code, state: rawState, installation_id: installationId } = search;
const state = rawState.includes("<:>") ? rawState.split("<:>")[0] : rawState;
const appConnection = rawState.includes("<:>") ? rawState.split("<:>")[1] : rawAppConnection;
const clearState = (app: AppConnection) => {
if (state !== localStorage.getItem("latestCSRFToken")) {
@@ -85,18 +91,18 @@ export const OAuthCallbackPage = () => {
}
};
const handleAzure = useCallback(async () => {
const formData = getFormData(AppConnection.Azure);
const handleAzureKeyVault = useCallback(async () => {
const formData = getFormData(AppConnection.AzureKeyVault);
if (formData === null) return null;
clearState(AppConnection.Azure);
clearState(AppConnection.AzureKeyVault);
const { connectionId, name, description, returnUrl } = formData;
try {
if (connectionId) {
await updateAppConnection.mutateAsync({
app: AppConnection.Azure,
app: AppConnection.AzureKeyVault,
connectionId,
credentials: {
code: code as string
@@ -104,12 +110,11 @@ export const OAuthCallbackPage = () => {
});
} else {
await createAppConnection.mutateAsync({
app: AppConnection.Azure,
app: AppConnection.AzureKeyVault,
name,
description,
method: AzureConnectionMethod.OAuth,
method: AzureKeyVaultConnectionMethod.OAuth,
credentials: {
resource: formData.resource,
tenantId: formData.tenantId,
code: code as string
}
@@ -133,6 +138,52 @@ export const OAuthCallbackPage = () => {
};
}, []);
const handleAzureAppConfiguration = useCallback(async () => {
const formData = getFormData(AppConnection.AzureAppConfiguration);
if (formData === null) return null;
clearState(AppConnection.AzureAppConfiguration);
const { connectionId, name, description, returnUrl } = formData;
try {
if (connectionId) {
await updateAppConnection.mutateAsync({
app: AppConnection.AzureAppConfiguration,
connectionId,
credentials: {
code: code as string
}
});
} else {
await createAppConnection.mutateAsync({
app: AppConnection.AzureAppConfiguration,
name,
description,
method: AzureAppConfigurationConnectionMethod.OAuth,
credentials: {
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;
@@ -215,8 +266,10 @@ export const OAuthCallbackPage = () => {
if (appConnection === AppConnection.GitHub) {
data = await handleGithub();
} else if (appConnection === AppConnection.Azure) {
data = await handleAzure();
} else if (appConnection === AppConnection.AzureKeyVault) {
data = await handleAzureKeyVault();
} else if (appConnection === AppConnection.AzureAppConfiguration) {
data = await handleAzureAppConfiguration();
}
if (data) {
@@ -224,6 +277,11 @@ export const OAuthCallbackPage = () => {
text: `Successfully ${data.connectionId ? "updated" : "added"} ${data.appConnectionName || ""} Connection`,
type: "success"
});
} else {
createNotification({
text: "Failed to add connection",
type: "error"
});
}
await navigate({
@@ -10,7 +10,8 @@ import { DiscriminativePick } from "@app/types";
import { AppConnectionHeader } from "../AppConnectionHeader";
import { AwsConnectionForm } from "./AwsConnectionForm";
import { AzureConnectionForm } from "./AzureConnectionForm";
import { AzureAppConfigurationConnectionForm } from "./AzureAppConfigurationConnectionForm";
import { AzureKeyVaultConnectionForm } from "./AzureKeyVaultConnectionForm";
import { GcpConnectionForm } from "./GcpConnectionForm";
import { GitHubConnectionForm } from "./GitHubConnectionForm";
@@ -54,8 +55,10 @@ const CreateForm = ({ app, onComplete }: CreateFormProps) => {
return <GitHubConnectionForm />;
case AppConnection.GCP:
return <GcpConnectionForm onSubmit={onSubmit} />;
case AppConnection.Azure:
return <AzureConnectionForm />;
case AppConnection.AzureKeyVault:
return <AzureKeyVaultConnectionForm />;
case AppConnection.AzureAppConfiguration:
return <AzureAppConfigurationConnectionForm />;
default:
throw new Error(`Unhandled App ${app}`);
}
@@ -95,8 +98,10 @@ const UpdateForm = ({ appConnection, onComplete }: UpdateFormProps) => {
return <GitHubConnectionForm appConnection={appConnection} />;
case AppConnection.GCP:
return <GcpConnectionForm appConnection={appConnection} onSubmit={onSubmit} />;
case AppConnection.Azure:
return <AzureConnectionForm appConnection={appConnection} />;
case AppConnection.AzureKeyVault:
return <AzureKeyVaultConnectionForm appConnection={appConnection} />;
case AppConnection.AzureAppConfiguration:
return <AzureAppConfigurationConnectionForm appConnection={appConnection} />;
default:
throw new Error(`Unhandled App ${(appConnection as TAppConnection).app}`);
}
@@ -0,0 +1,177 @@
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 {
AzureAppConfigurationConnectionMethod,
TAzureAppConfigurationConnection,
useGetAppConnectionOption
} from "@app/hooks/api/appConnections";
import { AppConnection } from "@app/hooks/api/appConnections/enums";
import {
genericAppConnectionFieldsSchema,
GenericAppConnectionsFields
} from "./GenericAppConnectionFields";
type Props = {
appConnection?: TAzureAppConfigurationConnection;
};
const formSchema = genericAppConnectionFieldsSchema.extend({
app: z.literal(AppConnection.AzureAppConfiguration),
method: z.nativeEnum(AzureAppConfigurationConnectionMethod),
tenantId: z.string().trim().optional()
});
type FormData = z.infer<typeof formSchema>;
export const AzureAppConfigurationConnectionForm = ({ appConnection }: Props) => {
const isUpdate = Boolean(appConnection);
const [isRedirecting, setIsRedirecting] = useState(false);
const {
option: { oauthClientId },
isLoading
} = useGetAppConnectionOption(AppConnection.AzureAppConfiguration);
const form = useForm<FormData>({
resolver: zodResolver(formSchema),
defaultValues: appConnection
? {
...appConnection
}
: {
app: AppConnection.AzureAppConfiguration,
method: AzureAppConfigurationConnectionMethod.OAuth
}
});
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(
"azureAppConfigurationConnectionFormData",
JSON.stringify({ ...formData, connectionId: appConnection?.id })
);
switch (formData.method) {
case AzureAppConfigurationConnectionMethod.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=https://azconfig.io/.default%20openid%20offline_access&state=${state}<:>azure-app-configuration`
);
break;
default:
throw new Error(`Unhandled Azure Connection method: ${(formData as FormData).method}`);
}
};
let isMissingConfig: boolean;
switch (selectedMethod) {
case AzureAppConfigurationConnectionMethod.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."
isError={Boolean(error?.message)}
label="Tenant ID"
isOptional
errorText={error?.message}
>
<Input {...field} placeholder="e4f34ea5-ad23-4291-8585-66d20d603cc8" />
</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.AzureAppConfiguration].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(AzureAppConfigurationConnectionMethod).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>
);
};
@@ -11,10 +11,9 @@ 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";
AzureKeyVaultConnectionMethod,
TAzureKeyVaultConnection
} from "@app/hooks/api/appConnections/types/azure-key-vault-connection";
import {
genericAppConnectionFieldsSchema,
@@ -22,43 +21,35 @@ import {
} from "./GenericAppConnectionFields";
type Props = {
appConnection?: TAzureConnection;
};
const resourceScopes: Record<AzureResources, string> = {
[AzureResources.AppConfiguration]: "https://azconfig.io/.default",
[AzureResources.KeyVault]: "https://vault.azure.net/.default"
appConnection?: TAzureKeyVaultConnection;
};
const formSchema = genericAppConnectionFieldsSchema.extend({
app: z.literal(AppConnection.Azure),
method: z.nativeEnum(AzureConnectionMethod),
tenantId: z.string().trim().optional(),
resource: z.nativeEnum(AzureResources)
app: z.literal(AppConnection.AzureKeyVault),
method: z.nativeEnum(AzureKeyVaultConnectionMethod),
tenantId: z.string().trim().optional()
});
type FormData = z.infer<typeof formSchema>;
export const AzureConnectionForm = ({ appConnection }: Props) => {
export const AzureKeyVaultConnectionForm = ({ appConnection }: Props) => {
const isUpdate = Boolean(appConnection);
const [isRedirecting, setIsRedirecting] = useState(false);
const {
option: { oauthClientId },
isLoading
} = useGetAppConnectionOption(AppConnection.Azure);
} = useGetAppConnectionOption(AppConnection.AzureKeyVault);
const form = useForm<FormData>({
resolver: zodResolver(formSchema),
defaultValues: appConnection
? {
...appConnection,
resource: appConnection?.credentials.resource
...appConnection
}
: {
app: AppConnection.Azure,
method: AzureConnectionMethod.OAuth,
resource: AzureResources.KeyVault
app: AppConnection.AzureKeyVault,
method: AzureKeyVaultConnectionMethod.OAuth
}
});
@@ -76,14 +67,14 @@ export const AzureConnectionForm = ({ appConnection }: Props) => {
const state = crypto.randomBytes(16).toString("hex");
localStorage.setItem("latestCSRFToken", state);
localStorage.setItem(
"azureConnectionFormData",
"azureKeyVaultConnectionFormData",
JSON.stringify({ ...formData, connectionId: appConnection?.id })
);
switch (formData.method) {
case AzureConnectionMethod.OAuth:
case AzureKeyVaultConnectionMethod.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}`
`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=https://vault.azure.net/.default%20openid%20offline_access&state=${state}<:>azure-key-vault`
);
break;
default:
@@ -94,7 +85,7 @@ export const AzureConnectionForm = ({ appConnection }: Props) => {
let isMissingConfig: boolean;
switch (selectedMethod) {
case AzureConnectionMethod.OAuth:
case AzureKeyVaultConnectionMethod.OAuth:
isMissingConfig = !oauthClientId;
break;
default:
@@ -113,7 +104,7 @@ export const AzureConnectionForm = ({ appConnection }: Props) => {
control={control}
render={({ field, fieldState: { error } }) => (
<FormControl
tooltipText="The Azure Active Directory (Entra ID) Tenant ID. This field cannot be changed after creation."
tooltipText="The Azure Active Directory (Entra ID) Tenant ID."
isError={Boolean(error?.message)}
label="Tenant ID"
isOptional
@@ -124,40 +115,13 @@ export const AzureConnectionForm = ({ appConnection }: Props) => {
)}
/>
<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
APP_CONNECTION_MAP[AppConnection.AzureKeyVault].name
}. This field cannot be changed after creation.`}
errorText={
!isLoading && isMissingConfig
@@ -179,7 +143,7 @@ export const AzureConnectionForm = ({ appConnection }: Props) => {
position="popper"
dropdownContainerClassName="max-w-none"
>
{Object.values(AzureConnectionMethod).map((method) => {
{Object.values(AzureKeyVaultConnectionMethod).map((method) => {
return (
<SelectItem value={method} key={method}>
{getAppConnectionMethodDetails(method).name}
@@ -27,8 +27,7 @@ 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 { azureResourcesMap, TAppConnection } from "@app/hooks/api/appConnections";
import { AppConnection } from "@app/hooks/api/appConnections/enums";
import { TAppConnection } from "@app/hooks/api/appConnections";
type Props = {
appConnection: TAppConnection;
@@ -43,7 +42,7 @@ export const AppConnectionRow = ({
onEditCredentials,
onEditDetails
}: Props) => {
const { id, name, method, app, description, credentials } = appConnection;
const { id, name, method, app, description } = appConnection;
const [isIdCopied, setIsIdCopied] = useToggle(false);
@@ -76,10 +75,7 @@ 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}
{app === AppConnection.Azure && ` ${azureResourcesMap[credentials.resource]}`}
</span>
<span className="hidden lg:inline">{APP_CONNECTION_MAP[app].name}</span>
</div>
</Td>
<Td className="!min-w-[8rem] max-w-0">