Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

fix: validate instance forms before submission (#21419)

p0ny8ab6e4dc3eb4
diff --git a/frontend/scripts/ui-guideline-legacy-debt.json b/frontend/scripts/ui-guideline-legacy-debt.json
index b9833dcd9c..20691114c2 100644
--- a/frontend/scripts/ui-guideline-legacy-debt.json
+++ b/frontend/scripts/ui-guideline-legacy-debt.json
@@ -444,12 +444,6 @@
"token": "button",
"count": 1
},
- {
- "path": "src/components/instance/SslCertificateForm.tsx",
- "rule": "no-native-control",
- "token": "textarea",
- "count": 1
- },
{
"path": "src/components/InstanceAssignmentSheet.tsx",
"rule": "no-raw-table",
diff --git a/frontend/src/components/instance/CredentialSourceForm.tsx b/frontend/src/components/instance/CredentialSourceForm.tsx
index d1c4b9048c..9e8ca6095f 100644
--- a/frontend/src/components/instance/CredentialSourceForm.tsx
+++ b/frontend/src/components/instance/CredentialSourceForm.tsx
@@ -7,10 +7,7 @@ import {
useState,
} from "react";
import { Trans, useTranslation } from "react-i18next";
-import { FormField } from "@/components/ui/form";
-import { Input } from "@/components/ui/input";
import { SegmentedControl } from "@/components/ui/segmented-control";
-import { Textarea } from "@/components/ui/textarea";
import { useServerState } from "@/hooks/useAppState";
import { Engine } from "@/types/proto-es/v1/common_pb";
import {
@@ -21,6 +18,11 @@ import {
DataSource_GCPCredentialSchema,
} from "@/types/proto-es/v1/instance_service_pb";
import type { EditDataSource } from "./common";
+import {
+ ValidationField as FormField,
+ ValidationInput as Input,
+ ValidationTextarea as Textarea,
+} from "./ValidationField";
type CredentialSource = "default" | "specific-credential";
@@ -219,7 +221,10 @@ function CredentialSourceForm({
return (
<div className="flex flex-col gap-4 sm:col-span-3 sm:col-start-1">
- <FormField title={t("instance.iam-extension.credential-source")}>
+ <FormField
+ validationField="iamExtension"
+ title={t("instance.iam-extension.credential-source")}
+ >
<SegmentedControl
value={credentialSource}
onValueChange={(value) =>
@@ -386,7 +391,10 @@ function AzureCredentialFields({
return (
<div className="flex flex-col gap-4">
- <FormField title={t("instance.iam-extension.tenant-id")}>
+ <FormField
+ validationField="iamExtension.tenantId"
+ title={t("instance.iam-extension.tenant-id")}
+ >
<Input
aria-label={t("instance.iam-extension.tenant-id")}
className="w-full"
@@ -395,7 +403,10 @@ function AzureCredentialFields({
onChange={(e) => onFieldChange("tenantId", e.target.value)}
/>
</FormField>
- <FormField title={t("instance.iam-extension.client-id")}>
+ <FormField
+ validationField="iamExtension.clientId"
+ title={t("instance.iam-extension.client-id")}
+ >
<Input
aria-label={t("instance.iam-extension.client-id")}
className="w-full"
@@ -404,7 +415,10 @@ function AzureCredentialFields({
onChange={(e) => onFieldChange("clientId", e.target.value)}
/>
</FormField>
- <FormField title={t("instance.iam-extension.client-secret")}>
+ <FormField
+ validationField="iamExtension.clientSecret"
+ title={t("instance.iam-extension.client-secret")}
+ >
<Input
aria-label={t("instance.iam-extension.client-secret")}
type="password"
@@ -444,7 +458,10 @@ function AwsCredentialFields({
return (
<div className="flex flex-col gap-4">
- <FormField title={"Access Key ID"}>
+ <FormField
+ validationField="iamExtension.accessKeyId"
+ title={"Access Key ID"}
+ >
<Input
aria-label={"Access Key ID"}
className="w-full"
@@ -474,7 +491,10 @@ function AwsCredentialFields({
onChange={(e) => onFieldChange("sessionToken", e.target.value)}
/>
</FormField>
- <FormField title={t("instance.role-arn")}>
+ <FormField
+ validationField="iamExtension.roleArn"
+ title={t("instance.role-arn")}
+ >
<Input
aria-label={t("instance.role-arn")}
className="w-full"
@@ -542,7 +562,10 @@ function GcpCredentialField({
};
return (
- <FormField title={t("instance.iam-extension.specific-credential")}>
+ <FormField
+ validationField="iamExtension.content"
+ title={t("instance.iam-extension.specific-credential")}
+ >
<div className="flex flex-col gap-y-1 w-full">
<p className="textinfolabel">
<span>{t("instance.create-gcp-credentials")}</span>
diff --git a/frontend/src/components/instance/DataSourceForm.tsx b/frontend/src/components/instance/DataSourceForm.tsx
index 086822f8ef..88d1f3509a 100644
--- a/frontend/src/components/instance/DataSourceForm.tsx
+++ b/frontend/src/components/instance/DataSourceForm.tsx
@@ -9,10 +9,8 @@ import {
FormControlGroup,
FormControlRow,
FormError,
- FormField,
ResponsiveFormLayout,
} from "@/components/ui/form";
-import { Input } from "@/components/ui/input";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { SegmentedControl } from "@/components/ui/segmented-control";
import {
@@ -65,6 +63,11 @@ import {
LOCAL_TLS_POSTURE_TLS,
type LocalTlsPosture,
} from "./tls";
+import {
+ ValidationField as FormField,
+ ValidationInput as Input,
+ ValidationProvider,
+} from "./ValidationField";
interface DataSourceFormProps {
dataSource: EditDataSource;
@@ -120,6 +123,7 @@ export function RedisSentinelFields({
return (
<>
<FormField
+ validationField="masterName"
title={
<>
{t("instance.master-name")} <span className="text-error">*</span>
@@ -853,7 +857,10 @@ export function DataSourceForm({
);
return (
- <div className="grid grid-cols-1 gap-y-4 gap-x-4 border-none sm:grid-cols-3">
+ <ValidationProvider
+ className="grid grid-cols-1 gap-y-4 gap-x-4 border-none sm:grid-cols-3"
+ errors={ctx.getDataSourceErrors(dataSource)}
+ >
{authOnly
? authenticationTypeControl
: !optionsOnly && (
@@ -908,6 +915,10 @@ export function DataSourceForm({
className="flex flex-col gap-4 rounded-xs border border-control-border px-3 py-2"
>
<FormField
+ validationField={[
+ "saslConfig.primary",
+ "saslConfig.realm",
+ ]}
title={
<>
{t("instance.kerberos-principal")}{" "}
@@ -991,6 +1002,7 @@ export function DataSourceForm({
</FormControlRow>
</FormField>
<FormField
+ validationField="saslConfig.kdcHost"
title={
<>
{t("instance.kerberos-kdc")}{" "}
@@ -1082,6 +1094,11 @@ export function DataSourceForm({
</FormControlRow>
</FormField>
<FormField
+ validationField={
+ keytabResupplyRequired
+ ? undefined
+ : "saslConfig.keytab"
+ }
title={
<>
{t("instance.keytab-file")}
@@ -1304,6 +1321,7 @@ export function DataSourceForm({
DataSourceExternalSecret_SecretType.VAULT_KV_V2 && (
<div className="flex flex-col gap-y-4">
<FormField
+ validationField="externalSecret.url"
title={
<>
{t(
@@ -1423,6 +1441,7 @@ export function DataSourceForm({
}
return (
<FormField
+ validationField="externalSecret.token"
title={
<>
{tokenLabel}{" "}
@@ -1515,6 +1534,7 @@ export function DataSourceForm({
?.case === "appRole" && (
<div className="flex flex-col gap-y-4">
<FormField
+ validationField="externalSecret.roleId"
title={
<>
{t(
@@ -1536,7 +1556,9 @@ export function DataSourceForm({
disabled={!allowEdit}
placeholder={`${t("instance.external-secret-vault.vault-auth-type.approle.role-id")} - ${t("common.write-only")}`}
onChange={(e) => {
- const ds = { ...dataSource };
+ const ds = {
+ ...dataSource,
+ };
if (
ds.externalSecret
?.authOption?.case ===
@@ -1561,6 +1583,7 @@ export function DataSourceForm({
/>
</FormField>
<FormField
+ validationField="externalSecret.secretId"
title={
<>
{t(
@@ -1640,7 +1663,9 @@ export function DataSourceForm({
className="mt-2 w-full"
disabled={!allowEdit}
onChange={(e) => {
- const ds = { ...dataSource };
+ const ds = {
+ ...dataSource,
+ };
if (
ds.externalSecret
?.authOption?.case ===
@@ -1731,6 +1756,7 @@ export function DataSourceForm({
</FormField>
{/* Engine name */}
<FormField
+ validationField="externalSecret.engineName"
title={
<>
{t(
@@ -1777,6 +1803,7 @@ export function DataSourceForm({
{passwordType ===
DataSourceExternalSecret_SecretType.AZURE_KEY_VAULT && (
<FormField
+ validationField="externalSecret.url"
title={
<>
{t(
@@ -1819,6 +1846,7 @@ export function DataSourceForm({
{/* Secret name (common) */}
<FormField
+ validationField="externalSecret.secretName"
title={
<>
{secretNameLabel}{" "}
@@ -1853,6 +1881,7 @@ export function DataSourceForm({
passwordType !==
DataSourceExternalSecret_SecretType.AZURE_KEY_VAULT && (
<FormField
+ validationField="externalSecret.passwordKeyName"
title={
<>
{secretKeyLabel}{" "}
@@ -2012,6 +2041,7 @@ export function DataSourceForm({
{basicInfo.engine === Engine.DATABRICKS && (
<>
<FormField
+ validationField="warehouseId"
title={
<>
Warehouse ID <span className="text-error">*</span>
@@ -2025,6 +2055,7 @@ export function DataSourceForm({
/>
</FormField>
<FormField
+ validationField="updatedToken"
title={
<>
Token <span className="text-error">*</span>
@@ -2063,7 +2094,9 @@ export function DataSourceForm({
disabled={!allowEdit}
value={dataSource.authenticationDatabase ?? ""}
onChange={(e) =>
- update({ authenticationDatabase: e.target.value.trim() })
+ update({
+ authenticationDatabase: e.target.value.trim(),
+ })
}
/>
</FormField>
@@ -2075,6 +2108,7 @@ export function DataSourceForm({
<>
{hasReadonlyReplicaHost && (
<FormField
+ validationField="host"
className="sm:col-span-3 sm:col-start-1"
title={<>{t("data-source.read-replica-host")}</>}
>
@@ -2133,7 +2167,7 @@ export function DataSourceForm({
{!authOnly && !hideOptions && (
<>
{/* SSL */}
- {showSSL && isPasswordAuth && (
+ {showSSL && (isPasswordAuth || dataSource.useSsl) && (
<FormField
className="sm:col-span-3 sm:col-start-1"
title={
@@ -2327,37 +2361,48 @@ export function DataSourceForm({
)}
{extraConnectionParamsList.map((param, index) => (
- <FormControlRow key={param.key}>
- <Input
- className="min-w-0 flex-1"
- value={param.key}
- disabled={!allowEdit}
- aria-label={t("instance.parameter-name-placeholder")}
- placeholder={t("instance.parameter-name-placeholder")}
- onChange={(e) =>
- updateExtraConnectionParamKey(index, e.target.value)
- }
- />
- <Input
- className="min-w-0 flex-1"
- value={param.value}
- disabled={!allowEdit}
- aria-label={t("instance.parameter-value-placeholder")}
- placeholder={t("instance.parameter-value-placeholder")}
- onChange={(e) =>
- updateExtraConnectionParamValue(index, e.target.value)
- }
- />
- {allowEdit && (
- <Button
- variant="destructive"
- className="shrink-0"
- onClick={() => removeExtraConnectionParam(index)}
- >
- {t("common.remove")}
- </Button>
- )}
- </FormControlRow>
+ <FormField
+ key={param.key}
+ validationField={`extraConnectionParameters.${param.key}`}
+ showErrors
+ >
+ <FormControlRow>
+ <Input
+ className="min-w-0 flex-1"
+ value={param.key}
+ disabled={!allowEdit}
+ aria-label={t("instance.parameter-name-placeholder")}
+ placeholder={t("instance.parameter-name-placeholder")}
+ onChange={(e) =>
+ updateExtraConnectionParamKey(index, e.target.value)
+ }
+ />
+ <Input
+ className="min-w-0 flex-1"
+ value={param.value}
+ disabled={!allowEdit}
+ aria-label={t("instance.parameter-value-placeholder")}
+ placeholder={t(
+ "instance.parameter-value-placeholder"
+ )}
+ onChange={(e) =>
+ updateExtraConnectionParamValue(
+ index,
+ e.target.value
+ )
+ }
+ />
+ {allowEdit && (
+ <Button
+ variant="destructive"
+ className="shrink-0"
+ onClick={() => removeExtraConnectionParam(index)}
+ >
+ {t("common.remove")}
+ </Button>
+ )}
+ </FormControlRow>
+ </FormField>
))}
</FormControlGroup>
@@ -2381,7 +2426,7 @@ export function DataSourceForm({
))}
</>
)}
- </div>
+ </ValidationProvider>
);
}
@@ -2412,7 +2457,10 @@ function OracleSIDServiceNameInput({
};
return (
- <div className="sm:col-span-3 sm:col-start-1">
+ <FormField
+ validationField="serviceName"
+ className="sm:col-span-3 sm:col-start-1"
+ >
<RadioGroup
className="textlabel mb-2 gap-x-4"
value={mode}
@@ -2439,7 +2487,7 @@ function OracleSIDServiceNameInput({
}
}}
/>
- </div>
+ </FormField>
);
}
@@ -2457,6 +2505,7 @@ function AwsRegionField({
const { t } = useTranslation();
return (
<FormField
+ validationField="region"
className="sm:col-span-3 sm:col-start-1"
title={
<>
diff --git a/frontend/src/components/instance/InstanceFormBody.tsx b/frontend/src/components/instance/InstanceFormBody.tsx
index 24649c00b2..34ab426364 100644
--- a/frontend/src/components/instance/InstanceFormBody.tsx
+++ b/frontend/src/components/instance/InstanceFormBody.tsx
@@ -30,12 +30,10 @@ import { Checkbox } from "@/components/ui/checkbox";
import {
FormControlGroup,
FormControlRow,
- FormField,
FormLabel,
FormSection,
ResponsiveFormLayout,
} from "@/components/ui/form";
-import { Input } from "@/components/ui/input";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { SegmentedControl } from "@/components/ui/segmented-control";
import { Switch } from "@/components/ui/switch";
@@ -84,6 +82,11 @@ import { DataSourceForm, RedisSentinelFields } from "./DataSourceForm";
import { DataSourceSection } from "./DataSourceSection";
import { useInstanceFormContext } from "./InstanceFormContext";
import { hasInfoContent, type InfoSection } from "./info-content";
+import {
+ ValidationField as FormField,
+ ValidationInput as Input,
+ ValidationProvider,
+} from "./ValidationField";
// --- Inline sub-components ---
@@ -182,6 +185,7 @@ function SpannerHostInput({
return (
<div className="grid grid-cols-2 gap-x-2 gap-y-1">
<FormField
+ validationField="projectId"
title={
<>
{t("instance.project-id")}
@@ -190,6 +194,7 @@ function SpannerHostInput({
}
>
<Input
+ aria-label={t("instance.project-id")}
value={projectId}
required
placeholder="projectId"
@@ -202,6 +207,7 @@ function SpannerHostInput({
/>
</FormField>
<FormField
+ validationField="instanceId"
title={
<>
{t("instance.instance-id")}
@@ -210,6 +216,7 @@ function SpannerHostInput({
}
>
<Input
+ aria-label={t("instance.instance-id")}
value={instanceId}
required
placeholder="instanceId"
@@ -270,6 +277,7 @@ function BigQueryHostInput({
return (
<div className="grid grid-cols-2 gap-x-2 gap-y-1">
<FormField
+ validationField="projectId"
title={
<>
{t("instance.project-id")}
@@ -278,6 +286,7 @@ function BigQueryHostInput({
}
>
<Input
+ aria-label={t("instance.project-id")}
value={projectId}
required
placeholder="projectId"
@@ -1219,7 +1228,13 @@ export function InstanceFormBody({ onOpenInfoPanel }: InstanceFormBodyProps) {
);
return (
- <div className="flex flex-col pb-2">
+ <ValidationProvider
+ className="flex flex-col pb-2"
+ errors={{
+ ...ctx.getDataSourceErrors(adminDataSource),
+ ...(!basicInfo.title.trim() ? { title: "required" } : {}),
+ }}
+ >
<div className="w-full max-w-5xl flex flex-col">
{/* Basic Info Card */}
<FormSection layout="stacked" title={t("instance.section.basic-info")}>
@@ -1257,7 +1272,7 @@ export function InstanceFormBody({ onOpenInfoPanel }: InstanceFormBodyProps) {
)}
{/* Instance Name */}
- <FormField>
+ <FormField validationField="title">
<FormLabel htmlFor="name" className="flex flex-row items-center">
{t("instance.instance-name")}
<span className="ml-0.5 text-error">*</span>
@@ -1477,6 +1492,7 @@ export function InstanceFormBody({ onOpenInfoPanel }: InstanceFormBodyProps) {
/>
) : (
<FormField
+ validationField="host"
title={
<span className="flex items-center gap-1">
<FormLabel htmlFor="host">
@@ -1758,6 +1774,6 @@ export function InstanceFormBody({ onOpenInfoPanel }: InstanceFormBodyProps) {
)}
</FormSection>
</div>
- </div>
+ </ValidationProvider>
);
}
diff --git a/frontend/src/components/instance/InstanceFormButtons.test.tsx b/frontend/src/components/instance/InstanceFormButtons.test.tsx
index 3c461249ee..1b269055f5 100644
--- a/frontend/src/components/instance/InstanceFormButtons.test.tsx
+++ b/frontend/src/components/instance/InstanceFormButtons.test.tsx
@@ -4,6 +4,8 @@ import { createRoot } from "react-dom/client";
import { beforeEach, describe, expect, test, vi } from "vitest";
import { Engine } from "@/types/proto-es/v1/common_pb";
import {
+ DataSource_AuthenticationType,
+ DataSourceExternalSecret_SecretType,
DataSourceSchema,
DataSourceType,
InstanceSchema,
@@ -26,6 +28,7 @@ const mocks = vi.hoisted(() => ({
fetchDatabases: vi.fn(),
batchUpdateDatabases: vi.fn(),
captureMetric: vi.fn(),
+ hasFeature: vi.fn(() => true),
onCreated: vi.fn(),
context: undefined as Record<string, unknown> | undefined,
}));
@@ -63,7 +66,7 @@ vi.mock("@/app/analytics/provider", () => ({
vi.mock("@/stores/app", () => {
const appState = {
- hasFeature: () => true,
+ hasFeature: mocks.hasFeature,
instanceLicenseCount: () => 100,
activatedInstanceCount: () => 1,
isSaaSMode: () => false,
@@ -167,6 +170,7 @@ const flushPromises = async () => {
beforeEach(() => {
vi.clearAllMocks();
+ mocks.hasFeature.mockReturnValue(true);
mocks.routerCurrentName = "workspace.instance.create";
mocks.routerCurrentQuery = {};
@@ -202,6 +206,7 @@ beforeEach(() => {
}),
setBasicInfo: vi.fn(),
labelKVList: [],
+ labelErrors: [],
adminDataSource,
editingDataSource: adminDataSource,
readonlyDataSourceList: [],
@@ -235,6 +240,96 @@ beforeEach(() => {
});
describe("InstanceFormButtons", () => {
+ test("does not require the external-secret feature for an inactive IAM draft", async () => {
+ mocks.hasFeature.mockReturnValue(false);
+ const dataSource = create(DataSourceSchema, {
+ id: "admin", type: DataSourceType.ADMIN,
+ authenticationType: DataSource_AuthenticationType.AZURE_IAM,
+ host: "db.example.com", password: "{{inactive-password}}",
+ externalSecret: { secretType: DataSourceExternalSecret_SecretType.AZURE_KEY_VAULT },
+ });
+ const saved = create(InstanceSchema, {
+ name: "instances/prod", title: "Before", engine: Engine.POSTGRES,
+ dataSources: [dataSource],
+ });
+ mocks.getInstanceByName.mockReturnValue(saved);
+ mocks.updateInstance.mockResolvedValue(saved);
+ mocks.context = {
+ ...mocks.context, instance: saved, isCreating: false,
+ basicInfo: { ...saved, title: "After" },
+ adminDataSource: dataSource, editingDataSource: dataSource,
+ };
+ const container = document.createElement("div");
+ const root = createRoot(container);
+ try {
+ await act(async () => { root.render(<InstanceFormButtons />); });
+ const update = Array.from(container.querySelectorAll("button")).find((button) => button.textContent === "common.update")!;
+ await act(async () => { update.click(); });
+ expect(mocks.context.setMissingFeature).not.toHaveBeenCalled();
+ expect(mocks.updateInstance).toHaveBeenCalledOnce();
+ } finally {
+ await act(async () => { root.unmount(); });
+ }
+ });
+
+ test.each([
+ { title: "Production", labelErrors: ["invalid label"] },
+ { title: " ", labelErrors: [] },
+ ])("blocks Update but allows connection testing for invalid metadata: %j", async ({ title, labelErrors }) => {
+ mocks.context = {
+ ...mocks.context,
+ isCreating: false,
+ instance: create(InstanceSchema, { name: "instances/prod" }),
+ basicInfo: create(InstanceSchema, { title, engine: Engine.POSTGRES }),
+ labelErrors,
+ };
+ const container = document.createElement("div");
+ const root = createRoot(container);
+ try {
+ await act(async () => { root.render(<InstanceFormButtons />); });
+ const buttons = Array.from(container.querySelectorAll("button"));
+ const update = buttons.find((button) => button.textContent === "common.update")!;
+ const testConnection = buttons.find((button) => button.textContent === "instance.test-connection")!;
+ expect(update.disabled).toBe(true);
+ expect(testConnection.disabled).toBe(false);
+ await act(async () => {
+ update.click();
+ testConnection.click();
+ });
+ expect(mocks.updateInstance).not.toHaveBeenCalled();
+ expect(mocks.context.testConnection).toHaveBeenCalledExactlyOnceWith(
+ mocks.context.editingDataSource, false
+ );
+ } finally {
+ await act(async () => { root.unmount(); });
+ }
+ });
+
+ test.each(["isRequesting", "isTestingConnection"])(
+ "blocks connection testing during %s on edit",
+ async (pendingState) => {
+ mocks.context = {
+ ...mocks.context,
+ isCreating: false,
+ instance: create(InstanceSchema, { name: "instances/prod" }),
+ state: { isRequesting: false, isTestingConnection: false, [pendingState]: true },
+ };
+ const container = document.createElement("div");
+ const root = createRoot(container);
+ try {
+ await act(async () => { root.render(<InstanceFormButtons />); });
+ const testConnection = Array.from(container.querySelectorAll("button")).find(
+ (button) => ["instance.test-connection", "instance.testing-connection"].includes(button.textContent ?? "")
+ )!;
+ expect(testConnection.disabled).toBe(true);
+ await act(async () => { testConnection.click(); });
+ expect(mocks.context.testConnection).not.toHaveBeenCalled();
+ } finally {
+ await act(async () => { root.unmount(); });
+ }
+ }
+ );
+
test("invalidates provider drafts only after a successful server-backed save", async () => {
const saved = create(InstanceSchema, {
name: "instances/prod",
diff --git a/frontend/src/components/instance/InstanceFormButtons.tsx b/frontend/src/components/instance/InstanceFormButtons.tsx
index f8a137100d..d8c89c3d24 100644
--- a/frontend/src/components/instance/InstanceFormButtons.tsx
+++ b/frontend/src/components/instance/InstanceFormButtons.tsx
@@ -1,6 +1,6 @@
import { create } from "@bufbuild/protobuf";
import { cloneDeep, isEqual } from "lodash-es";
-import { useMemo, useState } from "react";
+import { useState } from "react";
import { useTranslation } from "react-i18next";
import { createBehaviorMetric } from "@/app/analytics/behavior";
import { behaviorAnalytics } from "@/app/analytics/provider";
@@ -14,7 +14,6 @@ import {
} from "@/lib/productIntro";
import { pushNotification } from "@/stores";
import { useAppStore } from "@/stores/app";
-import { Engine } from "@/types/proto-es/v1/common_pb";
import type {
DataSource,
Instance,
@@ -24,12 +23,7 @@ import {
InstanceSchema,
} from "@/types/proto-es/v1/instance_service_pb";
import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
-import {
- convertKVListToLabels,
- extractInstanceResourceName,
- isValidBigQueryDataSource,
- isValidSpannerDataSource,
-} from "@/utils";
+import { convertKVListToLabels, extractInstanceResourceName } from "@/utils";
import {
AlertDialog,
AlertDialogContent,
@@ -39,6 +33,7 @@ import {
} from "../ui/alert-dialog";
import { Button } from "../ui/button";
import { StickyActionFooter } from "../ui/sticky-action-footer";
+import { isIAMAuthentication } from "./authentication";
import {
type ConnectionFailureCategory,
ConnectionRecovery,
@@ -120,7 +115,9 @@ export function InstanceFormButtons({
const checkExternalSecretFeature = (dataSources: DataSource[]) => {
if (hasExternalSecretFeature) return true;
return dataSources.every(
- (ds) => !ds.externalSecret && !/^{{.+}}$/.test(ds.password)
+ (ds) =>
+ isIAMAuthentication(ds.authenticationType) ||
+ (!ds.externalSecret && !/^{{.+}}$/.test(ds.password))
);
};
@@ -141,46 +138,14 @@ export function InstanceFormButtons({
return readonlyDataSourceList.every(checkOne);
};
- const allowUpdate = useMemo((): boolean => {
- if (!valueChanged) return false;
- if (basicInfo.engine === Engine.SPANNER) {
- if (!isValidSpannerDataSource(adminDataSource)) return false;
- if (readonlyDataSourceList.length > 0) {
- if (readonlyDataSourceList.some((ds) => !isValidSpannerDataSource(ds)))
- return false;
- }
- return !!basicInfo.title.trim();
- }
- if (basicInfo.engine === Engine.BIGQUERY) {
- if (!isValidBigQueryDataSource(adminDataSource)) return false;
- if (readonlyDataSourceList.length > 0) {
- if (readonlyDataSourceList.some((ds) => !isValidBigQueryDataSource(ds)))
- return false;
- }
- return !!basicInfo.title.trim();
- }
- return checkDataSource([adminDataSource, ...readonlyDataSourceList]);
- }, [
- valueChanged,
- basicInfo,
- adminDataSource,
- readonlyDataSourceList,
- checkDataSource,
- ]);
+ const allowUpdate =
+ valueChanged &&
+ !!basicInfo.title.trim() &&
+ context.labelErrors.length === 0 &&
+ checkDataSource([adminDataSource, ...readonlyDataSourceList]);
- const allowTestConnection = useMemo(() => {
- if (!allowEdit || !editingDataSource) return false;
- if (basicInfo.engine === Engine.SPANNER) {
- return isValidSpannerDataSource(editingDataSource);
- }
- if (basicInfo.engine === Engine.BIGQUERY) {
- return isValidBigQueryDataSource(editingDataSource);
- }
- if (basicInfo.engine !== Engine.DYNAMODB && editingDataSource.host === "") {
- return false;
- }
- return checkDataSource([editingDataSource]);
- }, [allowEdit, basicInfo.engine, checkDataSource, editingDataSource]);
+ const allowTestConnection =
+ allowEdit && !!editingDataSource && checkDataSource([editingDataSource]);
const hasConfiguredConnectionOptions = (ds: EditDataSource): boolean => {
const hasExtraParameters =
@@ -253,7 +218,7 @@ export function InstanceFormButtons({
};
const doCreate = async () => {
- if (!isCreating) return;
+ if (!isCreating || !allowCreate) return;
const payload = buildCreateInstance();
if (!checkExternalSecretFeature(payload.dataSources)) {
@@ -303,6 +268,7 @@ export function InstanceFormButtons({
};
const tryCreate = async () => {
+ if (!allowCreate) return;
behaviorAnalytics.captureMetric(
createBehaviorMetric("instance create clicked", {
routeId: router.currentRoute.value.name?.toString(),
@@ -345,7 +311,7 @@ export function InstanceFormButtons({
const doUpdate = async () => {
const inst = instance;
- if (!inst) return;
+ if (!inst || !allowUpdate) return;
if (!checkRODataSourceFeature(inst)) {
setMissingFeature(PlanFeature.FEATURE_INSTANCE_READ_ONLY_CONNECTION);
@@ -675,7 +641,11 @@ export function InstanceFormButtons({
<>
<Button
appearance="secondary"
- disabled={!allowUpdate || state.isRequesting || !allowEdit}
+ disabled={
+ !allowTestConnection ||
+ state.isRequesting ||
+ state.isTestingConnection
+ }
onClick={testConnectionForCurrentEditingDS}
>
{state.isTestingConnection
diff --git a/frontend/src/components/instance/InstanceFormContext.test.tsx b/frontend/src/components/instance/InstanceFormContext.test.tsx
index f1ffc03aa2..49f547369a 100644
--- a/frontend/src/components/instance/InstanceFormContext.test.tsx
+++ b/frontend/src/components/instance/InstanceFormContext.test.tsx
@@ -1,4 +1,5 @@
import { create } from "@bufbuild/protobuf";
+import { fireEvent } from "@testing-library/react";
import { Code, ConnectError } from "@connectrpc/connect";
import type { ReactElement } from "react";
import { act } from "react";
@@ -9,6 +10,7 @@ import type { DataSource } from "@/types/proto-es/v1/instance_service_pb";
import {
DataSource_AuthenticationType,
DataSource_AWSCredentialSchema,
+ DataSourceExternalSecret_SecretType,
DataSourceSchema,
DataSourceType,
InstanceSchema,
@@ -25,10 +27,13 @@ import {
} from "./InstanceFormContext";
const mocks = vi.hoisted(() => ({
+ translate: (key: string) => key,
hasInstancePermission: vi.fn(() => true),
pushNotification: vi.fn(),
createInstance: vi.fn(),
isSaaSMode: false,
+ hasSSL: false,
+ hasExtraParameters: false,
listInstanceDatabases: vi.fn(async () => ({
databases: ["app", "analytics"],
})),
@@ -59,13 +64,13 @@ vi.mock("./permission", () => ({
vi.mock("react-i18next", () => ({
useTranslation: () => ({
- t: (key: string) => key,
+ t: mocks.translate,
}),
}));
vi.mock("@/lib/i18n", () => ({
default: {
- t: (key: string) => key,
+ t: mocks.translate,
},
}));
@@ -121,15 +126,16 @@ vi.mock("@/stores/app", () => {
});
vi.mock("@/utils", () => ({
+ MAX_LABEL_VALUE_LENGTH: 63,
calcUpdateMask: () => [],
convertKVListToLabels: (list: { key: string; value: string }[]) =>
Object.fromEntries(list.map(({ key, value }) => [key, value])),
convertLabelsToKVList: (labels: Record<string, string>) =>
Object.entries(labels).map(([key, value]) => ({ key, value })),
hasWorkspacePermissionV2: () => true,
- instanceV1HasExtraParameters: () => false,
+ instanceV1HasExtraParameters: () => mocks.hasExtraParameters,
instanceV1HasSSH: () => false,
- instanceV1HasSSL: () => false,
+ instanceV1HasSSL: () => mocks.hasSSL,
isValidSpannerDataSource: (ds: { projectId: string; instanceId: string }) =>
ds.projectId !== "" && ds.instanceId !== "",
isValidBigQueryDataSource: (ds: { projectId: string }) =>
@@ -249,6 +255,8 @@ describe("InstanceFormProvider", () => {
vi.clearAllMocks();
mocks.hasInstancePermission.mockReturnValue(true);
mocks.isSaaSMode = false;
+ mocks.hasSSL = false;
+ mocks.hasExtraParameters = false;
mocks.createInstance.mockResolvedValue(create(InstanceSchema, {}));
mockEnvironmentList = [];
vi.useRealTimers();
@@ -783,6 +791,232 @@ describe("InstanceFormProvider", () => {
harness.unmount();
});
+ test.each([
+ DataSource_AuthenticationType.AWS_RDS_IAM,
+ DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM,
+ DataSource_AuthenticationType.AZURE_IAM,
+ ])("omits inactive password sources from IAM payloads for method %s", async (authenticationType) => {
+ let context!: ReturnType<typeof useInstanceFormContext>;
+ const Capture = () => { context = useInstanceFormContext(); return null; };
+ const harness = renderIntoContainer();
+ try {
+ await harness.render(<InstanceFormProvider><Capture /></InstanceFormProvider>);
+ const draft = wrapEditDataSource(create(DataSourceSchema, {
+ authenticationType,
+ host: "project:region:instance",
+ region: "us-east-1",
+ password: "{{inactive-password}}",
+ externalSecret: { secretType: DataSourceExternalSecret_SecretType.AZURE_KEY_VAULT },
+ }));
+ expect(context.checkDataSource([draft])).toBe(true);
+ const payload = context.extractDataSourceFromEdit(Engine.MYSQL, draft);
+ expect(payload.externalSecret).toBeUndefined();
+ expect(payload.password).toBe("");
+ expect(draft.externalSecret).toBeDefined();
+ expect(draft.password).toBe("{{inactive-password}}");
+ } finally {
+ harness.unmount();
+ }
+ });
+
+ test.each([
+ DataSource_AuthenticationType.AWS_RDS_IAM,
+ DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM,
+ DataSource_AuthenticationType.AZURE_IAM,
+ ])(
+ "keeps TLS drafts editable after switching to IAM method %s",
+ async (authenticationType) => {
+ mocks.hasSSL = true;
+ const { DataSourceForm } = await vi.importActual<
+ typeof import("./DataSourceForm")
+ >("./DataSourceForm");
+ let context!: ReturnType<typeof useInstanceFormContext>;
+ const Editor = () => {
+ context = useInstanceFormContext();
+ return (
+ <DataSourceForm
+ dataSource={context.adminDataSource}
+ onDataSourceChange={(ds) =>
+ context.setDataSourceEditState((state) => ({
+ ...state,
+ dataSources: [ds],
+ }))
+ }
+ optionsOnly
+ />
+ );
+ };
+ const harness = renderIntoContainer();
+ try {
+ await harness.render(
+ <InstanceFormProvider><Editor /></InstanceFormProvider>
+ );
+ await act(async () => {
+ context.setDataSourceEditState((state) => ({
+ ...state,
+ dataSources: [{
+ ...context.adminDataSource,
+ authenticationType: DataSource_AuthenticationType.PASSWORD,
+ useSsl: true,
+ verifyTlsCertificate: true,
+ sslCaPath: "relative.pem",
+ updateSsl: undefined,
+ }],
+ }));
+ });
+ const caInput = () => harness.container.querySelector<HTMLInputElement>(
+ 'input[value="relative.pem"]'
+ );
+ expect(caInput()).not.toBeNull();
+ await act(async () => {
+ context.setDataSourceEditState((state) => ({
+ ...state,
+ dataSources: [{ ...context.adminDataSource, authenticationType }],
+ }));
+ });
+ expect(caInput()).not.toBeNull();
+ expect(caInput()?.disabled).toBe(false);
+ expect(context.extractDataSourceFromEdit(
+ Engine.MYSQL, context.adminDataSource
+ ).useSsl).toBe(true);
+ } finally {
+ harness.unmount();
+ }
+ }
+ );
+
+ test.each(["add", "rename"])(
+ "shows forbidden parameter feedback immediately after %s",
+ async (operation) => {
+ mocks.hasExtraParameters = true;
+ const { DataSourceForm } = await vi.importActual<
+ typeof import("./DataSourceForm")
+ >("./DataSourceForm");
+ let context!: ReturnType<typeof useInstanceFormContext>;
+ const Editor = () => {
+ context = useInstanceFormContext();
+ return (
+ <DataSourceForm
+ dataSource={context.adminDataSource}
+ onDataSourceChange={(ds) => context.setDataSourceEditState((state) => ({
+ ...state, dataSources: [ds],
+ }))}
+ optionsOnly
+ />
+ );
+ };
+ const harness = renderIntoContainer();
+ const button = (text: string) => Array.from(
+ harness.container.querySelectorAll("button")
+ ).find((element) => element.textContent === text)!;
+ const input = (value: string) => Array.from(
+ harness.container.querySelectorAll<HTMLInputElement>(
+ 'input[aria-label="instance.parameter-name-placeholder"]'
+ )
+ ).find((element) => element.value === value)!;
+ try {
+ await harness.render(
+ <InstanceFormProvider><Editor /></InstanceFormProvider>
+ );
+ await act(async () => {
+ context.setDataSourceEditState((state) => ({
+ ...state,
+ dataSources: [{ ...context.adminDataSource, host: "db.example.com" }],
+ }));
+ });
+ expect(context.checkDataSource([context.adminDataSource])).toBe(true);
+ await act(async () => { button("instance.add-parameter").click(); });
+ await act(async () => {
+ fireEvent.change(input(""), {
+ target: { value: operation === "add" ? "allowAllFiles" : "timeout" },
+ });
+ });
+ await act(async () => { button("common.add").click(); });
+ if (operation === "rename") {
+ await act(async () => {
+ fireEvent.change(input("timeout"), { target: { value: "allowAllFiles" } });
+ });
+ }
+ expect(context.checkDataSource([context.adminDataSource])).toBe(false);
+ expect(harness.container.textContent).toContain("instance.validation.forbidden-parameter");
+ expect(input("allowAllFiles").getAttribute("aria-invalid")).toBe("true");
+ const errorId = input("allowAllFiles").getAttribute("aria-describedby");
+ expect(errorId).toBeTruthy();
+ expect(harness.container.querySelector(`[id="${errorId}"]`)?.textContent).toBe(
+ "instance.validation.forbidden-parameter"
+ );
+ await act(async () => {
+ fireEvent.change(input("allowAllFiles"), { target: { value: "timeout" } });
+ });
+ expect(context.checkDataSource([context.adminDataSource])).toBe(true);
+ expect(harness.container.textContent).not.toContain("instance.validation.forbidden-parameter");
+ } finally {
+ harness.unmount();
+ }
+ }
+ );
+
+ test("clears errors when deleting the final invalid label unmounts its editor", async () => {
+ const { LabelListEditor } = await vi.importActual<
+ typeof import("@/components/LabelListEditor")
+ >("@/components/LabelListEditor");
+ let context!: ReturnType<typeof useInstanceFormContext>;
+ const Labels = () => {
+ context = useInstanceFormContext();
+ return context.labelKVList.length > 0 ? (
+ <LabelListEditor
+ kvList={context.labelKVList}
+ onChange={context.setLabelKVList}
+ onErrorsChange={context.setLabelErrors}
+ readonly={false}
+ showErrors
+ />
+ ) : null;
+ };
+ const harness = renderIntoContainer();
+ try {
+ await harness.render(
+ <InstanceFormProvider
+ instance={create(InstanceSchema, {
+ name: "instances/prod",
+ labels: { team: "platform" },
+ engine: Engine.POSTGRES,
+ })}
+ >
+ <Labels />
+ </InstanceFormProvider>
+ );
+ await act(async () => {
+ context.setLabelKVList([{ key: "team", value: "" }]);
+ });
+ expect(context.labelErrors).toEqual(["label.error.value-necessary"]);
+ const remove = harness.container.querySelector<HTMLButtonElement>("button")!;
+ await act(async () => { remove.click(); });
+ expect(context.labelKVList).toEqual([]);
+ expect(harness.container.querySelector("input")).toBeNull();
+ expect(context.labelErrors).toEqual([]);
+ } finally {
+ harness.unmount();
+ }
+ });
+
+ test.each([Engine.BIGQUERY, Engine.SPANNER])("requires resource ID and valid labels when creating GCP engine %s", async (engine) => {
+ let context!: ReturnType<typeof useInstanceFormContext>;
+ const Capture = () => { context = useInstanceFormContext(); return null; };
+ const harness = renderIntoContainer();
+ await harness.render(<InstanceFormProvider><Capture /></InstanceFormProvider>);
+ await act(async () => {
+ context.setBasicInfo((previous) => ({ ...previous, engine, title: "Production" }));
+ context.setDataSourceEditState((previous) => ({ ...previous, dataSources: [wrapEditDataSource(create(DataSourceSchema, { id: "admin", type: DataSourceType.ADMIN, projectId: "valid-project", instanceId: "valid-instance" }))] }));
+ });
+ expect(context.allowCreate).toBe(false);
+ await act(async () => { context.setResourceIdValidated(true); });
+ expect(context.allowCreate).toBe(true);
+ await act(async () => { context.setLabelErrors(["invalid label"]); });
+ expect(context.allowCreate).toBe(false);
+ harness.unmount();
+ });
+
describe("checkDataSource AWS region requirement", () => {
const awsDataSource = (region: string, withCredential: boolean) => {
const ds = wrapEditDataSource(
@@ -790,6 +1024,7 @@ describe("InstanceFormProvider", () => {
id: "admin",
type: DataSourceType.ADMIN,
authenticationType: DataSource_AuthenticationType.AWS_RDS_IAM,
+ host: "db.example.com",
region,
})
);
diff --git a/frontend/src/components/instance/InstanceFormContext.tsx b/frontend/src/components/instance/InstanceFormContext.tsx
index a92dc8c2fb..da377545a3 100644
--- a/frontend/src/components/instance/InstanceFormContext.tsx
+++ b/frontend/src/components/instance/InstanceFormContext.tsx
@@ -21,23 +21,15 @@ import type {
Instance,
} from "@/types/proto-es/v1/instance_service_pb";
import {
- DataSource_AuthenticationType,
- DataSource_RedisType,
- DataSourceExternalSecret_AuthType,
- DataSourceExternalSecret_SecretType,
DataSourceType,
InstanceSchema,
} from "@/types/proto-es/v1/instance_service_pb";
import type { Project } from "@/types/proto-es/v1/project_service_pb";
import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
-import {
- convertKVListToLabels,
- convertLabelsToKVList,
- isValidBigQueryDataSource,
- isValidSpannerDataSource,
-} from "@/utils";
+import { convertKVListToLabels, convertLabelsToKVList } from "@/utils";
import { extractGrpcErrorMessage } from "@/utils/connect";
import { FeatureModal } from "../ui/feature-modal";
+import { isIAMAuthentication } from "./authentication";
import {
type ConnectionFailureCategory,
connectionFailureCategoryHeader,
@@ -54,6 +46,7 @@ import {
import { effectivePortForEngine } from "./constants";
import { hasInstancePermission } from "./permission";
import { type InstanceSpecs, useInstanceSpecs } from "./specs";
+import { type ValidationErrors, validateDataSource } from "./validation";
export type LocalState = {
editingDataSourceId: string | undefined;
@@ -116,6 +109,7 @@ export interface InstanceFormContextValue {
setResourceIdValidated: React.Dispatch<React.SetStateAction<boolean>>;
labelErrors: string[];
setLabelErrors: React.Dispatch<React.SetStateAction<string[]>>;
+ getDataSourceErrors: (dataSource: EditDataSource) => ValidationErrors;
checkDataSource: (dataSources: EditDataSource[]) => boolean;
needsKeytabResupply: (dataSource: EditDataSource) => boolean;
resetDataSource: () => void;
@@ -202,6 +196,13 @@ export function InstanceFormProvider({
});
const isCreating = instance === undefined;
+ useEffect(() => {
+ // Removing the final label unmounts the editor before it can clear errors.
+ if (labelKVList.length === 0) {
+ setLabelErrors((errors) => (errors.length > 0 ? [] : errors));
+ }
+ }, [labelKVList.length]);
+
useEffect(() => {
const previous = syncedInstanceRef.current;
const next = {
@@ -316,6 +317,11 @@ export function InstanceFormProvider({
ds.masterPassword = edit.updatedMasterPassword;
if (edit.useEmptyMasterPassword) ds.masterPassword = "";
if (edit.updatedToken) ds.authenticationPrivateKey = edit.updatedToken;
+ // Preserve inactive drafts in the form, but send only the active source.
+ if (isIAMAuthentication(ds.authenticationType)) {
+ ds.password = "";
+ ds.externalSecret = undefined;
+ }
ds.port = effectivePortForEngine(engine, ds.port, ds.srv);
if (!specs.showDatabase) ds.database = "";
if (engine !== Engine.ORACLE) {
@@ -358,128 +364,31 @@ export function InstanceFormProvider({
[basicInfo.engine, extractDataSourceFromEdit, instance]
);
+ const getDataSourceErrors = useCallback(
+ (ds: EditDataSource) =>
+ validateDataSource(ds, {
+ engine: basicInfo.engine,
+ isSaaSMode,
+ stored: instance?.dataSources.find((stored) => stored.id === ds.id),
+ keytabResupply: needsKeytabResupply(ds),
+ }),
+ [basicInfo.engine, isSaaSMode, instance, needsKeytabResupply]
+ );
+
const checkDataSource = useCallback(
- (dataSources: EditDataSource[]) => {
- return dataSources.every((ds) => {
- if (
- ds.authenticationType ===
- DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM
- ) {
- return /.+:.+:.+/.test(ds.host);
- }
- if (
- ds.authenticationType === DataSource_AuthenticationType.AWS_RDS_IAM
- ) {
- // DynamoDB can run on the deployment's default credential chain,
- // where the region may also come from the environment. A specific
- // credential must pin its region.
- if (basicInfo.engine === Engine.DYNAMODB) {
- return ds.iamExtension?.case !== "awsCredential" || !!ds.region;
- }
- return !!ds.region;
- }
- if (basicInfo.engine === Engine.ORACLE) {
- if (!ds.sid && !ds.serviceName) return false;
- } else if (basicInfo.engine === Engine.DATABRICKS) {
- if (!ds.warehouseId) return false;
- // Token is INPUT_ONLY: backend never returns it. Require it only on
- // create; on edit, an empty updatedToken means "keep existing token".
- if (ds.pendingCreate && !ds.updatedToken) return false;
- }
- const krbConfig = krbConfigOf(ds);
- if (krbConfig) {
- if (!krbConfig.primary || !krbConfig.realm || !krbConfig.kdcHost) {
- return false;
- }
- // Keytab is INPUT_ONLY: the backend never returns it. Require it
- // only on create; on edit, an empty keytab keeps the existing one.
- if (ds.pendingCreate && krbConfig.keytab.length === 0) {
- return false;
- }
- // Unless the edit moves where the data source connects, which the
- // backend refuses to let the stored keytab follow.
- if (needsKeytabResupply(ds)) {
- return false;
- }
- }
- if (!ds.externalSecret) return true;
- switch (ds.externalSecret.secretType) {
- case DataSourceExternalSecret_SecretType.VAULT_KV_V2:
- if (
- !ds.externalSecret.url ||
- !ds.externalSecret.engineName ||
- !ds.externalSecret.secretName ||
- !ds.externalSecret.passwordKeyName
- )
- return false;
- break;
- case DataSourceExternalSecret_SecretType.AWS_SECRETS_MANAGER:
- if (
- !ds.externalSecret.secretName ||
- !ds.externalSecret.passwordKeyName
- )
- return false;
- break;
- case DataSourceExternalSecret_SecretType.GCP_SECRET_MANAGER:
- if (!ds.externalSecret.secretName) return false;
- break;
- }
- switch (ds.externalSecret.authType) {
- case DataSourceExternalSecret_AuthType.TOKEN:
- return !!(
- ds.externalSecret.authOption?.case === "token" &&
- ds.externalSecret.authOption.value
- );
- case DataSourceExternalSecret_AuthType.VAULT_APP_ROLE:
- return !!(
- ds.externalSecret.authOption?.case === "appRole" &&
- ds.externalSecret.authOption.value.roleId &&
- ds.externalSecret.authOption.value.secretId
- );
- }
- return true;
- });
- },
- [basicInfo.engine, needsKeytabResupply]
+ (dataSources: EditDataSource[]) =>
+ dataSources.every(
+ (ds) => Object.keys(getDataSourceErrors(ds)).length === 0
+ ),
+ [getDataSourceErrors]
);
- const allowCreate = useMemo(() => {
- if (!hasPermission("bb.instances.create")) return false;
- if (basicInfo.engine === Engine.SPANNER) {
- return (
- !!basicInfo.title.trim() && isValidSpannerDataSource(adminDataSource)
- );
- }
- if (basicInfo.engine === Engine.BIGQUERY) {
- return (
- !!basicInfo.title.trim() && isValidBigQueryDataSource(adminDataSource)
- );
- }
- if (basicInfo.engine !== Engine.DYNAMODB) {
- if (adminDataSource.host === "") return false;
- }
- if (basicInfo.engine === Engine.REDIS) {
- if (
- adminDataSource.redisType === DataSource_RedisType.SENTINEL &&
- adminDataSource.masterName === ""
- )
- return false;
- }
- const hasLabelErrs = labelErrors.length > 0;
- return (
- !!basicInfo.title.trim() &&
- resourceIdValidated &&
- checkDataSource([adminDataSource]) &&
- !hasLabelErrs
- );
- }, [
- basicInfo,
- adminDataSource,
- resourceIdValidated,
- labelErrors,
- checkDataSource,
- hasPermission,
- ]);
+ const allowCreate =
+ hasPermission("bb.instances.create") &&
+ !!basicInfo.title.trim() &&
+ resourceIdValidated &&
+ labelErrors.length === 0 &&
+ checkDataSource([adminDataSource]);
const emitDataSourceReset = useCallback(() => {
setDataSourceResetEvent((event) => event + 1);
@@ -724,6 +633,7 @@ export function InstanceFormProvider({
labelErrors,
setLabelErrors,
checkDataSource,
+ getDataSourceErrors,
needsKeytabResupply,
resetDataSource,
extractDataSourceFromEdit,
@@ -761,6 +671,7 @@ export function InstanceFormProvider({
resourceIdValidated,
labelErrors,
checkDataSource,
+ getDataSourceErrors,
needsKeytabResupply,
resetDataSource,
extractDataSourceFromEdit,
diff --git a/frontend/src/components/instance/SslCertificateForm.test.tsx b/frontend/src/components/instance/SslCertificateForm.test.tsx
index e7d384cde4..d79f856fd6 100644
--- a/frontend/src/components/instance/SslCertificateForm.test.tsx
+++ b/frontend/src/components/instance/SslCertificateForm.test.tsx
@@ -228,6 +228,38 @@ describe("SslCertificateForm", () => {
});
});
+ test.each(["posture", "groups"])("keeps CA drafts editable after disabling verification in %s mode", (mode) => {
+ const container = document.createElement("div");
+ document.body.appendChild(container);
+ const root = createRoot(container);
+ const render = (verify: boolean) => act(() => {
+ root.render(<SslCertificateForm
+ posture={mode === "posture" ? "TLS" : undefined}
+ onPostureChange={() => {}}
+ caSource="FILE_PATH"
+ onCaSourceChange={() => {}}
+ clientCertSource="NONE"
+ onClientCertSourceChange={() => {}}
+ useSsl={true}
+ verify={verify}
+ onVerifyChange={() => {}}
+ caPath="relative.pem"
+ onCaPathChange={() => {}}
+ engineType={Engine.POSTGRES}
+ />);
+ });
+ try {
+ render(true);
+ expect(container.querySelector('input[value="relative.pem"]')).not.toBeNull();
+ render(false);
+ const input = container.querySelector<HTMLInputElement>('input[value="relative.pem"]');
+ expect(input).not.toBeNull();
+ expect(input?.disabled).toBe(false);
+ } finally {
+ act(() => root.unmount());
+ }
+ });
+
test("falls back to legacy UI when posture source props are incomplete", () => {
const container = document.createElement("div");
document.body.appendChild(container);
diff --git a/frontend/src/components/instance/SslCertificateForm.tsx b/frontend/src/components/instance/SslCertificateForm.tsx
index d7c1fb4a44..19da89963d 100644
--- a/frontend/src/components/instance/SslCertificateForm.tsx
+++ b/frontend/src/components/instance/SslCertificateForm.tsx
@@ -1,8 +1,7 @@
import { type DragEvent, useCallback } from "react";
import { useTranslation } from "react-i18next";
import { Badge } from "@/components/ui/badge";
-import { FormField, ResponsiveFormLayout } from "@/components/ui/form";
-import { Input } from "@/components/ui/input";
+import { ResponsiveFormLayout } from "@/components/ui/form";
import {
SegmentedControl,
type SegmentedControlOption,
@@ -27,6 +26,11 @@ import {
type LocalTlsClientCertSource,
type LocalTlsPosture,
} from "./tls";
+import {
+ ValidationField as FormField,
+ ValidationInput as Input,
+ ValidationTextarea as Textarea,
+} from "./ValidationField";
interface SslCertificateFormProps {
useSsl?: boolean;
@@ -73,11 +77,13 @@ function DroppableTextarea({
onChange,
disabled,
placeholder,
+ label,
}: {
value: string;
onChange: (val: string) => void;
disabled?: boolean;
placeholder: string;
+ label: string;
}) {
const handleDrop = useCallback(
(e: DragEvent<HTMLTextAreaElement>) => {
@@ -100,14 +106,15 @@ function DroppableTextarea({
}, []);
return (
- <textarea
+ <Textarea
+ aria-label={label}
value={value}
onChange={(e) => onChange(e.target.value)}
onDrop={handleDrop}
onDragOver={handleDragOver}
disabled={disabled}
placeholder={placeholder}
- className="w-full h-24 whitespace-pre-wrap resize-none rounded-xs border border-control-border bg-background px-3 py-2 text-sm focus:outline-hidden focus:border-accent disabled:cursor-not-allowed disabled:opacity-50"
+ className="w-full whitespace-pre-wrap resize-none"
/>
);
}
@@ -269,6 +276,9 @@ export function SslCertificateForm({
showClientCertSourceUi;
const showPerGroupSourceUi = showCaSourceUi || showClientCertSourceUi;
+ // Configured CA material is still submitted when verification is disabled.
+ // Keep its controls reachable so validation cannot block on hidden fields.
+ const showCaMaterial = verify || !!(ca || caPath || hasCa || hasCaPath);
const hasClientIdentityMaterial = !!(
cert ||
sslKey ||
@@ -399,9 +409,13 @@ export function SslCertificateForm({
if (resolvedCaSource === LOCAL_TLS_CA_SOURCE_FILE_PATH) {
return (
- <FormField title={renderLabel(resolvedCaPathLabel, hasCaPath, caPath)}>
+ <FormField
+ validationField="sslCaPath"
+ title={renderLabel(resolvedCaPathLabel, hasCaPath, caPath)}
+ >
<Input
data-testid="tls-ca-path-input"
+ aria-label={resolvedCaPathLabel}
value={caPath}
onChange={(e) => onCaPathChange?.(e.target.value)}
disabled={disabled || isSaaSMode}
@@ -412,11 +426,15 @@ export function SslCertificateForm({
}
return (
- <FormField title={renderLabel(resolvedCaLabel, hasCa, ca)}>
+ <FormField
+ validationField="sslCa"
+ title={renderLabel(resolvedCaLabel, hasCa, ca)}
+ >
<DroppableTextarea
value={ca}
onChange={(val) => onCaChange?.(val)}
disabled={disabled}
+ label={resolvedCaLabel}
placeholder={resolvedCaPlaceholder}
/>
</FormField>
@@ -434,10 +452,12 @@ export function SslCertificateForm({
return (
<div className="flex flex-col gap-4">
<FormField
+ validationField="sslCertPath"
title={renderLabel(resolvedCertPathLabel, hasCertPath, certPath)}
>
<Input
data-testid="tls-cert-path-input"
+ aria-label={resolvedCertPathLabel}
value={certPath}
onChange={(e) => onCertPathChange?.(e.target.value)}
disabled={disabled || isSaaSMode}
@@ -445,10 +465,12 @@ export function SslCertificateForm({
/>
</FormField>
<FormField
+ validationField="sslKeyPath"
title={renderLabel(resolvedKeyPathLabel, hasKeyPath, keyPath)}
>
<Input
data-testid="tls-key-path-input"
+ aria-label={resolvedKeyPathLabel}
value={keyPath}
onChange={(e) => onKeyPathChange?.(e.target.value)}
disabled={disabled || isSaaSMode}
@@ -461,19 +483,27 @@ export function SslCertificateForm({
return (
<div className="flex flex-col gap-4">
- <FormField title={renderLabel(resolvedCertLabel, hasCert, cert)}>
+ <FormField
+ validationField="sslCert"
+ title={renderLabel(resolvedCertLabel, hasCert, cert)}
+ >
<DroppableTextarea
value={cert}
onChange={(val) => onCertChange?.(val)}
disabled={disabled}
+ label={resolvedCertLabel}
placeholder={resolvedCertPlaceholder}
/>
</FormField>
- <FormField title={renderLabel(resolvedKeyLabel, hasKey, sslKey)}>
+ <FormField
+ validationField="sslKey"
+ title={renderLabel(resolvedKeyLabel, hasKey, sslKey)}
+ >
<DroppableTextarea
value={sslKey}
onChange={(val) => onKeyChange?.(val)}
disabled={disabled}
+ label={resolvedKeyLabel}
placeholder={resolvedKeyPlaceholder}
/>
</FormField>
@@ -486,10 +516,12 @@ export function SslCertificateForm({
return (
<div className="flex flex-col gap-4">
<FormField
+ validationField="sslCaPath"
title={renderLabel(resolvedCaPathLabel, hasCaPath, caPath)}
>
<Input
data-testid="tls-ca-path-input"
+ aria-label={resolvedCaPathLabel}
value={caPath}
onChange={(e) => onCaPathChange?.(e.target.value)}
disabled={disabled || isSaaSMode}
@@ -498,10 +530,12 @@ export function SslCertificateForm({
</FormField>
{showKeyAndCertFields && (
<FormField
+ validationField="sslCertPath"
title={renderLabel(resolvedCertPathLabel, hasCertPath, certPath)}
>
<Input
data-testid="tls-cert-path-input"
+ aria-label={resolvedCertPathLabel}
value={certPath}
onChange={(e) => onCertPathChange?.(e.target.value)}
disabled={disabled || isSaaSMode}
@@ -511,10 +545,12 @@ export function SslCertificateForm({
)}
{showKeyAndCertFields && (
<FormField
+ validationField="sslKeyPath"
title={renderLabel(resolvedKeyPathLabel, hasKeyPath, keyPath)}
>
<Input
data-testid="tls-key-path-input"
+ aria-label={resolvedKeyPathLabel}
value={keyPath}
onChange={(e) => onKeyPathChange?.(e.target.value)}
disabled={disabled || isSaaSMode}
@@ -569,6 +605,7 @@ export function SslCertificateForm({
value={ca}
onChange={(val) => onCaChange?.(val)}
disabled={disabled}
+ label={resolvedCaLabel}
placeholder={resolvedCaPlaceholder}
/>
</TabsPanel>
@@ -578,6 +615,7 @@ export function SslCertificateForm({
value={sslKey}
onChange={(val) => onKeyChange?.(val)}
disabled={disabled}
+ label={resolvedKeyLabel}
placeholder={resolvedKeyPlaceholder}
/>
</TabsPanel>
@@ -588,6 +626,7 @@ export function SslCertificateForm({
value={cert}
onChange={(val) => onCertChange?.(val)}
disabled={disabled}
+ label={resolvedCertLabel}
placeholder={resolvedCertPlaceholder}
/>
</TabsPanel>
@@ -642,7 +681,7 @@ export function SslCertificateForm({
{t("data-source.ssl.server-identity")}
</legend>
{renderVerifyControl()}
- {verify && (
+ {showCaMaterial && (
<div className="flex flex-col gap-4">
{showCaSourceUi && (
<FormField
@@ -725,7 +764,7 @@ export function SslCertificateForm({
renderLegacyMaterial()
) : (
<>
- {verify && (
+ {showCaMaterial && (
<div className="flex flex-col gap-4">
{showCaSourceUi && (
<FormField
diff --git a/frontend/src/components/instance/ValidationField.test.tsx b/frontend/src/components/instance/ValidationField.test.tsx
new file mode 100644
index 0000000000..5e109da254
--- /dev/null
+++ b/frontend/src/components/instance/ValidationField.test.tsx
@@ -0,0 +1,48 @@
+import { fireEvent, render, screen } from "@testing-library/react";
+import { useState } from "react";
+import { expect, test, vi } from "vitest";
+import { SslCertificateForm } from "./SslCertificateForm";
+import { ValidationField, ValidationInput, ValidationProvider } from "./ValidationField";
+
+vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+
+test("shows a field error on blur, associates it with the input, and clears it when corrected", () => {
+ const form = (errors: Record<string, string>) => (
+ <ValidationProvider errors={errors}>
+ <ValidationField validationField="host" title="Host">
+ <ValidationInput defaultValue="" />
+ </ValidationField>
+ </ValidationProvider>
+ );
+ const view = render(form({ host: "required" }));
+ const input = screen.getByRole("textbox", { name: "Host" });
+ expect(screen.queryByText("instance.validation.required")).toBeNull();
+ fireEvent.blur(input);
+ const error = screen.getByText("instance.validation.required");
+ expect(input.getAttribute("aria-invalid")).toBe("true");
+ expect(input.getAttribute("aria-describedby")).toBe(error.id);
+ view.rerender(form({}));
+ expect(screen.queryByText("instance.validation.required")).toBeNull();
+ expect(input.getAttribute("aria-invalid")).not.toBe("true");
+ view.unmount();
+});
+
+test("TLS path feedback is visible before submitting and clears while correcting the field", () => {
+ function Form() {
+ const [path, setPath] = useState("certs/ca.pem");
+ return (
+ <ValidationProvider errors={path && !path.startsWith("/") ? { sslCaPath: "absolute-path" } : {}}>
+ <SslCertificateForm useSsl verify caSource="FILE_PATH" onCaSourceChange={() => {}} caPath={path} onCaPathChange={setPath} />
+ </ValidationProvider>
+ );
+ }
+ const view = render(<Form />);
+ const input = screen.getByTestId("tls-ca-path-input");
+ expect(screen.queryByText("instance.validation.absolute-path")).toBeNull();
+ fireEvent.blur(input);
+ expect(screen.getByText("instance.validation.absolute-path")).toBeTruthy();
+ expect(input.getAttribute("aria-invalid")).toBe("true");
+ fireEvent.change(input, { target: { value: "/certs/ca.pem" } });
+ expect(screen.queryByText("instance.validation.absolute-path")).toBeNull();
+ view.unmount();
+});
diff --git a/frontend/src/components/instance/ValidationField.tsx b/frontend/src/components/instance/ValidationField.tsx
new file mode 100644
index 0000000000..471aa96585
--- /dev/null
+++ b/frontend/src/components/instance/ValidationField.tsx
@@ -0,0 +1,138 @@
+import type { TFunction } from "i18next";
+import {
+ type ComponentProps,
+ createContext,
+ type ReactNode,
+ useContext,
+ useId,
+ useState,
+} from "react";
+import { useTranslation } from "react-i18next";
+import { FormError, FormField } from "@/components/ui/form";
+import { Input } from "@/components/ui/input";
+import { Textarea } from "@/components/ui/textarea";
+import type { ValidationErrors } from "./validation";
+
+const validationMessages: Record<string, (t: TFunction) => string> = {
+ "absolute-path": (t) => t("instance.validation.absolute-path"),
+ "aws-credential": (t) => t("instance.validation.aws-credential"),
+ "cloud-sql-host": (t) => t("instance.validation.cloud-sql-host"),
+ "forbidden-parameter": (t) => t("instance.validation.forbidden-parameter"),
+ "gcp-instance": (t) => t("instance.validation.gcp-instance"),
+ "gcp-project": (t) => t("instance.validation.gcp-project"),
+ "keytab-resupply": (t) => t("instance.validation.keytab-resupply"),
+ "oracle-service": (t) => t("instance.validation.oracle-service"),
+ "pem-certificate": (t) => t("instance.validation.pem-certificate"),
+ "pem-key": (t) => t("instance.validation.pem-key"),
+ required: (t) => t("instance.validation.required"),
+ "specific-credential": (t) => t("instance.validation.specific-credential"),
+ "tls-pair": (t) => t("instance.validation.tls-pair"),
+ "tls-source-conflict": (t) => t("instance.validation.tls-source-conflict"),
+};
+
+const ErrorsContext = createContext<ValidationErrors>({});
+const FieldContext = createContext<{
+ invalid: boolean;
+ description?: string;
+ label?: string;
+}>({ invalid: false });
+
+export function ValidationProvider({
+ errors,
+ children,
+ className,
+}: {
+ errors: ValidationErrors;
+ children: ReactNode;
+ className?: string;
+}) {
+ return (
+ <ErrorsContext.Provider value={errors}>
+ {className ? <div className={className}>{children}</div> : children}
+ </ErrorsContext.Provider>
+ );
+}
+
+export function ValidationField({
+ validationField,
+ showErrors = false,
+ children,
+ ...props
+}: ComponentProps<typeof FormField> & {
+ validationField?: string | string[];
+ showErrors?: boolean;
+}) {
+ const { t } = useTranslation();
+ const errors = useContext(ErrorsContext);
+ const [touched, setTouched] = useState(false);
+ const id = useId();
+ const fields =
+ typeof validationField === "string"
+ ? [validationField]
+ : (validationField ?? []);
+ const messages = [
+ ...new Set(
+ fields.flatMap((field) => (errors[field] ? [errors[field]] : []))
+ ),
+ ];
+ const invalid = (showErrors || touched) && messages.length > 0;
+ return (
+ <FieldContext.Provider
+ value={{
+ invalid,
+ description: invalid ? id : undefined,
+ label: typeof props.title === "string" ? props.title : undefined,
+ }}
+ >
+ <FormField
+ {...props}
+ data-invalid={invalid || undefined}
+ onBlurCapture={(event) => {
+ setTouched(true);
+ props.onBlurCapture?.(event);
+ }}
+ >
+ {children}
+ {invalid && (
+ <FormError id={id} aria-live="polite">
+ {messages
+ .map((message) => validationMessages[message](t))
+ .join(" ")}
+ </FormError>
+ )}
+ </FormField>
+ </FieldContext.Provider>
+ );
+}
+
+export function ValidationInput(props: ComponentProps<typeof Input>) {
+ const field = useContext(FieldContext);
+ return (
+ <Input
+ {...props}
+ aria-label={props["aria-label"] ?? field.label}
+ aria-invalid={field.invalid || props["aria-invalid"]}
+ aria-describedby={
+ [props["aria-describedby"], field.description]
+ .filter(Boolean)
+ .join(" ") || undefined
+ }
+ />
+ );
+}
+
+export function ValidationTextarea(props: ComponentProps<typeof Textarea>) {
+ const field = useContext(FieldContext);
+ return (
+ <Textarea
+ {...props}
+ aria-label={props["aria-label"] ?? field.label}
+ aria-invalid={field.invalid || props["aria-invalid"]}
+ aria-describedby={
+ [props["aria-describedby"], field.description]
+ .filter(Boolean)
+ .join(" ") || undefined
+ }
+ />
+ );
+}
diff --git a/frontend/src/components/instance/authentication.ts b/frontend/src/components/instance/authentication.ts
new file mode 100644
index 0000000000..7d5bc6dd72
--- /dev/null
+++ b/frontend/src/components/instance/authentication.ts
@@ -0,0 +1,6 @@
+import { DataSource_AuthenticationType } from "@/types/proto-es/v1/instance_service_pb";
+
+export const isIAMAuthentication = (type: DataSource_AuthenticationType) =>
+ type === DataSource_AuthenticationType.AWS_RDS_IAM ||
+ type === DataSource_AuthenticationType.GOOGLE_CLOUD_SQL_IAM ||
+ type === DataSource_AuthenticationType.AZURE_IAM;
diff --git a/frontend/src/components/instance/validation.test.ts b/frontend/src/components/instance/validation.test.ts
new file mode 100644
index 0000000000..1f5ff3627c
--- /dev/null
+++ b/frontend/src/components/instance/validation.test.ts
@@ -0,0 +1,194 @@
+import { create } from "@bufbuild/protobuf";
+import { describe, expect, test } from "vitest";
+import { Engine } from "@/types/proto-es/v1/common_pb";
+import {
+ DataSource_AuthenticationType as Auth,
+ DataSource_AWSCredentialSchema,
+ DataSource_AzureCredentialSchema,
+ DataSourceSchema,
+ DataSourceExternalSecret_SecretType as SecretType,
+} from "@/types/proto-es/v1/instance_service_pb";
+import type { EditDataSource } from "./common";
+import { validateDataSource } from "./validation";
+
+const draft = (patch: Partial<EditDataSource> = {}): EditDataSource => ({
+ ...create(DataSourceSchema, { host: "db.example.com" }),
+ pendingCreate: true,
+ updatedPassword: "",
+ updatedMasterPassword: "",
+ updatedToken: "",
+ ...patch,
+});
+const validate = (ds: EditDataSource, engine = Engine.MYSQL) =>
+ validateDataSource(ds, { engine, isSaaSMode: true });
+
+describe("instance validation", () => {
+ test.each(["sslCaPath", "sslCertPath", "sslKeyPath"] as const)(
+ "rejects relative %s",
+ (field) => {
+ const errors = validate(
+ draft({
+ useSsl: true,
+ sslCertPath: "/cert.pem",
+ sslKeyPath: "/key.pem",
+ [field]: "relative.pem",
+ })
+ );
+ expect(errors[field]).toBe("absolute-path");
+ }
+ );
+ test("requires both TLS identity fields and ignores material when TLS is off", () => {
+ const ds = draft({ useSsl: true, sslCertPath: "/cert.pem" });
+ expect(validate(ds).sslKeyPath).toBe("tls-pair");
+ expect(validate({ ...ds, useSsl: false })).toEqual({});
+ });
+ test("keeps stored TLS material until its group is replaced", () => {
+ const ds = draft({
+ pendingCreate: false,
+ useSsl: true,
+ sslCertSet: true,
+ sslKeySet: true,
+ });
+ expect(validate(ds)).toEqual({});
+ expect(
+ validate({
+ ...ds,
+ sslCertPath: "/cert.pem",
+ updateSsl: { clientCert: true },
+ }).sslKeyPath
+ ).toBe("tls-pair");
+ expect(
+ validate({
+ ...ds,
+ sslCertPath: "/cert.pem",
+ sslKeyPath: "/key.pem",
+ updateSsl: { clientCert: true },
+ })
+ ).toEqual({});
+ });
+ test("catches malformed PEM and conflicting sources", () => {
+ expect(validate(draft({ useSsl: true, sslCa: "not PEM" })).sslCa).toBe(
+ "pem-certificate"
+ );
+ expect(
+ validate(draft({ useSsl: true, sslCa: "not PEM", sslCaPath: "/ca.pem" }))
+ .sslCaPath
+ ).toBe("tls-source-conflict");
+ });
+ test.each(["allowAllFiles", " ALLOWALLFILES "])(
+ "rejects unsafe MySQL parameter %s",
+ (key) => {
+ const ds = draft({ extraConnectionParameters: { [key]: "false" } });
+ expect(validate(ds)[`extraConnectionParameters.${key}`]).toBe(
+ "forbidden-parameter"
+ );
+ expect(validate(ds, Engine.POSTGRES)).toEqual({});
+ }
+ );
+ test("AWS region does not short circuit credential or TLS validation", () => {
+ const ds = draft({
+ authenticationType: Auth.AWS_RDS_IAM,
+ region: "us-east-1",
+ iamExtension: {
+ case: "awsCredential",
+ value: create(DataSource_AWSCredentialSchema),
+ },
+ useSsl: true,
+ sslCaPath: "relative",
+ });
+ const errors = validate(ds);
+ expect(errors["iamExtension.accessKeyId"]).toBe("aws-credential");
+ expect(errors.sslCaPath).toBe("absolute-path");
+ });
+ test("Azure Key Vault requires its URL and secret name", () => {
+ const ds = draft(
+ create(DataSourceSchema, {
+ host: "db.example.com",
+ externalSecret: { secretType: SecretType.AZURE_KEY_VAULT },
+ })
+ );
+ expect(validate(ds)).toMatchObject({
+ "externalSecret.url": "required",
+ "externalSecret.secretName": "required",
+ });
+ });
+ test.each([Auth.AWS_RDS_IAM, Auth.GOOGLE_CLOUD_SQL_IAM, Auth.AZURE_IAM])(
+ "ignores the inactive external-secret draft for IAM method %s",
+ (authenticationType) => {
+ const ds = draft(
+ create(DataSourceSchema, {
+ authenticationType: Auth.PASSWORD,
+ host: "project:region:instance",
+ region: "us-east-1",
+ externalSecret: { secretType: SecretType.AZURE_KEY_VAULT },
+ })
+ );
+ const options = { engine: Engine.MYSQL, isSaaSMode: false };
+ expect(validateDataSource(ds, options)["externalSecret.url"]).toBe(
+ "required"
+ );
+ expect(
+ validateDataSource({ ...ds, authenticationType }, options)
+ ).toEqual({});
+ expect(validateDataSource(ds, options)["externalSecret.secretName"]).toBe(
+ "required"
+ );
+ }
+ );
+
+ test("stored redacted credentials pass, replacements require complete credentials", () => {
+ const stored = create(DataSourceSchema, {
+ host: "db.example.com",
+ authenticationType: Auth.AZURE_IAM,
+ iamExtension: {
+ case: "azureCredential",
+ value: { tenantId: "tenant", clientId: "client" },
+ },
+ });
+ const ds = draft({ ...stored, pendingCreate: false });
+ expect(
+ validateDataSource(ds, {
+ engine: Engine.POSTGRES,
+ isSaaSMode: true,
+ stored,
+ })
+ ).toEqual({});
+ const replacement = draft({
+ ...stored,
+ pendingCreate: false,
+ iamExtension: {
+ case: "azureCredential",
+ value: create(DataSource_AzureCredentialSchema, {
+ tenantId: "other",
+ clientId: "client",
+ }),
+ },
+ });
+ expect(
+ validateDataSource(replacement, {
+ engine: Engine.POSTGRES,
+ isSaaSMode: true,
+ stored,
+ })["iamExtension.clientSecret"]
+ ).toBe("required");
+ });
+ test("BigQuery validates credentials without requiring a Cloud SQL host", () => {
+ const ds = draft(
+ create(DataSourceSchema, {
+ host: "",
+ projectId: "valid-project",
+ authenticationType: Auth.GOOGLE_CLOUD_SQL_IAM,
+ iamExtension: { case: "gcpCredential", value: {} },
+ })
+ );
+ const errors = validate(ds, Engine.BIGQUERY);
+ expect(errors.host).toBeUndefined();
+ expect(errors["iamExtension.content"]).toBe("required");
+ });
+ test("self-hosted DynamoDB can use the default credential chain without a region or host", () => {
+ const ds = draft({ host: "", authenticationType: Auth.AWS_RDS_IAM });
+ expect(
+ validateDataSource(ds, { engine: Engine.DYNAMODB, isSaaSMode: false })
+ ).toEqual({});
+ });
+});
diff --git a/frontend/src/components/instance/validation.ts b/frontend/src/components/instance/validation.ts
new file mode 100644
index 0000000000..93f55e9f22
--- /dev/null
+++ b/frontend/src/components/instance/validation.ts
@@ -0,0 +1,222 @@
+import { isEqual } from "lodash-es";
+import { Engine } from "@/types/proto-es/v1/common_pb";
+import {
+ DataSource_AuthenticationType as Auth,
+ type DataSource,
+ DataSource_RedisType,
+ DataSourceExternalSecret_AuthType as SecretAuth,
+ DataSourceExternalSecret_SecretType as SecretType,
+} from "@/types/proto-es/v1/instance_service_pb";
+import { isIAMAuthentication } from "./authentication";
+import type { EditDataSource } from "./common";
+
+export type ValidationErrors = Record<string, string>;
+
+// This catches malformed envelopes and base64 before a request. Certificate
+// parsing, key matching, and trust verification remain authoritative on the server.
+function hasPem(value: string, kind: "certificate" | "key"): boolean {
+ const pattern =
+ /-----BEGIN ([A-Z ]+)-----\s+([A-Za-z0-9+/=\s]+?)\s+-----END \1-----/g;
+ for (const match of value.matchAll(pattern)) {
+ if (
+ kind === "certificate"
+ ? match[1] !== "CERTIFICATE"
+ : !["PRIVATE KEY", "RSA PRIVATE KEY", "EC PRIVATE KEY"].includes(
+ match[1]
+ )
+ )
+ continue;
+ try {
+ const decoded = atob(match[2].replace(/\s/g, ""));
+ if (decoded.length > 2 && decoded.charCodeAt(0) === 0x30) return true;
+ } catch {
+ // Try another PEM block in a certificate bundle.
+ }
+ }
+ return false;
+}
+
+export function validateDataSource(
+ ds: EditDataSource,
+ {
+ engine,
+ isSaaSMode,
+ stored,
+ keytabResupply = false,
+ }: {
+ engine: Engine;
+ isSaaSMode: boolean;
+ stored?: DataSource;
+ keytabResupply?: boolean;
+ }
+): ValidationErrors {
+ const errors: ValidationErrors = {};
+ const require = (field: string, value: string | undefined) => {
+ if (!value?.trim()) errors[field] = "required";
+ };
+ const gcpEngine = engine === Engine.BIGQUERY || engine === Engine.SPANNER;
+ if (gcpEngine) {
+ if (!/^[a-z\d.:-]+$/.test(ds.projectId)) errors.projectId = "gcp-project";
+ if (engine === Engine.SPANNER && !/^[a-z\d-]+$/.test(ds.instanceId))
+ errors.instanceId = "gcp-instance";
+ } else if (engine !== Engine.DYNAMODB) {
+ require("host", ds.host);
+ }
+ if (
+ ds.authenticationType === Auth.GOOGLE_CLOUD_SQL_IAM &&
+ !gcpEngine &&
+ !/.+:.+:.+/.test(ds.host)
+ )
+ errors.host = "cloud-sql-host";
+ if (
+ ds.authenticationType === Auth.AWS_RDS_IAM &&
+ (engine !== Engine.DYNAMODB || ds.iamExtension?.case === "awsCredential")
+ )
+ require("region", ds.region);
+ if (engine === Engine.ORACLE && !ds.sid && !ds.serviceName)
+ errors.serviceName = "oracle-service";
+ if (engine === Engine.DATABRICKS) {
+ require("warehouseId", ds.warehouseId);
+ if (ds.pendingCreate) require("updatedToken", ds.updatedToken);
+ }
+ if (engine === Engine.REDIS && ds.redisType === DataSource_RedisType.SENTINEL)
+ require("masterName", ds.masterName);
+
+ const krb =
+ ds.saslConfig?.mechanism.case === "krbConfig"
+ ? ds.saslConfig.mechanism.value
+ : undefined;
+ if (krb) {
+ for (const field of ["primary", "realm", "kdcHost"] as const)
+ require(`saslConfig.${field}`, krb[field]);
+ if (ds.pendingCreate && !krb.keytab.length)
+ errors["saslConfig.keytab"] = "required";
+ if (keytabResupply) errors["saslConfig.keytab"] = "keytab-resupply";
+ }
+
+ const iam = ds.iamExtension;
+ // Credential update masks replace the complete credential. Only the unchanged
+ // redacted value can inherit the stored secrets.
+ const keepsCredential =
+ !ds.pendingCreate &&
+ stored?.iamExtension.case &&
+ stored.authenticationType === ds.authenticationType &&
+ isEqual(stored.iamExtension, iam);
+ if (
+ isSaaSMode &&
+ isIAMAuthentication(ds.authenticationType) &&
+ !keepsCredential
+ ) {
+ if (!iam?.case) errors.iamExtension = "specific-credential";
+ if (
+ iam?.case === "awsCredential" &&
+ !iam.value.accessKeyId &&
+ !iam.value.roleArn
+ ) {
+ errors["iamExtension.accessKeyId"] = "aws-credential";
+ errors["iamExtension.roleArn"] = "aws-credential";
+ }
+ if (iam?.case === "gcpCredential")
+ require("iamExtension.content", iam.value.content);
+ if (iam?.case === "azureCredential") {
+ for (const field of ["tenantId", "clientId", "clientSecret"] as const)
+ require(`iamExtension.${field}`, iam.value[field]);
+ }
+ }
+
+ const secret = ds.externalSecret;
+ if (secret && !isIAMAuthentication(ds.authenticationType)) {
+ if (
+ [SecretType.VAULT_KV_V2, SecretType.AZURE_KEY_VAULT].includes(
+ secret.secretType
+ )
+ )
+ require("externalSecret.url", secret.url);
+ if (secret.secretType === SecretType.VAULT_KV_V2)
+ require("externalSecret.engineName", secret.engineName);
+ require("externalSecret.secretName", secret.secretName);
+ if (
+ [SecretType.VAULT_KV_V2, SecretType.AWS_SECRETS_MANAGER].includes(
+ secret.secretType
+ )
+ )
+ require("externalSecret.passwordKeyName", secret.passwordKeyName);
+ if (secret.authType === SecretAuth.TOKEN)
+ require("externalSecret.token", secret.authOption.case === "token"
+ ? secret.authOption.value
+ : "");
+ if (secret.authType === SecretAuth.VAULT_APP_ROLE) {
+ const role =
+ secret.authOption.case === "appRole"
+ ? secret.authOption.value
+ : undefined;
+ require("externalSecret.roleId", role?.roleId);
+ require("externalSecret.secretId", role?.secretId);
+ }
+ }
+
+ if (ds.useSsl) {
+ const caChanged =
+ ds.updateSsl === true ||
+ (typeof ds.updateSsl === "object" && ds.updateSsl.ca);
+ const clientChanged =
+ ds.updateSsl === true ||
+ (typeof ds.updateSsl === "object" && ds.updateSsl.clientCert);
+ const retained = (
+ field:
+ | "sslCaSet"
+ | "sslCaPathSet"
+ | "sslCertSet"
+ | "sslCertPathSet"
+ | "sslKeySet"
+ | "sslKeyPathSet"
+ ) =>
+ !(field === "sslCaSet" || field === "sslCaPathSet"
+ ? caChanged
+ : clientChanged) && ds[field];
+ for (const [inline, path, set, pathSet] of [
+ ["sslCa", "sslCaPath", "sslCaSet", "sslCaPathSet"],
+ ["sslCert", "sslCertPath", "sslCertSet", "sslCertPathSet"],
+ ["sslKey", "sslKeyPath", "sslKeySet", "sslKeyPathSet"],
+ ] as const) {
+ if ((ds[inline] || retained(set)) && (ds[path] || retained(pathSet)))
+ errors[path] = "tls-source-conflict";
+ if (ds[path] && !ds[path].startsWith("/")) errors[path] = "absolute-path";
+ if (
+ ds[inline] &&
+ !hasPem(ds[inline], inline === "sslKey" ? "key" : "certificate")
+ )
+ errors[inline] = inline === "sslKey" ? "pem-key" : "pem-certificate";
+ }
+ const cert = !!(
+ ds.sslCert ||
+ ds.sslCertPath ||
+ retained("sslCertSet") ||
+ retained("sslCertPathSet")
+ );
+ const key = !!(
+ ds.sslKey ||
+ ds.sslKeyPath ||
+ retained("sslKeySet") ||
+ retained("sslKeyPathSet")
+ );
+ if (cert !== key) {
+ errors.sslCert =
+ errors.sslCertPath =
+ errors.sslKey =
+ errors.sslKeyPath =
+ "tls-pair";
+ }
+ }
+ if (
+ [Engine.MYSQL, Engine.MARIADB, Engine.OCEANBASE, Engine.TIDB].includes(
+ engine
+ )
+ ) {
+ for (const key of Object.keys(ds.extraConnectionParameters ?? {})) {
+ if (key.trim().toLowerCase() === "allowallfiles")
+ errors[`extraConnectionParameters.${key}`] = "forbidden-parameter";
+ }
+ }
+ return errors;
+}
diff --git a/frontend/src/components/ui/input.tsx b/frontend/src/components/ui/input.tsx
index 37286c09ed..1136aa2fa6 100644
--- a/frontend/src/components/ui/input.tsx
+++ b/frontend/src/components/ui/input.tsx
@@ -9,6 +9,7 @@ const inputVariants = cva(
cn(
"flex w-full rounded-xs border border-control-border bg-transparent text-main transition-colors",
"placeholder:text-control-placeholder",
+ "aria-invalid:border-error",
"focus:outline-hidden",
"disabled:cursor-not-allowed disabled:bg-control-bg disabled:opacity-50",
"read-only:cursor-default read-only:bg-control-bg read-only:focus:ring-0 read-only:focus:border-control-border"
diff --git a/frontend/src/components/ui/textarea.tsx b/frontend/src/components/ui/textarea.tsx
index 3a41c3c7fd..ba6ac3cb2f 100644
--- a/frontend/src/components/ui/textarea.tsx
+++ b/frontend/src/components/ui/textarea.tsx
@@ -8,6 +8,7 @@ const textareaVariants = cva(
cn(
"flex min-h-25 w-full rounded-xs border border-control-border bg-transparent text-main transition-colors",
"placeholder:text-control-placeholder",
+ "aria-invalid:border-error",
"focus:outline-hidden focus:ring-1 focus:ring-accent focus:border-accent",
"disabled:cursor-not-allowed disabled:bg-control-bg disabled:opacity-50"
)
diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.json
index 175702f4ea..6c0dac5638 100644
--- a/frontend/src/locales/en-US.json
+++ b/frontend/src/locales/en-US.json
@@ -1358,6 +1358,22 @@
"use-sample-instance": "Use sample instance (Available for 7 days)",
"use-sample-instance-self-host": "Use sample instance",
"users": "Users",
+ "validation": {
+ "absolute-path": "Enter an absolute path, starting with /.",
+ "aws-credential": "Enter an access key ID or a role ARN.",
+ "cloud-sql-host": "Enter the instance name as project:region:instance.",
+ "forbidden-parameter": "The allowAllFiles parameter is not allowed because it exposes files on the Bytebase server.",
+ "gcp-instance": "Use lowercase letters, numbers, or hyphens.",
+ "gcp-project": "Use lowercase letters, numbers, periods, colons, or hyphens.",
+ "keytab-resupply": "Upload the keytab again for the new connection destination.",
+ "oracle-service": "Enter a service name or SID.",
+ "pem-certificate": "Enter a PEM certificate, including the BEGIN and END CERTIFICATE lines.",
+ "pem-key": "Enter a PEM private key (PKCS#1, PKCS#8, or EC).",
+ "required": "This field is required.",
+ "specific-credential": "Provide specific credentials. Default credentials are unavailable in Bytebase Cloud.",
+ "tls-pair": "Provide both the client certificate and private key.",
+ "tls-source-conflict": "Use either PEM content or a file path, not both."
+ },
"your-snowflake-account-locator": "Your Snowflake account locator"
},
"issue": {
diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.json
index edec98cfac..21b769d854 100644
--- a/frontend/src/locales/es-ES.json
+++ b/frontend/src/locales/es-ES.json
@@ -1358,6 +1358,22 @@
"use-sample-instance": "Usar instancia de ejemplo (Disponible durante 7 días)",
"use-sample-instance-self-host": "Usar instancia de ejemplo",
"users": "Usuarios",
+ "validation": {
+ "absolute-path": "Introduce una ruta absoluta que comience por /.",
+ "aws-credential": "Introduce un ID de clave de acceso o un ARN de rol.",
+ "cloud-sql-host": "Introduce el nombre de la instancia como project:region:instance.",
+ "forbidden-parameter": "El parámetro allowAllFiles no está permitido porque expone archivos del servidor Bytebase.",
+ "gcp-instance": "Usa letras minúsculas, números o guiones.",
+ "gcp-project": "Usa letras minúsculas, números, puntos, dos puntos o guiones.",
+ "keytab-resupply": "Vuelve a cargar el archivo keytab para el nuevo destino de conexión.",
+ "oracle-service": "Introduce un nombre de servicio o SID.",
+ "pem-certificate": "Introduce un certificado PEM, incluidas las líneas BEGIN y END CERTIFICATE.",
+ "pem-key": "Introduce una clave privada PEM (PKCS#1, PKCS#8 o EC).",
+ "required": "Este campo es obligatorio.",
+ "specific-credential": "Proporciona credenciales específicas. Las credenciales predeterminadas no están disponibles en Bytebase Cloud.",
+ "tls-pair": "Proporciona tanto el certificado de cliente como la clave privada.",
+ "tls-source-conflict": "Usa contenido PEM o una ruta de archivo, pero no ambos."
+ },
"your-snowflake-account-locator": "Su localizador de cuentas Snowflake"
},
"issue": {
diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.json
index 775d87c5b9..635d4fcf87 100644
--- a/frontend/src/locales/ja-JP.json
+++ b/frontend/src/locales/ja-JP.json
@@ -1358,6 +1358,22 @@
"use-sample-instance": "サンプルインスタンスを使用する(7日間利用可能)",
"use-sample-instance-self-host": "サンプルインスタンスを使用する",
"users": "ユーザー",
+ "validation": {
+ "absolute-path": "/ で始まる絶対パスを入力してください。",
+ "aws-credential": "アクセスキー ID またはロール ARN を入力してください。",
+ "cloud-sql-host": "インスタンス名を project:region:instance の形式で入力してください。",
+ "forbidden-parameter": "allowAllFiles パラメーターは Bytebase サーバーのファイルを公開するため使用できません。",
+ "gcp-instance": "小文字、数字、ハイフンを使用してください。",
+ "gcp-project": "小文字、数字、ピリオド、コロン、ハイフンを使用してください。",
+ "keytab-resupply": "接続先が変更されたため、keytab ファイルを再度アップロードしてください。",
+ "oracle-service": "サービス名または SID を入力してください。",
+ "pem-certificate": "BEGIN および END CERTIFICATE 行を含む PEM 形式の証明書を入力してください。",
+ "pem-key": "PEM 形式の秘密鍵(PKCS#1、PKCS#8、または EC)を入力してください。",
+ "required": "この項目は必須です。",
+ "specific-credential": "認証情報を指定してください。Bytebase Cloud ではデフォルトの認証情報を使用できません。",
+ "tls-pair": "クライアント証明書と秘密鍵の両方を指定してください。",
+ "tls-source-conflict": "PEM の内容またはファイルパスのいずれか一方を使用してください。"
+ },
"your-snowflake-account-locator": "Snowflake アカウント ロケーター"
},
"issue": {
diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.json
index eca49fdf98..30550a1ed7 100644
--- a/frontend/src/locales/vi-VN.json
+++ b/frontend/src/locales/vi-VN.json
@@ -1358,6 +1358,22 @@
"use-sample-instance": "Sử dụng phiên bản mẫu (Có sẵn trong 7 ngày)",
"use-sample-instance-self-host": "Sử dụng phiên bản mẫu",
"users": "Người dùng",
+ "validation": {
+ "absolute-path": "Nhập đường dẫn tuyệt đối bắt đầu bằng /.",
+ "aws-credential": "Nhập ID khóa truy cập hoặc ARN của vai trò.",
+ "cloud-sql-host": "Nhập tên phiên bản theo định dạng project:region:instance.",
+ "forbidden-parameter": "Tham số allowAllFiles không được phép vì làm lộ các tệp trên máy chủ Bytebase.",
+ "gcp-instance": "Sử dụng chữ thường, số hoặc dấu gạch nối.",
+ "gcp-project": "Sử dụng chữ thường, số, dấu chấm, dấu hai chấm hoặc dấu gạch nối.",
+ "keytab-resupply": "Tải lại tệp keytab cho đích kết nối mới.",
+ "oracle-service": "Nhập tên dịch vụ hoặc SID.",
+ "pem-certificate": "Nhập chứng chỉ PEM, bao gồm các dòng BEGIN và END CERTIFICATE.",
+ "pem-key": "Nhập khóa riêng PEM (PKCS#1, PKCS#8 hoặc EC).",
+ "required": "Trường này là bắt buộc.",
+ "specific-credential": "Cung cấp thông tin xác thực cụ thể. Bytebase Cloud không hỗ trợ thông tin xác thực mặc định.",
+ "tls-pair": "Cung cấp cả chứng chỉ máy khách và khóa riêng.",
+ "tls-source-conflict": "Sử dụng nội dung PEM hoặc đường dẫn tệp, không dùng cả hai."
+ },
"your-snowflake-account-locator": "Định vị tài khoản Snowflake của bạn"
},
"issue": {
diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.json
index 6a32c75f61..4ea9820cb2 100644
--- a/frontend/src/locales/zh-CN.json
+++ b/frontend/src/locales/zh-CN.json
@@ -1358,6 +1358,22 @@
"use-sample-instance": "使用示例实例(可用 7 天)",
"use-sample-instance-self-host": "使用示例实例",
"users": "用户",
+ "validation": {
+ "absolute-path": "请输入以 / 开头的绝对路径。",
+ "aws-credential": "请输入访问密钥 ID 或角色 ARN。",
+ "cloud-sql-host": "请输入格式为 project:region:instance 的实例名称。",
+ "forbidden-parameter": "不允许使用 allowAllFiles 参数,因为它会暴露 Bytebase 服务器上的文件。",
+ "gcp-instance": "请使用小写字母、数字或连字符。",
+ "gcp-project": "请使用小写字母、数字、句点、冒号或连字符。",
+ "keytab-resupply": "连接目标已更改,请重新上传 keytab 文件。",
+ "oracle-service": "请输入服务名称或 SID。",
+ "pem-certificate": "请输入 PEM 格式的证书,包含 BEGIN 和 END CERTIFICATE 行。",
+ "pem-key": "请输入 PEM 格式的私钥(PKCS#1、PKCS#8 或 EC)。",
+ "required": "此字段为必填项。",
+ "specific-credential": "请提供指定凭证。Bytebase Cloud 不支持默认凭证。",
+ "tls-pair": "请同时提供客户端证书和私钥。",
+ "tls-source-conflict": "请选择 PEM 内容或文件路径,不可同时使用。"
+ },
"your-snowflake-account-locator": "您的 Snowflake 账户定位符"
},
"issue": {