Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
fix(instance): ask for the keytab in the form, not through a failed connection (#21175)
Vincent Huang51a6764910d1
diff --git a/frontend/src/components/instance/DataSourceForm.tsx b/frontend/src/components/instance/DataSourceForm.tsxindex 3e7d8ce0fd..42a71c3df8 100644--- a/frontend/src/components/instance/DataSourceForm.tsx+++ b/frontend/src/components/instance/DataSourceForm.tsx@@ -8,10 +8,12 @@ import { Checkbox } from "@/components/ui/checkbox";import {FormControlGroup,FormControlRow,+ FormError,FormField,} from "@/components/ui/form";import { Input } from "@/components/ui/input";import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";+import { cn } from "@/lib/utils";import { useAppStore } from "@/stores/app";import { Engine } from "@/types/proto-es/v1/common_pb";import {@@ -92,7 +94,7 @@ export function DataSourceForm({optionsOnly = false,onDataSourceChange,onOpenInfoPanel,-}: DataSourceFormProps) {+}: Readonly<DataSourceFormProps>) {const { t } = useTranslation();const currentPlan = useAppStore((s) => s.currentPlan());const isSaaSMode = useAppStore((s) => s.isSaaSMode());@@ -107,6 +109,7 @@ export function DataSourceForm({hasReadonlyReplicaFeature,setMissingFeature,hideAdvancedFeatures,+ needsKeytabResupply,} = ctx;const {@@ -522,6 +525,10 @@ export function DataSourceForm({const [keytabFileName, setKeytabFileName] = useState("");+ // The stored keytab cannot follow the data source to a new destination, so+ // the operator has to upload it again before this edit can be saved.+ const keytabResupplyRequired = needsKeytabResupply(dataSource);+const handleKeytabUpload = (e: React.ChangeEvent<HTMLInputElement>) => {const file = e.target.files?.[0];if (!file) return;@@ -660,7 +667,8 @@ export function DataSourceForm({className="sm:col-span-3 sm:col-start-1"title={<>- Principal <span className="text-error">*</span>+ {t("instance.kerberos-principal")}{" "}+ <span className="text-error">*</span></>}>@@ -671,7 +679,7 @@ export function DataSourceForm({dataSource.saslConfig.mechanism.value.primary ?? ""}disabled={!allowEdit}- placeholder="primary"+ placeholder={t("instance.kerberos-primary-placeholder")}onChange={(e) => {const updated = { ...dataSource };if (@@ -692,7 +700,9 @@ export function DataSourceForm({dataSource.saslConfig.mechanism.value.instance ?? ""}disabled={!allowEdit}- placeholder="instance, optional"+ placeholder={t(+ "instance.kerberos-instance-placeholder"+ )}onChange={(e) => {const updated = { ...dataSource };if (@@ -713,7 +723,7 @@ export function DataSourceForm({dataSource.saslConfig.mechanism.value.realm ?? ""}disabled={!allowEdit}- placeholder="realm"+ placeholder={t("instance.kerberos-realm-placeholder")}onChange={(e) => {const updated = { ...dataSource };if (@@ -731,7 +741,8 @@ export function DataSourceForm({className="sm:col-span-3 sm:col-start-1"title={<>- KDC <span className="text-error">*</span>+ {t("instance.kerberos-kdc")}{" "}+ <span className="text-error">*</span></>}>@@ -769,7 +780,9 @@ export function DataSourceForm({dataSource.saslConfig.mechanism.value.kdcHost ?? ""}disabled={!allowEdit}- placeholder="KDC host"+ placeholder={t(+ "instance.kerberos-kdc-host-placeholder"+ )}onChange={(e) => {const updated = { ...dataSource };if (@@ -790,7 +803,9 @@ export function DataSourceForm({dataSource.saslConfig.mechanism.value.kdcPort ?? ""}disabled={!allowEdit}- placeholder="KDC port, optional"+ placeholder={t(+ "instance.kerberos-kdc-port-placeholder"+ )}onChange={(e) => {if (e.target.value &&@@ -813,8 +828,9 @@ export function DataSourceForm({className="sm:col-span-3 sm:col-start-1"title={<>- Keytab File- {dataSource.pendingCreate && (+ {t("instance.keytab-file")}+ {(dataSource.pendingCreate ||+ keytabResupplyRequired) && (<>{" "}<span className="text-error">*</span>@@ -823,7 +839,12 @@ export function DataSourceForm({</>}>- <div className="mt-3 border-2 border-dashed rounded-lg p-6 text-center">+ <div+ className={cn(+ "mt-3 border-2 border-dashed rounded-lg p-6 text-center",+ keytabResupplyRequired && "border-error"+ )}+ ><inputtype="file"accept=".keytab"@@ -835,7 +856,7 @@ export function DataSourceForm({htmlFor="keytab-upload"className="cursor-pointer textinfolabel">- Click or Drag your .keytab file here+ {t("instance.keytab-upload-placeholder")}</label>{keytabFileName && (<p className="mt-2 textinfolabel truncate">@@ -843,11 +864,18 @@ export function DataSourceForm({</p>)}</div>- {!dataSource.pendingCreate && (+ {/* The write-only hint offers to keep the stored keytab,+ which is the offer the resupply error withdraws. */}+ {!dataSource.pendingCreate && !keytabResupplyRequired && (<p className="mt-1 textinfolabel">{t("instance.keytab-write-only")}</p>)}+ {keytabResupplyRequired && (+ <FormError className="mt-1">+ {t("instance.keytab-resupply-required")}+ </FormError>+ )}</FormField></>)}diff --git a/frontend/src/components/instance/DataSourceSection.test.tsx b/frontend/src/components/instance/DataSourceSection.test.tsxnew file mode 100644index 0000000000..2cc0bdfdcb--- /dev/null+++ b/frontend/src/components/instance/DataSourceSection.test.tsx@@ -0,0 +1,187 @@+import { create } from "@bufbuild/protobuf";+import { act } from "react";+import { createRoot } from "react-dom/client";+import { beforeEach, describe, expect, test, vi } from "vitest";+import { Engine } from "@/types/proto-es/v1/common_pb";+import {+ DataSourceSchema,+ DataSourceType,+ InstanceSchema,+} from "@/types/proto-es/v1/instance_service_pb";+import type { EditDataSource } from "./common";+import { DataSourceSection } from "./DataSourceSection";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++const mocks = vi.hoisted(() => ({+ context: undefined as Record<string, unknown> | undefined,+ checkDataSource: vi.fn((_dataSources: EditDataSource[]) => true),+}));++vi.mock("react-i18next", () => ({+ initReactI18next: { type: "3rdParty", init: () => {} },+ useTranslation: () => ({ t: (key: string) => key }),+}));++vi.mock("@/lib/i18n", () => ({+ default: { t: (key: string) => key },+}));++vi.mock("./InstanceFormContext", () => ({+ useInstanceFormContext: () => mocks.context,+}));++vi.mock("./DataSourceForm", () => ({+ DataSourceForm: ({ dataSource }: { dataSource: EditDataSource }) => (+ <div data-testid="data-source-form" data-id={dataSource.id} />+ ),+}));++vi.mock("@/components/ui/alert", () => ({+ Alert: ({ description }: { description: React.ReactNode }) => (+ <div>{description}</div>+ ),+}));++vi.mock("@/components/ui/button", () => ({+ Button: ({ children }: { children: React.ReactNode }) => (+ <button type="button">{children}</button>+ ),+}));++vi.mock("@/stores/app", () => ({+ useAppStore: { getState: () => ({ deleteDataSource: vi.fn() }) },+}));++vi.mock("@/types", () => ({+ DATASOURCE_READONLY_USER_NAME: "bytebase_readonly",+}));++const editDataSource = (+ id: string,+ type: DataSourceType,+ host: string+): EditDataSource => ({+ ...create(DataSourceSchema, { id, type, host, port: "10000" }),+ pendingCreate: false,+ updatedPassword: "",+ updatedMasterPassword: "",+ updatedToken: "",+});++const adminDataSource = editDataSource(+ "admin",+ DataSourceType.ADMIN,+ "hive.example.com"+);+const readonlyDataSource = editDataSource(+ "readonly",+ DataSourceType.READ_ONLY,+ "hive-replica.example.com"+);++beforeEach(() => {+ vi.clearAllMocks();+ mocks.checkDataSource.mockImplementation(() => true);+ mocks.context = {+ instance: create(InstanceSchema, { name: "instances/hive" }),+ isCreating: false,+ allowEdit: true,+ basicInfo: create(InstanceSchema, { engine: Engine.HIVE }),+ dataSourceEditState: {+ dataSources: [adminDataSource, readonlyDataSource],+ editingDataSourceId: "admin",+ },+ setDataSourceEditState: vi.fn(),+ adminDataSource,+ editingDataSource: adminDataSource,+ readonlyDataSourceList: [readonlyDataSource],+ hasReadOnlyDataSource: true,+ hasPermission: () => true,+ checkDataSource: mocks.checkDataSource,+ isEditing: true,+ };+});++const renderSection = async () => {+ const container = document.createElement("div");+ const root = createRoot(container);+ await act(async () => {+ root.render(<DataSourceSection />);+ });+ const tabs = Array.from(container.querySelectorAll("button")).filter(+ (button) =>+ button.textContent?.startsWith("common.admin") ||+ button.textContent?.startsWith("common.read-only")+ );+ return {+ unmount: () =>+ act(() => {+ root.unmount();+ }),+ tabs: tabs.map((button) => ({+ label: button.textContent ?? "",+ marked: button.querySelector(".text-error") !== null,+ described:+ button.querySelector(".text-error")?.textContent?.includes(+ "instance.open-data-source"+ ) ?? false,+ })),+ };+};++// A data source that fails the check disables Update from any tab, but only+// the open tab renders its own errors. Without the marker the operator sees a+// dead button and nothing else — the silent failure this whole gate replaces.+describe("DataSourceSection incomplete markers", () => {+ test("marks no tab while every data source passes the check", async () => {+ const { tabs, unmount } = await renderSection();++ expect(tabs).toHaveLength(2);+ expect(tabs.every((tab) => tab.marked)).toBe(false);++ unmount();+ });++ test("marks the failing tab, and only that one", async () => {+ mocks.checkDataSource.mockImplementation(+ ([ds]: EditDataSource[]) => ds.id !== "readonly"+ );++ const { tabs, unmount } = await renderSection();++ expect(tabs.map((tab) => tab.marked)).toEqual([false, true]);+ // Every data source is asked about itself, never about the whole list.+ for (const call of mocks.checkDataSource.mock.calls) {+ expect(call[0]).toHaveLength(1);+ }++ unmount();+ });++ // Nothing to save means no Update button to explain.+ test("marks nothing while the form is unedited", async () => {+ mocks.checkDataSource.mockImplementation(() => false);+ mocks.context = { ...mocks.context, isEditing: false };++ const { tabs, unmount } = await renderSection();++ expect(tabs.some((tab) => tab.marked)).toBe(false);++ unmount();+ });++ // A bare asterisk in an error color says a tab is wrong to whoever can see+ // both, and nothing to anyone else.+ test("the marker carries text, not just a color", async () => {+ mocks.checkDataSource.mockImplementation(() => false);++ const { tabs, unmount } = await renderSection();++ expect(tabs.every((tab) => tab.described)).toBe(true);++ unmount();+ });+});diff --git a/frontend/src/components/instance/DataSourceSection.tsx b/frontend/src/components/instance/DataSourceSection.tsxindex 56faada0f8..c0d1f04f2b 100644--- a/frontend/src/components/instance/DataSourceSection.tsx+++ b/frontend/src/components/instance/DataSourceSection.tsx@@ -36,8 +36,20 @@ export function DataSourceSection({readonlyDataSourceList,hasReadOnlyDataSource,hasPermission,+ checkDataSource,+ isEditing,} = ctx;+ // Only the open tab renders its own field errors, and any data source that+ // fails the check disables Update from anywhere. Say which tab to open —+ // while there is an edit to save, which is when those buttons are on screen.+ const incompleteMarker = (ds: EditDataSource) =>+ !isEditing || checkDataSource([ds]) ? null : (+ <span className="ml-1 text-error" title={t("instance.open-data-source")}>+ *<span className="sr-only"> {t("instance.open-data-source")}</span>+ </span>+ );+const allowUpdate = hasPermission("bb.instances.update");const handleCreateRODataSource = useCallback(() => {@@ -151,6 +163,7 @@ export function DataSourceSection({onClick={() => handleTabChange(adminDataSource.id)}>{t("common.admin")}+ {incompleteMarker(adminDataSource)}</button>{readonlyDataSourceList.map((ds) => (<div key={ds.id} className="flex items-center">@@ -164,6 +177,7 @@ export function DataSourceSection({onClick={() => handleTabChange(ds.id)}>{t("common.read-only")}+ {incompleteMarker(ds)}</button>{hasReadOnlyDataSource && (<buttondiff --git a/frontend/src/components/instance/InstanceFormButtons.test.tsx b/frontend/src/components/instance/InstanceFormButtons.test.tsxindex 517c1a5177..27f19cf3ec 100644--- a/frontend/src/components/instance/InstanceFormButtons.test.tsx+++ b/frontend/src/components/instance/InstanceFormButtons.test.tsx@@ -504,4 +504,73 @@ describe("InstanceFormButtons", () => {root.unmount();});});++ // Pins the contract every field-level validation in this form rests on:+ // failing checkDataSource is what keeps a data source away from the+ // connection test, so the operator reads the form's own message instead of a+ // connection failure. The keytab resupply gate is one caller of it; this+ // test covers the wiring, not that gate — InstanceFormContext.test.tsx+ // covers which data sources checkDataSource fails.+ test("a failing data source check keeps both save actions off the connection test", async () => {+ const adminDataSource = create(DataSourceSchema, {+ id: "admin",+ type: DataSourceType.ADMIN,+ host: "prod.example.com",+ port: "5432",+ });+ const editState = {+ ...adminDataSource,+ pendingCreate: false,+ updatedPassword: "",+ updatedMasterPassword: "",+ updatedToken: "",+ };+ mocks.context = {+ ...mocks.context,+ instance: create(InstanceSchema, {+ name: "instances/prod",+ title: "Production",+ engine: Engine.POSTGRES,+ dataSources: [adminDataSource],+ }),+ isCreating: false,+ adminDataSource: editState,+ editingDataSource: editState,+ checkDataSource: vi.fn(() => false),+ valueChanged: true,+ };+ const context = mocks.context as {+ testConnection: ReturnType<typeof vi.fn>;+ };++ const container = document.createElement("div");+ const root = createRoot(container);++ await act(async () => {+ root.render(<InstanceFormButtons />);+ });++ const buttons = Array.from(container.querySelectorAll("button"));+ const updateButton = buttons.find((button) =>+ button.textContent?.includes("common.update")+ ) as HTMLButtonElement;+ const testConnectionButton = buttons.find((button) =>+ button.textContent?.includes("instance.test-connection")+ ) as HTMLButtonElement;++ expect(updateButton.disabled).toBe(true);+ expect(testConnectionButton.disabled).toBe(true);++ await act(async () => {+ updateButton.click();+ testConnectionButton.click();+ await flushPromises();+ });++ expect(context.testConnection).not.toHaveBeenCalled();++ await act(async () => {+ root.unmount();+ });+ });});diff --git a/frontend/src/components/instance/InstanceFormContext.test.tsx b/frontend/src/components/instance/InstanceFormContext.test.tsxindex 7aab904a03..d3e0294597 100644--- a/frontend/src/components/instance/InstanceFormContext.test.tsx+++ b/frontend/src/components/instance/InstanceFormContext.test.tsx@@ -4,6 +4,7 @@ import { act } from "react";import { createRoot } from "react-dom/client";import { beforeEach, describe, expect, test, vi } from "vitest";import { Engine, State } from "@/types/proto-es/v1/common_pb";+import type { DataSource } from "@/types/proto-es/v1/instance_service_pb";import {DataSource_AuthenticationType,DataSource_AWSCredentialSchema,@@ -14,6 +15,7 @@ import {import { ProjectSchema } from "@/types/proto-es/v1/project_service_pb";import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";import { unknownInstance } from "@/types/v1/instance";+import type { EditDataSource } from "./common";import { wrapEditDataSource } from "./common";import {InstanceFormProvider,@@ -459,4 +461,180 @@ describe("InstanceFormProvider", () => {harness.unmount();});});++ // The server refuses to carry a stored Kerberos keytab to a destination the+ // caller moved, so the form has to fail the data source before it offers to+ // save it — otherwise the refusal arrives as a connection failure.+ describe("checkDataSource Kerberos keytab resupply", () => {+ const storedDataSource = create(DataSourceSchema, {+ id: "admin",+ type: DataSourceType.ADMIN,+ host: "hive.example.com",+ port: "10000",+ saslConfig: {+ mechanism: {+ case: "krbConfig",+ value: {+ primary: "bytebase",+ realm: "EXAMPLE.COM",+ kdcHost: "kdc.example.com",+ kdcPort: "88",+ },+ },+ },+ });++ const editedDataSource = (edit: (ds: EditDataSource) => void) => {+ const ds = wrapEditDataSource(storedDataSource);+ edit(ds);+ return ds;+ };++ const movedHost = () =>+ editedDataSource((ds) => {+ ds.host = "hive-2.example.com";+ });++ const KeytabProbe = () => {+ const ctx = useInstanceFormContext();+ return (+ <div+ data-username-only={String(+ ctx.checkDataSource([+ editedDataSource((ds) => {+ ds.username = "hive";+ }),+ ])+ )}+ data-moved-host={String(ctx.checkDataSource([movedHost()]))}+ data-moved-kdc={String(+ ctx.checkDataSource([+ editedDataSource((ds) => {+ if (ds.saslConfig?.mechanism?.case === "krbConfig") {+ ds.saslConfig.mechanism.value.kdcHost = "kdc-2.example.com";+ }+ }),+ ])+ )}+ data-moved-with-keytab={String(+ ctx.checkDataSource([+ editedDataSource((ds) => {+ ds.host = "hive-2.example.com";+ if (ds.saslConfig?.mechanism?.case === "krbConfig") {+ ds.saslConfig.mechanism.value.keytab = new Uint8Array([5, 2]);+ }+ }),+ ])+ )}+ data-needs-resupply={String(ctx.needsKeytabResupply(movedHost()))}+ />+ );+ };++ test("a moved destination fails the data source until the keytab is uploaded again", async () => {+ const harness = renderIntoContainer();++ await harness.render(+ <InstanceFormProvider+ instance={create(InstanceSchema, {+ name: "instances/hive",+ title: "Hive",+ engine: Engine.HIVE,+ environment: "environments/prod",+ dataSources: [storedDataSource],+ })}+ >+ <KeytabProbe />+ </InstanceFormProvider>+ );++ const probe = harness.container.firstElementChild as HTMLElement;+ expect(probe.dataset.usernameOnly).toBe("true");+ expect(probe.dataset.movedHost).toBe("false");+ expect(probe.dataset.movedKdc).toBe("false");+ expect(probe.dataset.movedWithKeytab).toBe("true");+ expect(probe.dataset.needsResupply).toBe("true");++ harness.unmount();+ });++ const ResupplyProbe = ({ build }: { build: () => EditDataSource }) => {+ const ctx = useInstanceFormContext();+ return <div data-needs-resupply={String(ctx.needsKeytabResupply(build()))} />;+ };++ const renderWithStored = async (+ stored: DataSource[],+ build: () => EditDataSource+ ) => {+ const harness = renderIntoContainer();+ await harness.render(+ <InstanceFormProvider+ instance={create(InstanceSchema, {+ name: "instances/hive",+ title: "Hive",+ engine: Engine.HIVE,+ environment: "environments/prod",+ dataSources: stored,+ })}+ >+ <ResupplyProbe build={build} />+ </InstanceFormProvider>+ );+ const probe = harness.container.firstElementChild as HTMLElement;+ const result = probe.dataset.needsResupply;+ harness.unmount();+ return result;+ };++ // The comparison runs on what the form would send, not on the edit state,+ // because that is what the server merges and then compares.+ test("the port the form fills in for the engine counts as a move", async () => {+ const withoutPort = create(DataSourceSchema, {+ ...storedDataSource,+ port: "",+ });+ expect(+ await renderWithStored([withoutPort], () =>+ wrapEditDataSource(withoutPort)+ )+ ).toBe("true");+ });++ test("an SSH tunnel the form drops for the engine counts as a move", async () => {+ const withTunnel = create(DataSourceSchema, {+ ...storedDataSource,+ sshHost: "bastion.example.com",+ sshPort: "22",+ });+ expect(+ await renderWithStored([withTunnel], () =>+ wrapEditDataSource(withTunnel)+ )+ ).toBe("true");+ });++ // checkDataSource runs over every data source, so the stored record has to+ // be the one with the same ID rather than whichever comes first.+ test("each data source is compared against its own stored record", async () => {+ const readonlyDataSource = create(DataSourceSchema, {+ ...storedDataSource,+ id: "readonly",+ type: DataSourceType.READ_ONLY,+ host: "hive-replica.example.com",+ });+ expect(+ await renderWithStored([storedDataSource, readonlyDataSource], () =>+ wrapEditDataSource(readonlyDataSource)+ )+ ).toBe("false");+ expect(+ await renderWithStored([storedDataSource, readonlyDataSource], () => {+ const ds = wrapEditDataSource(readonlyDataSource);+ ds.host = "hive-replica-2.example.com";+ return ds;+ })+ ).toBe("true");+ });+ });});diff --git a/frontend/src/components/instance/InstanceFormContext.tsx b/frontend/src/components/instance/InstanceFormContext.tsxindex 853d22920f..e893278604 100644--- a/frontend/src/components/instance/InstanceFormContext.tsx+++ b/frontend/src/components/instance/InstanceFormContext.tsx@@ -48,6 +48,8 @@ import {calcDataSourceUpdateMask,extractBasicInfo,extractDataSourceEditState,+ krbConfigOf,+ movesKeytabToNewDestination,} from "./common";import { effectivePortForEngine } from "./constants";import { hasInstancePermission } from "./permission";@@ -104,6 +106,7 @@ export interface InstanceFormContextValue {labelErrors: string[];setLabelErrors: React.Dispatch<React.SetStateAction<string[]>>;checkDataSource: (dataSources: EditDataSource[]) => boolean;+ needsKeytabResupply: (dataSource: EditDataSource) => boolean;resetDataSource: () => void;extractDataSourceFromEdit: (engine: Engine,@@ -278,6 +281,68 @@ export function InstanceFormProvider({[basicInfo.environment, environmentList]);+ const extractDataSourceFromEdit = useCallback(+ (engine: Engine, edit: EditDataSource): DataSource => {+ const ds = cloneDeep(+ omit(+ edit,+ "pendingCreate",+ "updatedPassword",+ "useEmptyPassword",+ "updatedMasterPassword",+ "useEmptyMasterPassword",+ "updatedToken",+ "updateSsl"+ )+ );+ if (edit.updatedPassword) ds.password = edit.updatedPassword;+ if (edit.useEmptyPassword) ds.password = "";+ if (edit.updatedMasterPassword)+ ds.masterPassword = edit.updatedMasterPassword;+ if (edit.useEmptyMasterPassword) ds.masterPassword = "";+ if (edit.updatedToken) ds.authenticationPrivateKey = edit.updatedToken;+ ds.port = effectivePortForEngine(engine, ds.port, ds.srv);+ if (!specs.showDatabase) ds.database = "";+ if (engine !== Engine.ORACLE) {+ ds.sid = "";+ ds.serviceName = "";+ }+ if (engine !== Engine.MONGODB) {+ ds.srv = false;+ ds.authenticationDatabase = "";+ }+ if (!specs.showSSH) {+ ds.sshHost = "";+ ds.sshPort = "";+ ds.sshUser = "";+ ds.sshPassword = "";+ ds.sshPrivateKey = "";+ }+ if (!specs.showSSL) {+ ds.sslCa = "";+ ds.sslCert = "";+ ds.sslKey = "";+ }+ return ds;+ },+ [specs]+ );++ // Asks movesKeytabToNewDestination about one data source of the form,+ // resolving both sides it compares: the stored data source by ID, and the+ // value this edit would send. The Kerberos filter comes first so that an+ // ordinary data source never pays for that extraction.+ const needsKeytabResupply = useCallback(+ (ds: EditDataSource): boolean => {+ if (!krbConfigOf(ds)) return false;+ return movesKeytabToNewDestination(+ extractDataSourceFromEdit(basicInfo.engine, ds),+ instance?.dataSources.find((d) => d.id === ds.id)+ );+ },+ [basicInfo.engine, extractDataSourceFromEdit, instance]+ );+const checkDataSource = useCallback((dataSources: EditDataSource[]) => {return dataSources.every((ds) => {@@ -306,8 +371,8 @@ export function InstanceFormProvider({// create; on edit, an empty updatedToken means "keep existing token".if (ds.pendingCreate && !ds.updatedToken) return false;}- if (ds.saslConfig?.mechanism?.case === "krbConfig") {- const krbConfig = ds.saslConfig.mechanism.value;+ const krbConfig = krbConfigOf(ds);+ if (krbConfig) {if (!krbConfig.primary || !krbConfig.realm || !krbConfig.kdcHost) {return false;}@@ -316,6 +381,11 @@ export function InstanceFormProvider({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) {@@ -355,7 +425,7 @@ export function InstanceFormProvider({return true;});},- [basicInfo.engine]+ [basicInfo.engine, needsKeytabResupply]);const allowCreate = useMemo(() => {@@ -400,53 +470,6 @@ export function InstanceFormProvider({setDataSourceEditState(extractDataSourceEditState(instance));}, [instance]);- const extractDataSourceFromEdit = useCallback(- (engine: Engine, edit: EditDataSource): DataSource => {- const ds = cloneDeep(- omit(- edit,- "pendingCreate",- "updatedPassword",- "useEmptyPassword",- "updatedMasterPassword",- "useEmptyMasterPassword",- "updatedToken",- "updateSsl"- )- );- if (edit.updatedPassword) ds.password = edit.updatedPassword;- if (edit.useEmptyPassword) ds.password = "";- if (edit.updatedMasterPassword)- ds.masterPassword = edit.updatedMasterPassword;- if (edit.useEmptyMasterPassword) ds.masterPassword = "";- if (edit.updatedToken) ds.authenticationPrivateKey = edit.updatedToken;- ds.port = effectivePortForEngine(engine, ds.port, ds.srv);- if (!specs.showDatabase) ds.database = "";- if (engine !== Engine.ORACLE) {- ds.sid = "";- ds.serviceName = "";- }- if (engine !== Engine.MONGODB) {- ds.srv = false;- ds.authenticationDatabase = "";- }- if (!specs.showSSH) {- ds.sshHost = "";- ds.sshPort = "";- ds.sshUser = "";- ds.sshPassword = "";- ds.sshPrivateKey = "";- }- if (!specs.showSSL) {- ds.sslCa = "";- ds.sslCert = "";- ds.sslKey = "";- }- return ds;- },- [specs]- );-// Debounced to avoid expensive cloneDeep + extraction on every keystroke.const [pendingCreateInstance, setPendingCreateInstance] = useState<Instance>(() => create(InstanceSchema, {})@@ -642,6 +665,7 @@ export function InstanceFormProvider({labelErrors,setLabelErrors,checkDataSource,+ needsKeytabResupply,resetDataSource,extractDataSourceFromEdit,testConnection,@@ -676,6 +700,7 @@ export function InstanceFormProvider({resourceIdValidated,labelErrors,checkDataSource,+ needsKeytabResupply,resetDataSource,extractDataSourceFromEdit,testConnection,diff --git a/frontend/src/components/instance/common.test.ts b/frontend/src/components/instance/common.test.tsindex 8aec784859..f3589a81c4 100644--- a/frontend/src/components/instance/common.test.ts+++ b/frontend/src/components/instance/common.test.ts@@ -1,5 +1,13 @@+import { create, type MessageInitShape } from "@bufbuild/protobuf";import { describe, expect, test } from "vitest";import { Engine } from "@/types/proto-es/v1/common_pb";+import type { DataSource } from "@/types/proto-es/v1/instance_service_pb";+import {+ DataSourceSchema,+ KerberosConfigSchema,+ SASLConfigSchema,+} from "@/types/proto-es/v1/instance_service_pb";+import { movesKeytabToNewDestination } from "./common";import {applyLocalTlsCaSource,applyLocalTlsClientCertSource,@@ -189,3 +197,226 @@ describe("TLS posture helpers", () => {expect(isLocalTlsClientIdentitySupported(Engine.POSTGRES)).toBe(true);});});++const KEYTAB = new Uint8Array([0x05, 0x02, 0x00, 0x00]);++const kerberosDataSource = (+ overrides: MessageInitShape<typeof DataSourceSchema> = {},+ krbOverrides: MessageInitShape<typeof KerberosConfigSchema> = {}+): DataSource =>+ create(DataSourceSchema, {+ id: "admin",+ host: "hive.example.com",+ port: "10000",+ username: "bytebase",+ ...overrides,+ saslConfig: create(SASLConfigSchema, {+ mechanism: {+ case: "krbConfig",+ value: create(KerberosConfigSchema, {+ primary: "bytebase",+ realm: "EXAMPLE.COM",+ kdcHost: "kdc.example.com",+ kdcPort: "88",+ kdcTransportProtocol: "tcp",+ ...krbOverrides,+ }),+ },+ }),+ });++describe("Kerberos keytab resupply", () => {+ const stored = kerberosDataSource();++ test("an edit that keeps the destination inherits the stored keytab", () => {+ expect(+ movesKeytabToNewDestination(+ kerberosDataSource({ username: "hive" }),+ stored+ )+ ).toBe(false);+ });++ test.each([+ ["host", kerberosDataSource({ host: "hive-2.example.com" })],+ ["port", kerberosDataSource({ port: "10001" })],+ [+ "additional_addresses",+ kerberosDataSource({+ additionalAddresses: [{ host: "hive-2.example.com", port: "10000" }],+ }),+ ],+ ["ssh_host", kerberosDataSource({ sshHost: "bastion.example.com" })],+ ["ssh_port", kerberosDataSource({ sshPort: "22" })],+ [+ "extra_connection_parameters",+ kerberosDataSource({+ extraConnectionParameters: { host: "hive-2.example.com" },+ }),+ ],+ ["kdc_host", kerberosDataSource({}, { kdcHost: "kdc-2.example.com" })],+ ["kdc_port", kerberosDataSource({}, { kdcPort: "8888" })],+ ])("moving %s requires the keytab again", (_field, editing) => {+ expect(movesKeytabToNewDestination(editing, stored)).toBe(true);+ });++ test.each([+ ["realm", kerberosDataSource({}, { realm: "OTHER.EXAMPLE.COM" })],+ ["primary", kerberosDataSource({}, { primary: "hive" })],+ [+ "kdc_transport_protocol",+ kerberosDataSource({}, { kdcTransportProtocol: "udp" }),+ ],+ ["database", kerberosDataSource({ database: "warehouse" })],+ ])("changing %s leaves the destination alone", (_field, editing) => {+ expect(movesKeytabToNewDestination(editing, stored)).toBe(false);+ });++ test("a re-uploaded keytab clears the requirement", () => {+ expect(+ movesKeytabToNewDestination(+ kerberosDataSource({ host: "hive-2.example.com" }, { keytab: KEYTAB }),+ stored+ )+ ).toBe(false);+ });++ test("a data source that did not authenticate with Kerberos has no stored keytab", () => {+ const passwordDataSource = create(DataSourceSchema, {+ id: "admin",+ host: "hive.example.com",+ port: "10000",+ });+ expect(+ movesKeytabToNewDestination(+ kerberosDataSource({ host: "hive-2.example.com" }),+ passwordDataSource+ )+ ).toBe(false);+ expect(movesKeytabToNewDestination(passwordDataSource, stored)).toBe(false);+ });++ test("a data source with no stored counterpart is a create", () => {+ expect(+ movesKeytabToNewDestination(+ kerberosDataSource({ host: "hive-2.example.com" }),+ undefined+ )+ ).toBe(false);+ });+});++// Mirrors TestDataSourceDestinationClassifiesEveryField in+// backend/api/v1/instance_service_converter_test.go. dataSourceDestination is+// a projection, so a field added later is silently treated as "not a+// destination" — and if it carries an address, this copy stops seeing a move+// the server still refuses, which puts the refusal back in the connection+// dialog. This fails until the new field is named in one list or the other.+describe("Kerberos keytab resupply field classification", () => {+ const classify = (+ schema: { fields: readonly { name: string }[] },+ inDestination: string[],+ notDestination: string[]+ ) => {+ const listed = [...inDestination, ...notDestination];+ expect(new Set(listed).size).toBe(listed.length);+ const declared = schema.fields.map((field) => field.name);+ return {+ unclassified: declared.filter((name) => !listed.includes(name)),+ stale: listed.filter((name) => !declared.includes(name)),+ };+ };++ test("every DataSource field is either an address or explained", () => {+ const { unclassified, stale } = classify(+ DataSourceSchema,+ [+ "host",+ "port",+ "additional_addresses",+ "ssh_host",+ "ssh_port",+ "extra_connection_parameters",+ "sasl_config", // kdc_host / kdc_port only; classified again below+ ],+ // Out for the reasons dataSourceDestination records in Go: they name a+ // target inside a server already reached, select which cloud API serves+ // it, follow a peer the operator's own server advertises, or carry a+ // secret rather than an address.+ [+ "id",+ "type",+ "username",+ "password",+ "use_ssl",+ "verify_tls_certificate",+ "ssl_ca",+ "ssl_cert",+ "ssl_key",+ "ssl_ca_path",+ "ssl_cert_path",+ "ssl_key_path",+ "ssl_ca_set",+ "ssl_cert_set",+ "ssl_key_set",+ "ssl_ca_path_set",+ "ssl_cert_path_set",+ "ssl_key_path_set",+ "database",+ "srv",+ "authentication_database",+ "replica_set",+ "sid",+ "service_name",+ "ssh_user",+ "ssh_password",+ "ssh_private_key",+ "authentication_private_key",+ "authentication_private_key_passphrase",+ "external_secret",+ "authentication_type",+ "cloud_sql_ip_type",+ "azure_credential",+ "aws_credential",+ "gcp_credential",+ "direct_connection",+ "region",+ "warehouse_id",+ "master_name",+ "master_username",+ "master_password",+ "redis_type",+ "project_id",+ "instance_id",+ ]+ );+ expect(unclassified).toEqual([]);+ expect(stale).toEqual([]);+ });++ // sasl_config is the one field the projection picks apart rather than+ // copying whole, so the walk has to go a level down with it.+ test("every KerberosConfig field is either an address or explained", () => {+ const { unclassified, stale } = classify(+ KerberosConfigSchema,+ ["kdc_host", "kdc_port"],+ // primary, instance and realm choose the principal kinit claims rather+ // than where it sends the claim; kdc_transport_protocol reaches the same+ // kdc_host:kdc_port either way; keytab is the credential itself.+ ["primary", "instance", "realm", "keytab", "kdc_transport_protocol"]+ );+ expect(unclassified).toEqual([]);+ expect(stale).toEqual([]);+ });++ // krbConfigOf reads one mechanism, so a second one would carry its own+ // endpoint past both walks above: sasl_config is already classified in.+ test("Kerberos is still the only SASL mechanism", () => {+ expect(SASLConfigSchema.oneofs.map((oneof) => oneof.name)).toEqual([+ "mechanism",+ ]);+ expect(+ SASLConfigSchema.oneofs[0].fields.map((field) => field.name)+ ).toEqual(["krb_config"]);+ });+});diff --git a/frontend/src/components/instance/common.ts b/frontend/src/components/instance/common.tsindex c07970aacc..8850c1e48b 100644--- a/frontend/src/components/instance/common.ts+++ b/frontend/src/components/instance/common.ts@@ -1,4 +1,4 @@-import { cloneDeep, first } from "lodash-es";+import { cloneDeep, first, isEqual } from "lodash-es";import i18n from "@/lib/i18n";import { useAppStore } from "@/stores/app";import { UNKNOWN_INSTANCE_NAME, unknownDataSource } from "@/types";@@ -113,22 +113,64 @@ export const wrapEditDataSource = (ds: DataSource | undefined) => {};};-export const applyExtraConnectionParameters = (- dataSource: DataSource,- editState: EditDataSource-): DataSource => {- if (editState.extraConnectionParameters) {- const params: Record<string, string> = {};- Object.entries(editState.extraConnectionParameters).forEach(- ([key, value]) => {- params[key] = value;- }- );- dataSource.extraConnectionParameters = params;- } else {- dataSource.extraConnectionParameters = {};+export const krbConfigOf = (dataSource: DataSource) =>+ dataSource.saslConfig?.mechanism?.case === "krbConfig"+ ? dataSource.saslConfig.mechanism.value+ : undefined;++// The fields through which the operator names where a data source connects.+// Mirrors dataSourceDestination in+// backend/api/v1/instance_service_converter.go, which the server compares to+// decide whether a stored Kerberos keytab may be inherited.+const dataSourceDestination = (dataSource: DataSource) => {+ const krbConfig = krbConfigOf(dataSource);+ return {+ host: dataSource.host,+ port: dataSource.port,+ additionalAddresses: dataSource.additionalAddresses.map(+ ({ host, port }) => ({ host, port })+ ),+ sshHost: dataSource.sshHost,+ sshPort: dataSource.sshPort,+ extraConnectionParameters: { ...dataSource.extraConnectionParameters },+ kdcHost: krbConfig?.kdcHost ?? "",+ kdcPort: krbConfig?.kdcPort ?? "",+ };+};++/**+ * Reports whether this update would carry the stored Kerberos keytab to a+ * destination the operator moved, which the server refuses: the keytab has to+ * be supplied again, and supplying it is proof the operator still holds it.+ *+ * Pass the value the form will send as `editing`. The server compares its+ * merged result against the stored data source as read, so the default port+ * `extractDataSourceFromEdit` fills in, and the SSH fields it clears, count as+ * a move here exactly as they do there.+ *+ * The form is deliberately stricter than the server on one point. The server+ * refuses only when a keytab is actually stored; the keytab is INPUT_ONLY and+ * no `keytab_set` companion exists, so a read cannot tell, and a saved data+ * source that still authenticates with Kerberos is taken to hold one. A+ * Kerberos data source stored without a keytab — reachable through the API,+ * not through this form — is blocked here on an edit the server would accept.+ * Carrying a presence flag the way `ssl_ca_set` does would remove the guess.+ */+export const movesKeytabToNewDestination = (+ editing: DataSource,+ original: DataSource | undefined+): boolean => {+ const editingKrbConfig = krbConfigOf(editing);+ if (!editingKrbConfig || editingKrbConfig.keytab.length > 0) {+ return false;}- return dataSource;+ if (!original || !krbConfigOf(original)) {+ return false;+ }+ return !isEqual(+ dataSourceDestination(editing),+ dataSourceDestination(original)+ );};export const calcDataSourceUpdateMask = (diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex 049544de40..ff39204030 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -1172,12 +1172,23 @@},"instance-id": "Instance ID","instance-name": "Instance Name",+ "kerberos-instance-placeholder": "instance, optional",+ "kerberos-kdc": "KDC",+ "kerberos-kdc-host-placeholder": "KDC host",+ "kerberos-kdc-port-placeholder": "KDC port, optional",+ "kerberos-primary-placeholder": "primary",+ "kerberos-principal": "Principal",+ "kerberos-realm-placeholder": "realm",+ "keytab-file": "Keytab File",+ "keytab-resupply-required": "This data source now connects somewhere new. Re-upload the keytab to confirm you still hold it.",+ "keytab-upload-placeholder": "Click or drag your .keytab file here","keytab-write-only": "Keytab is write-only. Upload a new file to replace the existing one.","new-instance": "New Instance","no-environment": "This instance has not been bound to the environment","no-extra-params-configured": "No extra connection parameters configured","no-params-yet-add-above": "No parameters configured yet. Add parameters using the form above.","no-password": "No password",+ "open-data-source": "Open this data source to see what it needs.","parameter-name-placeholder": "Parameter name","parameter-value-placeholder": "Parameter value","password-type": {diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex 7fe955305a..3ad062116d 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -1172,12 +1172,23 @@},"instance-id": "ID de la instancia","instance-name": "Nombre de la instancia",+ "kerberos-instance-placeholder": "instance, opcional",+ "kerberos-kdc": "KDC",+ "kerberos-kdc-host-placeholder": "Host del KDC",+ "kerberos-kdc-port-placeholder": "Puerto del KDC, opcional",+ "kerberos-primary-placeholder": "primary",+ "kerberos-principal": "Principal",+ "kerberos-realm-placeholder": "realm",+ "keytab-file": "Archivo keytab",+ "keytab-resupply-required": "Esta fuente de datos ahora se conecta a un destino nuevo. Vuelva a subir el keytab para confirmar que todavía lo tiene.",+ "keytab-upload-placeholder": "Haga clic o arrastre su archivo .keytab aquí","keytab-write-only": "El keytab es de solo escritura. Suba un archivo nuevo para reemplazar el existente.","new-instance": "Nueva instancia","no-environment": "Esta instancia no ha sido ligada al entorno.","no-extra-params-configured": "No hay parámetros de conexión adicionales configurados","no-params-yet-add-above": "No hay parámetros configurados todavía. \nAgregue parámetros usando el formulario anterior.","no-password": "Sin contraseña",+ "open-data-source": "Abra esta fuente de datos para ver qué necesita.","parameter-name-placeholder": "Nombre de parámetro","parameter-value-placeholder": "Valor de parámetro","password-type": {diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex 2a79fc1fe2..0a3147951b 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -1172,12 +1172,23 @@},"instance-id": "インスタンスID","instance-name": "@:common.instance@:instance.name",+ "kerberos-instance-placeholder": "instance(任意)",+ "kerberos-kdc": "KDC",+ "kerberos-kdc-host-placeholder": "KDC ホスト",+ "kerberos-kdc-port-placeholder": "KDC ポート(任意)",+ "kerberos-primary-placeholder": "primary",+ "kerberos-principal": "プリンシパル",+ "kerberos-realm-placeholder": "realm",+ "keytab-file": "キータブファイル",+ "keytab-resupply-required": "このデータソースの接続先が変わりました。keytab を再アップロードして、引き続き保持していることを確認してください。",+ "keytab-upload-placeholder": ".keytab ファイルをクリックまたはドラッグしてください","keytab-write-only": "キータブは書き込み専用です。新しいファイルをアップロードすると既存のものを置き換えます。","new-instance": "新しいインスタンス","no-environment": "このインスタンスは環境にバインドされていません","no-extra-params-configured": "追加の接続パラメーターは構成されていません","no-params-yet-add-above": "まだ構成されていません。\n上記のフォームを使用してパラメーターを追加します。","no-password": "パスワードがありません",+ "open-data-source": "このデータソースを開いて、何が必要か確認してください。","parameter-name-placeholder": "パラメーター名","parameter-value-placeholder": "パラメーター値","password-type": {diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.jsonindex a399bedb4e..909d426e20 100644--- a/frontend/src/locales/vi-VN.json+++ b/frontend/src/locales/vi-VN.json@@ -1172,12 +1172,23 @@},"instance-id": "ID phiên bản","instance-name": "Tên phiên bản",+ "kerberos-instance-placeholder": "instance, tùy chọn",+ "kerberos-kdc": "KDC",+ "kerberos-kdc-host-placeholder": "Máy chủ KDC",+ "kerberos-kdc-port-placeholder": "Cổng KDC, tùy chọn",+ "kerberos-primary-placeholder": "primary",+ "kerberos-principal": "Principal",+ "kerberos-realm-placeholder": "realm",+ "keytab-file": "Tệp keytab",+ "keytab-resupply-required": "Nguồn dữ liệu này hiện kết nối tới một đích đến mới. Hãy tải lên lại keytab để xác nhận bạn vẫn giữ nó.",+ "keytab-upload-placeholder": "Nhấp hoặc kéo tệp .keytab của bạn vào đây","keytab-write-only": "Keytab chỉ ghi. Tải lên tệp mới để thay thế keytab hiện có.","new-instance": "Phiên bản mới","no-environment": "Trường hợp này không bị ràng buộc với môi trường","no-extra-params-configured": "Không có thông số kết nối bổ sung được cấu hình","no-params-yet-add-above": "Chưa có thông số nào được cấu hình. \nThêm tham số bằng cách sử dụng biểu mẫu trên.","no-password": "Không có mật khẩu",+ "open-data-source": "Mở nguồn dữ liệu này để xem nó cần gì.","parameter-name-placeholder": "Tên tham số","parameter-value-placeholder": "Giá trị tham số","password-type": {diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex a6a54bedb1..026444a15f 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -1172,12 +1172,23 @@},"instance-id": "实例 ID","instance-name": "实例名称",+ "kerberos-instance-placeholder": "instance,可选",+ "kerberos-kdc": "KDC",+ "kerberos-kdc-host-placeholder": "KDC 主机",+ "kerberos-kdc-port-placeholder": "KDC 端口,可选",+ "kerberos-primary-placeholder": "primary",+ "kerberos-principal": "主体",+ "kerberos-realm-placeholder": "realm",+ "keytab-file": "Keytab 文件",+ "keytab-resupply-required": "该数据源现在连接到新的目标地址。请重新上传 keytab,以确认您仍持有它。",+ "keytab-upload-placeholder": "点击或拖拽 .keytab 文件到此处","keytab-write-only": "Keytab 仅写入。上传新文件以替换现有 keytab。","new-instance": "新实例","no-environment": "此实例尚未绑定到环境","no-extra-params-configured": "没有配置的额外连接参数","no-params-yet-add-above": "尚未配置参数。\n使用上面的形式添加参数。","no-password": "无密码",+ "open-data-source": "打开该数据源,查看还需要什么。","parameter-name-placeholder": "参数名称","parameter-value-placeholder": "参数值","password-type": {