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
sql database dynamic secret migration
x03220530918db81aaa
diff --git a/backend/src/server/routes/v3/external-migration-router.ts b/backend/src/server/routes/v3/external-migration-router.tsindex 367490c82a..aeba699c9a 100644--- a/backend/src/server/routes/v3/external-migration-router.ts+++ b/backend/src/server/routes/v3/external-migration-router.ts@@ -443,6 +443,54 @@ export const registerExternalMigrationRouter = async (server: FastifyZodProvider}});+ server.route({+ method: "GET",+ url: "/vault/database-roles",+ config: {+ rateLimit: readLimit+ },+ schema: {+ querystring: z.object({+ namespace: z.string(),+ mountPath: z.string()+ }),+ response: {+ 200: z.object({+ roles: z.array(+ z.object({+ name: z.string(),+ mountPath: z.string(),+ db_name: z.string(),+ default_ttl: z.number().nullish(),+ max_ttl: z.number().nullish(),+ creation_statements: z.array(z.string()).nullish(),+ revocation_statements: z.array(z.string()).nullish(),+ renew_statements: z.array(z.string()).nullish(),+ config: z.object({+ connection_details: z.object({+ connection_url: z.string(),+ tls_ca: z.string().nullish(),+ username: z.string().nullish()+ }),+ plugin_name: z.string()+ })+ })+ )+ })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT]),+ handler: async (req) => {+ const roles = await server.services.migration.getVaultDatabaseRoles({+ actor: req.permission,+ namespace: req.query.namespace,+ mountPath: req.query.mountPath+ });++ return { roles };+ }+ });+server.route({method: "GET",url: "/vault/secret-paths",diff --git a/backend/src/services/app-connection/hc-vault/hc-vault-connection-fns.ts b/backend/src/services/app-connection/hc-vault/hc-vault-connection-fns.tsindex 5eb9202fd6..3e35285f7c 100644--- a/backend/src/services/app-connection/hc-vault/hc-vault-connection-fns.ts+++ b/backend/src/services/app-connection/hc-vault/hc-vault-connection-fns.ts@@ -18,6 +18,8 @@ import {THCVaultAuthMountResponse,THCVaultConnection,THCVaultConnectionConfig,+ THCVaultDatabaseConfig,+ THCVaultDatabaseRole,THCVaultKubernetesAuthConfig,THCVaultKubernetesAuthRole,THCVaultKubernetesAuthRoleWithConfig,@@ -937,3 +939,169 @@ export const getHCVaultKubernetesRoles = async (});}};++export const getHCVaultDatabaseRoles = async (+ namespace: string,+ mountPath: string,+ connection: THCVaultConnection,+ gatewayService: Pick<TGatewayServiceFactory, "fnGetGatewayClientTlsByGatewayId">+): Promise<THCVaultDatabaseRole[]> => {+ // Remove trailing slash from mount path+ const cleanMountPath = mountPath.endsWith("/") ? mountPath.slice(0, -1) : mountPath;++ try {+ const instanceUrl = await getHCVaultInstanceUrl(connection);+ const accessToken = await getHCVaultAccessToken(connection, gatewayService);++ // 1. List all database connections in this mount to get their configs+ let connectionNames: string[] = [];+ try {+ const { data: connectionListResponse } = await requestWithHCVaultGateway<{ data: { keys: string[] } }>(+ connection,+ gatewayService,+ {+ url: `${instanceUrl}/v1/${cleanMountPath}/config?list=true`,+ method: "GET",+ headers: {+ "X-Vault-Token": accessToken,+ "X-Vault-Namespace": namespace+ }+ }+ );+ connectionNames = connectionListResponse.data.keys || [];+ } catch (error) {+ // Vault returns 404 when no connections are configured yet+ if (error && typeof error === "object" && "response" in error) {+ const axiosError = error as { response?: { status?: number } };+ if (axiosError.response?.status === 404) {+ return [];+ }+ }+ throw error;+ }++ // 2. Fetch config for each database connection+ const limiter = createConcurrencyLimiter(HC_VAULT_CONCURRENCY_LIMIT);+ const connectionConfigs: Map<string, THCVaultDatabaseConfig> = new Map();++ await Promise.all(+ connectionNames.map((connName) =>+ limiter(async () => {+ try {+ const { data: configResponse } = await requestWithHCVaultGateway<{+ data: THCVaultDatabaseConfig;+ }>(connection, gatewayService, {+ url: `${instanceUrl}/v1/${cleanMountPath}/config/${connName}`,+ method: "GET",+ headers: {+ "X-Vault-Token": accessToken,+ "X-Vault-Namespace": namespace+ }+ });+ connectionConfigs.set(connName, configResponse.data);+ } catch {+ // Skip connections we can't read+ }+ })+ )+ );++ // 3. List all roles in this mount+ let roleNames: string[] = [];+ try {+ const { data: roleListResponse } = await requestWithHCVaultGateway<{ data: { keys: string[] } }>(+ connection,+ gatewayService,+ {+ url: `${instanceUrl}/v1/${cleanMountPath}/roles?list=true`,+ method: "GET",+ headers: {+ "X-Vault-Token": accessToken,+ "X-Vault-Namespace": namespace+ }+ }+ );+ roleNames = roleListResponse.data.keys || [];+ } catch (error) {+ // Vault returns 404 when no roles are configured yet+ if (error && typeof error === "object" && "response" in error) {+ const axiosError = error as { response?: { status?: number } };+ if (axiosError.response?.status === 404) {+ return [];+ }+ }+ throw error;+ }++ if (!roleNames || roleNames.length === 0) {+ return [];+ }++ // 4. Fetch details for each role with concurrency control+ const roleDetailsPromises = roleNames.map((roleName) =>+ limiter(async () => {+ const { data: roleResponse } = await requestWithHCVaultGateway<{+ data: {+ db_name: string;+ default_ttl?: number;+ max_ttl?: number;+ creation_statements?: string[];+ revocation_statements?: string[];+ rollback_statements?: string[];+ renew_statements?: string[];+ rotation_statements?: string[];+ credential_type?: string;+ credential_config?: {+ password_policy?: string;+ };+ };+ }>(connection, gatewayService, {+ url: `${instanceUrl}/v1/${cleanMountPath}/roles/${roleName}`,+ method: "GET",+ headers: {+ "X-Vault-Token": accessToken,+ "X-Vault-Namespace": namespace+ }+ });++ // Get the connection config for this role's db_name+ const dbConfig = connectionConfigs.get(roleResponse.data.db_name) || {+ plugin_name: "",+ connection_details: {+ connection_url: ""+ }+ };++ return {+ name: roleName,+ db_name: roleResponse.data.db_name,+ default_ttl: roleResponse.data.default_ttl,+ max_ttl: roleResponse.data.max_ttl,+ creation_statements: roleResponse.data.creation_statements,+ revocation_statements: roleResponse.data.revocation_statements,+ renew_statements: roleResponse.data.renew_statements,+ config: dbConfig,+ mountPath: cleanMountPath+ } as THCVaultDatabaseRole;+ })+ );++ const roles = await Promise.all(roleDetailsPromises);++ return roles;+ } catch (error: unknown) {+ logger.error(error, "Unable to list HC Vault database secrets engine roles");++ if (error instanceof AxiosError) {+ const errorMessage =+ (error.response?.data as { errors?: string[] })?.errors?.[0] || error.message || "Unknown error";+ throw new BadRequestError({+ message: `Failed to list database secrets engine roles: ${errorMessage}`+ });+ }++ throw new BadRequestError({+ message: "Unable to list database secrets engine roles from HashiCorp Vault"+ });+ }+};diff --git a/backend/src/services/app-connection/hc-vault/hc-vault-connection-types.ts b/backend/src/services/app-connection/hc-vault/hc-vault-connection-types.tsindex 2b1956c848..693d7ef3d0 100644--- a/backend/src/services/app-connection/hc-vault/hc-vault-connection-types.ts+++ b/backend/src/services/app-connection/hc-vault/hc-vault-connection-types.ts@@ -118,3 +118,24 @@ export type THCVaultKubernetesRole = {config: THCVaultKubernetesSecretsConfig;mountPath: string;};++export type THCVaultDatabaseConfig = {+ connection_details: {+ connection_url: string;+ tls_ca?: string;+ username?: string;+ };+ plugin_name: string;+};++export type THCVaultDatabaseRole = {+ name: string;+ db_name: string;+ default_ttl?: number;+ max_ttl?: number;+ creation_statements?: string[];+ revocation_statements?: string[];+ renew_statements?: string[];+ config: THCVaultDatabaseConfig;+ mountPath: string;+};diff --git a/backend/src/services/external-migration/external-migration-service.ts b/backend/src/services/external-migration/external-migration-service.tsindex 42fdc2c26c..39e9321326 100644--- a/backend/src/services/external-migration/external-migration-service.ts+++ b/backend/src/services/external-migration/external-migration-service.ts@@ -18,6 +18,7 @@ import { TAppConnectionServiceFactory } from "../app-connection/app-connection-simport {convertVaultValueToString,getHCVaultAuthMounts,+ getHCVaultDatabaseRoles,getHCVaultKubernetesAuthRoles,getHCVaultKubernetesRoles,getHCVaultSecretsForPath,@@ -813,6 +814,56 @@ export const externalMigrationServiceFactory = ({return getHCVaultKubernetesRoles(namespace, mountPath, connection, gatewayService);};+ const getVaultDatabaseRoles = async ({+ actor,+ namespace,+ mountPath+ }: {+ actor: OrgServiceActor;+ namespace: string;+ mountPath: string;+ }) => {+ const { hasRole } = await permissionService.getOrgPermission({+ scope: OrganizationActionScope.Any,+ actor: actor.type,+ actorId: actor.id,+ orgId: actor.orgId,+ actorAuthMethod: actor.authMethod,+ actorOrgId: actor.orgId+ });++ if (!hasRole(OrgMembershipRole.Admin)) {+ throw new ForbiddenRequestError({ message: "Only admins can get database roles" });+ }++ const vaultConfig = await vaultExternalMigrationConfigDAL.findOne({+ orgId: actor.orgId,+ namespace+ });++ if (!vaultConfig) {+ throw new NotFoundError({ message: "Vault migration config not found for this namespace" });+ }++ if (!vaultConfig.connection) {+ throw new BadRequestError({ message: "Vault migration connection is not configured for this namespace" });+ }++ const credentials = await decryptAppConnectionCredentials({+ orgId: vaultConfig.orgId,+ encryptedCredentials: vaultConfig.connection.encryptedCredentials,+ kmsService,+ projectId: null+ });++ const connection = {+ ...vaultConfig.connection,+ credentials+ } as THCVaultConnection;++ return getHCVaultDatabaseRoles(namespace, mountPath, connection, gatewayService);+ };+return {importEnvKeyData,importVaultData,@@ -828,6 +879,7 @@ export const externalMigrationServiceFactory = ({getVaultSecretPaths,importVaultSecrets,getVaultKubernetesAuthRoles,- getVaultKubernetesRoles+ getVaultKubernetesRoles,+ getVaultDatabaseRoles};};diff --git a/frontend/src/hooks/api/migration/queries.tsx b/frontend/src/hooks/api/migration/queries.tsxindex 198bf887b3..b20b13661d 100644--- a/frontend/src/hooks/api/migration/queries.tsx+++ b/frontend/src/hooks/api/migration/queries.tsx@@ -5,6 +5,7 @@ import { apiRequest } from "@app/config/request";import {ExternalMigrationProviders,TVaultExternalMigrationConfig,+ VaultDatabaseRole,VaultKubernetesAuthRole,VaultKubernetesRole} from "./types";@@ -37,6 +38,11 @@ export const externalMigrationQueryKeys = {"vault-kubernetes-roles",namespace,mountPath+ ],+ vaultDatabaseRoles: (namespace?: string, mountPath?: string) => [+ "vault-database-roles",+ namespace,+ mountPath]};@@ -205,3 +211,30 @@ export const useGetVaultKubernetesRoles = (enabled: enabled && !!namespace && !!mountPath});};++export const useGetVaultDatabaseRoles = (+ enabled = true,+ namespace?: string,+ mountPath?: string+) => {+ return useQuery({+ queryKey: externalMigrationQueryKeys.vaultDatabaseRoles(namespace, mountPath),+ queryFn: async () => {+ if (!namespace || !mountPath) {+ throw new Error("Both namespace and mountPath are required");+ }++ const { data } = await apiRequest.get<{+ roles: VaultDatabaseRole[];+ }>("/api/v3/external-migration/vault/database-roles", {+ params: {+ namespace,+ mountPath+ }+ });++ return data.roles;+ },+ enabled: enabled && !!namespace && !!mountPath+ });+};diff --git a/frontend/src/hooks/api/migration/types.ts b/frontend/src/hooks/api/migration/types.tsindex 4c101548cd..0e2b175c4d 100644--- a/frontend/src/hooks/api/migration/types.ts+++ b/frontend/src/hooks/api/migration/types.ts@@ -70,3 +70,22 @@ export type VaultKubernetesRole = {kubernetes_ca_cert?: string;};};++export type VaultDatabaseRole = {+ name: string;+ mountPath: string;+ db_name: string;+ default_ttl?: number;+ max_ttl?: number;+ creation_statements?: string[];+ revocation_statements?: string[];+ renew_statements?: string[];+ config: {+ connection_details: {+ connection_url: string;+ tls_ca?: string;+ username?: string;+ };+ plugin_name: string;+ };+};diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/SqlDatabaseInputForm.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/SqlDatabaseInputForm.tsxindex aaf2e43d15..02a4efe9db 100644--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/SqlDatabaseInputForm.tsx+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/SqlDatabaseInputForm.tsx@@ -1,3 +1,4 @@+import { useState } from "react";import { Controller, useForm } from "react-hook-form";import { zodResolver } from "@hookform/resolvers/zod";import { useQuery } from "@tanstack/react-query";@@ -5,6 +6,7 @@ import ms from "ms";import { z } from "zod";import { TtlFormLabel } from "@app/components/features";+import { createNotification } from "@app/components/notifications";import { OrgPermissionCan } from "@app/components/permissions";import {Accordion,@@ -28,10 +30,13 @@ import {} from "@app/context/OrgPermissionContext/types";import { gatewaysQueryKeys, useCreateDynamicSecret } from "@app/hooks/api";import { DynamicSecretProviders, SqlProviders } from "@app/hooks/api/dynamicSecret/types";+import { VaultDatabaseRole } from "@app/hooks/api/migration/types";import { ProjectEnv } from "@app/hooks/api/types";import { slugSchema } from "@app/lib/schemas";import { MetadataForm } from "../../DynamicSecretListView/MetadataForm";+import { LoadFromVaultBanner } from "./components/LoadFromVaultBanner";+import { VaultSqlDatabaseImportModal } from "./VaultSqlDatabaseImportModal";const passwordRequirementsSchema = z.object({@@ -170,6 +175,8 @@ export const SqlDatabaseInputForm = ({projectSlug,isSingleEnvironmentMode}: Props) => {+ const [isVaultImportModalOpen, setIsVaultImportModalOpen] = useState(false);+const {control,setValue,@@ -241,10 +248,135 @@ export const SqlDatabaseInputForm = ({setValue("provider.passwordRequirements.length", length);};+ const handleVaultImport = (role: VaultDatabaseRole) => {+ try {+ setValue("name", role.name);++ // Determine the SQL provider from the plugin name+ const pluginName = role.config.plugin_name?.toLowerCase() || "";+ let sqlProvider = SqlProviders.Postgres;+ if (pluginName.includes("mysql")) {+ sqlProvider = SqlProviders.MySql;+ } else if (pluginName.includes("oracle")) {+ sqlProvider = SqlProviders.Oracle;+ } else if (pluginName.includes("mssql")) {+ sqlProvider = SqlProviders.MsSQL;+ }+ setValue("provider.client", sqlProvider);++ // Parse connection URL to extract host, port, database+ const connectionUrl = role.config.connection_details.connection_url || "";+ try {+ const trimmedUrl = connectionUrl.trim();+ if (!trimmedUrl) throw new Error("Empty URL");++ const defaultPort = getDefaultPort(sqlProvider);++ const setConnectionDetails = (host: string, port: number | undefined, database: string) => {+ if (host) setValue("provider.host", host);+ const parsedPort = port ?? defaultPort;+ setValue("provider.port", Number.isNaN(parsedPort) ? defaultPort : parsedPort);+ if (database) setValue("provider.database", database);+ };++ const parseStandardUrl = (url: URL, dbFromParams?: string) => {+ const port = url.port ? parseInt(url.port, 10) : undefined;+ const database = dbFromParams || url.pathname.replace(/^\//, "");+ setConnectionDetails(url.hostname, port, database);+ };++ if (sqlProvider === SqlProviders.MySql) {+ // MySQL format: user:pass@tcp(host:port)/database or standard URL+ const tcpMatch = trimmedUrl.match(/@tcp\(([^:]+):?(\d+)?\)\/([^?#]+)/);+ if (tcpMatch) {+ const port = tcpMatch[2] ? parseInt(tcpMatch[2], 10) : undefined;+ setConnectionDetails(tcpMatch[1], port, tcpMatch[3]);+ } else if (trimmedUrl.includes("://")) {+ parseStandardUrl(new URL(trimmedUrl));+ }+ } else if (sqlProvider === SqlProviders.Oracle) {+ // Oracle format: user/pass@host:port/service_name or user/pass@//host:port/service_name+ const oracleMatch = trimmedUrl.match(/@(?:\/\/)?([^:/]+):?(\d+)?\/(.+)/);+ if (oracleMatch) {+ const port = oracleMatch[2] ? parseInt(oracleMatch[2], 10) : undefined;+ setConnectionDetails(oracleMatch[1], port, oracleMatch[3]);+ }+ } else if (sqlProvider === SqlProviders.MsSQL) {+ // MSSQL format: sqlserver://user:pass@host:port?database=name+ const url = new URL(trimmedUrl);+ const dbParam =+ url.searchParams.get("database") || url.searchParams.get("databaseName") || "";+ parseStandardUrl(url, dbParam);+ } else {+ // PostgreSQL format: postgresql://user:pass@host:port/database+ parseStandardUrl(new URL(trimmedUrl));+ }+ } catch {+ // Connection URL parsing failed, user will need to fill in manually+ }++ if (role.config.connection_details.username) {+ setValue("provider.username", role.config.connection_details.username);+ }++ if (role.config.connection_details.tls_ca) {+ setValue("provider.ca", role.config.connection_details.tls_ca);+ }++ // Convert {{name}} variable to {{username}}+ const convertVaultVariables = (statement: string) =>+ statement.replace(/\{\{name\}\}/g, "{{username}}");++ // Set statements+ if (role.creation_statements && role.creation_statements.length > 0) {+ setValue(+ "provider.creationStatement",+ role.creation_statements.map(convertVaultVariables).join("\n")+ );+ }++ if (role.revocation_statements && role.revocation_statements.length > 0) {+ setValue(+ "provider.revocationStatement",+ role.revocation_statements.map(convertVaultVariables).join("\n")+ );+ }++ if (role.renew_statements && role.renew_statements.length > 0) {+ setValue(+ "provider.renewStatement",+ role.renew_statements.map(convertVaultVariables).join("\n")+ );+ }++ // Set TTLs+ if (role.default_ttl) {+ const defaultTTL = `${role.default_ttl}s`;+ setValue("defaultTTL", defaultTTL);+ }++ if (role.max_ttl) {+ const maxTTL = `${role.max_ttl}s`;+ setValue("maxTTL", maxTTL);+ }++ createNotification({+ type: "info",+ text: "Configuration loaded successfully from HashiCorp Vault"+ });+ } catch {+ createNotification({+ type: "error",+ text: "Failed to load configuration from HashiCorp Vault"+ });+ }+ };+return (<div><form onSubmit={handleSubmit(handleCreateDynamicSecret)} autoComplete="off"><div>+ <LoadFromVaultBanner onClick={() => setIsVaultImportModalOpen(true)} /><div className="flex items-center space-x-2"><div className="grow"><Controller@@ -767,6 +899,11 @@ export const SqlDatabaseInputForm = ({</Button></div></form>+ <VaultSqlDatabaseImportModal+ isOpen={isVaultImportModalOpen}+ onOpenChange={setIsVaultImportModalOpen}+ onImport={handleVaultImport}+ /></div>);};diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/VaultSqlDatabaseImportModal.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/VaultSqlDatabaseImportModal.tsxnew file mode 100644index 0000000000..36807bcbfe--- /dev/null+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateDynamicSecretForm/VaultSqlDatabaseImportModal.tsx@@ -0,0 +1,224 @@+import { useEffect, useState } from "react";+import { faInfoCircle } from "@fortawesome/free-solid-svg-icons";+import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";++import { createNotification } from "@app/components/notifications";+import {+ Button,+ FilterableSelect,+ FormControl,+ Modal,+ ModalClose,+ ModalContent+} from "@app/components/v2";+import {+ useGetVaultDatabaseRoles,+ useGetVaultMounts,+ useGetVaultNamespaces+} from "@app/hooks/api/migration/queries";+import { VaultDatabaseRole } from "@app/hooks/api/migration/types";++type Props = {+ isOpen: boolean;+ onOpenChange: (isOpen: boolean) => void;+ onImport: (role: VaultDatabaseRole) => void;+};++type ContentProps = {+ onClose: () => void;+ onImport: (role: VaultDatabaseRole) => void;+};++const Content = ({ onClose, onImport }: ContentProps) => {+ const [selectedNamespace, setSelectedNamespace] = useState<string | null>(null);+ const [selectedMountPath, setSelectedMountPath] = useState<string | null>(null);+ const [selectedRole, setSelectedRole] = useState<VaultDatabaseRole | null>(null);+ const [shouldFetchRoles, setShouldFetchRoles] = useState(false);+ const [shouldFetchMounts, setShouldFetchMounts] = useState(false);++ const { data: namespaces, isLoading: isLoadingNamespaces } = useGetVaultNamespaces();+ const { data: roles, isLoading: isLoadingRoles } = useGetVaultDatabaseRoles(+ shouldFetchRoles,+ selectedNamespace ?? undefined,+ selectedMountPath ?? undefined+ );+ const { data: mounts, isLoading: isLoadingMounts } = useGetVaultMounts(+ shouldFetchMounts,+ selectedNamespace ?? undefined+ );++ // Filter to only show database mounts+ const databaseMounts = mounts?.filter((mount) => mount.type === "database");++ // Enable fetching mounts when namespace is selected+ useEffect(() => {+ if (selectedNamespace) {+ setShouldFetchMounts(true);+ }+ }, [selectedNamespace]);++ // Enable fetching roles when both namespace and mount path are selected+ useEffect(() => {+ if (selectedNamespace && selectedMountPath) {+ setShouldFetchRoles(true);+ } else {+ setShouldFetchRoles(false);+ }+ }, [selectedNamespace, selectedMountPath]);++ const handleImport = () => {+ if (!selectedRole) {+ createNotification({+ type: "error",+ text: "Please select a Vault database role to load"+ });+ return;+ }++ if (!selectedNamespace) {+ createNotification({ type: "error", text: "Please select a namespace" });+ return;+ }++ if (!mounts || mounts.length === 0) {+ createNotification({+ type: "error",+ text: "No Vault mounts found. Please ensure you have database secrets engine configured."+ });+ return;+ }++ onImport(selectedRole);+ onClose();+ };++ return (+ <>+ <div className="mb-4 rounded-md bg-primary/10 p-3 text-sm text-mineshaft-200">+ <div className="flex items-start gap-2">+ <FontAwesomeIcon icon={faInfoCircle} className="mt-0.5 text-primary" />+ <div className="space-y-1.5 text-xs leading-relaxed">+ <p>+ Select a database secrets engine role from Vault to pre-fill the form with its+ configuration including connection details, creation/revocation statements, TTL+ settings, etc.+ </p>+ </div>+ </div>+ </div>++ <FormControl+ label="Namespace"+ className="mb-4"+ tooltipText="Select the Vault namespace containing the database secrets engine."+ >+ <>+ <FilterableSelect+ value={namespaces?.find((ns) => ns.name === selectedNamespace)}+ onChange={(value) => {+ if (value && !Array.isArray(value)) {+ const namespace = value as { id: string; name: string };+ setSelectedNamespace(namespace.name);+ setSelectedMountPath(null);+ setSelectedRole(null);+ }+ }}+ options={namespaces || []}+ getOptionValue={(option) => option.name}+ getOptionLabel={(option) => (option.name === "/" ? "root" : option.name)}+ isDisabled={isLoadingNamespaces}+ placeholder="Select namespace..."+ className="w-full"+ />+ <p className="mt-1 text-xs text-mineshaft-400">+ Select the Vault namespace to fetch available database secrets engines+ </p>+ </>+ </FormControl>++ <FormControl+ label="Database Secrets Engine"+ className="mb-4"+ tooltipText="Select the database secrets engine mount to fetch available roles."+ >+ <>+ <FilterableSelect+ value={databaseMounts?.find((mount) => mount.path === selectedMountPath)}+ onChange={(value) => {+ if (value && !Array.isArray(value)) {+ const mount = value as { path: string; type: string; version: string | null };+ setSelectedMountPath(mount.path.replace(/\/$/, "")); // Remove trailing slash+ setSelectedRole(null);+ }+ }}+ options={databaseMounts || []}+ getOptionValue={(option) => option.path}+ getOptionLabel={(option) => option.path.replace(/\/$/, "")}+ isDisabled={isLoadingMounts || !databaseMounts?.length}+ placeholder="Select database secrets engine..."+ className="w-full"+ />+ <p className="mt-1 text-xs text-mineshaft-400">+ Choose a database secrets engine mount to list available roles+ </p>+ </>+ </FormControl>++ <FormControl label="Database Role" className="mb-6">+ <>+ <FilterableSelect+ value={selectedRole}+ onChange={(value) => {+ if (value && !Array.isArray(value)) {+ setSelectedRole(value as VaultDatabaseRole);+ } else {+ setSelectedRole(null);+ }+ }}+ options={roles || []}+ getOptionValue={(option) => option.name}+ getOptionLabel={(option) => option.name}+ isDisabled={isLoadingRoles || !roles?.length || !selectedMountPath}+ placeholder={+ !selectedMountPath ? "Select a mount path first..." : "Select a role to load..."+ }+ isClearable+ className="w-full"+ />+ <p className="mt-1 text-xs text-mineshaft-400">+ Choose a database role from the selected mount to load its configuration+ </p>+ </>+ </FormControl>++ <div className="mt-8 flex space-x-4">+ <Button+ onClick={handleImport}+ isDisabled={!selectedRole || isLoadingMounts || isLoadingRoles}+ >+ Load Configuration+ </Button>+ <ModalClose asChild>+ <Button colorSchema="secondary" variant="plain">+ Cancel+ </Button>+ </ModalClose>+ </div>+ </>+ );+};++export const VaultSqlDatabaseImportModal = ({ isOpen, onOpenChange, onImport }: Props) => {+ return (+ <Modal isOpen={isOpen} onOpenChange={onOpenChange}>+ <ModalContent+ bodyClassName="overflow-visible"+ title="Load from HashiCorp Vault"+ subTitle="Select a database secrets engine role to load its configuration."+ className="max-w-2xl"+ >+ <Content onClose={() => onOpenChange(false)} onImport={onImport} />+ </ModalContent>+ </Modal>+ );+};