25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
feat(elasticsearch): support API key authentication
seth-shi1da66686e954
diff --git a/apps/desktop/src/components/connection/ConnectionDialog.vue b/apps/desktop/src/components/connection/ConnectionDialog.vueindex dbb10c0cb0..44d72a12dd 100644--- a/apps/desktop/src/components/connection/ConnectionDialog.vue+++ b/apps/desktop/src/components/connection/ConnectionDialog.vue@@ -188,6 +188,8 @@ import { hasCloudflareD1Credentials, isCloudflareD1Connection, normalizeCloudflaimport { hasSpannerResourcePath, isSpannerConnection, normalizeSpannerConnection } from "@/lib/connection/spannerResourcePath";import {buildElasticsearchExternalConfig,+ elasticsearchAuthTypeFromConfig,+ type ElasticsearchAuthType,elasticsearchConnectionModeFromConfig,elasticsearchConnectivityCheckDisabledFromConfig,elasticsearchConnectivityCheckPathFromConfig,@@ -491,6 +493,7 @@ function resetCassandraTlsFields(externalConfig: unknown) {Object.assign(cassandraTls, cassandraTlsConfigFromExternalConfig(externalConfig));}+const elasticsearchAuthType = ref<ElasticsearchAuthType>("basic");const elasticsearchConnectionMode = ref<ElasticsearchConnectionMode>("direct");const elasticsearchKibanaBasePath = ref("");const elasticsearchConnectivityCheckPath = ref("");@@ -500,7 +503,15 @@ const elasticsearchConnectionPorts = ref<Record<ElasticsearchConnectionMode, numdirect: 9200,kibana: 5601,});+function switchElasticsearchAuthType(authType: ElasticsearchAuthType) {+ if (authType === elasticsearchAuthType.value) return;+ elasticsearchAuthType.value = authType;+ form.value.password = "";+ resetTestState();+}+function resetElasticsearchProxyFields(externalConfig?: unknown) {+ elasticsearchAuthType.value = elasticsearchAuthTypeFromConfig(externalConfig);const mode = elasticsearchConnectionModeFromConfig(externalConfig);elasticsearchConnectionMode.value = mode;elasticsearchKibanaBasePath.value = elasticsearchKibanaBasePathFromConfig(externalConfig);@@ -5220,7 +5231,11 @@ function connectionConfigForSubmit(id: string, generatedName = "", validatePlugiconfig.external_config = { ...existing, auth };}} else if (config.db_type === "elasticsearch") {- config.external_config = buildElasticsearchExternalConfig(elasticsearchConnectionMode.value, elasticsearchKibanaBasePath.value, elasticsearchConnectivityCheckPath.value, elasticsearchIndexGroupingPattern.value, elasticsearchConnectivityCheckDisabled.value);+ config.external_config = buildElasticsearchExternalConfig(elasticsearchConnectionMode.value, elasticsearchKibanaBasePath.value, elasticsearchConnectivityCheckPath.value, elasticsearchIndexGroupingPattern.value, elasticsearchConnectivityCheckDisabled.value, elasticsearchAuthType.value);+ if (elasticsearchAuthType.value === "apiKey") {+ config.username = "";+ config.password = config.password.trim();+ }} else if (config.db_type === "meilisearch") {config.username = "";config.password = config.password.trim();@@ -9477,14 +9492,22 @@ function openExternalUrl(url: string) {<Input v-model="form.informix_server" class="col-span-3" placeholder="ol_informix1170" /></div>- <div v-if="form.db_type !== 'meilisearch' && form.db_type !== 'spanner'" class="grid grid-cols-4 items-center gap-4">+ <div v-if="form.db_type === 'elasticsearch'" class="grid grid-cols-4 items-center gap-4">+ <Label :class="connectionLabelClass">{{ t("connection.mqAuth") }}</Label>+ <div class="col-span-3 flex items-center gap-2">+ <Button type="button" size="sm" :variant="elasticsearchAuthType === 'basic' ? 'default' : 'outline'" :aria-pressed="elasticsearchAuthType === 'basic'" @click="switchElasticsearchAuthType('basic')">{{ t("connection.mqAuthBasic") }}</Button>+ <Button type="button" size="sm" :variant="elasticsearchAuthType === 'apiKey' ? 'default' : 'outline'" :aria-pressed="elasticsearchAuthType === 'apiKey'" @click="switchElasticsearchAuthType('apiKey')">{{ t("connection.mqAuthApiKey") }}</Button>+ </div>+ </div>++ <div v-if="form.db_type !== 'meilisearch' && form.db_type !== 'spanner' && !(form.db_type === 'elasticsearch' && elasticsearchAuthType === 'apiKey')" class="grid grid-cols-4 items-center gap-4"><Label :class="connectionLabelClass">{{ t("connection.user") }}</Label><Input v-model="form.username" class="col-span-3" /></div><div v-if="form.db_type !== 'spanner'" class="grid grid-cols-4 items-center gap-4">- <Label :class="connectionLabelClass">{{ form.db_type === "meilisearch" ? t("connection.mqAuthApiKey") : t("connection.password") }}</Label>- <PasswordInput v-model="form.password" class="col-span-3" />+ <Label :class="connectionLabelClass">{{ form.db_type === "meilisearch" || (form.db_type === "elasticsearch" && elasticsearchAuthType === "apiKey") ? t("connection.mqAuthApiKey") : t("connection.password") }}</Label>+ <PasswordInput v-model="form.password" class="col-span-3" :placeholder="form.db_type === 'elasticsearch' && elasticsearchAuthType === 'apiKey' ? 'Base64(id:api_key)' : undefined" /></div><SavePasswordCheckbox v-if="form.db_type !== 'spanner'" v-model="form.save_password" />diff --git a/apps/desktop/src/components/connection/__tests__/ConnectionDialog.savePassword.spec.ts b/apps/desktop/src/components/connection/__tests__/ConnectionDialog.savePassword.spec.tsindex 93e999d407..d6a156761f 100644--- a/apps/desktop/src/components/connection/__tests__/ConnectionDialog.savePassword.spec.ts+++ b/apps/desktop/src/components/connection/__tests__/ConnectionDialog.savePassword.spec.ts@@ -100,10 +100,11 @@ vi.mock("@/components/ui/PasswordInput.vue", async () => {return {default: defineComponent({props: ["modelValue"],+ emits: ["update:modelValue"],setup:- (props, { attrs }) =>+ (props, { attrs, emit }) =>() =>- h("input", { ...attrs, type: "password", value: props.modelValue }),+ h("input", { ...attrs, type: "password", value: props.modelValue, onInput: (event: Event) => emit("update:modelValue", (event.target as HTMLInputElement).value) }),}),};});@@ -276,3 +277,46 @@ describe("ConnectionDialog save-password checkbox", () => {expect(savePasswordCheckbox()).toBeNull();});});++function elasticsearchConnection(overrides: Partial<ConnectionConfig> = {}): ConnectionConfig {+ return { id: "es-1", name: "Elasticsearch", db_type: "elasticsearch", host: "search.example.com", port: 9243, username: "elastic", password: "basic-password", ssl: true, save_password: true, ...overrides } as ConnectionConfig;+}++function buttonNamed(name: string): HTMLButtonElement {+ const button = Array.from(document.querySelectorAll<HTMLButtonElement>("button")).find((button) => button.textContent?.trim() === name);+ expect(button, `Expected button ${name}`).toBeTruthy();+ return button!;+}++describe("Elasticsearch API key authentication", () => {+ it("clears the previous credential on switch, hides username and submits the key in the secret slot", async () => {+ await mountDialog(elasticsearchConnection());+ expect(buttonNamed("Basic").getAttribute("aria-pressed")).toBe("true");+ buttonNamed("API Key").click();+ await settle();+ const input = document.querySelector<HTMLInputElement>('input[placeholder="Base64(id:api_key)"]')!;+ expect(input.type).toBe("password");+ expect(input.value).toBe("");+ expect(Array.from(document.querySelectorAll("label")).some((label) => label.textContent?.trim() === "User")).toBe(false);+ input.value = " c3ludGhldGljOmtleQ== ";+ input.dispatchEvent(new Event("input", { bubbles: true }));+ await settle();+ buttonNamed("Test").click();+ await settle();+ expect(backend.testConnectionWithInfo).toHaveBeenCalledWith(expect.objectContaining({ username: "", password: "c3ludGhldGljOmtleQ==", external_config: { authType: "apiKey" } }));+ buttonNamed("Save").click();+ await settle();+ expect(store.updateConnection).toHaveBeenCalledWith(expect.objectContaining({ username: "", password: "c3ludGhldGljOmtleQ==", external_config: { authType: "apiKey" }, save_password: true }));+ });++ it("restores the API key mode when editing and clears the key when switching back to Basic", async () => {+ await mountDialog(elasticsearchConnection({ username: "", password: "encoded-key", external_config: { authType: "apiKey" }, save_password: false }));+ expect(buttonNamed("API Key").getAttribute("aria-pressed")).toBe("true");+ expect(document.querySelector<HTMLInputElement>('input[placeholder="Base64(id:api_key)"]')!.value).toBe("encoded-key");+ expect(savePasswordCheckbox()!.checked).toBe(false);+ buttonNamed("Basic").click();+ await settle();+ expect(document.querySelector<HTMLInputElement>('input[type="password"]')!.value).toBe("");+ expect(document.querySelector('input[placeholder="Base64(id:api_key)"]')).toBeNull();+ });+});diff --git a/apps/desktop/src/lib/__tests__/connection/connectionUrlBuilder.spec.ts b/apps/desktop/src/lib/__tests__/connection/connectionUrlBuilder.spec.tsindex a4377586b0..5aece482df 100644--- a/apps/desktop/src/lib/__tests__/connection/connectionUrlBuilder.spec.ts+++ b/apps/desktop/src/lib/__tests__/connection/connectionUrlBuilder.spec.ts@@ -429,3 +429,12 @@ describe("buildConnectionUrlCopy host:port, DSN and psql", () => {expect(buildConnectionUrlCopy(config({ db_type: "mysql", port: 3306 }), "dsnWithPassword")).toBeNull();});});++describe("Elasticsearch API key connection URL copies", () => {+ it("copies only the endpoint and never represents an API key as Basic-auth userinfo", () => {+ const search = config({ db_type: "elasticsearch", host: "search.example.com", port: 9243, ssl: true, database: "", username: "stale-user", password: "synthetic-api-key", external_config: { authType: "apiKey" } });+ expect(buildConnectionUrlCopy(search, "url")).toBe("https://search.example.com:9243");+ expect(buildConnectionUrlCopy(search, "urlWithPassword")).toBe("https://search.example.com:9243");+ expect(connectionUrlCopyFormats(search)).toEqual(["url", "hostPort"]);+ });+});diff --git a/apps/desktop/src/lib/connection/connectionUrlBuilder.ts b/apps/desktop/src/lib/connection/connectionUrlBuilder.tsindex 9ceb33cd78..c03dc990a2 100644--- a/apps/desktop/src/lib/connection/connectionUrlBuilder.ts+++ b/apps/desktop/src/lib/connection/connectionUrlBuilder.ts@@ -1,3 +1,4 @@+import { elasticsearchAuthTypeFromConfig } from "@/lib/connection/elasticsearchKibanaProxy";import type { ConnectionConfig, DatabaseType } from "@/types/database";import { GAUSSDB_M_JDBC_DRIVER_PROFILE } from "@/lib/database/jdbcDialect";import { effectiveRedisDatabaseIndex } from "@/lib/redis/redisDatabaseIndex";@@ -23,7 +24,7 @@ export type ConnectionUrlCopyFormat = "url" | "urlWithPassword" | "jdbcUrl" | "j/** Formats whose output embeds the stored password; callers should confirm before copying. */export const CONNECTION_URL_COPY_WITH_PASSWORD_FORMATS: ReadonlySet<ConnectionUrlCopyFormat> = new Set(["urlWithPassword", "jdbcUrlWithCredentials", "dsnWithPassword"]);-export type ConnectionUrlCopyConfig = Pick<ConnectionConfig, "db_type" | "host" | "port" | "username" | "password" | "database" | "url_params" | "ssl" | "connection_string"> & Partial<Pick<ConnectionConfig, "driver_profile" | "oracle_connection_type">>;+export type ConnectionUrlCopyConfig = Pick<ConnectionConfig, "db_type" | "host" | "port" | "username" | "password" | "database" | "url_params" | "ssl" | "connection_string"> & Partial<Pick<ConnectionConfig, "driver_profile" | "oracle_connection_type" | "external_config">>;export interface ConnectionUrlCopyOptions {/** Overrides `config.database` (e.g. the database tree node that was right-clicked). */@@ -292,7 +293,8 @@ function buildStandardUrl(config: ConnectionUrlCopyConfig, options: ConnectionUrconst database = effectiveDatabase(config, options);const encode = scheme === "oceanbase" ? encodeOceanBaseUrlCredential : config.db_type === "oracle" ? encodeOracleUrlCredential : encodeCredential;- const userInfo = buildUserInfo(config, options.includePassword, encode, scheme === "oceanbase" ? encodeOceanBaseUrlUsername : encode);+ const usesApiKey = config.db_type === "elasticsearch" && elasticsearchAuthTypeFromConfig(config.external_config) === "apiKey";+ const userInfo = usesApiKey ? "" : buildUserInfo(config, options.includePassword, encode, scheme === "oceanbase" ? encodeOceanBaseUrlUsername : encode);const hostPart = formatHostForUrl(host);const portPart = shouldAppendPort(config) ? `:${config.port}` : "";const path = database ? `/${encodeURIComponent(database)}` : "";diff --git a/apps/desktop/src/lib/connection/elasticsearchKibanaProxy.ts b/apps/desktop/src/lib/connection/elasticsearchKibanaProxy.tsindex ae141fc5e8..3893e53021 100644--- a/apps/desktop/src/lib/connection/elasticsearchKibanaProxy.ts+++ b/apps/desktop/src/lib/connection/elasticsearchKibanaProxy.ts@@ -1,6 +1,9 @@export type ElasticsearchConnectionMode = "direct" | "kibana";+export type ElasticsearchAuthType = "basic" | "apiKey";export interface ElasticsearchExternalConfig {+ /** API keys use the encrypted main password slot; no credential is stored here. */+ authType?: ElasticsearchAuthType;mode?: "kibana" | "direct";kibanaBasePath?: string;/** GET path for connect/test/health. Empty means GET /. */@@ -30,6 +33,10 @@ export function normalizeElasticsearchConnectivityCheckPath(value: string): strireturn withoutMethod.startsWith("/") ? withoutMethod : `/${withoutMethod}`;}+export function elasticsearchAuthTypeFromConfig(value: unknown): ElasticsearchAuthType {+ return externalConfigRecord(value).authType === "apiKey" ? "apiKey" : "basic";+}+export function elasticsearchConnectionModeFromConfig(value: unknown): ElasticsearchConnectionMode {const config = externalConfigRecord(value);return config.mode === "kibana" ? "kibana" : "direct";@@ -62,12 +69,13 @@ export function elasticsearchIndexGroupingPatternFromConfig(value: unknown): strreturn typeof pattern === "string" ? pattern.trim() : "";}-export function buildElasticsearchExternalConfig(mode: ElasticsearchConnectionMode, kibanaBasePath: string, connectivityCheckPath = "", indexGroupingPattern = "", connectivityCheckDisabled = false): ElasticsearchExternalConfig | undefined {+export function buildElasticsearchExternalConfig(mode: ElasticsearchConnectionMode, kibanaBasePath: string, connectivityCheckPath = "", indexGroupingPattern = "", connectivityCheckDisabled = false, authType: ElasticsearchAuthType = "basic"): ElasticsearchExternalConfig | undefined {const checkPath = normalizeElasticsearchConnectivityCheckPath(connectivityCheckPath);const grouping = indexGroupingPattern.trim();if (mode !== "kibana") {- if (!checkPath && !grouping && !connectivityCheckDisabled) return undefined;+ if (!checkPath && !grouping && !connectivityCheckDisabled && authType === "basic") return undefined;const config: ElasticsearchExternalConfig = {};+ if (authType === "apiKey") config.authType = authType;if (checkPath) config.connectivityCheckPath = checkPath;if (connectivityCheckDisabled) config.connectivityCheckDisabled = true;if (grouping) config.indexGroupingPattern = grouping;@@ -75,6 +83,7 @@ export function buildElasticsearchExternalConfig(mode: ElasticsearchConnectionMo}const normalizedPath = normalizeKibanaBasePath(kibanaBasePath);const config: ElasticsearchExternalConfig = { mode: "kibana" };+ if (authType === "apiKey") config.authType = authType;if (normalizedPath) config.kibanaBasePath = normalizedPath;if (checkPath) config.connectivityCheckPath = checkPath;if (connectivityCheckDisabled) config.connectivityCheckDisabled = true;diff --git a/crates/dbx-driver-elasticsearch/src/lib.rs b/crates/dbx-driver-elasticsearch/src/lib.rsindex 160e20c0b2..3dc9a37ac0 100644--- a/crates/dbx-driver-elasticsearch/src/lib.rs+++ b/crates/dbx-driver-elasticsearch/src/lib.rs@@ -1,5 +1,6 @@use percent_encoding::{percent_decode_str, utf8_percent_encode, AsciiSet, CONTROLS};use regex::Regex;+use reqwest::header::{HeaderValue, AUTHORIZATION};use reqwest::{Client as HttpClient, Method, StatusCode};use serde::{Deserialize, Serialize};use serde_json::Value;@@ -61,6 +62,7 @@ pub struct EsClient {base_url: String,fallback_base_urls: Vec<String>,auth: Option<(String, String)>,+ api_key: Option<HeaderValue>,transport_mode: ElasticsearchTransportMode,/// GET path used for connect / health / test (default "/").connectivity_check_path: String,@@ -137,6 +139,7 @@ impl EsClient {base_url,fallback_base_urls,auth,+ api_key: None,transport_mode,connectivity_check_path,connectivity_check_disabled,@@ -168,7 +171,7 @@ impl EsClient {let connectivity_check_path = elasticsearch_connectivity_check_path(external_config);let connectivity_check_disabled = elasticsearch_connectivity_check_disabled(external_config);let index_grouping = elasticsearch_index_grouping(external_config);- Self::new_with_mode(+ let mut client = Self::new_with_mode(&base_url,username,password,@@ -181,7 +184,20 @@ impl EsClient {ca_cert_path,client_cert_path,client_key_path,- )+ )?;+ if external_config.and_then(|config| config.get("authType")).and_then(Value::as_str) == Some("apiKey") {+ // Reuse the encrypted main password slot rather than storing a secret in external_config.+ let key = password+ .map(str::trim)+ .filter(|key| !key.is_empty())+ .ok_or_else(|| "Elasticsearch API key is required".to_string())?;+ let mut header = HeaderValue::from_str(&format!("ApiKey {key}"))+ .map_err(|_| "Invalid Elasticsearch API key".to_string())?;+ header.set_sensitive(true);+ client.auth = None;+ client.api_key = Some(header);+ }+ Ok(client)}fn get(&self, path: &str) -> reqwest::RequestBuilder {@@ -214,7 +230,9 @@ impl EsClient {}fn with_auth(&self, req: reqwest::RequestBuilder) -> reqwest::RequestBuilder {- if let Some((ref user, ref pass)) = self.auth {+ if let Some(ref api_key) = self.api_key {+ req.header(AUTHORIZATION, api_key.clone())+ } else if let Some((ref user, ref pass)) = self.auth {req.basic_auth(user, Some(pass))} else {req@@ -260,6 +278,7 @@ impl Clone for EsClient {base_url: self.base_url.clone(),fallback_base_urls: self.fallback_base_urls.clone(),auth: self.auth.clone(),+ api_key: self.api_key.clone(),transport_mode: self.transport_mode,connectivity_check_path: self.connectivity_check_path.clone(),connectivity_check_disabled: self.connectivity_check_disabled,@@ -3685,6 +3704,93 @@ mod tests {server.await.unwrap();}+ #[tokio::test]+ async fn api_key_authenticates_connectivity_and_query_requests_in_both_modes() {+ for mode in ["direct", "kibana"] {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = listener.local_addr().unwrap();+ let server = tokio::spawn(async move {+ for _ in 0..2 {+ let (mut socket, _) = listener.accept().await.unwrap();+ let request = read_http_request(&mut socket).await;+ let auth = request+ .lines()+ .filter_map(|line| line.split_once(':'))+ .find(|(name, _)| name.eq_ignore_ascii_case("authorization"))+ .map(|(_, value)| value.trim());+ assert_eq!(auth, Some("ApiKey c3ludGhldGljOmtleQ=="));+ if mode == "kibana" {+ assert!(request.starts_with("POST /api/console/proxy?"));+ assert!(request.contains("kbn-xsrf: true"));+ }+ write_json_http_response(&mut socket, 200, "{}").await;+ }+ });+ let config = json!({ "mode": mode, "authType": "apiKey" });+ let mut client = EsClient::from_config(+ &format!("http://{addr}"),+ Some("ignored-user"),+ Some(" c3ludGhldGljOmtleQ== "),+ false,+ None,+ Some(&config),+ Duration::from_secs(2),+ None,+ None,+ None,+ )+ .unwrap();+ super::test_connection(&mut client, Duration::from_secs(2)).await.unwrap();+ let cloned = client.clone();+ super::execute_rest_query(&cloned, "GET /_cluster/health").await.unwrap();+ server.await.unwrap();+ }+ }++ #[test]+ fn api_key_mode_rejects_missing_or_invalid_keys_without_echoing_the_credential() {+ for key in [None, Some(" "), Some("synthetic-secret\r\nX-Injected: yes")] {+ let result = EsClient::from_config(+ "http://localhost:9200",+ None,+ key,+ false,+ None,+ Some(&json!({ "authType": "apiKey" })),+ Duration::from_secs(1),+ None,+ None,+ None,+ );+ let error = result.err().expect("invalid API key should be rejected");+ assert!(!error.contains("synthetic-secret"));+ }+ }++ #[test]+ fn existing_connections_keep_basic_or_anonymous_authentication() {+ for (username, expected) in [(Some("elastic"), Some("Basic ZWxhc3RpYzpzZWNyZXQ=")), (None, None)] {+ let client = EsClient::from_config(+ "http://localhost:9200",+ username,+ Some("secret"),+ false,+ None,+ None,+ Duration::from_secs(1),+ None,+ None,+ None,+ )+ .unwrap();+ let request = client.get("/").build().unwrap();+ assert_eq!(+ request.headers().get(reqwest::header::AUTHORIZATION).map(|value| value.to_str().unwrap()),+ expected+ );+ }+ }+#[test]fn elasticsearch_client_from_config_uses_url_params_for_tls_verification() {let client = EsClient::from_config(diff --git a/docs/content/docs/databases.cn.mdx b/docs/content/docs/databases.cn.mdxindex c57a197929..c450299c74 100644--- a/docs/content/docs/databases.cn.mdx+++ b/docs/content/docs/databases.cn.mdx@@ -110,6 +110,16 @@ RabbitMQ 等服务可能同时有业务端口和管理 API 端口;自定义 AMDBX 可以解析许多常见 DSN/URL,但不同数据库版本和云厂商参数差异很大。连接测试成功后仍应检查实际数据库、Schema、SSL 和权限范围。+### Elasticsearch API Key 认证++++在连接表单中选择 **认证 → API Key**,把编码后的 Elasticsearch API Key(`Base64(id:api_key)`)粘贴到隐藏显示的 **API Key** 输入框。只填编码值,不要加 `ApiKey ` 前缀;DBX 会为每次请求添加 `Authorization: ApiKey …` 请求头。此模式不使用用户名,直连和 Kibana 代理连接均使用所选认证方式。++API Key 复用现有的加密密码存储,并遵循 **保存密码** 设置(取消勾选则仅在当前会话使用)。已有连接继续使用 Basic 用户名/密码认证;切换认证方式会清空凭据输入框,以便输入新凭据。++CLI/MCP 配置中,将 `external_config.authType` 设为 `"apiKey"`,编码后的 Key 填入 `password`;不要把密钥放入 URL 参数或 `external_config`。+## 本地测试环境仓库提供 ClickHouse、MariaDB、MongoDB、MySQL、PostgreSQL 和 Redis 的固定 Docker Compose 测试环境,适合验证连接、驱动行为和回归。详见 [数据库测试实验室](/cn/docs/database-lab)。diff --git a/docs/content/docs/databases.mdx b/docs/content/docs/databases.mdxindex a06fb7c8c4..4771e2d338 100644--- a/docs/content/docs/databases.mdx+++ b/docs/content/docs/databases.mdx@@ -110,6 +110,16 @@ Services such as RabbitMQ may expose separate business and management ports. A cDBX parses many common DSNs and URLs, but parameters vary by version and cloud vendor. After a successful connection test, still verify the actual database, schema, SSL, and privilege scope.+### Elasticsearch API Key Authentication++++In the connection form, choose **Auth → API Key** and paste the encoded Elasticsearch API key (`Base64(id:api_key)`) into the masked **API Key** field. Paste only the encoded value, without the `ApiKey ` prefix; DBX adds the `Authorization: ApiKey …` header to every request. Username is not used in this mode. Both direct and Kibana proxy connections use the selected authentication method.++API keys use the existing encrypted password storage and follow **Save password** (uncheck it for session-only credentials). Existing connections continue to use Basic username/password authentication. Switching authentication methods clears the credential field so you can enter the new credential.++For CLI/MCP configurations, set `external_config.authType` to `"apiKey"` and put the encoded key in `password`; do not put the key in URL parameters or `external_config`.+## Local Test EnvironmentsThe repository includes pinned Docker Compose labs for ClickHouse, MariaDB, MongoDB, MySQL, PostgreSQL, and Redis. Use [Database Test Lab](/en/docs/database-lab) for connection, driver, and regression testing.diff --git a/docs/public/screenshots/elasticsearch-api-key.png b/docs/public/screenshots/elasticsearch-api-key.pngnew file mode 100644index 0000000000..9f9428144bBinary files /dev/null and b/docs/public/screenshots/elasticsearch-api-key.png differdiff --git a/packages/app-tests/elasticsearchKibanaProxy.test.ts b/packages/app-tests/elasticsearchKibanaProxy.test.tsindex 4d443b9907..d02fbc7f02 100644--- a/packages/app-tests/elasticsearchKibanaProxy.test.ts+++ b/packages/app-tests/elasticsearchKibanaProxy.test.ts@@ -2,6 +2,7 @@ import { strict as assert } from "node:assert";import { test } from "vitest";import {buildElasticsearchExternalConfig,+ elasticsearchAuthTypeFromConfig,elasticsearchConnectionModeFromConfig,elasticsearchConnectivityCheckPathFromConfig,elasticsearchKibanaBasePathFromConfig,@@ -41,3 +42,15 @@ test("stores connectivity check path for direct and kibana modes", () => {connectivityCheckPath: "/my-index/_search",});});++test("round trips API key authentication without storing the credential in external config", () => {+ assert.equal(elasticsearchAuthTypeFromConfig(undefined), "basic");+ assert.equal(elasticsearchAuthTypeFromConfig({ authType: "unknown" }), "basic");+ for (const mode of ["direct", "kibana"] as const) {+ const config = buildElasticsearchExternalConfig(mode, "/kibana", "/orders/_search", "", false, "apiKey");+ assert.equal(elasticsearchAuthTypeFromConfig(config), "apiKey");+ assert.equal(config?.connectivityCheckPath, "/orders/_search");+ assert.equal(elasticsearchConnectionModeFromConfig(config), mode);+ }+ assert.deepEqual(buildElasticsearchExternalConfig("direct", "", "", "", false, "apiKey"), { authType: "apiKey" });+});