diff --git a/Dockerfile b/Dockerfile index 458b1dbed..7ac929cd4 100644 --- a/Dockerfile +++ b/Dockerfile @@ -11,6 +11,9 @@ COPY frontend/ ./ RUN npm install && npm run build FROM ${SQLBOT_RUNTIME_IMAGE} AS runtime-base +RUN apt-get update \ + && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends krb5-user libgssapi-krb5-2 \ + && rm -rf /var/lib/apt/lists/* # Rebuild Dockerfile-base first, then point this build at the rebuilt image. RUN if ! node -e 'if (process.versions.node.split(".")[0] !== "22") process.exit(1)' \ || [ -e /opt/dmdbms/bin/libssl.so ] \ diff --git a/backend/README.md b/backend/README.md index f0c99ce2a..e996812ad 100644 --- a/backend/README.md +++ b/backend/README.md @@ -36,3 +36,23 @@ python3 -c 'import base64,json,secrets; key=base64.b64encode(secrets.token_bytes 轮换时先停止该部署的 API 和 MCP,保留旧密钥,加入新密钥并将 `active` 切换到新标识,原子替换文件。启动 API,等待现有配置重新加密,再恢复其他进程。用当前密钥文件验证数据库备份恢复后,可从在线文件移除旧密钥。历史备份所需密钥应离线保留至备份过期。恢复时先准备匹配该备份的密钥文件,再启动 API。已暴露的旧 ECB 密文仍可解密,应轮换对应数据源自身的凭据。 浏览器写入仍兼容旧请求编码,部署通过 HTTPS 保护传输。数据源列表和写入响应省略配置,授权编辑详情仅提供表单字段,密码和额外连接参数留空表示沿用。连接目标变化时需要重新提供已保存的敏感连接字段。API 客户端可发送显式空字符串清除密码或额外连接参数。 + +### Impala / Hive Kerberos 认证 + +Hive / Impala 数据源可在编辑表单开启 Kerberos,填写客户端 principal 和服务名,上传 krb5.conf(最多 64 KiB)及 keytab(最多 256 KiB)。服务名默认分别为 hive / impala;host 必须与服务 principal 对应,Impala 的 HiveServer2 端口通常为 21050。用户名是会话用户名,实际认证身份来自客户端 principal/keytab,不应上传 Hive/Impala 服务端账号的 keytab。 + +每个数据源的上传内容随连接配置使用 AES-256-GCM 加密存储,不新增明文持久文件;编辑详情只返回已配置状态,不返回文件内容。编辑时留空沿用,连接目标或认证参数改变时必须重新提供凭据。关闭 Kerberos 会清除该数据源保存的 conf/keytab;删除数据源同时删除加密配置。备份及恢复必须保留部署的数据源存储密钥。浏览器上传仍使用已有兼容编码,生产环境必须通过 HTTPS 保护传输。 + +每次建立 Kerberos 连接都在独立子进程中创建权限为 0700 的临时目录,文件权限为 0600,使用 kinit -kt 自动获取新票据,再用 PyHive 建立连接。查询结束、超时或失败时停止子进程并清理目录,不更改 API/MCP 父进程环境,也不共用部署票据缓存。当前策略不复用 Kerberos 长连接池,不需要后台定时续期:下一次连接自动重新认证;单次连接操作受数据源超时(最多 300 秒)限制。每个 API/MCP 进程最多同时运行 8 个此类连接;其余请求有界等待。异常关机可能留下临时目录,由部署侧临时目录清理策略处理。 + +上传配置只接受 libdefaults、realms、domain_realm 三个区段的受限参数(校验入口 apps/db/kerberos_connection.py)。不支持 include/includedir、插件、自定义文件路径、auth_to_local 或系统级配置覆盖;应上传不包含这些内容的最小客户端配置。当前上传认证模式仅支持 HiveServer2 二进制 TCP,不支持额外连接参数/TLS/HTTP;需要这些模式时应先适配传输参数,不能通过关闭证书验证绕过。 + +部署仍需安装 kinit、Kerberos/GSSAPI 运行库和 Python kerberos 模块,并保证 DNS、时间同步及 KDC/数据源网络可达。backend/pyproject.toml 已声明 Python 依赖;应用 Dockerfile 安装 krb5-user 和 libgssapi-krb5-2,构建基础镜像需具备现有 libkrb5-dev。使用当前源码重新构建镜像后生效,官方旧镜像不包含这些改动。本地开发应在 backend 下运行 uv sync 安装依赖;macOS 需准备对应 Kerberos 开发工具链。 + +保留原有额外参数 auth=KERBEROS&kerberos_service_name=impala(Hive 使用 hive)的部署侧票据缓存模式;只有打开表单 Kerberos 开关时才启用上传和自动获取模式。 + +离线回归以合成 kinit/驱动验证身份隔离、加密凭据保留和清理,不代表已完成真实集群握手。上线前需验证测试连接、表/字段读取、查询、错误 keytab/KDC 不可达、替换凭据及删除数据源;实际 Impala/Hive 版本、TLS 和授权策略需在目标环境验收。 + +Kerberos 服务主机名为 Hive/Impala 共用的选填字段:留空时使用连接主机,填写后仅作为 SASL 服务身份中的主机名,TCP 地址保持不变。例如连接 47.104.211.244、认证主机 impala.impala.test。修改该认证目标时必须重新上传凭据。 + +KDC 地址支持受限的 tcp/host:port、udp/host:port 写法(仅限 realms 区段的 kdc 项),可用于 macOS 客户端明确指定传输协议。 diff --git a/backend/apps/datasource/api/datasource.py b/backend/apps/datasource/api/datasource.py index 6ba7886f1..653db674d 100644 --- a/backend/apps/datasource/api/datasource.py +++ b/backend/apps/datasource/api/datasource.py @@ -109,10 +109,11 @@ async def get_datasource(session: SessionDep, user: CurrentUser, trans: Trans, i editable_fields = { "host", "port", "username", "database", "dbSchema", "filename", "sheets", "mode", "timeout", "lowVersion", "ssl", "poolSize", "engine", "extraJdbc", + "kerberosMode", "kerberosPrincipal", "kerberosService", "kerberosHost", } - result["configuration"] = json.dumps({ - field: configuration[field] for field in editable_fields if field in configuration - }) + editable = {field: configuration[field] for field in editable_fields if field in configuration} + editable["kerberosConfigured"] = bool(configuration.get("kerberosConf") and configuration.get("kerberosKeytab")) + result["configuration"] = json.dumps(editable) return result diff --git a/backend/apps/datasource/crud/datasource.py b/backend/apps/datasource/crud/datasource.py index a978edc35..9ada9935c 100644 --- a/backend/apps/datasource/crud/datasource.py +++ b/backend/apps/datasource/crud/datasource.py @@ -66,19 +66,35 @@ def seal_browser_configuration(configuration: str, previous: str | None = None) incoming = parse_configuration(decode_legacy_configuration(configuration)) if previous: saved = parse_configuration(aes_decrypt(previous)) - retained = {field: saved[field] for field in ("password", "extraJdbc") + secret_fields = ["password", "extraJdbc"] + if incoming.get("kerberosMode", saved.get("kerberosMode")): + secret_fields += ["kerberosConf", "kerberosKeytab"] + retained = {field: saved[field] for field in secret_fields if field not in incoming and saved.get(field)} # Never send a stored secret to a destination selected by the request. - destination = ("host", "port", "username", "database", "dbSchema", "mode", "engine", "ssl", "extraJdbc") + destination = ("host", "port", "username", "database", "dbSchema", "mode", "engine", "ssl", "extraJdbc", "kerberosMode") + if saved.get("kerberosMode") or incoming.get("kerberosMode"): + destination += ("kerberosPrincipal", "kerberosService", "kerberosHost", "kerberosConf") defaults = DatasourceConf().model_dump() existing = {**defaults, **saved} candidate = {**existing, **incoming} if any(candidate[field] != existing[field] for field in destination): + if "kerberosKeytab" in retained and candidate.get("kerberosMode"): + raise DatasourceConfigurationError("Connection settings changed while retaining Kerberos credentials") # A changed destination must never receive credentials from the old one. incoming.setdefault("password", "") if "extraJdbc" in retained: incoming["extraJdbc"] = "" incoming = {**saved, **incoming} + if incoming.get("kerberosMode"): + from apps.db.kerberos_connection import validate_credentials + try: + validate_credentials(incoming) + except ValueError: + raise DatasourceConfigurationError("Invalid Kerberos configuration") from None + elif "kerberosMode" in incoming: + incoming["kerberosConf"] = "" + incoming["kerberosKeytab"] = "" if "sheets" in incoming: validate_excel_sheet_names(incoming) return aes_encrypt(json.dumps(incoming)).decode("ascii") @@ -416,7 +432,7 @@ def preview(session: SessionDep, current_user: CurrentUser, id: int, data: Table table = session.query(CoreTable).filter(CoreTable.id == data.table.id).first() conf = DatasourceConf(**json.loads(aes_decrypt(ds.configuration))) if ds.type != "excel" else get_engine_config() sql: str = "" - if ds.type == "mysql" or ds.type == "doris" or ds.type == "starrocks" or ds.type == "hive": + if ds.type == "mysql" or ds.type == "doris" or ds.type == "starrocks" or ds.type == "hive" or ds.type == "impala": sql = f"""SELECT `{"`, `".join(fields)}` FROM `{table.table_name}` {where} LIMIT 100""" @@ -535,7 +551,7 @@ def get_table_sample_data(ds: CoreDatasource, table_name: str, fields: list) -> query = f"SELECT TOP 3 {','.join(field_names)} FROM {prefix}{table_name}{suffix}" elif equals_ignore_case(ds.type, "ck"): query = f"SELECT {','.join(field_names)} FROM {table_name} LIMIT 3" - elif equals_ignore_case(ds.type, "hive"): + elif equals_ignore_case(ds.type, "hive", "impala"): query = f"SELECT {','.join(field_names)} FROM {table_name} LIMIT 3" elif equals_ignore_case(ds.type, "oracle"): query = f"SELECT {','.join(field_names)} FROM \"{table_name}\" WHERE ROWNUM <= 3" @@ -606,7 +622,7 @@ def get_table_schema(session: SessionDep, current_user: CurrentUser, ds: CoreDat continue schema_table = '' - no_schema_types = ["mysql", "es", "sqlite", "hive", "doris", "starrocks"] + no_schema_types = ["mysql", "es", "sqlite", "hive", "impala", "doris", "starrocks"] schema_table += f"# Table: {db_name}.{obj.table.table_name}" if ds.type not in no_schema_types and db_name else f"# Table: {obj.table.table_name}" table_comment = '' if obj.table.custom_comment: diff --git a/backend/apps/datasource/models/datasource.py b/backend/apps/datasource/models/datasource.py index 12fbf7bbe..ad8bea8fe 100644 --- a/backend/apps/datasource/models/datasource.py +++ b/backend/apps/datasource/models/datasource.py @@ -124,6 +124,12 @@ class DatasourceConf(BaseModel): ssl: bool = False poolSize: int = 5 engine: str = 'hive' + kerberosMode: bool = False + kerberosPrincipal: str = '' + kerberosService: str = '' + kerberosHost: str = '' + kerberosConf: str = '' + kerberosKeytab: str = '' def to_dict(self): return { @@ -142,7 +148,13 @@ def to_dict(self): "lowVersion": self.lowVersion, "ssl": self.ssl, "poolSize": self.poolSize, - "engine": self.engine + "engine": self.engine, + "kerberosMode": self.kerberosMode, + "kerberosPrincipal": self.kerberosPrincipal, + "kerberosService": self.kerberosService, + "kerberosHost": self.kerberosHost, + "kerberosConf": self.kerberosConf, + "kerberosKeytab": self.kerberosKeytab } diff --git a/backend/apps/db/constant.py b/backend/apps/db/constant.py index dcec81901..7e59f9100 100644 --- a/backend/apps/db/constant.py +++ b/backend/apps/db/constant.py @@ -29,6 +29,7 @@ class DB(Enum): pg = ('pg', 'PostgreSQL', '"', '"', ConnectType.sqlalchemy, 'PostgreSQL', []) starrocks = ('starrocks', 'StarRocks', '`', '`', ConnectType.py_driver, 'StarRocks', []) hive = ('hive', 'Apache Hive', '`', '`', ConnectType.py_driver, 'Hive', []) + impala = ('impala', 'Apache Impala', '`', '`', ConnectType.py_driver, 'Impala', []) def __init__(self, type, db_name, prefix, suffix, connect_type: ConnectType, template_name: str, illegalParams: List[str]): diff --git a/backend/apps/db/db.py b/backend/apps/db/db.py index e37d5695e..fed629412 100644 --- a/backend/apps/db/db.py +++ b/backend/apps/db/db.py @@ -108,6 +108,21 @@ def get_extra_config(conf: DatasourceConf): return config_dict +def get_hs2_auth_config(ds_type: str, conf: DatasourceConf, extra_config: dict) -> dict: + """Resolve HS2 authentication without overriding explicit Kerberos settings.""" + config = dict(extra_config) + auth = config.get('auth', '').upper() + if auth == 'KERBEROS': + config['auth'] = auth + config.setdefault('kerberos_service_name', 'impala' if ds_type == 'impala' else 'hive') + # Kerberos uses the worker's credential cache, never a database password. + config.pop('password', None) + elif conf.password: + config['password'] = conf.password + config['auth'] = auth or 'LDAP' + return config + + def get_origin_connect(type: str, conf: DatasourceConf): extra_config_dict = get_extra_config(conf) if equals_ignore_case(type, "sqlServer"): @@ -266,6 +281,11 @@ def get_session(ds: CoreDatasource | AssistantOutDsSchema): def get_driver_connection(ds: CoreDatasource | AssistantOutDsSchema, db_config: dict = {}, use_pool: bool = False): conf = DatasourceConf(**json.loads(aes_decrypt(ds.configuration))) + if getattr(conf, 'kerberosMode', False): + if not equals_ignore_case(ds.type, 'hive', 'impala'): + raise ValueError('Kerberos requires HiveServer2') + from apps.db.kerberos_connection import KerberosConnection, KerberosPool + return KerberosPool(conf.model_dump()) if use_pool else KerberosConnection(conf.model_dump()) extra_config_dict = get_extra_config(conf) pool_config = { @@ -346,10 +366,8 @@ def get_driver_connection(ds: CoreDatasource | AssistantOutDsSchema, db_config: options=f"-c statement_timeout={conf.timeout * 1000}", **conn_conf ) - elif equals_ignore_case(ds.type, 'hive'): - if conf.password: - conn_conf['password'] = conf.password - conn_conf['auth'] = 'LDAP' + elif equals_ignore_case(ds.type, 'hive', 'impala'): + conn_conf = get_hs2_auth_config(ds.type, conf, conn_conf) if not use_pool: conn = hive.connect(host=conf.host, port=conf.port, username=conf.username, database=conf.database, @@ -368,6 +386,9 @@ def get_driver_connection(ds: CoreDatasource | AssistantOutDsSchema, db_config: def get_driver_pool(ds: CoreDatasource | AssistantOutDsSchema, db_config: dict = {}): + conf = DatasourceConf(**json.loads(aes_decrypt(ds.configuration))) + if getattr(conf, 'kerberosMode', False): + return get_driver_connection(ds, db_config, use_pool=True) pool = driver_pool_manager.get_pool(ds, db_config) return pool @@ -391,6 +412,15 @@ def check_connection(trans: Optional[Trans], ds: CoreDatasource | AssistantOutDs return False else: conf = DatasourceConf(**json.loads(aes_decrypt(ds.configuration))) + if getattr(conf, 'kerberosMode', False): + try: + with get_driver_connection(ds) as connection, connection.cursor() as cursor: + cursor.execute('select 1') + return True + except Exception: + if is_raise: + raise HTTPException(status_code=500, detail=trans('i18n_ds_kerberos_failed')) from None + return False extra_config_dict = get_extra_config(conf) if equals_ignore_case(ds.type, 'dm'): with dmPython.connect(user=conf.username, password=conf.password, server=conf.host, @@ -446,12 +476,12 @@ def check_connection(trans: Optional[Trans], ds: CoreDatasource | AssistantOutDs if is_raise: raise HTTPException(status_code=500, detail=trans('i18n_ds_invalid') + f': {e.args}') return False - elif equals_ignore_case(ds.type, 'hive'): - if conf.password: - extra_config_dict['password'] = conf.password - extra_config_dict['auth'] = 'LDAP' - with hive.connect(host=conf.host, port=conf.port, username=conf.username, database=conf.database, - **extra_config_dict) as conn, conn.cursor() as cursor: + elif equals_ignore_case(ds.type, 'hive', 'impala'): + extra_config_dict = get_hs2_auth_config(ds.type, conf, extra_config_dict) + connection = (get_driver_connection(ds) if getattr(conf, 'kerberosMode', False) else + hive.connect(host=conf.host, port=conf.port, username=conf.username, + database=conf.database, **extra_config_dict)) + with connection as conn, conn.cursor() as cursor: try: cursor.execute('select 1') SQLBotLogUtil.info("success") @@ -517,7 +547,7 @@ def get_version(ds: CoreDatasource | AssistantOutDsSchema): cursor.execute(sql) res = cursor.fetchall() version = res[0][0] - elif equals_ignore_case(ds.type, 'redshift', 'es', 'hive'): + elif equals_ignore_case(ds.type, 'redshift', 'es', 'hive', 'impala'): version = '' except Exception as e: print(e) @@ -617,7 +647,7 @@ def get_tables(ds: CoreDatasource): res = get_es_index(conf) res_list = [TableSchema(*item) for item in res] return res_list - elif equals_ignore_case(ds.type, 'hive'): + elif equals_ignore_case(ds.type, 'hive', 'impala'): with get_driver_connection(ds) as conn, conn.cursor() as cursor: cursor.execute(sql) res = cursor.fetchall() @@ -668,7 +698,7 @@ def get_fields(ds: CoreDatasource, table_name: str = None): res = get_es_fields(conf, table_name) res_list = [ColumnSchema(*item) for item in res] return res_list - elif equals_ignore_case(ds.type, 'hive'): + elif equals_ignore_case(ds.type, 'hive', 'impala'): with get_driver_pool(ds).connection() as conn, conn.cursor() as cursor: cursor.execute(sql) res = cursor.fetchall() @@ -1015,7 +1045,7 @@ def exec_sql(ds: CoreDatasource | AssistantOutDsSchema, sql: str, origin_column= "sql": bytes.decode(base64.b64encode(bytes(sql, 'utf-8')))} except Exception as ex: raise Exception(str(ex)) - elif equals_ignore_case(ds.type, 'hive'): + elif equals_ignore_case(ds.type, 'hive', 'impala'): with get_driver_pool(ds).connection() as conn, conn.cursor() as cursor: try: # Hive uses backticks for identifiers; normalize quoted identifiers as a compatibility fallback. @@ -1143,7 +1173,7 @@ def get_sqlglot_dialect(ds_type: str) -> str: return 'mysql' elif equals_ignore_case(ds_type, 'sqlServer'): return 'tsql' - elif equals_ignore_case(ds_type, 'hive'): + elif equals_ignore_case(ds_type, 'hive', 'impala'): return 'hive' return None @@ -1171,6 +1201,7 @@ def get_sqlglot_dialect(ds_type: str) -> str: 'sqlserver': {'EXEC', 'xp_cmdshell', 'sp_executesql'}, 'oracle': {'UTL_FILE', 'DBMS_PIPE', 'DBMS_LOCK'}, 'hive': {'ADD FILE', 'ADD JAR'}, + 'impala': {'ADD FILE', 'ADD JAR'}, } # 危险模式正则表达式(用于检查特殊语法) diff --git a/backend/apps/db/db_sql.py b/backend/apps/db/db_sql.py index 79b85a09e..d03158aa4 100644 --- a/backend/apps/db/db_sql.py +++ b/backend/apps/db/db_sql.py @@ -29,7 +29,7 @@ def get_version_sql(ds: CoreDatasource, conf: DatasourceConf): return """ SELECT * FROM v$version """ - elif equals_ignore_case(ds.type, "redshift", "sqlite", "hive"): + elif equals_ignore_case(ds.type, "redshift", "sqlite", "hive", "impala"): return '' @@ -162,7 +162,7 @@ def get_table_sql(ds: CoreDatasource, conf: DatasourceConf, db_version: str = '' """, conf.dbSchema elif equals_ignore_case(ds.type, "es"): return "", None - elif equals_ignore_case(ds.type, "hive"): + elif equals_ignore_case(ds.type, "hive", "impala"): return """ SHOW TABLES """, None @@ -316,6 +316,6 @@ def get_field_sql(ds: CoreDatasource, conf: DatasourceConf, table_name: str = No return sql1 + sql2, conf.dbSchema, table_name elif equals_ignore_case(ds.type, "es"): return "", None, None - elif equals_ignore_case(ds.type, "hive"): + elif equals_ignore_case(ds.type, "hive", "impala"): sql1 = f"DESCRIBE {table_name}" return sql1, None, None diff --git a/backend/apps/db/kerberos_connection.py b/backend/apps/db/kerberos_connection.py new file mode 100644 index 000000000..e1f7551ba --- /dev/null +++ b/backend/apps/db/kerberos_connection.py @@ -0,0 +1,307 @@ +"""Datasource-local Kerberos credentials; no changes to the API process environment.""" + +import base64 +import multiprocessing +import os +import re +import signal +import subprocess +import tempfile +import threading +from pathlib import Path + +_LIMIT = threading.BoundedSemaphore(8) +_ERROR = ( + "Kerberos connection failed; check credentials, KDC, DNS and runtime dependencies" +) + + +def validate_profile(text: str) -> str: + """Accept a deliberately small krb5 profile subset, excluding file/plugin directives.""" + if not isinstance(text, str) or len(text.encode()) > 65536: + raise ValueError("Invalid Kerberos profile") + section = "" + realm_open = False + output = [] + allowed = { + "default_realm", + "dns_lookup_kdc", + "dns_lookup_realm", + "rdns", + "dns_canonicalize_hostname", + "ticket_lifetime", + "renew_lifetime", + "forwardable", + "udp_preference_limit", + "clockskew", + } + for raw in text.splitlines(): + line = raw.strip() + if not line or line.startswith(("#", ";")): + continue + if line in ("[libdefaults]", "[realms]", "[domain_realm]") and not realm_open: + section = line[1:-1] + elif ( + section == "realms" + and not realm_open + and re.fullmatch(r"[A-Za-z0-9_.-]+\s*=\s*\{", line) + ): + realm_open = True + elif section == "realms" and realm_open and line == "}": + realm_open = False + else: + if "=" not in line: + raise ValueError("Unsupported Kerberos profile directive") + key, value = (part.strip() for part in line.split("=", 1)) + valid_key = ( + section == "libdefaults" + and key in allowed + or section == "realms" + and realm_open + and key in {"kdc", "admin_server", "kpasswd_server"} + or section == "domain_realm" + and re.fullmatch(r"\.?[A-Za-z0-9_.-]+", key) + ) + valid_value = re.fullmatch(r"[A-Za-z0-9_.:@-]+", value) or ( + section == "realms" + and key == "kdc" + and re.fullmatch(r"(?:tcp|udp)/[A-Za-z0-9_.-]+(?::[0-9]+)?", value) + ) + if not valid_key or not valid_value: + raise ValueError("Unsupported Kerberos profile setting") + output.append(line) + if realm_open or not output: + raise ValueError("Invalid Kerberos profile") + return "\n".join(output) + "\n" + + +def validate_credentials(config: dict) -> bytes: + validate_profile(config.get("kerberosConf", "")) + principal = config.get("kerberosPrincipal", "") + if not isinstance(principal, str) or not re.fullmatch( + r"[A-Za-z0-9_][A-Za-z0-9_./-]*@[A-Za-z0-9_.-]+", principal + ): + raise ValueError("Invalid Kerberos principal") + service = config.get("kerberosService", "") + if not isinstance(service, str) or not re.fullmatch( + r"[A-Za-z][A-Za-z0-9_-]{0,63}", service + ): + raise ValueError("Invalid Kerberos service") + host = config.get("kerberosHost", "") + if not isinstance(host, str) or ( + host + and ( + len(host) > 253 + or not all( + re.fullmatch(r"[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?", label) + for label in host.rstrip(".").split(".") + ) + ) + ): + raise ValueError("Invalid Kerberos service hostname") + encoded = config.get("kerberosKeytab", "") + if not isinstance(encoded, str) or len(encoded) > 350000: + raise ValueError("Invalid keytab size") + try: + keytab = base64.b64decode(encoded, validate=True) + except (ValueError, TypeError): + raise ValueError("Invalid keytab encoding") from None + if not 4 <= len(keytab) <= 262144 or keytab[:2] not in (b"\x05\x01", b"\x05\x02"): + raise ValueError("Invalid keytab") + return keytab + + +def connect_hs2(hive, config): + """Called only in a datasource-owned worker; keep TCP and SASL targets separate.""" + original = hive.get_installed_sasl + + def sasl_client(host, sasl_auth, service=None, username=None, password=None): + return original( + host=config.get("kerberosHost") or host, + sasl_auth=sasl_auth, + service=service, + username=username, + password=password, + ) + + hive.get_installed_sasl = sasl_client + try: + return hive.connect( + host=config["host"], + port=config["port"], + username=config["username"], + database=config["database"], + auth="KERBEROS", + kerberos_service_name=config["kerberosService"], + ) + finally: + hive.get_installed_sasl = original + + +def _worker(pipe, config, directory): + conn = cursor = None + # Include kinit in the worker's process group so cancellation cannot orphan it. + if hasattr(os, "setsid"): + os.setsid() + try: + root = Path(directory) + profile = root / "krb5.conf" + keytab = root / "client.keytab" + profile.write_text(validate_profile(config["kerberosConf"])) + keytab.write_bytes(validate_credentials(config)) + profile.chmod(0o600) + keytab.chmod(0o600) + # This process belongs to exactly one connection/identity. + os.environ["KRB5_CONFIG"] = str(profile) + os.environ["KRB5CCNAME"] = "FILE:" + str(root / "ccache") + os.environ["KRB5_CLIENT_KTNAME"] = str(keytab) + subprocess.run( + ["kinit", "-k", "-t", str(keytab), config["kerberosPrincipal"]], + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=30, + check=True, + ) + from pyhive import hive + + conn = connect_hs2(hive, config) + cursor = conn.cursor() + pipe.send((True, None)) + while True: + command, value = pipe.recv() + if command == "close": + break + if command == "execute": + cursor.execute(value) + pipe.send((True, cursor.description)) + elif command == "fetchall": + pipe.send((True, cursor.fetchall())) + else: + raise ValueError("Unsupported operation") + except (EOFError, BrokenPipeError): + pass + except Exception: + try: + pipe.send((False, _ERROR)) + except (EOFError, BrokenPipeError): + pass + finally: + if cursor is not None: + try: + cursor.close() + except Exception: + pass + if conn is not None: + try: + conn.close() + except Exception: + pass + pipe.close() + + +class KerberosConnection: + """Small DB-API facade. Each connection obtains fresh tickets and cleans them on close.""" + + def __init__(self, config): + validate_credentials(config) + self.timeout = max(1, min(config.get("timeout") or 30, 300)) + self.closed = False + self.description = None + if not _LIMIT.acquire(timeout=self.timeout): + raise RuntimeError(_ERROR) + self.directory = tempfile.TemporaryDirectory(prefix="sqlbot-kerberos-") + self.process = None + self.pipe = None + try: + context = multiprocessing.get_context("spawn") + self.pipe, child = context.Pipe() + self.process = context.Process( + target=_worker, args=(child, config, self.directory.name), daemon=True + ) + self.process.start() + child.close() + self._receive() + except BaseException: + self.close() + raise + + def _receive(self): + if not self.pipe.poll(self.timeout): + self.close() + raise RuntimeError(_ERROR) + try: + ok, result = self.pipe.recv() + except (EOFError, OSError): + self.close() + raise RuntimeError(_ERROR) from None + if not ok: + self.close() + raise RuntimeError(_ERROR) + return result + + def cursor(self): + return _Cursor(self) + + def close(self): + if self.closed: + return + self.closed = True + if self.pipe is not None: + self.pipe.close() + if self.process is not None and self.process.pid is not None: + self.process.join(timeout=0.2) + if self.process.is_alive(): + self._terminate_group(signal.SIGTERM) + self.process.join(timeout=2) + if self.process.is_alive(): + self._terminate_group(signal.SIGKILL) + self.process.join() + self.directory.cleanup() + _LIMIT.release() + + def _terminate_group(self, sig): + if hasattr(os, "killpg"): + try: + os.killpg(self.process.pid, sig) + return + except ProcessLookupError: + pass + if sig == signal.SIGTERM: + self.process.terminate() + else: + self.process.kill() + + def __enter__(self): + return self + + def __exit__(self, *args): + self.close() + + +class _Cursor: + def __init__(self, connection): + self.connection = connection + self.description = None + + def execute(self, sql): + self.connection.pipe.send(("execute", sql)) + self.description = self.connection._receive() + + def fetchall(self): + self.connection.pipe.send(("fetchall", None)) + return self.connection._receive() + + def __enter__(self): + return self + + def __exit__(self, *args): + pass + + +class KerberosPool: + def __init__(self, config): + self.config = config + + def connection(self): + return KerberosConnection(self.config) diff --git a/backend/locales/en.json b/backend/locales/en.json index 0e75ab900..7901f7f1d 100644 --- a/backend/locales/en.json +++ b/backend/locales/en.json @@ -1,4 +1,5 @@ { + "i18n_ds_kerberos_failed": "Kerberos connection failed. Check credentials, KDC connectivity, DNS and runtime dependencies.", "i18n_platform_token_cache_error": "Platform authentication is temporarily unavailable. Please retry or contact the administrator.", "ws_model_settings": "Workspace model settings", "system_model_workspace_impact": "Model change impact", diff --git a/backend/locales/ko-KR.json b/backend/locales/ko-KR.json index cd5350729..6f958d02e 100644 --- a/backend/locales/ko-KR.json +++ b/backend/locales/ko-KR.json @@ -1,4 +1,5 @@ { + "i18n_ds_kerberos_failed": "Kerberos 연결에 실패했습니다. 자격 증명, KDC 연결, DNS 및 런타임 종속성을 확인하세요.", "i18n_platform_token_cache_error": "플랫폼 인증을 일시적으로 사용할 수 없습니다. 다시 시도하거나 관리자에게 문의하세요.", "ws_model_settings": "워크스페이스 모델 설정", "system_model_workspace_impact": "모델 변경 영향", diff --git a/backend/locales/th-TH.json b/backend/locales/th-TH.json index bbc61c725..cb35a70d8 100644 --- a/backend/locales/th-TH.json +++ b/backend/locales/th-TH.json @@ -1,4 +1,5 @@ { + "i18n_ds_kerberos_failed": "เชื่อมต่อ Kerberos ไม่สำเร็จ โปรดตรวจสอบข้อมูลรับรอง การเชื่อมต่อ KDC, DNS และไลบรารีที่จำเป็น", "i18n_platform_token_cache_error": "ไม่สามารถใช้การยืนยันตัวตนของแพลตฟอร์มได้ชั่วคราว โปรดลองอีกครั้งหรือติดต่อผู้ดูแลระบบ", "ws_model_settings": "การตั้งค่าโมเดลเวิร์กสเปซ", "system_model_workspace_impact": "ผลกระทบจากการเปลี่ยนโมเดล", diff --git a/backend/locales/zh-CN.json b/backend/locales/zh-CN.json index a62d940ba..034dbcd81 100644 --- a/backend/locales/zh-CN.json +++ b/backend/locales/zh-CN.json @@ -1,4 +1,5 @@ { + "i18n_ds_kerberos_failed": "Kerberos 连接失败,请检查凭据、KDC 网络、DNS 和运行依赖。", "i18n_platform_token_cache_error": "平台认证暂时不可用,请重试或联系管理员。", "ws_model_settings": "工作空间模型设置", "system_model_workspace_impact": "模型变更影响", diff --git a/backend/locales/zh-TW.json b/backend/locales/zh-TW.json index a193b4d34..c1b5405e1 100644 --- a/backend/locales/zh-TW.json +++ b/backend/locales/zh-TW.json @@ -1,4 +1,5 @@ { + "i18n_ds_kerberos_failed": "Kerberos 連線失敗,請檢查憑證、KDC 網路、DNS 及執行環境相依套件。", "i18n_platform_token_cache_error": "平台驗證暫時無法使用,請重試或聯絡管理員。", "ws_model_settings": "工作空間模型設定", "system_model_workspace_impact": "模型變更影響", diff --git a/backend/pyproject.toml b/backend/pyproject.toml index 52619d104..bc79b40f4 100644 --- a/backend/pyproject.toml +++ b/backend/pyproject.toml @@ -56,6 +56,7 @@ dependencies = [ "numpy==2.3.5", "pyhive[hive_pure_sasl]>=0.7.0", "thrift-sasl", + "kerberos>=1.3.1,<2", "dbutils>=3.1.2", "mcp<2.0.0", ] diff --git a/backend/templates/sql_examples/Impala.yaml b/backend/templates/sql_examples/Impala.yaml new file mode 100644 index 000000000..ffe491ff0 --- /dev/null +++ b/backend/templates/sql_examples/Impala.yaml @@ -0,0 +1,109 @@ +template: + quot_rule: | + + 必须对数据库名、表名、字段名、别名外层加反引号(`)。 + + 1. 点号(.)不能包含在引号内,必须写成 `database`.`table` + 2. 即使标识符不含特殊字符或非关键字,也需强制加反引号 + 3. 在多表关联(JOIN)/ 多子查询的 SQL 中,只要多个表 / 子查询存在 同名字段,所有引用该字段的位置,必须显式指定 表别名 + + + + limit_rule: | + + 当需要限制行数时,必须使用标准的LIMIT语法 + + + other_rule: | + 必须为每个表生成别名(不加AS) + {multi_table_condition} + 禁止使用星号(*),必须明确字段名 + 中文/特殊字符字段需保留原名并添加英文别名 + 不能用 + 拼接字符串,字符串必须使用单引号 + 分组非常严格:SELECT 里的字段必须出现在 GROUP BY 里,或者是聚合函数 + 函数字段必须加别名 + 百分比字段保留两位小数并以%结尾 + WHERE 条件中不能使用 >、<、>=、<= 等比较运算符,必须使用 = + HIVE 中没有 NOT IN 操作符,必须使用 LEFT JOIN 或 EXISTS 替代 + 判空使用 NVL()函数 + 避免与数据库关键字冲突 + + basic_example: | + + + 📌 以下示例严格遵循中的 Impala 规范,展示符合要求的 SQL 写法与典型错误案例。 + ⚠️ 注意:示例中的表名、字段名均为演示虚构,实际使用时需替换为用户提供的真实标识符。 + 🔍 重点观察: + 1. 反引号包裹所有数据库对象的规范用法 + 2. 中英别名/百分比/函数等特殊字段的处理 + 3. 关键字冲突的规避方式 + + + 查询 ods.orders 表的前100条订单(含中文字段和百分比) + + SELECT * FROM ods.orders LIMIT 100 -- 错误:未加引号、使用星号 + SELECT `订单ID`, `金额` FROM `ods`.`orders` `t1` LIMIT 100 -- 错误:缺少英文别名 + SELECT COUNT(`订单ID`) FROM `ods`.`orders` `t1` -- 错误:函数未加别名 + + + SELECT + `t1`.`订单ID` AS `order_id`, + `t1`.`金额` AS `amount`, + COUNT(`t1`.`订单ID`) AS `total_orders`, + CONCAT(CAST(ROUND(`t1`.`折扣率` * 100, 2) AS STRING), '%') AS `discount_percent` + FROM `ods`.`orders` `t1` + GROUP BY `t1`.`订单ID`, `t1`.`金额`, `t1`.`折扣率` + LIMIT 100 + + + + + 统计 dim.users(含关键字字段user)的活跃占比 + + SELECT user, status FROM dim.users -- 错误:未处理关键字和引号 + SELECT `user`, ROUND(active_ratio) FROM `dim`.`users` -- 错误:百分比格式错误 + + + SELECT + `u`.`user` AS `username`, + CONCAT(CAST(ROUND(`u`.`active_ratio` * 100, 2) AS STRING), '%') AS `active_percent` + FROM `dim`.`users` `u` + WHERE `u`.`status` = 1 + + + + + 统计订单表 ods.orders 中2024年每个客户的消费总金额,返回金额最高的前100名客户 + + SELECT `t`.`customer_id` AS `customer_id`, SUM(`t`.`amount`) AS `total_amount` + FROM (SELECT `customer_id`, `amount` FROM `ods`.`orders` WHERE YEAR(`create_time`) = 2024 LIMIT 100) `t` + GROUP BY `t`.`customer_id` + -- 严重错误:LIMIT加在了内层子查询中,聚合只基于被截断的100行数据计算,结果错误! + + + SELECT + `o`.`customer_id` AS `customer_id`, + SUM(`o`.`amount`) AS `total_amount` + FROM `ods`.`orders` `o` + WHERE YEAR(`o`.`create_time`) = 2024 + GROUP BY `o`.`customer_id` + ORDER BY `total_amount` DESC + LIMIT 100 + -- 正确:聚合基于完整数据计算,LIMIT只限制最终返回结果的行数,且只出现在最外层查询 + + + + + example_engine: Apache Impala + example_answer_1: | + {"success":true,"sql":"SELECT `country` AS `country_name`, `continent` AS `continent_name`, `year` AS `year`, `gdp` AS `gdp` FROM `Sample_Database`.`sample_country_gdp` ORDER BY `country`, `year`","tables":["sample_country_gdp"],"chart-type":"line"} + example_answer_1_with_limit: | + {"success":true,"sql":"SELECT `country` AS `country_name`, `continent` AS `continent_name`, `year` AS `year`, `gdp` AS `gdp` FROM `Sample_Database`.`sample_country_gdp` ORDER BY `country`, `year` LIMIT 1000","tables":["sample_country_gdp"],"chart-type":"line"} + example_answer_2: | + {"success":true,"sql":"SELECT `country` AS `country_name`, `gdp` AS `gdp` FROM `Sample_Database`.`sample_country_gdp` WHERE `year` = '2024' ORDER BY `gdp` DESC","tables":["sample_country_gdp"],"chart-type":"pie"} + example_answer_2_with_limit: | + {"success":true,"sql":"SELECT `country` AS `country_name`, `gdp` AS `gdp` FROM `Sample_Database`.`sample_country_gdp` WHERE `year` = '2024' ORDER BY `gdp` DESC LIMIT 1000","tables":["sample_country_gdp"],"chart-type":"pie"} + example_answer_3: | + {"success":true,"sql":"SELECT `country` AS `country_name`, `gdp` AS `gdp` FROM `Sample_Database`.`sample_country_gdp` WHERE `year` = '2025' AND `country` = '中国'","tables":["sample_country_gdp"],"chart-type":"table"} + example_answer_3_with_limit: | + {"success":true,"sql":"SELECT `country` AS `country_name`, `gdp` AS `gdp` FROM `Sample_Database`.`sample_country_gdp` WHERE `year` = '2025' AND `country` = '中国' LIMIT 1000","tables":["sample_country_gdp"],"chart-type":"table"} diff --git a/backend/tests/test_datasource_configuration_crypto.py b/backend/tests/test_datasource_configuration_crypto.py index cfadb1f20..a8c4839ba 100644 --- a/backend/tests/test_datasource_configuration_crypto.py +++ b/backend/tests/test_datasource_configuration_crypto.py @@ -372,6 +372,85 @@ def post(path, **kwargs): assert saved not in caplog.text +def test_kerberos_encrypted_retention_rotation_and_disable(key_file): + from apps.datasource.crud.datasource import seal_browser_configuration + + config = { + "host": "hive.example.invalid", "port": 10000, "username": "sqlbot", + "database": "default", "password": "", "extraJdbc": "", + "kerberosMode": True, "kerberosPrincipal": "sqlbot@EXAMPLE.COM", + "kerberosService": "hive", + "kerberosConf": "[libdefaults]\ndefault_realm = EXAMPLE.COM\n", + "kerberosKeytab": base64.b64encode(b"\x05\x02synthetic-only").decode(), + } + stored = seal_browser_configuration(legacy(json.dumps(config))) + assert "synthetic-only" not in stored + assert aes_decrypt(stored) == json.dumps(config) + edited = {key: value for key, value in config.items() + if key not in {"kerberosConf", "kerberosKeytab"}} + retained = seal_browser_configuration(legacy(json.dumps(edited)), stored) + assert json.loads(aes_decrypt(retained)) == config + for change in ({"host": "other.example.invalid"}, + {"kerberosPrincipal": "other@EXAMPLE.COM"}, + {"kerberosService": "impala"}, + {"kerberosHost": "other.example.invalid"}, + {"kerberosConf": "[libdefaults]\ndefault_realm = OTHER.COM\n"}): + with pytest.raises(DatasourceConfigurationError): + seal_browser_configuration(legacy(json.dumps(edited | change)), stored) + rotated = config | {"kerberosKeytab": base64.b64encode(b"\x05\x02replacement").decode()} + assert json.loads(aes_decrypt(seal_browser_configuration(legacy(json.dumps(rotated)), stored))) == rotated + disabled = seal_browser_configuration(legacy(json.dumps(edited | {"kerberosMode": False})), stored) + assert json.loads(aes_decrypt(disabled))["kerberosKeytab"] == "" + assert json.loads(aes_decrypt(disabled))["kerberosConf"] == "" + with pytest.raises(DatasourceConfigurationError): + seal_browser_configuration(legacy(json.dumps(config | {"kerberosConf": "include /etc/passwd"}))) + + +def test_kerberos_details_redact_uploads_and_reject_other_workspace(key_file, monkeypatch): + import asyncio + import inspect + from types import SimpleNamespace + + from fastapi import HTTPException + + config = { + "kerberosMode": True, "kerberosPrincipal": "sqlbot@EXAMPLE.COM", + "kerberosService": "hive", "kerberosConf": "private-profile", + "kerberosKeytab": "private-keytab", "host": "hive.example.invalid", + } + record = CoreDatasource(id=123, oid=1, type="hive", configuration=aes_encrypt(json.dumps(config)).decode()) + monkeypatch.setattr(datasource, "get_ds", lambda *_: record) + handler = inspect.unwrap(datasource.get_datasource) + details = asyncio.run(handler(None, SimpleNamespace(oid=1), lambda key: key, 123)) + editable = json.loads(details["configuration"]) + assert editable["kerberosConfigured"] is True + assert editable["kerberosPrincipal"] == config["kerberosPrincipal"] + assert "kerberosConf" not in editable + assert "kerberosKeytab" not in editable + assert "private-" not in json.dumps(details) + with pytest.raises(HTTPException) as error: + asyncio.run(handler(None, SimpleNamespace(oid=2), lambda key: key, 123)) + assert error.value.status_code == 404 + request = CoreDatasource(id=123, type="hive", configuration=legacy(json.dumps(config))) + with pytest.raises(HTTPException) as error: + datasource._browser_configuration(None, SimpleNamespace(oid=2), lambda key: key, request) + assert error.value.status_code == 404 + + +def test_password_auth_edit_ignores_inactive_kerberos_defaults(key_file): + from apps.datasource.crud.datasource import seal_browser_configuration + + original = {"host": "db.example.invalid", "port": 21050, "username": "test", + "password": "synthetic-password", "database": "test", "extraJdbc": ""} + stored = seal_browser_configuration(legacy(json.dumps(original))) + request = {key: value for key, value in original.items() if key != "password"} + request.update(kerberosMode=False, kerberosPrincipal="", kerberosService="impala", kerberosHost="") + result = seal_browser_configuration(legacy(json.dumps(request)), stored) + assert json.loads(aes_decrypt(result))["password"] == original["password"] + changed = seal_browser_configuration(legacy(json.dumps(request | {"host": "other.example.invalid"})), stored) + assert json.loads(aes_decrypt(changed))["password"] == "" + + @pytest.mark.parametrize("field,value", [("host", "other.invalid"), ("database", "other"), ("extraJdbc", "sslmode=require")]) def test_changed_connection_does_not_reuse_password(key_file, field, value): from apps.datasource.crud.datasource import seal_browser_configuration diff --git a/backend/tests/test_hive_fields.py b/backend/tests/test_hive_fields.py index 378058a91..f7f9628dc 100644 --- a/backend/tests/test_hive_fields.py +++ b/backend/tests/test_hive_fields.py @@ -22,8 +22,8 @@ def _load_symbol(relative_path, name, namespace): return namespace[name] -@pytest.fixture -def get_hive_fields(): +@pytest.fixture(params=["hive", "impala"]) +def get_hive_fields(request): cursor = Mock() connection = SimpleNamespace(cursor=lambda: nullcontext(cursor)) pool = SimpleNamespace(connection=lambda: nullcontext(connection)) @@ -47,7 +47,7 @@ def get_hive_fields(): def discover(rows): cursor.fetchall.return_value = rows - fields = get_fields(SimpleNamespace(type="hive", configuration="{}"), "sample") + fields = get_fields(SimpleNamespace(type=request.param, configuration="{}"), "sample") return [(field.fieldName, field.fieldType, field.fieldComment) for field in fields] return discover diff --git a/docs/agents/packaging.md b/docs/agents/packaging.md index 47c37f9e4..f64e271d5 100644 --- a/docs/agents/packaging.md +++ b/docs/agents/packaging.md @@ -84,3 +84,7 @@ node --check g2-ssr/charts/ 6. 构建在线 / 离线安装包。 发布版本号、镜像 tag、离线包名、backend 包版本和 Git tag 必须由使用者明确确认。agent 不要自行发布、上传、打 tag 或推送。 + +## Kerberos 运行依赖 + +Hive/Impala 的应用内认证使用 Python kerberos(backend/pyproject.toml)和 kinit。应用 Dockerfile 在 runtime-base 安装 krb5-user、libgssapi-krb5-2;Python 扩展编译依赖现有构建基础镜像的 libkrb5-dev。无需挂载全局 keytab/票据缓存,上传文件由后端按连接临时解密使用。/opt/sqlbot 工作目录和现有数据、图表、日志挂载保持原布局。验证边界及客户端配置限制见 backend/README.md。 diff --git a/docs/agents/security.md b/docs/agents/security.md index ae9dd2f6d..53636a6c2 100644 --- a/docs/agents/security.md +++ b/docs/agents/security.md @@ -109,6 +109,10 @@ - 列表和写入响应省略配置。授权编辑详情只返回表单所需的字段,省略密码;额外连接参数向有权编辑的用户回显,允许修改或清空。编辑时连接目标不变且密码字段缺省表示保留原密码;连接目标变化且密码字段缺省时使用空密码,不沿用旧目标凭据。测试连接与更新沿用已存凭据时必须核对工作空间和连接目标。 - 启动迁移、备份恢复和密钥轮换见 [后端运行说明](../../backend/README.md#数据源存储密钥)。 +## 数据源 Kerberos + +Hive/Impala 上传的 krb5.conf 和 keytab 随数据源配置加密保存,编辑详情不回传;改变认证目标时重新提供凭据。配置文件必须通过 apps/db/kerberos_connection.py 的受限解析,禁止文件包含、插件和客户端指定服务器文件路径。认证在独立工作进程中执行,不修改请求服务进程的 Kerberos 环境或共享身份缓存。当前每次连接重新获取票据,结束时销毁临时缓存,不复用 Kerberos 长连接池;部署与验收边界见 backend/README.md。 + ## 本地账号绑定第三方身份 - 绑定业务在 xpack 的 `authentication/bindings.py`、`binding_providers.py`;共享存储契约在 `apps/system/models/user.py`,由主工程 Alembic 迁移管理。 diff --git a/docs/agents/testing.md b/docs/agents/testing.md index 8a88e064f..1af68e3c0 100644 --- a/docs/agents/testing.md +++ b/docs/agents/testing.md @@ -120,6 +120,10 @@ SQLBOT_PASSWORD_TEST_PG=1 uv run --no-sync pytest -q tests/test_local_password_h `backend/tests/test_datasource_configuration_crypto.py` 默认执行合成配置的离线加密回归。显式设置 `SQLBOT_DATASOURCE_TEST_DATABASE_URL` 后,在指定隔离 PostgreSQL 数据库内创建并清理随机 schema,执行配置迁移和真实 FastAPI 数据源路由测试。HTTP 测试注入合成身份,保留工作空间权限检查,隔离审计写入与 embedding 调度。预览使用真实连接,查询通过正常执行函数验证。 +## 数据源 Kerberos 离线回归 + +在 backend 目录运行 `uv run --no-sync python -m pytest -q tests/test_kerberos_connection.py tests/test_hs2_auth.py tests/test_hive_fields.py tests/test_connection_pool_manager.py tests/test_datasource_configuration_crypto.py`。子进程测试使用合成 kinit 和 PyHive 驱动,不访问 KDC,覆盖并发身份隔离、超时/失败清理及恶意配置拒绝;配置加密测试覆盖凭据保留/替换/清除、编辑详情脱敏和跨工作空间拒绝。配置加密模块中的 PostgreSQL 集成测试仍需按前文显式提供隔离数据库,离线通过不代表真实 KDC/数据库或完整 UI 验收。 + ## 账号绑定回归 绑定后端跨仓库回归位于 xpack 的 `tests/test_account_bindings.py`。在已按 xpack 联调步骤准备的隔离环境中,从主工程 `backend/` 执行(解释器必须确实导入待测的主工程和 xpack checkout): diff --git a/frontend/src/assets/datasource/impala-ds.png b/frontend/src/assets/datasource/impala-ds.png new file mode 100644 index 000000000..d414518b3 Binary files /dev/null and b/frontend/src/assets/datasource/impala-ds.png differ diff --git a/frontend/src/i18n/en.json b/frontend/src/i18n/en.json index 48e8d9907..d131e3721 100644 --- a/frontend/src/i18n/en.json +++ b/frontend/src/i18n/en.json @@ -424,6 +424,16 @@ "field_comment_label": "Field Comment" }, "form": { + "kerberos_host": "Kerberos service hostname", + "kerberos_host_hint": "Optional; defaults to connection host", + "kerberos_auth": "Kerberos authentication", + "kerberos_principal": "Client principal", + "kerberos_service": "Service name", + "kerberos_required": "Enter the client principal", + "kerberos_selected": "Selected", + "kerberos_saved": "Credentials saved. Leave uploads empty to retain them. When changing connection settings, upload both files again.", + "kerberos_upload_hint": "Upload krb5.conf (up to 64 KB) and keytab (up to 256 KB). Tickets are obtained automatically for each connection.", + "kerberos_file_error": "Unable to read file or file exceeds size limit", "title": { "add": "Add Datasource", "edit": "Edit Datasource", diff --git a/frontend/src/i18n/ko-KR.json b/frontend/src/i18n/ko-KR.json index 165d76f2d..c7e4717ba 100644 --- a/frontend/src/i18n/ko-KR.json +++ b/frontend/src/i18n/ko-KR.json @@ -424,6 +424,16 @@ "field_comment_label": "필드 주석" }, "form": { + "kerberos_host": "Kerberos 서비스 호스트 이름", + "kerberos_host_hint": "선택 사항, 비워두면 연결 호스트 사용", + "kerberos_auth": "Kerberos 인증", + "kerberos_principal": "클라이언트 principal", + "kerberos_service": "서비스 이름", + "kerberos_required": "클라이언트 principal을 입력하세요", + "kerberos_selected": "선택됨", + "kerberos_saved": "자격 증명이 저장되었습니다. 유지하려면 업로드하지 마세요. 연결 설정을 변경하면 두 파일을 다시 업로드하세요.", + "kerberos_upload_hint": "krb5.conf(최대 64 KB)와 keytab(최대 256 KB)을 업로드하세요. 연결마다 티켓을 자동 발급합니다.", + "kerberos_file_error": "파일을 읽을 수 없거나 크기 제한을 초과했습니다", "title": { "add": "데이터 소스 추가", "edit": "데이터 소스 편집", diff --git a/frontend/src/i18n/th-TH.json b/frontend/src/i18n/th-TH.json index b653e0f26..4fcc46eb0 100644 --- a/frontend/src/i18n/th-TH.json +++ b/frontend/src/i18n/th-TH.json @@ -424,6 +424,16 @@ "field_comment_label": "คำอธิบายฟิลด์" }, "form": { + "kerberos_host": "ชื่อโฮสต์บริการ Kerberos", + "kerberos_host_hint": "ไม่บังคับ หากเว้นว่างจะใช้โฮสต์การเชื่อมต่อ", + "kerberos_auth": "การยืนยันตัวตน Kerberos", + "kerberos_principal": "principal ของไคลเอนต์", + "kerberos_service": "ชื่อบริการ", + "kerberos_required": "กรอก principal ของไคลเอนต์", + "kerberos_selected": "เลือกแล้ว", + "kerberos_saved": "บันทึกข้อมูลรับรองแล้ว เว้นไฟล์ว่างเพื่อเก็บค่าเดิม หากเปลี่ยนการเชื่อมต่อให้อัปโหลดทั้งสองไฟล์ใหม่", + "kerberos_upload_hint": "อัปโหลด krb5.conf (สูงสุด 64 KB) และ keytab (สูงสุด 256 KB) ระบบรับตั๋วใหม่ทุกครั้งที่เชื่อมต่อ", + "kerberos_file_error": "อ่านไฟล์ไม่ได้หรือไฟล์เกินขนาดที่กำหนด", "title": { "add": "เพิ่มแหล่งข้อมูล", "edit": "แก้ไขแหล่งข้อมูล", diff --git a/frontend/src/i18n/zh-CN.json b/frontend/src/i18n/zh-CN.json index e35193c2b..2e9edb93b 100644 --- a/frontend/src/i18n/zh-CN.json +++ b/frontend/src/i18n/zh-CN.json @@ -424,6 +424,16 @@ "field_comment_label": "字段注释" }, "form": { + "kerberos_host": "Kerberos 服务主机名", + "kerberos_host_hint": "选填,留空时使用连接主机", + "kerberos_auth": "Kerberos 认证", + "kerberos_principal": "客户端 principal", + "kerberos_service": "服务名", + "kerberos_required": "请填写客户端 principal", + "kerberos_selected": "已选择", + "kerberos_saved": "凭据已保存。不上传时保留;更改连接目标或认证配置时,请重新上传两个文件。", + "kerberos_upload_hint": "请上传 krb5.conf(最多 64 KB)和 keytab(最多 256 KB),每次建立连接自动获取票据。", + "kerberos_file_error": "文件读取失败或超过大小限制", "title": { "add": "添加数据源", "edit": "编辑数据源", diff --git a/frontend/src/i18n/zh-TW.json b/frontend/src/i18n/zh-TW.json index a5d516d92..759deb403 100644 --- a/frontend/src/i18n/zh-TW.json +++ b/frontend/src/i18n/zh-TW.json @@ -424,6 +424,16 @@ "field_comment_label": "欄位註解" }, "form": { + "kerberos_host": "Kerberos 服務主機名稱", + "kerberos_host_hint": "選填,留空時使用連線主機", + "kerberos_auth": "Kerberos 驗證", + "kerberos_principal": "用戶端 principal", + "kerberos_service": "服務名稱", + "kerberos_required": "請填寫用戶端 principal", + "kerberos_selected": "已選擇", + "kerberos_saved": "憑證已儲存。不上傳時保留;變更連線目標或驗證設定時,請重新上傳兩個檔案。", + "kerberos_upload_hint": "請上傳 krb5.conf(最多 64 KB)及 keytab(最多 256 KB),每次建立連線自動取得票證。", + "kerberos_file_error": "檔案讀取失敗或超過大小限制", "title": { "add": "新增資料來源", "edit": "編輯資料來源", diff --git a/frontend/src/views/ds/DatasourceForm.vue b/frontend/src/views/ds/DatasourceForm.vue index 3639717ae..7ef34f911 100644 --- a/frontend/src/views/ds/DatasourceForm.vue +++ b/frontend/src/views/ds/DatasourceForm.vue @@ -6,7 +6,7 @@ import icon_upload_outlined from '@/assets/svg/icon_upload_outlined.svg' import icon_searchOutline_outlined from '@/assets/svg/icon_search-outline_outlined.svg' import { encrypted } from './js/aes' import { ElMessage } from 'element-plus-secondary' -import type { FormInstance, FormRules } from 'element-plus-secondary' +import type { FormInstance, FormRules, UploadFile } from 'element-plus-secondary' import icon_form_outlined from '@/assets/svg/icon_form_outlined.svg' import FixedSizeList from 'element-plus-secondary/es/components/virtual-list/src/components/fixed-size-list.mjs' import { debounce } from 'lodash-es' @@ -148,6 +148,13 @@ const form = ref({ ssl: false, poolSize: 5, engine: 'hive', + kerberosMode: false, + kerberosPrincipal: '', + kerberosService: '', + kerberosHost: '', + kerberosConf: '', + kerberosKeytab: '', + kerberosConfigured: false, }) const close = () => { @@ -203,6 +210,13 @@ const initForm = (item: any, editTable: boolean = false) => { ? configuration.poolSize : 5 form.value.engine = configuration.engine ? configuration.engine : 'hive' + form.value.kerberosMode = configuration.kerberosMode ?? false + form.value.kerberosPrincipal = configuration.kerberosPrincipal ?? '' + form.value.kerberosService = configuration.kerberosService ?? '' + form.value.kerberosHost = configuration.kerberosHost ?? '' + form.value.kerberosConf = '' + form.value.kerberosKeytab = '' + form.value.kerberosConfigured = configuration.kerberosConfigured ?? false } savedConnection.value = connectionSnapshot() @@ -279,6 +293,13 @@ const initForm = (item: any, editTable: boolean = false) => { ssl: false, poolSize: 5, engine: 'hive', + kerberosMode: false, + kerberosPrincipal: '', + kerberosService: '', + kerberosHost: '', + kerberosConf: '', + kerberosKeytab: '', + kerberosConfigured: false, } } dialogVisible.value = true @@ -352,15 +373,39 @@ const save = async (formEl: FormInstance | undefined) => { }) } +const readKerberosFile = async (upload: UploadFile, field: 'kerberosConf' | 'kerberosKeytab') => { + const file = upload.raw + if (!file) return + try { + const limit = field === 'kerberosConf' ? 65536 : 262144 + if (file.size > limit || file.size === 0) throw new Error('size') + if (field === 'kerberosConf') { + form.value[field] = await file.text() + } else { + const bytes = new Uint8Array(await file.arrayBuffer()) + let binary = '' + for (const byte of bytes) binary += String.fromCharCode(byte) + form.value[field] = btoa(binary) + } + } catch { + form.value[field] = '' + ElMessage.error(t('ds.form.kerberos_file_error')) + } +} + const buildConf = () => { form.value.configuration = encrypted( JSON.stringify({ host: form.value.host, port: form.value.port, username: form.value.username, - password: form.value.id && !form.value.password ? undefined : form.value.password, + password: form.value.kerberosMode + ? '' + : form.value.id && !form.value.password + ? undefined + : form.value.password, database: form.value.database, - extraJdbc: form.value.extraJdbc, + extraJdbc: form.value.kerberosMode ? '' : form.value.extraJdbc, dbSchema: form.value.dbSchema, filename: form.value.filename, sheets: form.value.sheets, @@ -370,6 +415,14 @@ const buildConf = () => { ssl: form.value.ssl, poolSize: form.value.poolSize, engine: form.value.engine, + kerberosMode: ['hive', 'impala'].includes(form.value.type) && form.value.kerberosMode, + kerberosPrincipal: form.value.kerberosPrincipal, + kerberosHost: form.value.kerberosHost, + kerberosService: + form.value.kerberosService || (form.value.type === 'impala' ? 'impala' : 'hive'), + kerberosConf: form.value.id && !form.value.kerberosConf ? undefined : form.value.kerberosConf, + kerberosKeytab: + form.value.id && !form.value.kerberosKeytab ? undefined : form.value.kerberosKeytab, }) ) const obj = JSON.parse(JSON.stringify(form.value)) @@ -389,6 +442,13 @@ const buildConf = () => { delete obj.ssl delete obj.poolSize delete obj.engine + delete obj.kerberosMode + delete obj.kerberosPrincipal + delete obj.kerberosService + delete obj.kerberosHost + delete obj.kerberosConf + delete obj.kerberosKeytab + delete obj.kerberosConfigured return obj } @@ -729,7 +789,72 @@ defineExpose({ " /> - + + + + +