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
feat: migrate organization KMS settings to v3
andrewhuhh954776bb4bd3
diff --git a/frontend/src/pages/organization/SettingsPage/components/OrgEncryptionTab/AddExternalKmsForm.tsx b/frontend/src/pages/organization/SettingsPage/components/OrgEncryptionTab/AddExternalKmsForm.tsxindex 6068b13e76..186b16583a 100644--- a/frontend/src/pages/organization/SettingsPage/components/OrgEncryptionTab/AddExternalKmsForm.tsx+++ b/frontend/src/pages/organization/SettingsPage/components/OrgEncryptionTab/AddExternalKmsForm.tsx@@ -1,9 +1,17 @@import { useState } from "react";import { faAws, faGoogle } from "@fortawesome/free-brands-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";-import { AnimatePresence, motion } from "framer-motion";-import { Modal, ModalContent } from "@app/components/v2";+import {+ Button,+ Sheet,+ SheetContent,+ SheetDescription,+ SheetFooter,+ SheetHeader,+ SheetTitle+} from "@app/components/v3";+import { useOrganization } from "@app/context";import { ExternalKmsProvider } from "@app/hooks/api/kms/types";import { AwsKmsForm } from "./AwsKmsForm";@@ -14,103 +22,104 @@ type Props = {onToggle: (isOpen: boolean) => void;};-enum WizardSteps {- SelectProvider = "select-provider",- ProviderInputs = "provider-inputs"-}-const EXTERNAL_KMS_LIST = [{icon: faAws,provider: ExternalKmsProvider.Aws,- title: "AWS KMS"+ title: "AWS KMS",+ description: "Use an AWS KMS key to encrypt organization data."},{icon: faGoogle,provider: ExternalKmsProvider.Gcp,- title: "GCP KMS"+ title: "GCP KMS",+ description: "Use a Google Cloud KMS key to encrypt organization data."}];+const PROVIDER_TITLES: Record<ExternalKmsProvider, string> = {+ [ExternalKmsProvider.Aws]: "AWS KMS",+ [ExternalKmsProvider.Gcp]: "GCP KMS"+};+export const AddExternalKmsForm = ({ isOpen, onToggle }: Props) => {- const [wizardStep, setWizardStep] = useState(WizardSteps.SelectProvider);- const [selectedProvider, setSelectedProvider] = useState<string | null>(null);+ const { isSubOrganization } = useOrganization();+ const [selectedProvider, setSelectedProvider] = useState<ExternalKmsProvider | null>(null);- const handleFormReset = (state: boolean = false) => {+ const handleOpenChange = (state: boolean) => {onToggle(state);- setWizardStep(WizardSteps.SelectProvider);- setSelectedProvider(null);+ if (!state) {+ setSelectedProvider(null);+ }};return (- <Modal isOpen={isOpen} onOpenChange={(state) => handleFormReset(state)}>- <ModalContent- title="Add a Key Management System"- subTitle="Configure an external key management system (KMS)"- className="my-4"- bodyClassName="overflow-visible"- >- <AnimatePresence mode="wait">- {wizardStep === WizardSteps.SelectProvider && (- <motion.div- key="select-type-step"- transition={{ duration: 0.1 }}- initial={{ opacity: 0, translateX: 30 }}- animate={{ opacity: 1, translateX: 0 }}- exit={{ opacity: 0, translateX: -30 }}- >- <div className="mb-4 text-mineshaft-300">Select a KMS Provider</div>- <div className="flex items-center space-x-4">- {EXTERNAL_KMS_LIST.map(({ icon, provider, title }) => (- <div- key={`kms-${provider}`}- className="flex h-28 w-32 cursor-pointer flex-col items-center space-y-4 rounded-sm border border-mineshaft-500 bg-bunker-600 p-6 transition-all hover:border-primary/70 hover:bg-primary/10 hover:text-white"- role="button"- tabIndex={0}- onClick={() => {- setSelectedProvider(provider);- setWizardStep(WizardSteps.ProviderInputs);- }}- onKeyDown={(evt) => {- if (evt.key === "Enter") {- setSelectedProvider(provider);- setWizardStep(WizardSteps.ProviderInputs);- }- }}+ <Sheet open={isOpen} onOpenChange={handleOpenChange}>+ <SheetContent className="sm:max-w-lg">+ <SheetHeader className="border-b">+ <SheetTitle>+ {selectedProvider ? `Add ${PROVIDER_TITLES[selectedProvider]}` : "Add External KMS"}+ </SheetTitle>+ <SheetDescription>+ {selectedProvider+ ? `Configure ${PROVIDER_TITLES[selectedProvider]} for organization data encryption.`+ : "Select a provider for organization data encryption."}+ </SheetDescription>+ </SheetHeader>+ {!selectedProvider && (+ <>+ <div className="grid gap-3 px-4">+ {EXTERNAL_KMS_LIST.map(({ icon, provider, title, description }) => (+ <button+ type="button"+ key={provider}+ onClick={() => setSelectedProvider(provider)}+ className={`flex items-center gap-4 rounded-md border border-border bg-container p-4 text-left transition-colors outline-none hover:bg-container-hover focus-visible:ring-[3px] focus-visible:ring-ring/50 ${+ isSubOrganization+ ? "hover:border-sub-org/70 focus-visible:border-sub-org"+ : "hover:border-org/70 focus-visible:border-org"+ }`}+ >+ <span+ className={`flex size-10 shrink-0 items-center justify-center rounded-md border ${+ isSubOrganization+ ? "border-sub-org/20 bg-sub-org/10 text-sub-org"+ : "border-org/20 bg-org/10 text-org"+ }`}>- <FontAwesomeIcon icon={icon} size="lg" />- <div className="text-center text-sm whitespace-pre-wrap">{title}</div>- </div>- ))}- </div>- </motion.div>- )}- {wizardStep === WizardSteps.ProviderInputs &&- selectedProvider === ExternalKmsProvider.Aws && (- <motion.div- key="kms-aws"- transition={{ duration: 0.1 }}- initial={{ opacity: 0, translateX: 30 }}- animate={{ opacity: 1, translateX: 0 }}- exit={{ opacity: 0, translateX: -30 }}- >- <AwsKmsForm onCancel={() => onToggle(false)} onCompleted={() => onToggle(false)} />- </motion.div>- )}- {wizardStep === WizardSteps.ProviderInputs &&- selectedProvider === ExternalKmsProvider.Gcp && (- <motion.div- key="kms-gcp"- transition={{ duration: 0.1 }}- initial={{ opacity: 0, translateX: 30 }}- animate={{ opacity: 1, translateX: 0 }}- exit={{ opacity: 0, translateX: -30 }}- >- <GcpKmsForm onCancel={() => onToggle(false)} onCompleted={() => onToggle(false)} />- </motion.div>- )}- </AnimatePresence>- </ModalContent>- </Modal>+ <FontAwesomeIcon icon={icon} className="size-4" />+ </span>+ <span className="flex flex-col gap-1">+ <span className="text-sm font-medium text-foreground">{title}</span>+ <span className="text-xs text-accent">{description}</span>+ </span>+ </button>+ ))}+ </div>+ <SheetFooter className="justify-end border-t">+ <Button type="button" variant="ghost" onClick={() => handleOpenChange(false)}>+ Cancel+ </Button>+ </SheetFooter>+ </>+ )}+ {selectedProvider === ExternalKmsProvider.Aws && (+ <AwsKmsForm+ layout="sheet"+ secondaryActionLabel="Back"+ onCancel={() => setSelectedProvider(null)}+ onCompleted={() => handleOpenChange(false)}+ />+ )}+ {selectedProvider === ExternalKmsProvider.Gcp && (+ <GcpKmsForm+ layout="sheet"+ secondaryActionLabel="Back"+ onCancel={() => setSelectedProvider(null)}+ onCompleted={() => handleOpenChange(false)}+ />+ )}+ </SheetContent>+ </Sheet>);};diff --git a/frontend/src/pages/organization/SettingsPage/components/OrgEncryptionTab/AwsKmsForm.tsx b/frontend/src/pages/organization/SettingsPage/components/OrgEncryptionTab/AwsKmsForm.tsxindex fe063d88a9..b855c70ee9 100644--- a/frontend/src/pages/organization/SettingsPage/components/OrgEncryptionTab/AwsKmsForm.tsx+++ b/frontend/src/pages/organization/SettingsPage/components/OrgEncryptionTab/AwsKmsForm.tsx@@ -2,8 +2,24 @@ import { Controller, useForm } from "react-hook-form";import { zodResolver } from "@hookform/resolvers/zod";import { createNotification } from "@app/components/notifications";-import { Button, FormControl, Input, Select, SelectItem } from "@app/components/v2";-import { Badge } from "@app/components/v3";+import {+ Badge,+ Button,+ DialogFooter,+ Field,+ FieldDescription,+ FieldError,+ FieldGroup,+ FieldLabel,+ Input,+ SecretInput,+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+ SheetFooter+} from "@app/components/v3";import { useOrganization } from "@app/context";import { useAddExternalKms, useUpdateExternalKms } from "@app/hooks/api";import {@@ -52,9 +68,18 @@ type Props = {onCancel: () => void;kms?: Kms;mode?: "full" | "credentials" | "details";+ layout?: "dialog" | "sheet";+ secondaryActionLabel?: string;};-export const AwsKmsForm = ({ onCompleted, onCancel, kms, mode = "full" }: Props) => {+export const AwsKmsForm = ({+ onCompleted,+ onCancel,+ kms,+ mode = "full",+ layout = "dialog",+ secondaryActionLabel = "Cancel"+}: Props) => {const validationSchema = kms ? UpdateExternalKmsSchema : AddExternalKmsSchema;const {@@ -62,11 +87,11 @@ export const AwsKmsForm = ({ onCompleted, onCancel, kms, mode = "full" }: Props)handleSubmit,watch,setValue,- formState: { isSubmitting }+ formState: { isSubmitting, isDirty }} = useForm<AddExternalKmsType>({resolver: zodResolver(validationSchema),defaultValues: {- name: kms?.name,+ name: kms?.name ?? "",description: kms?.description ?? "",configuration: {type: ExternalKmsProvider.Aws,@@ -98,7 +123,7 @@ export const AwsKmsForm = ({ onCompleted, onCancel, kms, mode = "full" }: Props)}});- const { currentOrg } = useOrganization();+ const { currentOrg, isSubOrganization } = useOrganization();const { mutateAsync: addAwsExternalKms } = useAddExternalKms(currentOrg.id);const { mutateAsync: updateAwsExternalKms } = useUpdateExternalKms(currentOrg.id,@@ -144,8 +169,8 @@ export const AwsKmsForm = ({ onCompleted, onCancel, kms, mode = "full" }: Props)createNotification({text:mode === "credentials"- ? "Successfully updated AWS External KMS credentials"- : "Successfully updated AWS External KMS Details",+ ? "AWS external KMS credentials updated"+ : "AWS external KMS details updated",type: "success"});} else {@@ -156,179 +181,256 @@ export const AwsKmsForm = ({ onCompleted, onCancel, kms, mode = "full" }: Props)});createNotification({- text: "Successfully added AWS External KMS",+ text: "AWS external KMS created",type: "success"});}onCompleted();- } catch (err) {- console.error(err);+ } catch {+ createNotification({+ text: kms ? "Failed to update AWS external KMS" : "Failed to create AWS external KMS",+ type: "error"+ });}};- return (- <form onSubmit={handleSubmit(handleAwsKmsFormSubmit)} autoComplete="off">- {(mode === "full" || mode === "details") && (- <>- <Controller- control={control}- name="name"- render={({ field, fieldState: { error } }) => (- <FormControl label="Alias" errorText={error?.message} isError={Boolean(error)}>- <Input placeholder="" {...field} />- </FormControl>- )}- />- <Controller- control={control}- name="description"- render={({ field, fieldState: { error } }) => (- <FormControl label="Description" errorText={error?.message} isError={Boolean(error)}>- <Input placeholder="" {...field} />- </FormControl>- )}- />- </>- )}- {(mode === "full" || mode === "credentials") && (- <>- <Controller- control={control}- name="configuration.inputs.credential.type"- defaultValue={KmsAwsCredentialType.AssumeRole}- render={({ field: { onChange, ...field }, fieldState: { error } }) => (- <FormControl- label="Authentication Mode"- errorText={error?.message}- isError={Boolean(error)}- >- <Select- defaultValue={field.value}- {...field}- onValueChange={(e) => {- setValue("configuration.inputs.credential.data.accessKey", "");- setValue("configuration.inputs.credential.data.secretKey", "");- setValue("configuration.inputs.credential.data.assumeRoleArn", "");- setValue("configuration.inputs.credential.data.externalId", "");+ let submitLabel = "Add KMS";+ if (kms) submitLabel = "Save Changes";+ if (mode === "credentials") submitLabel = "Update Credentials";- onChange(e);- }}- className="w-full"- >- <SelectItem value={KmsAwsCredentialType.AssumeRole}>AWS Assume Role</SelectItem>- <SelectItem value={KmsAwsCredentialType.AccessKey}>Access Key</SelectItem>- </Select>- </FormControl>- )}- />+ const formActions = (+ <>+ <Button type="button" variant="ghost" onClick={onCancel}>+ {secondaryActionLabel}+ </Button>+ <Button+ type="submit"+ variant={isSubOrganization ? "sub-org" : "org"}+ isPending={isSubmitting}+ isDisabled={isSubmitting || Boolean(kms && !isDirty)}+ >+ {submitLabel}+ </Button>+ </>+ );- {selectedAwsAuthType === KmsAwsCredentialType.AccessKey ? (- <>- <Controller- control={control}- name="configuration.inputs.credential.data.accessKey"- render={({ field, fieldState: { error } }) => (- <FormControl- label="Access Key ID"- errorText={error?.message}- isError={Boolean(error)}- >- <Input placeholder="" {...field} />- </FormControl>- )}- />- <Controller- control={control}- name="configuration.inputs.credential.data.secretKey"- render={({ field, fieldState: { error } }) => (- <FormControl- label="Secret Access Key"- errorText={error?.message}- isError={Boolean(error)}- >- <Input type="password" autoComplete="new-password" placeholder="" {...field} />- </FormControl>- )}- />- </>- ) : (- <>- <Controller- control={control}- name="configuration.inputs.credential.data.assumeRoleArn"- render={({ field, fieldState: { error } }) => (- <FormControl- label="IAM Role ARN For Role Assumption"- errorText={error?.message}+ return (+ <form+ onSubmit={handleSubmit(handleAwsKmsFormSubmit)}+ autoComplete="off"+ className={layout === "sheet" ? "flex min-h-0 flex-1 flex-col" : "flex flex-col gap-4"}+ >+ <FieldGroup className={layout === "sheet" ? "flex-1 overflow-y-auto px-4" : undefined}>+ {(mode === "full" || mode === "details") && (+ <>+ <Controller+ control={control}+ name="name"+ render={({ field, fieldState: { error } }) => (+ <Field data-invalid={Boolean(error)}>+ <FieldLabel htmlFor="aws-kms-alias">Alias</FieldLabel>+ <Input+ {...field}+ id="aws-kms-alias"+ value={field.value ?? ""}isError={Boolean(error)}- >- <Input placeholder="" {...field} />- </FormControl>- )}- />- <Controller- control={control}- name="configuration.inputs.credential.data.externalId"- render={({ field, fieldState: { error } }) => (- <FormControl- label="Assume Role External ID"- errorText={error?.message}+ placeholder="production-kms"+ />+ <FieldError>{error?.message}</FieldError>+ </Field>+ )}+ />+ <Controller+ control={control}+ name="description"+ render={({ field, fieldState: { error } }) => (+ <Field data-invalid={Boolean(error)}>+ <FieldLabel htmlFor="aws-kms-description">Description</FieldLabel>+ <Input+ {...field}+ id="aws-kms-description"+ value={field.value ?? ""}isError={Boolean(error)}+ placeholder="KMS for production organization data"+ />+ <FieldError>{error?.message}</FieldError>+ </Field>+ )}+ />+ </>+ )}+ {(mode === "full" || mode === "credentials") && (+ <>+ <Controller+ control={control}+ name="configuration.inputs.credential.type"+ defaultValue={KmsAwsCredentialType.AssumeRole}+ render={({ field: { onChange, value }, fieldState: { error } }) => (+ <Field data-invalid={Boolean(error)}>+ <FieldLabel htmlFor="aws-kms-auth-mode">Authentication Mode</FieldLabel>+ <Select+ value={value}+ onValueChange={(nextValue) => {+ setValue("configuration.inputs.credential.data.accessKey", "");+ setValue("configuration.inputs.credential.data.secretKey", "");+ setValue("configuration.inputs.credential.data.assumeRoleArn", "");+ setValue("configuration.inputs.credential.data.externalId", "");+ onChange(nextValue);+ }}>- <Input placeholder="" {...field} />- </FormControl>- )}- />- </>- )}- </>- )}- {(mode === "full" || mode === "details") && (- <>- <Controller- control={control}- name="configuration.inputs.awsRegion"- render={({ field: { onChange, ...field }, fieldState: { error } }) => (- <FormControl label="AWS Region" errorText={error?.message} isError={Boolean(error)}>- <Select- defaultValue={field.value}- {...field}- onValueChange={(e) => onChange(e)}- className="w-full border border-mineshaft-500"- >- {AWS_REGIONS.map((awsRegion) => (- <SelectItem value={awsRegion.slug} key={`kms-aws-region-${awsRegion.slug}`}>- {awsRegion.name} <Badge variant="neutral">{awsRegion.slug}</Badge>- </SelectItem>- ))}- </Select>- </FormControl>- )}- />- <Controller- control={control}- name="configuration.inputs.kmsKeyId"- render={({ field, fieldState: { error } }) => (- <FormControl- label="AWS KMS Key ID"- errorText={error?.message}- isError={Boolean(error)}- >- <Input placeholder="" {...field} />- </FormControl>+ <SelectTrigger+ id="aws-kms-auth-mode"+ className="w-full"+ isError={Boolean(error)}+ >+ <SelectValue placeholder="Select an authentication mode" />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value={KmsAwsCredentialType.AssumeRole}>+ AWS Assume Role+ </SelectItem>+ <SelectItem value={KmsAwsCredentialType.AccessKey}>Access Key</SelectItem>+ </SelectContent>+ </Select>+ <FieldError>{error?.message}</FieldError>+ </Field>+ )}+ />++ {selectedAwsAuthType === KmsAwsCredentialType.AccessKey ? (+ <>+ <Controller+ control={control}+ name="configuration.inputs.credential.data.accessKey"+ render={({ field, fieldState: { error } }) => (+ <Field data-invalid={Boolean(error)}>+ <FieldLabel htmlFor="aws-kms-access-key">Access Key ID</FieldLabel>+ <Input+ {...field}+ id="aws-kms-access-key"+ value={field.value ?? ""}+ isError={Boolean(error)}+ autoComplete="off"+ />+ <FieldError>{error?.message}</FieldError>+ </Field>+ )}+ />+ <Controller+ control={control}+ name="configuration.inputs.credential.data.secretKey"+ render={({ field, fieldState: { error } }) => (+ <Field data-invalid={Boolean(error)}>+ <FieldLabel htmlFor="aws-kms-secret-key">Secret Access Key</FieldLabel>+ <SecretInput+ {...field}+ id="aws-kms-secret-key"+ value={field.value ?? ""}+ containerClassName={error ? "border-danger" : undefined}+ autoComplete="new-password"+ />+ <FieldError>{error?.message}</FieldError>+ </Field>+ )}+ />+ </>+ ) : (+ <>+ <Controller+ control={control}+ name="configuration.inputs.credential.data.assumeRoleArn"+ render={({ field, fieldState: { error } }) => (+ <Field data-invalid={Boolean(error)}>+ <FieldLabel htmlFor="aws-kms-role-arn">IAM Role ARN</FieldLabel>+ <Input+ {...field}+ id="aws-kms-role-arn"+ value={field.value ?? ""}+ isError={Boolean(error)}+ placeholder="arn:aws:iam::123456789012:role/InfisicalKms"+ />+ <FieldDescription>+ The role Infisical assumes to access AWS KMS.+ </FieldDescription>+ <FieldError>{error?.message}</FieldError>+ </Field>+ )}+ />+ <Controller+ control={control}+ name="configuration.inputs.credential.data.externalId"+ render={({ field, fieldState: { error } }) => (+ <Field data-invalid={Boolean(error)}>+ <FieldLabel htmlFor="aws-kms-external-id">External ID</FieldLabel>+ <Input+ {...field}+ id="aws-kms-external-id"+ value={field.value ?? ""}+ isError={Boolean(error)}+ placeholder="Optional"+ />+ <FieldError>{error?.message}</FieldError>+ </Field>+ )}+ />+ </>)}- />- </>+ </>+ )}+ {(mode === "full" || mode === "details") && (+ <>+ <Controller+ control={control}+ name="configuration.inputs.awsRegion"+ render={({ field: { onChange, value }, fieldState: { error } }) => (+ <Field data-invalid={Boolean(error)}>+ <FieldLabel htmlFor="aws-kms-region">AWS Region</FieldLabel>+ <Select value={value} onValueChange={onChange}>+ <SelectTrigger id="aws-kms-region" className="w-full" isError={Boolean(error)}>+ <SelectValue placeholder="Select an AWS region" />+ </SelectTrigger>+ <SelectContent>+ {AWS_REGIONS.map((awsRegion) => (+ <SelectItem value={awsRegion.slug} key={`kms-aws-region-${awsRegion.slug}`}>+ <span>{awsRegion.name}</span>+ <Badge variant="neutral">{awsRegion.slug}</Badge>+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ <FieldError>{error?.message}</FieldError>+ </Field>+ )}+ />+ <Controller+ control={control}+ name="configuration.inputs.kmsKeyId"+ render={({ field, fieldState: { error } }) => (+ <Field data-invalid={Boolean(error)}>+ <FieldLabel htmlFor="aws-kms-key-id">AWS KMS Key ID</FieldLabel>+ <Input+ {...field}+ id="aws-kms-key-id"+ value={field.value ?? ""}+ isError={Boolean(error)}+ placeholder="Optional"+ />+ <FieldDescription>+ Leave blank to create a new AWS KMS key automatically.+ </FieldDescription>+ <FieldError>{error?.message}</FieldError>+ </Field>+ )}+ />+ </>+ )}+ </FieldGroup>+ {layout === "sheet" ? (+ <SheetFooter className="justify-end border-t">{formActions}</SheetFooter>+ ) : (+ <DialogFooter>{formActions}</DialogFooter>)}- <div className="mt-6 flex items-center space-x-4">- <Button type="submit" isLoading={isSubmitting}>- {mode === "credentials" ? "Update Credentials" : "Save"}- </Button>- <Button variant="outline_bg" onClick={onCancel}>- Cancel- </Button>- </div></form>);};diff --git a/frontend/src/pages/organization/SettingsPage/components/OrgEncryptionTab/EditExternalKmsCredentialsModal.tsx b/frontend/src/pages/organization/SettingsPage/components/OrgEncryptionTab/EditExternalKmsCredentialsModal.tsxindex b7c393d444..85660b08ae 100644--- a/frontend/src/pages/organization/SettingsPage/components/OrgEncryptionTab/EditExternalKmsCredentialsModal.tsx+++ b/frontend/src/pages/organization/SettingsPage/components/OrgEncryptionTab/EditExternalKmsCredentialsModal.tsx@@ -1,4 +1,11 @@-import { Modal, ModalContent } from "@app/components/v2";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle,+ Skeleton+} from "@app/components/v3";import { useGetExternalKmsById } from "@app/hooks/api";import { ExternalKmsProvider } from "@app/hooks/api/kms/types";@@ -18,14 +25,23 @@ export const EditExternalKmsCredentialsModal = ({provider,onOpenChange}: Props) => {- const { data: kms } = useGetExternalKmsById({ kmsId, provider });+ const { data: kms, isPending } = useGetExternalKmsById({ kmsId, provider });+return (- <Modal isOpen={isOpen} onOpenChange={onOpenChange}>- <ModalContent- title="Edit Credentials"- subTitle="Update the credentials for this KMS."- bodyClassName="overflow-visible"- >+ <Dialog open={isOpen} onOpenChange={onOpenChange}>+ <DialogContent className="sm:max-w-lg">+ <DialogHeader>+ <DialogTitle>Edit KMS Credentials</DialogTitle>+ <DialogDescription>+ Update the credentials used to access this external KMS.+ </DialogDescription>+ </DialogHeader>+ {isPending && (+ <div className="flex flex-col gap-4">+ <Skeleton className="h-14 w-full" />+ <Skeleton className="h-14 w-full" />+ </div>+ )}{kms?.externalKms?.provider === ExternalKmsProvider.Aws && (<AwsKmsFormkms={kms}@@ -42,7 +58,7 @@ export const EditExternalKmsCredentialsModal = ({onCompleted={() => onOpenChange(false)}/>)}- </ModalContent>- </Modal>+ </DialogContent>+ </Dialog>);};diff --git a/frontend/src/pages/organization/SettingsPage/components/OrgEncryptionTab/EditExternalKmsDetailsModal.tsx b/frontend/src/pages/organization/SettingsPage/components/OrgEncryptionTab/EditExternalKmsDetailsModal.tsxindex 7d6e125e30..cc61469490 100644--- a/frontend/src/pages/organization/SettingsPage/components/OrgEncryptionTab/EditExternalKmsDetailsModal.tsx+++ b/frontend/src/pages/organization/SettingsPage/components/OrgEncryptionTab/EditExternalKmsDetailsModal.tsx@@ -1,4 +1,11 @@-import { Modal, ModalContent } from "@app/components/v2";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle,+ Skeleton+} from "@app/components/v3";import { useGetExternalKmsById } from "@app/hooks/api";import { ExternalKmsProvider } from "@app/hooks/api/kms/types";@@ -13,15 +20,24 @@ type Props = {};export const EditExternalKmsDetailsModal = ({ isOpen, onOpenChange, kmsId, provider }: Props) => {- const { data: kms } = useGetExternalKmsById({ kmsId, provider });+ const { data: kms, isPending } = useGetExternalKmsById({ kmsId, provider });return (- <Modal isOpen={isOpen} onOpenChange={onOpenChange}>- <ModalContent- title="Edit KMS Details"- subTitle="Update the name and description for this KMS."- bodyClassName="overflow-visible"- >+ <Dialog open={isOpen} onOpenChange={onOpenChange}>+ <DialogContent className="sm:max-w-lg">+ <DialogHeader>+ <DialogTitle>Edit KMS Details</DialogTitle>+ <DialogDescription>+ Update the alias and provider configuration for this external KMS.+ </DialogDescription>+ </DialogHeader>+ {isPending && (+ <div className="flex flex-col gap-4">+ <Skeleton className="h-14 w-full" />+ <Skeleton className="h-14 w-full" />+ <Skeleton className="h-14 w-full" />+ </div>+ )}{kms?.externalKms?.provider === ExternalKmsProvider.Aws && (<AwsKmsFormkms={kms}@@ -38,7 +54,7 @@ export const EditExternalKmsDetailsModal = ({ isOpen, onOpenChange, kmsId, provionCompleted={() => onOpenChange(false)}/>)}- </ModalContent>- </Modal>+ </DialogContent>+ </Dialog>);};diff --git a/frontend/src/pages/organization/SettingsPage/components/OrgEncryptionTab/ExternalKmsItem.tsx b/frontend/src/pages/organization/SettingsPage/components/OrgEncryptionTab/ExternalKmsItem.tsxindex 734a8e0aba..5557ce248b 100644--- a/frontend/src/pages/organization/SettingsPage/components/OrgEncryptionTab/ExternalKmsItem.tsx+++ b/frontend/src/pages/organization/SettingsPage/components/OrgEncryptionTab/ExternalKmsItem.tsx@@ -1,20 +1,19 @@import { faAws, faGoogle } from "@fortawesome/free-brands-svg-icons";-import { faCheck, faCopy, faEllipsis } from "@fortawesome/free-solid-svg-icons";import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";-import { twMerge } from "tailwind-merge";+import { KeyRound, MoreHorizontal, Pencil, Trash2 } from "lucide-react";-import { createNotification } from "@app/components/notifications";import { OrgPermissionCan } from "@app/components/permissions/OrgPermissionCan";import {+ CopyButton,DropdownMenu,DropdownMenuContent,DropdownMenuItem,- DropdownMenuTrigger-} from "@app/components/v2/Dropdown";-import { IconButton } from "@app/components/v2/IconButton";-import { Td, Tr } from "@app/components/v2/Table";+ DropdownMenuTrigger,+ IconButton,+ TableCell,+ TableRow+} from "@app/components/v3";import { OrgPermissionActions, OrgPermissionSubjects } from "@app/context/OrgPermissionContext";-import { useToggle } from "@app/hooks";import { ExternalKmsProvider, KmsListEntry } from "@app/hooks/api/kms/types";import { SubscriptionPlan } from "@app/hooks/api/types";import { UsePopUpState } from "@app/hooks/usePopUp";@@ -36,119 +35,71 @@ type Props = {};export const ExternalKmsItem = ({ kms, handlePopUpOpen, subscription }: Props) => {- const [isKmsIdCopied, { timedToggle: toggleKmsIdCopied }] = useToggle(false);- const [isKmsAliasCopied, { timedToggle: toggleKmsAliasCopied }] = useToggle(false);+ const handleEdit = (popUpName: "editExternalKmsDetails" | "editExternalKmsCredentials") => {+ if (subscription && !subscription.externalKms) {+ handlePopUpOpen("upgradePlan", {+ isEnterpriseFeature: true+ });+ return;+ }++ handlePopUpOpen(popUpName, {+ kmsId: kms.id,+ name: kms.name,+ provider: kms.externalKms.provider+ });+ };return (- <Tr key={kms.id}>- <Td className="flex max-w-xs items-center overflow-hidden text-ellipsis hover:overflow-auto hover:break-all">- {kms.externalKms.provider === ExternalKmsProvider.Aws && <FontAwesomeIcon icon={faAws} />}- {kms.externalKms.provider === ExternalKmsProvider.Gcp && (- <FontAwesomeIcon icon={faGoogle} />- )}- <div className="ml-2">{kms.externalKms.provider.toUpperCase()}</div>- </Td>- <Td>- <div className="group flex items-center gap-2">- {kms.name}- <IconButton- size="xs"- ariaLabel="copy icon"- colorSchema="secondary"- className="relative rounded-md opacity-0 group-hover:opacity-100"- onClick={() => {- if (isKmsAliasCopied) {- return;- }- navigator.clipboard.writeText(kms.name);- createNotification({- text: "KMS alias copied to clipboard",- type: "success"- });- toggleKmsAliasCopied(2000);- }}- >- <FontAwesomeIcon icon={isKmsAliasCopied ? faCheck : faCopy} />- </IconButton>+ <TableRow key={kms.id}>+ <TableCell>+ <div className="flex items-center gap-2">+ {kms.externalKms.provider === ExternalKmsProvider.Aws && (+ <FontAwesomeIcon icon={faAws} className="size-4 text-accent" />+ )}+ {kms.externalKms.provider === ExternalKmsProvider.Gcp && (+ <FontAwesomeIcon icon={faGoogle} className="size-4 text-accent" />+ )}+ <span className="font-medium text-foreground">+ {kms.externalKms.provider.toUpperCase()}+ </span>+ </div>+ </TableCell>+ <TableCell>+ <div className="flex items-center gap-1.5">+ <span className="font-medium text-foreground">{kms.name}</span>+ <CopyButton value={kms.name} ariaLabel={`Copy KMS alias ${kms.name}`} /></div>- </Td>- <Td>- <div className="group flex items-center gap-2">- {kms.id}- <IconButton- size="xs"- ariaLabel="copy icon"- colorSchema="secondary"- className="relative rounded-md opacity-0 group-hover:opacity-100"- onClick={() => {- if (isKmsIdCopied) {- return;- }- navigator.clipboard.writeText(kms.id);- createNotification({- text: "KMS ID copied to clipboard",- type: "success"- });- toggleKmsIdCopied(2000);- }}- >- <FontAwesomeIcon icon={isKmsIdCopied ? faCheck : faCopy} />- </IconButton>+ </TableCell>+ <TableCell>+ <div className="flex items-center gap-1.5">+ <span className="max-w-80 truncate font-mono text-xs">{kms.id}</span>+ <CopyButton value={kms.id} ariaLabel={`Copy KMS ID ${kms.id}`} /></div>- </Td>- <Td>+ </TableCell>+ <TableCell className="text-right"><DropdownMenu>- <DropdownMenuTrigger asChild className="rounded-lg">- <div className="flex justify-end hover:text-primary-400 data-[state=open]:text-primary-400">- <FontAwesomeIcon size="sm" icon={faEllipsis} />- </div>+ <DropdownMenuTrigger asChild>+ <IconButton variant="ghost" size="xs" aria-label={`Actions for KMS ${kms.name}`}>+ <MoreHorizontal />+ </IconButton></DropdownMenuTrigger>- <DropdownMenuContent align="start" className="p-1">+ <DropdownMenuContent align="end" className="w-48"><OrgPermissionCan I={OrgPermissionActions.Edit} an={OrgPermissionSubjects.Kms}>{(isAllowed) => (<><DropdownMenuItem- disabled={!isAllowed}- className={twMerge(- !isAllowed && "pointer-events-none cursor-not-allowed opacity-50"- )}- onClick={(e) => {- e.stopPropagation();- if (subscription && !subscription?.externalKms) {- handlePopUpOpen("upgradePlan", {- isEnterpriseFeature: true- });- return;- }-- handlePopUpOpen("editExternalKmsDetails", {- kmsId: kms.id,- provider: kms.externalKms.provider- });- }}+ isDisabled={!isAllowed}+ onClick={() => handleEdit("editExternalKmsDetails")}>+ <Pencil />Edit Details</DropdownMenuItem><DropdownMenuItem- disabled={!isAllowed}- className={twMerge(- !isAllowed && "pointer-events-none cursor-not-allowed opacity-50"- )}- onClick={(e) => {- e.stopPropagation();- if (subscription && !subscription?.externalKms) {- handlePopUpOpen("upgradePlan", {- isEnterpriseFeature: true- });- return;- }-- handlePopUpOpen("editExternalKmsCredentials", {- kmsId: kms.id,- provider: kms.externalKms.provider- });- }}+ isDisabled={!isAllowed}+ onClick={() => handleEdit("editExternalKmsCredentials")}>+ <KeyRound />Edit Credentials</DropdownMenuItem></>@@ -157,26 +108,24 @@ export const ExternalKmsItem = ({ kms, handlePopUpOpen, subscription }: Props) =<OrgPermissionCan I={OrgPermissionActions.Delete} an={OrgPermissionSubjects.Kms}>{(isAllowed) => (<DropdownMenuItem- disabled={!isAllowed}- className={twMerge(- !isAllowed && "pointer-events-none cursor-not-allowed opacity-50"- )}- onClick={(e) => {- e.stopPropagation();+ variant="danger"+ isDisabled={!isAllowed}+ onClick={() =>handlePopUpOpen("removeExternalKms", {name: kms.name,kmsId: kms.id,provider: kms.externalKms.provider- });- }}+ })+ }>+ <Trash2 />Delete</DropdownMenuItem>)}</OrgPermissionCan></DropdownMenuContent></DropdownMenu>- </Td>- </Tr>+ </TableCell>+ </TableRow>);};diff --git a/frontend/src/pages/organization/SettingsPage/components/OrgEncryptionTab/GcpKmsForm.tsx b/frontend/src/pages/organization/SettingsPage/components/OrgEncryptionTab/GcpKmsForm.tsxindex 2ac44483e4..5d4bd6253b 100644--- a/frontend/src/pages/organization/SettingsPage/components/OrgEncryptionTab/GcpKmsForm.tsx+++ b/frontend/src/pages/organization/SettingsPage/components/OrgEncryptionTab/GcpKmsForm.tsx@@ -3,8 +3,20 @@ import { Controller, useForm } from "react-hook-form";import { zodResolver } from "@hookform/resolvers/zod";import { createNotification } from "@app/components/notifications";-import { Button, FilterableSelect, FormControl, Input } from "@app/components/v2";-import { Badge } from "@app/components/v3";+import {+ Badge,+ Button,+ DialogFooter,+ Field,+ FieldDescription,+ FieldError,+ FieldGroup,+ FieldLabel,+ FileDropzone,+ FilterableSelect,+ Input,+ SheetFooter+} from "@app/components/v3";import { useOrganization } from "@app/context";import {useAddExternalKms,@@ -25,9 +37,13 @@ type Props = {onCancel: () => void;kms?: Kms;mode?: "full" | "credentials" | "details";+ layout?: "dialog" | "sheet";+ secondaryActionLabel?: string;};-const GCP_REGIONS = [+type SelectOption = { label: string; value: string };++const GCP_REGIONS: SelectOption[] = [{ label: "Johannesburg", value: "africa-south1" },{ label: "Taiwan", value: "asia-east1" },{ label: "Hong Kong", value: "asia-east2" },@@ -70,16 +86,30 @@ const GCP_REGIONS = [{ label: "Las Vegas", value: "us-west4" }];-const formatOptionLabel = ({ value, label }: { value: string; label: string }) => (- <div className="flex w-full flex-row items-center justify-between">+const formatOptionLabel = ({ value, label }: SelectOption) => (+ <div className="flex w-full flex-row items-center justify-between gap-2"><span>{label}</span><Badge variant="neutral">{value}</Badge></div>);-export const GcpKmsForm = ({ onCompleted, onCancel, kms, mode = "full" }: Props) => {- const [isCredentialValid, setIsCredentialValid] = useState<boolean>(false);- const [keys, setKeys] = useState<{ value: string; label: string }[]>([]);+const filesToFileList = (files: File[]) => {+ const dataTransfer = new DataTransfer();+ files.forEach((file) => dataTransfer.items.add(file));+ return dataTransfer.files;+};++export const GcpKmsForm = ({+ onCompleted,+ onCancel,+ kms,+ mode = "full",+ layout = "dialog",+ secondaryActionLabel = "Cancel"+}: Props) => {+ const [isCredentialValid, setIsCredentialValid] = useState(false);+ const [credentialFiles, setCredentialFiles] = useState<File[]>([]);+ const [keys, setKeys] = useState<SelectOption[]>([]);const {control,@@ -89,7 +119,7 @@ export const GcpKmsForm = ({ onCompleted, onCancel, kms, mode = "full" }: Props)getValues,resetField,setValue,- formState: { isSubmitting, isDirty, isValid }+ formState: { isSubmitting, isDirty }} = useForm<AddExternalKmsGcpFormSchemaType>({resolver: zodResolver(AddExternalKmsGcpFormSchema),defaultValues: {@@ -99,8 +129,8 @@ export const GcpKmsForm = ({ onCompleted, onCancel, kms, mode = "full" }: Props)gcpRegion: kms? {label:- GCP_REGIONS.find((r) => r.value === kms.externalKms.configuration.gcpRegion)?.label ??- "",+ GCP_REGIONS.find((region) => region.value === kms.externalKms.configuration.gcpRegion)+ ?.label ?? "",value: kms.externalKms.configuration.gcpRegion}: undefined,@@ -108,7 +138,7 @@ export const GcpKmsForm = ({ onCompleted, onCancel, kms, mode = "full" }: Props)}});- const { currentOrg } = useOrganization();+ const { currentOrg, isSubOrganization } = useOrganization();const { mutateAsync: addGcpExternalKms } = useAddExternalKms(currentOrg.id);const { mutateAsync: updateGcpExternalKms } = useUpdateExternalKms(currentOrg.id,@@ -118,93 +148,145 @@ export const GcpKmsForm = ({ onCompleted, onCancel, kms, mode = "full" }: Props)const { mutateAsync: fetchGcpKeys, isPending: isFetchGcpKeysLoading } =useExternalKmsFetchGcpKeys(currentOrg?.id);- // transforms the credential file into a JSON object- async function getCredentialFileJson(): Promise<ExternalKmsGcpCredentialSchemaType | null> {- const files = getValues("credentialFile");- if (!files || !files.length) {+ const getCredentialFileJson = async (+ files: FileList | undefined = getValues("credentialFile")+ ): Promise<ExternalKmsGcpCredentialSchemaType | null> => {+ const file = files?.[0];+ if (!file) {+ setError("credentialFile", {+ message: "Service account credential JSON is required."+ });return null;}- const file = files[0];if (file.type !== "application/json") {setError("credentialFile", {message: "Only .json files are accepted."});return null;}- const jsonContents = await file.text();- const parsedJson = ExternalKmsGcpCredentialSchema.safeParse(JSON.parse(jsonContents));- if (!parsedJson.success) {++ try {+ const jsonContents = await file.text();+ const parsedJson = ExternalKmsGcpCredentialSchema.safeParse(JSON.parse(jsonContents));+ if (!parsedJson.success) {+ setError("credentialFile", {+ message: "Invalid service account credential JSON."+ });+ return null;+ }+ clearErrors("credentialFile");+ return parsedJson.data;+ } catch {setError("credentialFile", {- message: "Invalid Service Account credential JSON."+ message: "Invalid service account credential JSON."});return null;}- clearErrors("credentialFile");- return parsedJson.data;- }+ };- // handles the form submission- const handleGcpKmsFormSubmit = async (data: AddExternalKmsGcpFormSchemaType) => {- const { name, description, formType, gcpRegion: gcpRegionObject, keyObject } = data;+ const fetchGCPKeys = async ({+ gcpRegion = getValues("gcpRegion")?.value,+ files = getValues("credentialFile")+ }: { gcpRegion?: string; files?: FileList } = {}) => {+ resetField("keyObject");+ setKeys([]);+ setIsCredentialValid(false);++ if (!gcpRegion) return;++ const credentialJson = kms ? undefined : await getCredentialFileJson(files);+ if (!kms && !credentialJson) return;try {+ const response = await fetchGcpKeys({+ gcpRegion,+ ...(kms ? { kmsId: kms.id } : { credential: credentialJson! })+ });+ setIsCredentialValid(true);++ const returnedKeys = response.keys.map((key) => {+ const parts = key.split("/");+ return {+ value: key,+ label: `${parts[5]}/${parts[7]}`+ };+ });++ setKeys(returnedKeys);if (kms) {- if (formType === "updateGcpKms") {- const gcpRegion = gcpRegionObject?.value;- if (!gcpRegion) {- setError("gcpRegion", {- message: "Please select a GCP region."- });- return;- }+ const existingKey = returnedKeys.find(+ (key) => key.value === kms.externalKms.configuration.keyName+ );+ if (existingKey) {+ setValue("keyObject", existingKey, { shouldDirty: false, shouldValidate: true });+ }+ }+ } catch {+ createNotification({+ text: "Failed to load GCP KMS keys",+ type: "error"+ });+ }+ };- if (keyObject && !keys.find((k) => k.value === keyObject.value)) {- setError("keyObject", {- message: "Please select a valid key."- });- resetField("keyObject");- return;- }+ const handleGcpKmsFormSubmit = async (data: AddExternalKmsGcpFormSchemaType) => {+ const { name, description, formType, gcpRegion: gcpRegionObject, keyObject } = data;- await updateGcpExternalKms({- kmsId: kms.id,- name,- description,- configuration: {- type: ExternalKmsProvider.Gcp,- inputs: {- gcpRegion,- keyName: keyObject?.value ?? kms.externalKms.configuration.keyName- }- }+ try {+ if (kms && formType === "updateGcpKms") {+ const gcpRegion = gcpRegionObject?.value;+ if (!gcpRegion) {+ setError("gcpRegion", {+ message: "Select a GCP region."});+ return;+ }- createNotification({- text: "Successfully updated GCP External KMS Details",- type: "success"+ if (keyObject && !keys.find((key) => key.value === keyObject.value)) {+ setError("keyObject", {+ message: "Select a valid key."});+ resetField("keyObject");+ return;}- } else if (formType === "newGcpKms") {++ await updateGcpExternalKms({+ kmsId: kms.id,+ name,+ description,+ configuration: {+ type: ExternalKmsProvider.Gcp,+ inputs: {+ gcpRegion,+ keyName: keyObject?.value ?? kms.externalKms.configuration.keyName+ }+ }+ });++ createNotification({+ text: "GCP external KMS details updated",+ type: "success"+ });+ } else if (!kms && formType === "newGcpKms") {const gcpRegion = gcpRegionObject?.value;if (!gcpRegion) {setError("gcpRegion", {- message: "Please select a GCP region."+ message: "Select a GCP region."});return;}- if (!keys.find((k) => k.value === keyObject?.value)) {+ if (!keys.find((key) => key.value === keyObject?.value)) {setError("keyObject", {- message: "Please select a valid key."+ message: "Select a valid key."});resetField("keyObject");return;}const credentialJson = await getCredentialFileJson();- if (!credentialJson) {- return;- }+ if (!credentialJson) return;+await addGcpExternalKms({name,description,@@ -219,145 +301,159 @@ export const GcpKmsForm = ({ onCompleted, onCancel, kms, mode = "full" }: Props)});createNotification({- text: "Successfully added GCP External KMS",+ text: "GCP external KMS created",type: "success"});}onCompleted();- } catch (err) {- console.error(err);- }- };-- const fetchGCPKeys = async () => {- // @ts-expect-error - issue with the way react-select renders the placeholder. We need to set the value to null explicitly otherwise it will not re-render- setValue("keyObject", null);- setKeys([]);-- const credentialJson = kms ? undefined : await getCredentialFileJson();- if (!kms && !credentialJson) {- return;- }- const gcpRegionObject = getValues("gcpRegion");- const gcpRegion = gcpRegionObject?.value;- if (!gcpRegion) {- setError("gcpRegion", {- message: "Please select a GCP region to fetch GCP Keys."+ } catch {+ createNotification({+ text: kms ? "Failed to update GCP external KMS" : "Failed to create GCP external KMS",+ type: "error"});- return;- }- const res = await fetchGcpKeys({- gcpRegion,- ...(kms ? { kmsId: kms.id } : { credential: credentialJson! })- });- setIsCredentialValid(!!res.keys);- const returnedKeys = res.keys.map((key) => {- const parts = key.split("/");- const keyLabel = `${parts[5]}/${parts[7]}`;- return {- value: key,- label: keyLabel- };- });-- setKeys(returnedKeys);- if (kms) {- const existingKey = returnedKeys.find(- (k) => k.value === kms.externalKms.configuration.keyName- );- if (existingKey) {- setValue("keyObject", existingKey);- }}};const getPlaceholderText = () => {- if (isFetchGcpKeysLoading) {- return "Loading keys in this region...";- }- if (!isCredentialValid) {- return "Upload a valid credential file";- }- if (keys.length) {- return "Select a key";- }-- return "No valid keys found in this region";+ if (isFetchGcpKeysLoading) return "Loading keys in this region...";+ if (!isCredentialValid)+ return kms ? "Select a region to load keys" : "Upload a valid credential file";+ if (keys.length) return "Select a key";+ return "No keys found in this region";};useEffect(() => {- if (kms && !isCredentialValid) {- fetchGCPKeys();+ if (kms && mode !== "credentials") {+ fetchGCPKeys({ gcpRegion: kms.externalKms.configuration.gcpRegion });}- }, [kms]);+ // Fetch once when the selected KMS changes. Form callbacks intentionally stay out of this dependency list.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [kms?.id, mode]);++ const formActions = (+ <>+ <Button type="button" variant="ghost" onClick={onCancel}>+ {mode === "credentials" ? "Close" : secondaryActionLabel}+ </Button>+ {mode !== "credentials" && (+ <Button+ type="submit"+ variant={isSubOrganization ? "sub-org" : "org"}+ isPending={isSubmitting}+ isDisabled={isSubmitting || Boolean(kms && !isDirty)}+ >+ {kms ? "Save Changes" : "Add KMS"}+ </Button>+ )}+ </>+ );return (- <form onSubmit={handleSubmit(handleGcpKmsFormSubmit)} autoComplete="off">- {(mode === "full" || mode === "details") && (- <>+ <form+ onSubmit={handleSubmit(handleGcpKmsFormSubmit)}+ autoComplete="off"+ className={layout === "sheet" ? "flex min-h-0 flex-1 flex-col" : "flex flex-col gap-4"}+ >+ {mode === "credentials" ? (+ <p className="text-sm text-accent">+ GCP service account credentials cannot be changed after this KMS is created. Add a new+ external KMS and assign it to the projects that need to use it.+ </p>+ ) : (+ <FieldGroup className={layout === "sheet" ? "flex-1 overflow-y-auto px-4" : undefined}><Controllercontrol={control}name="name"render={({ field, fieldState: { error } }) => (- <FormControl label="Alias" errorText={error?.message} isError={Boolean(error)}>- <Input placeholder="" {...field} />- </FormControl>+ <Field data-invalid={Boolean(error)}>+ <FieldLabel htmlFor="gcp-kms-alias">Alias</FieldLabel>+ <Input+ {...field}+ id="gcp-kms-alias"+ value={field.value ?? ""}+ isError={Boolean(error)}+ placeholder="production-kms"+ />+ <FieldError>{error?.message}</FieldError>+ </Field>)}/><Controllercontrol={control}name="description"render={({ field, fieldState: { error } }) => (- <FormControl label="Description" errorText={error?.message} isError={Boolean(error)}>- <Input placeholder="" {...field} />- </FormControl>+ <Field data-invalid={Boolean(error)}>+ <FieldLabel htmlFor="gcp-kms-description">Description</FieldLabel>+ <Input+ {...field}+ id="gcp-kms-description"+ value={field.value ?? ""}+ isError={Boolean(error)}+ placeholder="KMS for production organization data"+ />+ <FieldError>{error?.message}</FieldError>+ </Field>)}/><Controllercontrol={control}name="gcpRegion"render={({ field, fieldState: { error } }) => (- <FormControl label="GCP Region" errorText={error?.message} isError={Boolean(error)}>- <FilterableSelect- className="w-full"+ <Field data-invalid={Boolean(error)}>+ <FieldLabel htmlFor="gcp-kms-region">GCP Region</FieldLabel>+ <FilterableSelect<SelectOption>+ inputId="gcp-kms-region"placeholder="Select a GCP region"- name="gcpRegion"options={GCP_REGIONS}value={field.value}- onChange={(e) => {- resetField("keyObject");- field.onChange(e);- fetchGCPKeys();+ isError={Boolean(error)}+ onChange={(option) => {+ const region = option as SelectOption | null;+ field.onChange(region);+ fetchGCPKeys({ gcpRegion: region?.value });}}formatOptionLabel={formatOptionLabel}/>- </FormControl>+ <FieldError>{error?.message}</FieldError>+ </Field>)}/>{!kms && (<Controllercontrol={control}name="credentialFile"- render={({ field: { value, onChange, ref, ...rest }, fieldState: { error } }) => (- <FormControl- label="Service Account Credential JSON"- errorText={error?.message}- isError={Boolean(error)}- >- <Input- {...rest}- ref={ref}- type="file"- accept=".json"- placeholder=""- value={value?.filename}- onChange={(e) => {- onChange(e.target.files);- fetchGCPKeys();+ render={({ field: { onChange }, fieldState: { error } }) => (+ <Field data-invalid={Boolean(error)}>+ <FieldLabel>Service Account Credential JSON</FieldLabel>+ <FileDropzone+ accept=".json,application/json"+ description=".json service account credential, up to 8 KB"+ files={credentialFiles}+ accentClassName={isSubOrganization ? "text-sub-org" : "text-org"}+ activeFrameClassName={isSubOrganization ? "text-sub-org" : "text-org"}+ activeEmptyClassName={isSubOrganization ? "bg-sub-org/10" : "bg-org/10"}+ onFilesSelect={(selectedFiles) => {+ const nextFiles = selectedFiles.slice(0, 1);+ const fileList = filesToFileList(nextFiles);+ setCredentialFiles(nextFiles);+ onChange(fileList);+ fetchGCPKeys({ files: fileList });+ }}+ onFileRemove={() => {+ const fileList = filesToFileList([]);+ setCredentialFiles([]);+ onChange(fileList);+ resetField("keyObject");+ setKeys([]);+ setIsCredentialValid(false);}}/>- </FormControl>+ <FieldDescription>+ Used only to discover and access KMS keys in the selected project.+ </FieldDescription>+ <FieldError>{error?.message}</FieldError>+ </Field>)}/>)}@@ -365,39 +461,29 @@ export const GcpKmsForm = ({ onCompleted, onCancel, kms, mode = "full" }: Props)control={control}name="keyObject"render={({ field, fieldState: { error } }) => (- <FormControl label="GCP Key Name" errorText={error?.message} isError={Boolean(error)}>- <FilterableSelect- className="w-full"+ <Field data-invalid={Boolean(error)}>+ <FieldLabel htmlFor="gcp-kms-key">GCP Key</FieldLabel>+ <FilterableSelect<SelectOption>+ inputId="gcp-kms-key"placeholder={getPlaceholderText()}isDisabled={!isCredentialValid || !keys.length}- name="key"+ isLoading={isFetchGcpKeysLoading}options={keys}value={field.value}+ isError={Boolean(error)}onChange={field.onChange}/>- </FormControl>+ <FieldError>{error?.message}</FieldError>+ </Field>)}/>- </>+ </FieldGroup>)}- {kms && mode === "credentials" && (- <span className="text-xs text-mineshaft-300">- To change your GCP credentials, create a new external KMS and assign it to project you- want to use it with.- </span>+ {layout === "sheet" ? (+ <SheetFooter className="justify-end border-t">{formActions}</SheetFooter>+ ) : (+ <DialogFooter>{formActions}</DialogFooter>)}- <div className="mt-6 flex items-center space-x-4">- <Button- type="submit"- isLoading={isSubmitting}- isDisabled={!isDirty || !isValid || mode === "credentials"}- >- Save- </Button>- <Button variant="outline_bg" onClick={onCancel}>- Cancel- </Button>- </div></form>);};diff --git a/frontend/src/pages/organization/SettingsPage/components/OrgEncryptionTab/OrgEncryptionTab.tsx b/frontend/src/pages/organization/SettingsPage/components/OrgEncryptionTab/OrgEncryptionTab.tsxindex f8db49c8b6..510201b90f 100644--- a/frontend/src/pages/organization/SettingsPage/components/OrgEncryptionTab/OrgEncryptionTab.tsx+++ b/frontend/src/pages/organization/SettingsPage/components/OrgEncryptionTab/OrgEncryptionTab.tsx@@ -1,21 +1,36 @@-import { faLock, faPlus } from "@fortawesome/free-solid-svg-icons";-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";+import { KeyRound, Plus, Trash2 } from "lucide-react";import { UpgradePlanModal } from "@app/components/license/UpgradePlanModal";import { createNotification } from "@app/components/notifications";import { OrgPermissionCan } from "@app/components/permissions";import {+ AlertDialog,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogMedia,+ AlertDialogTitle,Button,- DeleteActionModal,- EmptyState,+ Card,+ CardAction,+ CardContent,+ CardDescription,+ CardHeader,+ CardTitle,+ Empty,+ EmptyDescription,+ EmptyHeader,+ EmptyTitle,+ Skeleton,Table,- TableContainer,- TableSkeleton,- TBody,- Td,- THead,- Tr-} from "@app/components/v2";+ TableBody,+ TableCell,+ TableHead,+ TableHeader,+ TableRow+} from "@app/components/v3";import {OrgPermissionActions,OrgPermissionSubjects,@@ -32,12 +47,18 @@ import { EditExternalKmsCredentialsModal } from "./EditExternalKmsCredentialsModimport { EditExternalKmsDetailsModal } from "./EditExternalKmsDetailsModal";import { ExternalKmsItem } from "./ExternalKmsItem";+type RemoveExternalKmsData = {+ kmsId: string;+ name: string;+ provider: ExternalKmsProvider;+};+export const OrgEncryptionTab = withPermission(() => {const { currentOrg, isSubOrganization } = useOrganization();const { subscription } = useSubscription();const orgId = currentOrg?.id || "";- const { popUp, handlePopUpOpen, handlePopUpToggle } = usePopUp([+ const { popUp, handlePopUpClose, handlePopUpOpen, handlePopUpToggle } = usePopUp(["upgradePlan","addExternalKms","editExternalKmsDetails",@@ -47,81 +68,111 @@ export const OrgEncryptionTab = withPermission(const { data: externalKmsList, isPending: isExternalKmsListLoading } =useGetExternalKmsList(orgId);- const { mutateAsync: removeExternalKms } = useRemoveExternalKms(currentOrg.id);+ const { mutateAsync: removeExternalKms, isPending: isRemovingExternalKms } =+ useRemoveExternalKms(currentOrg.id);+ const removeExternalKmsData = popUp.removeExternalKms.data as RemoveExternalKmsData | undefined;const handleRemoveExternalKms = async () => {- const { kmsId, provider } = popUp?.removeExternalKms?.data as {- kmsId: string;- provider: ExternalKmsProvider;- };+ if (!removeExternalKmsData) return;- await removeExternalKms({ kmsId, provider });+ try {+ await removeExternalKms({+ kmsId: removeExternalKmsData.kmsId,+ provider: removeExternalKmsData.provider+ });- createNotification({- text: "Successfully deleted external KMS",- type: "success"- });+ createNotification({+ text: `External KMS "${removeExternalKmsData.name}" deleted`,+ type: "success"+ });- handlePopUpToggle("removeExternalKms", false);+ handlePopUpClose("removeExternalKms");+ } catch {+ createNotification({+ text: "Failed to delete external KMS",+ type: "error"+ });+ }};return (- <div className="mb-6 rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4">- <div className="flex justify-between">- <p className="text-xl font-medium text-mineshaft-100">Key Management System (KMS)</p>- <OrgPermissionCan I={OrgPermissionActions.Create} an={OrgPermissionSubjects.Kms}>- {(isAllowed) => (- <Button- onClick={() => {- if (subscription && !subscription?.externalKms) {- handlePopUpOpen("upgradePlan", {- isEnterpriseFeature: true- });- return;- }- handlePopUpOpen("addExternalKms");- }}- isDisabled={!isAllowed}- leftIcon={<FontAwesomeIcon icon={faPlus} />}- >- Add- </Button>- )}- </OrgPermissionCan>- </div>- <p className="mb-4 text-gray-400">- Encrypt your {isSubOrganization ? "sub-" : ""}organization's data with external KMS.- </p>- <TableContainer>- <Table>- <THead>- <Tr>- <Td>Provider</Td>- <Td>Alias</Td>- <Td>ID</Td>- </Tr>- </THead>- <TBody>- {isExternalKmsListLoading && <TableSkeleton columns={2} innerKey="kms-loading" />}- {!isExternalKmsListLoading && externalKmsList && externalKmsList?.length === 0 && (- <Tr>- <Td colSpan={5}>- <EmptyState title="No external KMS found" icon={faLock} />- </Td>- </Tr>+ <Card className="mb-6">+ <CardHeader>+ <CardTitle>+ <KeyRound className="size-4 text-accent" />+ Key Management System (KMS)+ </CardTitle>+ <CardDescription>+ Encrypt your {isSubOrganization ? "sub-" : ""}organization's data with an external+ KMS.+ </CardDescription>+ <CardAction>+ <OrgPermissionCan I={OrgPermissionActions.Create} an={OrgPermissionSubjects.Kms}>+ {(isAllowed) => (+ <Button+ variant={isSubOrganization ? "sub-org" : "org"}+ size="sm"+ onClick={() => {+ if (subscription && !subscription.externalKms) {+ handlePopUpOpen("upgradePlan", {+ isEnterpriseFeature: true+ });+ return;+ }+ handlePopUpOpen("addExternalKms");+ }}+ isDisabled={!isAllowed}+ >+ <Plus />+ Add KMS+ </Button>)}- {!isExternalKmsListLoading &&- externalKmsList?.map((kms) => (- <ExternalKmsItem- key={kms.id}- kms={kms}- handlePopUpOpen={handlePopUpOpen}- subscription={subscription}- />- ))}- </TBody>- </Table>- </TableContainer>+ </OrgPermissionCan>+ </CardAction>+ </CardHeader>+ <CardContent>+ {!isExternalKmsListLoading && (externalKmsList?.length ?? 0) === 0 ? (+ <Empty className="border">+ <EmptyHeader>+ <EmptyTitle>No external KMS configured</EmptyTitle>+ <EmptyDescription>+ Add an external KMS to encrypt organization data with a key you control.+ </EmptyDescription>+ </EmptyHeader>+ </Empty>+ ) : (+ <Table>+ <TableHeader>+ <TableRow>+ <TableHead className="w-1/4">Provider</TableHead>+ <TableHead>Alias</TableHead>+ <TableHead>ID</TableHead>+ <TableHead className="w-px text-right" aria-label="Actions" />+ </TableRow>+ </TableHeader>+ <TableBody>+ {isExternalKmsListLoading &&+ Array.from({ length: 2 }).map((_, index) => (+ // eslint-disable-next-line react/no-array-index-key+ <TableRow key={`external-kms-skeleton-${index}`}>+ <TableCell colSpan={4}>+ <Skeleton className="h-5 w-full" />+ </TableCell>+ </TableRow>+ ))}+ {!isExternalKmsListLoading &&+ externalKmsList?.map((kms) => (+ <ExternalKmsItem+ key={kms.id}+ kms={kms}+ handlePopUpOpen={handlePopUpOpen}+ subscription={subscription}+ />+ ))}+ </TableBody>+ </Table>+ )}+ </CardContent><UpgradePlanModalisOpen={popUp.upgradePlan.isOpen}onOpenChange={(isOpen) => handlePopUpToggle("upgradePlan", isOpen)}@@ -148,16 +199,38 @@ export const OrgEncryptionTab = withPermission(}onOpenChange={(state) => handlePopUpToggle("editExternalKmsCredentials", state)}/>- <DeleteActionModal- isOpen={popUp.removeExternalKms.isOpen}- title={`Are you sure you want to remove ${- (popUp?.removeExternalKms?.data as { slug: string })?.slug || ""- } from ${(popUp?.removeExternalKms?.data as { provider: string })?.provider || ""}?`}- onChange={(isOpen) => handlePopUpToggle("removeExternalKms", isOpen)}- deleteKey="confirm"- onDeleteApproved={handleRemoveExternalKms}- />- </div>+ <AlertDialog+ open={popUp.removeExternalKms.isOpen}+ onOpenChange={(isOpen) => handlePopUpToggle("removeExternalKms", isOpen)}+ >+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogMedia>+ <Trash2 />+ </AlertDialogMedia>+ <AlertDialogTitle>+ Delete external KMS "{removeExternalKmsData?.name}"?+ </AlertDialogTitle>+ <AlertDialogDescription>+ This removes the external KMS configuration from your organization. This cannot be+ undone.+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>Cancel</AlertDialogCancel>+ <Button+ variant="danger"+ size="sm"+ onClick={handleRemoveExternalKms}+ isPending={isRemovingExternalKms}+ isDisabled={isRemovingExternalKms}+ >+ Delete+ </Button>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </Card>);},{ action: OrgPermissionActions.Read, subject: OrgPermissionSubjects.Kms }