Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -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 ] \
Expand Down
20 changes: 20 additions & 0 deletions backend/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 客户端明确指定传输协议。
7 changes: 4 additions & 3 deletions backend/apps/datasource/api/datasource.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down
26 changes: 21 additions & 5 deletions backend/apps/datasource/crud/datasource.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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"""
Expand Down Expand Up @@ -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"
Expand Down Expand Up @@ -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:
Expand Down
14 changes: 13 additions & 1 deletion backend/apps/datasource/models/datasource.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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
}


Expand Down
1 change: 1 addition & 0 deletions backend/apps/db/constant.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]):
Expand Down
61 changes: 46 additions & 15 deletions backend/apps/db/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"):
Expand Down Expand Up @@ -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 = {
Expand Down Expand Up @@ -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,
Expand All @@ -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

Expand All @@ -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,
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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'},
}

# 危险模式正则表达式(用于检查特殊语法)
Expand Down
6 changes: 3 additions & 3 deletions backend/apps/db/db_sql.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 ''


Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Loading
Loading