From 8f8432856cc2d15b3bb342c5cb152c7856ef005f Mon Sep 17 00:00:00 2001 From: x_zhuo <12474586+zx06@users.noreply.github.com> Date: Fri, 6 Nov 2026 10:56:21 +0000 Subject: [PATCH 1/3] =?UTF-8?q?fix:=20=E5=8A=A0=E5=9B=BA=E5=8F=AA=E8=AF=BB?= =?UTF-8?q?=20SQL=20=E6=A0=A1=E9=AA=8C=E3=80=81Web/PG=20=E5=AE=89=E5=85=A8?= =?UTF-8?q?=E5=8F=8A=E5=85=A8=E9=93=BE=E8=B7=AF=E9=85=8D=E7=BD=AE=E4=B8=8E?= =?UTF-8?q?=E5=85=83=E6=95=B0=E6=8D=AE=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- AGENTS.md | 2 +- cmd/xsql/mcp.go | 40 ++++++---- cmd/xsql/root.go | 60 +++++++-------- cmd/xsql/stats.go | 49 +++++++++--- cmd/xsql/web.go | 3 +- docs/architecture.md | 5 +- docs/cli-spec.md | 6 +- docs/config.md | 5 +- docs/db.md | 6 +- docs/rfcs/0016-error-guidance-for-agents.md | 2 +- docs/rfcs/0017-query-result-size-limits.md | 2 +- docs/rfcs/README.md | 4 +- docs/testing.md | 1 - internal/app/app.go | 38 ++++++++++ internal/app/max_rows.go | 4 +- internal/app/service.go | 6 ++ internal/config/mask.go | 17 ++++- internal/config/mask_test.go | 13 +++- internal/config/write.go | 20 ++++- internal/db/mysql/schema.go | 18 ++++- internal/db/pg/driver.go | 19 +++-- internal/db/pg/driver_test.go | 19 +++++ internal/db/pg/schema.go | 63 ++++++++++------ internal/db/query.go | 10 +-- internal/db/readonly.go | 67 ++++++++++++----- internal/db/readonly_test.go | 8 ++ internal/errors/exitcode.go | 2 +- internal/errors/guidance.go | 18 +++++ internal/mcp/query_result.go | 10 ++- internal/mcp/tools.go | 38 +++++++--- internal/mcp/write.go | 2 +- internal/ssh/client.go | 2 +- internal/ssh/reconnect.go | 23 +++++- internal/stats/store.go | 15 ++-- internal/web/handler.go | 78 +++++++++++++++----- internal/web/handler_test.go | 30 ++++++++ internal/web/server.go | 2 +- internal/web/server_test.go | 2 +- tests/e2e/README.md | 1 - webui/dist/.keep | 0 webui/src/App.svelte | 4 + webui/src/lib/components/ConfigModal.svelte | 12 +++ webui/src/lib/components/Navbar.svelte | 12 +++ webui/src/lib/components/ResultsTable.svelte | 11 +++ webui/src/lib/result-grid.js | 6 +- webui/src/lib/web-ui.svelte.js | 27 +++++-- 46 files changed, 594 insertions(+), 188 deletions(-) create mode 100644 webui/dist/.keep diff --git a/AGENTS.md b/AGENTS.md index fe0b444a..c654203a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -71,7 +71,7 @@ - 目标数据库:MySQL + PostgreSQL。 - 可扩展性:通过 driver registry 扩展新 DB。 - **默认只读**:防止误操作,默认启用双重只读保护(SQL 静态分析 + 数据库事务级只读)。 -- **CLI 写入双重授权**:profile 必须配置 `unsafe_allow_write: true`,且当前 `query` 命令必须同时携带 `--unsafe-allow-write`;任一条件缺失都保持只读。 +- **CLI / MCP 写入双重授权**:profile 必须配置 `unsafe_allow_write: true`,且当前 `query` 命令或 `mcp server` 必须同时携带 `--unsafe-allow-write`(或 `XSQL_MCP_UNSAFE_ALLOW_WRITE=true`);任一条件缺失都保持只读。Web 始终强制只读。 - **AI 调用标记**:Codex 发起的 xsql CLI 调用必须携带 `--attr source=codex-cli`,建议同时追加 `agent`、`env`、`team`、`task` 等 attr;其他 AI 客户端应使用自己的稳定 source 值,且不得覆盖 source。 - 只读拦截必须返回明确错误码(退出码=4)。 diff --git a/cmd/xsql/mcp.go b/cmd/xsql/mcp.go index f057a8c8..297bffe8 100644 --- a/cmd/xsql/mcp.go +++ b/cmd/xsql/mcp.go @@ -62,6 +62,8 @@ func runMCPServer(opts *mcpServerOptions) error { // Load config cfg, _, xe := config.LoadConfig(config.Options{ ConfigPath: GlobalConfig.ConfigStr, + WorkDir: os.Getenv("XSQL_WORKDIR"), + HomeDir: os.Getenv("XSQL_HOMEDIR"), }) if xe != nil { return xe @@ -74,6 +76,7 @@ func runMCPServer(opts *mcpServerOptions) error { server, err := mcp_pkg.CreateServer(version, &cfg, GlobalConfig.Stats, mcp_pkg.ServerOptions{ UnsafeAllowWrite: resolved.unsafeAllowWrite, + Attrs: GlobalConfig.Attrs, }) if err != nil { if xe, ok := err.(*errors.XError); ok { @@ -90,10 +93,13 @@ func runMCPServer(opts *mcpServerOptions) error { sigChan := make(chan os.Signal, 1) signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM) + defer signal.Stop(sigChan) go func() { - <-sigChan - signal.Stop(sigChan) - cancel() + select { + case <-sigChan: + cancel() + case <-ctx.Done(): + } }() if err := runMCPStdioServer(ctx, server); err != nil && !stderrors.Is(err, context.Canceled) { @@ -109,23 +115,29 @@ func runMCPServer(opts *mcpServerOptions) error { return errors.Wrap(errors.CodeInternal, "failed to create streamable http handler", nil, err) } httpServer := &http.Server{ - Addr: resolved.httpAddr, - Handler: handler, - ReadTimeout: 30 * time.Second, - WriteTimeout: 30 * time.Second, - IdleTimeout: 120 * time.Second, + Addr: resolved.httpAddr, + Handler: handler, + ReadHeaderTimeout: 15 * time.Second, + ReadTimeout: 30 * time.Second, + WriteTimeout: 120 * time.Second, + IdleTimeout: 120 * time.Second, } sigChan := make(chan os.Signal, 1) signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM) + defer signal.Stop(sigChan) + done := make(chan struct{}) + defer close(done) go func() { - <-sigChan - signal.Stop(sigChan) - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) - defer cancel() - if shutdownErr := httpServer.Shutdown(ctx); shutdownErr != nil { - log.Printf("[mcp] http server shutdown error: %v", shutdownErr) + select { + case <-sigChan: + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if shutdownErr := httpServer.Shutdown(ctx); shutdownErr != nil { + log.Printf("[mcp] http server shutdown error: %v", shutdownErr) + } + case <-done: } }() diff --git a/cmd/xsql/root.go b/cmd/xsql/root.go index 20abf948..9598a67b 100644 --- a/cmd/xsql/root.go +++ b/cmd/xsql/root.go @@ -2,6 +2,7 @@ package main import ( "os" + "strconv" "github.com/spf13/cobra" @@ -38,34 +39,6 @@ func NewRootCommand() *cobra.Command { Use: "xsql", SilenceUsage: true, SilenceErrors: true, - PersistentPreRunE: func(cmd *cobra.Command, args []string) error { - // CLI > ENV > Config - formatSet := cmd.Flags().Changed("format") - profileSet := cmd.Flags().Changed("profile") - configSet := cmd.Flags().Changed("config") - if configSet && GlobalConfig.ConfigStr == "" { - return errors.New(errors.CodeCfgInvalid, "config path is empty", nil) - } - - r, xe := config.Resolve(config.Options{ - ConfigPath: GlobalConfig.ConfigStr, - CLIProfile: GlobalConfig.ProfileStr, - CLIProfileSet: profileSet, - CLIFormat: GlobalConfig.FormatStr, - CLIFormatSet: formatSet, - EnvProfile: os.Getenv("XSQL_PROFILE"), - EnvFormat: os.Getenv("XSQL_FORMAT"), - WorkDir: os.Getenv("XSQL_WORKDIR"), - HomeDir: os.Getenv("XSQL_HOMEDIR"), - }) - if xe != nil { - return xe - } - GlobalConfig.Resolved = r - GlobalConfig.FormatStr = r.Format - GlobalConfig.ProfileStr = r.ProfileName - return nil - }, } var cliAttrs []string @@ -104,8 +77,11 @@ func NewRootCommand() *cobra.Command { // Parse attributes: CLI > ENV GlobalConfig.Attrs = stats.ParseAttrs(cliAttrs, stats.GetXSQLAttrEnv()) + if err := stats.ValidateAttrs(GlobalConfig.Attrs); err != nil { + return errors.Wrap(errors.CodeCfgInvalid, err.Error(), nil, err) + } - // Load stats config from file + // Load stats config from file + ENV overrides GlobalConfig.Stats = loadStatsConfig(GlobalConfig.ConfigStr) return nil @@ -114,11 +90,27 @@ func NewRootCommand() *cobra.Command { return root } -// loadStatsConfig loads stats configuration from the config file. +// loadStatsConfig loads stats configuration from the config file and applies environment overrides. func loadStatsConfig(configPath string) stats.StatsConfig { - cfg, _, xe := config.LoadConfig(config.Options{ConfigPath: configPath}) - if xe != nil { - return stats.StatsConfig{} + var st stats.StatsConfig + cfg, _, xe := config.LoadConfig(config.Options{ + ConfigPath: configPath, + WorkDir: os.Getenv("XSQL_WORKDIR"), + HomeDir: os.Getenv("XSQL_HOMEDIR"), + }) + if xe == nil { + st = cfg.Stats + } + if envEnabled := os.Getenv("XSQL_STATS_ENABLED"); envEnabled != "" { + if parsed, err := strconv.ParseBool(envEnabled); err == nil { + st.Enabled = parsed + } } - return cfg.Stats + if envLogSQL := os.Getenv("XSQL_STATS_LOG_SQL"); envLogSQL != "" { + if parsed, err := strconv.ParseBool(envLogSQL); err == nil { + st.LogSQL = parsed + } + } + return st } + diff --git a/cmd/xsql/stats.go b/cmd/xsql/stats.go index e87d5ea6..5b84ce7a 100644 --- a/cmd/xsql/stats.go +++ b/cmd/xsql/stats.go @@ -47,7 +47,22 @@ func NewStatsCommand(w *output.Writer) *cobra.Command { return cmd } +func resolveStatsFormat(jsonFlag bool) (output.Format, error) { + if jsonFlag { + return output.FormatJSON, nil + } + if GlobalConfig.FormatStr != "" && GlobalConfig.FormatStr != string(output.FormatAuto) { + return parseOutputFormat(GlobalConfig.FormatStr) + } + return output.FormatTable, nil +} + func runStats(flags *StatsFlags, w *output.Writer) error { + format, err := resolveStatsFormat(flags.JSON) + if err != nil { + return err + } + store := stats.NewStore(GlobalConfig.Stats.FilePath) records, err := store.Load() if err != nil { @@ -61,11 +76,6 @@ func runStats(flags *StatsFlags, w *output.Writer) error { agg := stats.Query(records, filter) - format := output.FormatTable - if flags.JSON { - format = output.FormatJSON - } - return w.WriteOK(format, &stats.StatsResult{Records: agg}) } @@ -88,6 +98,11 @@ func newStatsLogCommand(w *output.Writer) *cobra.Command { } func runStatsLog(flags *StatsLogFlags, w *output.Writer) error { + format, err := resolveStatsFormat(flags.JSON) + if err != nil { + return err + } + store := stats.NewStore(GlobalConfig.Stats.FilePath) records, err := store.Load() if err != nil { @@ -116,11 +131,6 @@ func runStatsLog(flags *StatsLogFlags, w *output.Writer) error { result[i] = *r } - format := output.FormatTable - if flags.JSON { - format = output.FormatJSON - } - return w.WriteOK(format, &stats.LogResult{ Records: result, Total: len(records), @@ -128,13 +138,26 @@ func runStatsLog(flags *StatsLogFlags, w *output.Writer) error { } func newStatsResetCommand(w *output.Writer) *cobra.Command { - return &cobra.Command{ + var jsonFlag bool + cmd := &cobra.Command{ Use: "reset", Short: "Reset usage statistics", RunE: func(cmd *cobra.Command, args []string) error { + if jsonFlag || (GlobalConfig.FormatStr != "" && GlobalConfig.FormatStr != string(output.FormatAuto)) { + format, err := resolveStatsFormat(jsonFlag) + if err != nil { + return err + } + if err := runStatsReset(w); err != nil { + return err + } + return w.WriteOK(format, map[string]any{"reset": true}) + } return runStatsReset(w) }, } + cmd.Flags().BoolVar(&jsonFlag, "json", false, "Output as JSON") + return cmd } func runStatsReset(w *output.Writer) error { @@ -173,4 +196,8 @@ func recordCmdStats(cmd string, profile string, ok bool, start time.Duration, er // Best-effort: don't fail the command if stats recording fails _ = store.Append(r) + if GlobalConfig.Stats.RetentionDays > 0 { + _, _ = store.Cleanup(GlobalConfig.Stats.RetentionDays) + } } + diff --git a/cmd/xsql/web.go b/cmd/xsql/web.go index 86ef52f7..ec1e7b04 100644 --- a/cmd/xsql/web.go +++ b/cmd/xsql/web.go @@ -101,6 +101,7 @@ func runWebCommand(opts *webCommandOptions, w *output.Writer) error { AuthRequired: resolved.authRequired, AuthToken: resolved.authToken, Stats: GlobalConfig.Stats, + Attrs: GlobalConfig.Attrs, }) server := webpkg.NewServer(listener, handler) url := webpkg.PublicURL(server.Addr()) @@ -187,7 +188,7 @@ func resolveWebOptions(opts *webCommandOptions, cfg config.File) (resolvedWebOpt authToken = secretValue } - authRequired := !webpkg.IsLoopbackAddr(addr) + authRequired := !webpkg.IsLoopbackAddr(addr) || authToken != "" if authRequired && authToken == "" { return resolvedWebOptions{}, errors.New(errors.CodeCfgInvalid, "web auth token is required for non-loopback addresses", map[string]any{"addr": addr}) } diff --git a/docs/architecture.md b/docs/architecture.md index 2e6552ee..2411d104 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1,7 +1,7 @@ # 架构设计(Architecture) ## 分层原则 -- 核心能力(config/db/ssh/output)与 CLI 解耦,便于未来扩展 MCP/TUI/Web。 +- 核心能力(config/db/ssh/output)与 CLI 解耦,便于扩展 MCP/Web。 - 输出与错误遵循稳定契约,优先保证 AI/agent 可消费。 ## 建议目录结构 @@ -27,6 +27,7 @@ ## 关键扩展点 - DB driver:通过 registry 注册,实现新数据库无需改动核心逻辑。 - 输出 formatter:通过接口注册新格式。 -- Frontend:CLI/MCP/TUI/Web 仅是调用 `internal/app` 的不同适配层。 +- Frontend:CLI/MCP/Web 仅是调用 `internal/app` 的不同适配层。 - MCP:`internal/mcp` 注册 MCP tools,数据库与 schema 操作经 `internal/app`(与 Web 相同),不重复实现连接/SSH。 - Web:本地 HTTP server 与嵌入式前端通过 `internal/web` 适配,复用 `internal/app` 业务服务。 + diff --git a/docs/cli-spec.md b/docs/cli-spec.md index 9fb4bc29..1b88caf0 100644 --- a/docs/cli-spec.md +++ b/docs/cli-spec.md @@ -131,6 +131,7 @@ xsql schema dump -p dev --include-system | `--include-system` | false | 包含系统表 | | `--allow-plaintext` | false | 允许配置中使用明文密码 | | `--ssh-skip-known-hosts-check` | false | 跳过 SSH 主机密钥验证(危险) | +| `--schema-timeout` | 60 | Schema 导出超时(秒);profile 可用 `schema_timeout` 覆盖 | **输出示例(JSON):** ```json @@ -492,8 +493,9 @@ xsql config set ssh_proxy.bastion.user admin | Flag | 说明 | |------|------| | `--config ` | 指定 YAML 配置文件路径 | -| `--profile ` | 选择 profile(等价 ENV:`XSQL_PROFILE`) | -| `--format ` | 输出格式(等价 ENV:`XSQL_FORMAT`) | +| `-p, --profile ` | 选择 profile(等价 ENV:`XSQL_PROFILE`) | +| `-f, --format ` | 输出格式(等价 ENV:`XSQL_FORMAT`) | +| `--attr ` | 标记会话属性(可重复,等价 ENV:`XSQL_ATTR`) | ## 格式说明 diff --git a/docs/config.md b/docs/config.md index 589a8fe7..f2c4841f 100644 --- a/docs/config.md +++ b/docs/config.md @@ -155,15 +155,16 @@ Profile 还可设置 `max_rows`(query 默认行数上限,CLI/Web 默认 1000 | `user` | string | 数据库用户名 | | `password` | string | 密码(支持 `keyring:` 引用) | | `database` | string | 数据库名 | -| `unsafe_allow_write` | bool | 允许该 profile 进入写模式(默认 false);CLI 仍需本次命令携带 `--unsafe-allow-write` | +| `unsafe_allow_write` | bool | 允许该 profile 进入写模式(默认 false);CLI/MCP 仍需同时携带 `--unsafe-allow-write`(或 `XSQL_MCP_UNSAFE_ALLOW_WRITE=true`) | | `allow_plaintext` | bool | 允许明文密码(默认 false) | | `format` | string | 输出格式:json/yaml/table/csv/auto | | `local_port` | int | proxy 本地监听端口(默认 0,自动分配) | | `ssh_proxy` | string | SSH 代理名称(引用 `ssh_proxies` 中定义的名称) | | `query_timeout` | int | 查询超时秒数(默认 30 秒) | | `schema_timeout` | int | Schema 导出超时秒数(默认 60 秒) | +| `max_rows` | int | 查询默认返回行数上限(CLI/Web 默认 1000,MCP 默认 500) | -> **CLI 写入双重授权**:`xsql query` 只有在所选 profile 配置 `unsafe_allow_write: true` 且当前命令同时携带 `--unsafe-allow-write` 时才会绕过只读保护。配置或 flag 单独开启都不会允许 CLI 写入。MCP 仍由 profile 配置控制,Web 始终只读。 +> **CLI / MCP 写入双重授权**:`xsql query` 与 `xsql mcp server` 只有在所选 profile 配置 `unsafe_allow_write: true` 且当前运行入口同时携带 `--unsafe-allow-write`(MCP 也支持 `XSQL_MCP_UNSAFE_ALLOW_WRITE=true`)时才会绕过只读保护。配置或运行时开关单独开启都不会允许写入。Web 始终强制只读。 ## Stats 配置项 diff --git a/docs/db.md b/docs/db.md index 5b2899a0..c62753c3 100644 --- a/docs/db.md +++ b/docs/db.md @@ -16,13 +16,13 @@ xsql 采用**双重只读保护**机制确保数据安全: xsql 实现了完整的 SQL 词法分析器(`internal/db/readonly.go`),而非简单的字符串匹配: #### 词法分析能力 -- **注释处理**:支持 `--` 行注释和 `/* */` 块注释(包括嵌套注释) +- **注释处理**:支持 `--`、`#` 行注释和 `/* */` 块注释(包括嵌套注释) - **字符串解析**: - 单引号字符串 `'...'`(MySQL/PostgreSQL) - 双引号字符串 `"..."`(PostgreSQL/ANSI) - 反引号标识符 `` `...` ``(MySQL) - 美元引号字符串 `$tag$...$tag$`(PostgreSQL) -- **转义处理**:正确处理 `''`、`""`、`` `` `` 等转义序列 +- **转义处理**:正确处理 `''`、`""`、`` `` `` 及反斜杠 `\\`/`\'` 等转义序列 #### 允许的首关键字(Allowlist) 以下 SQL 语句被视为安全的只读操作: @@ -132,7 +132,7 @@ xsql query "SELECT * FROM users" -p prod xsql query "INSERT INTO logs VALUES ('test')" -p prod --unsafe-allow-write ``` -profile 配置或 CLI flag 单独开启时仍保持只读。两者同时开启后,当前 CLI 调用会绕过客户端静态分析和服务端事务级只读,请谨慎使用。MCP 仍由 profile 配置控制,Web 始终强制只读。 +profile 配置或 CLI/MCP 运行时开关单独开启时仍保持只读。两者同时开启后,当前 CLI 调用或 MCP 会话会绕过客户端静态分析和服务端事务级只读,请谨慎使用。Web 始终强制只读。 ### 绕过检测的风险提示 diff --git a/docs/rfcs/0016-error-guidance-for-agents.md b/docs/rfcs/0016-error-guidance-for-agents.md index cd82591e..26ce1a96 100644 --- a/docs/rfcs/0016-error-guidance-for-agents.md +++ b/docs/rfcs/0016-error-guidance-for-agents.md @@ -1,6 +1,6 @@ # RFC 0016: AI Agent 错误指引(Error Guidance) -Status: Accepted +Status: Implemented ## 摘要 为 xsql 的 JSON/YAML 错误 `details` 增加面向 AI/agent 的稳定指引字段(`hint`、`retryable`、`category`、方言与原生 DB 错误码),在不改变顶层 `error.code`、退出码与 `schema_version` 的前提下,减少 agent 对 DB/连接/只读类错误的无效重试。 diff --git a/docs/rfcs/0017-query-result-size-limits.md b/docs/rfcs/0017-query-result-size-limits.md index a6be3e19..319fc594 100644 --- a/docs/rfcs/0017-query-result-size-limits.md +++ b/docs/rfcs/0017-query-result-size-limits.md @@ -1,6 +1,6 @@ # RFC 0017: Query result size limits -Status: Accepted +Status: Implemented ## 摘要 diff --git a/docs/rfcs/README.md b/docs/rfcs/README.md index d2896c7d..dd74740f 100644 --- a/docs/rfcs/README.md +++ b/docs/rfcs/README.md @@ -21,8 +21,8 @@ | [0013](0013-ai-multi-tool-calls-sequential-execution.md) | AI Multi Tool Call Sequential Execution (AI TUI) | Removed | | [0014](0014-mcp-write-dual-authorization.md) | MCP 写入双重授权 | Implemented | | [0015](0015-mcp-app-layer-schema-tools.md) | MCP 复用 app 层与 Schema Tools | Implemented | -| [0016](0016-error-guidance-for-agents.md) | AI Agent 错误指引(Error Guidance) | Accepted | -| [0017](0017-query-result-size-limits.md) | Query 结果行数/体积上限 | Accepted | +| [0016](0016-error-guidance-for-agents.md) | AI Agent 错误指引(Error Guidance) | Implemented | +| [0017](0017-query-result-size-limits.md) | Query 结果行数/体积上限 | Implemented | ## 何时需要 RFC 当变更会影响以下任一项时,必须先提交/更新 RFC(并同步更新对应 `docs/*`): diff --git a/docs/testing.md b/docs/testing.md index 56efccfa..e1d36fd1 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -257,7 +257,6 @@ export XSQL_TEST_PG_DSN="..." ### 目录结构 ``` tests/e2e/ - ├── ai_test.go # AI TUI 命令测试 ├── config_test.go # config 命令测试 ├── e2e_test.go # 共享 helper 和基础设施 ├── mcp_test.go # MCP Server 测试 diff --git a/internal/app/app.go b/internal/app/app.go index 55249f35..047f90d4 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -65,6 +65,29 @@ func (a App) BuildSpec() spec.Spec { spec.FlagSpec{Name: "include-system", Default: "false", Description: "Include system tables"}, spec.FlagSpec{Name: "allow-plaintext", Default: "false", Description: "Allow plaintext secrets in config"}, spec.FlagSpec{Name: "ssh-skip-known-hosts-check", Default: "false", Description: "Skip SSH known_hosts check (dangerous)"}, + spec.FlagSpec{Name: "schema-timeout", Default: "60", Description: "Schema dump timeout in seconds"}, + ), + }, + { + Name: "config init", + Description: "Create a template configuration file", + Flags: append(globalFlags, + spec.FlagSpec{Name: "path", Default: "", Description: "Config file path (default: $HOME/.config/xsql/xsql.yaml)"}, + ), + }, + { + Name: "config set", + Description: "Set a configuration value (e.g., profile.dev.host localhost)", + Flags: globalFlags, + }, + { + Name: "mcp server", + Description: "Start MCP server for AI assistant integration", + Flags: append(globalFlags, + spec.FlagSpec{Name: "transport", Env: "XSQL_MCP_TRANSPORT", Default: "stdio", Description: "MCP transport: stdio|streamable_http"}, + spec.FlagSpec{Name: "http-addr", Env: "XSQL_MCP_HTTP_ADDR", Default: "127.0.0.1:8787", Description: "Streamable HTTP listen address"}, + spec.FlagSpec{Name: "http-auth-token", Env: "XSQL_MCP_HTTP_AUTH_TOKEN", Default: "", Description: "Streamable HTTP auth token (required for streamable_http)"}, + spec.FlagSpec{Name: "unsafe-allow-write", Env: "XSQL_MCP_UNSAFE_ALLOW_WRITE", Default: "false", Description: "Allow writes when profile unsafe_allow_write is true"}, ), }, { @@ -104,6 +127,21 @@ func (a App) BuildSpec() spec.Spec { spec.FlagSpec{Name: "json", Default: "false", Description: "Output as JSON"}, ), }, + { + Name: "stats log", + Description: "Show detailed stats log", + Flags: append(globalFlags, + spec.FlagSpec{Name: "json", Default: "false", Description: "Output as JSON"}, + spec.FlagSpec{Name: "limit", Default: "100", Description: "Maximum number of records to show"}, + ), + }, + { + Name: "stats reset", + Description: "Reset usage statistics", + Flags: append(globalFlags, + spec.FlagSpec{Name: "json", Default: "false", Description: "Output as JSON"}, + ), + }, }, ErrorCodes: errors.AllCodes(), } diff --git a/internal/app/max_rows.go b/internal/app/max_rows.go index 3e245d2d..b635e10d 100644 --- a/internal/app/max_rows.go +++ b/internal/app/max_rows.go @@ -9,7 +9,7 @@ import ( ) const ( - // DefaultQueryMaxRows is the default row cap for CLI, Web, and TUI queries. + // DefaultQueryMaxRows is the default row cap for CLI and Web queries. DefaultQueryMaxRows = 1000 // DefaultMCPQueryMaxRows is a lower default for MCP tool responses (smaller agent payloads). DefaultMCPQueryMaxRows = 500 @@ -32,7 +32,7 @@ type MCPMaxRowsMeta struct { Limit int } -// ResolveQueryMaxRows returns the effective row limit for CLI/Web/TUI. +// ResolveQueryMaxRows returns the effective row limit for CLI and Web. // limit 0 means unlimited. Negative values are invalid. func ResolveQueryMaxRows(profile config.Profile, envMaxRows string, cliValue int, cliSet bool) (limit int, xe *errors.XError) { if cliSet { diff --git a/internal/app/service.go b/internal/app/service.go index 86a9dc9f..e92b2d48 100644 --- a/internal/app/service.go +++ b/internal/app/service.go @@ -171,6 +171,12 @@ func Query(ctx context.Context, req QueryRequest) (*db.QueryResult, *errors.XErr if req.Profile.DB == "" { return nil, errors.New(errors.CodeCfgInvalid, "db type is required (mysql|pg)", nil) } + if _, ok := db.Get(req.Profile.DB); !ok { + return nil, errors.New(errors.CodeDBDriverUnsupported, "unsupported database driver", map[string]any{"db": req.Profile.DB}) + } + if xe := db.EnforceReadOnly(req.SQL, req.UnsafeAllowWrite); xe != nil { + return nil, xe + } conn, xe := ResolveConnection(ctx, ConnectionOptions{ Profile: req.Profile, diff --git a/internal/config/mask.go b/internal/config/mask.go index 87aadd25..ce9b6a02 100644 --- a/internal/config/mask.go +++ b/internal/config/mask.go @@ -85,11 +85,26 @@ func FileForAPI(f File) File { return out } -// MergeProfileSecrets copies stored secrets from existing when incoming values are omitted or masked. +// MergeProfileSecrets copies stored secrets and unexposed advanced fields from existing when incoming values are omitted or masked. func MergeProfileSecrets(incoming, existing Profile) Profile { out := incoming out.Password = CoalesceSecret(incoming.Password, existing.Password) out.DSN = CoalesceSecret(incoming.DSN, existing.DSN) + if out.Format == "" { + out.Format = existing.Format + } + if out.LocalPort == 0 { + out.LocalPort = existing.LocalPort + } + if out.QueryTimeout == 0 { + out.QueryTimeout = existing.QueryTimeout + } + if out.SchemaTimeout == 0 { + out.SchemaTimeout = existing.SchemaTimeout + } + if out.MaxRows == 0 { + out.MaxRows = existing.MaxRows + } return out } diff --git a/internal/config/mask_test.go b/internal/config/mask_test.go index 5ef45111..3f39c88f 100644 --- a/internal/config/mask_test.go +++ b/internal/config/mask_test.go @@ -77,7 +77,15 @@ func TestFileForAPI_ShowsKeyringReferences(t *testing.T) { } func TestMergeProfileSecrets_PreservesOnMask(t *testing.T) { - existing := Profile{Password: "stored-pass", DSN: "stored-dsn"} + existing := Profile{ + Password: "stored-pass", + DSN: "stored-dsn", + Format: "json", + LocalPort: 13306, + QueryTimeout: 45, + SchemaTimeout: 90, + MaxRows: 500, + } incoming := Profile{Password: MaskedSecret, DSN: MaskedSecret, Host: "new-host"} merged := MergeProfileSecrets(incoming, existing) if merged.Password != "stored-pass" || merged.DSN != "stored-dsn" { @@ -86,4 +94,7 @@ func TestMergeProfileSecrets_PreservesOnMask(t *testing.T) { if merged.Host != "new-host" { t.Fatalf("non-secret fields should copy through") } + if merged.Format != "json" || merged.LocalPort != 13306 || merged.QueryTimeout != 45 || merged.SchemaTimeout != 90 || merged.MaxRows != 500 { + t.Fatalf("advanced profile fields not preserved: %+v", merged) + } } diff --git a/internal/config/write.go b/internal/config/write.go index 21daf14e..c9851f48 100644 --- a/internal/config/write.go +++ b/internal/config/write.go @@ -144,6 +144,24 @@ func setProfileField(cfg *File, name, field, value string) *errors.XError { p.UnsafeAllowWrite = parseBool(value) case "allow_plaintext": p.AllowPlaintext = parseBool(value) + case "query_timeout": + v, err := strconv.Atoi(value) + if err != nil || v < 0 { + return errors.New(errors.CodeCfgInvalid, "query_timeout must be a non-negative integer", map[string]any{"value": value}) + } + p.QueryTimeout = v + case "schema_timeout": + v, err := strconv.Atoi(value) + if err != nil || v < 0 { + return errors.New(errors.CodeCfgInvalid, "schema_timeout must be a non-negative integer", map[string]any{"value": value}) + } + p.SchemaTimeout = v + case "max_rows": + v, err := strconv.Atoi(value) + if err != nil || v < 0 { + return errors.New(errors.CodeCfgInvalid, "max_rows must be a non-negative integer", map[string]any{"value": value}) + } + p.MaxRows = v default: return errors.New(errors.CodeCfgInvalid, fmt.Sprintf("unknown profile field: %s", field), map[string]any{"field": field}) @@ -186,7 +204,7 @@ func setSSHProxyField(cfg *File, name, field, value string) *errors.XError { func writeFile(path string, cfg File) *errors.XError { if dir := filepath.Dir(path); dir != "" { - if err := os.MkdirAll(dir, 0755); err != nil { + if err := os.MkdirAll(dir, 0700); err != nil { return errors.Wrap(errors.CodeInternal, "failed to create config directory", map[string]any{"path": path}, err) } } diff --git a/internal/db/mysql/schema.go b/internal/db/mysql/schema.go index 041345ad..ce1d0845 100644 --- a/internal/db/mysql/schema.go +++ b/internal/db/mysql/schema.go @@ -329,6 +329,20 @@ func (d *Driver) getForeignKeys(ctx context.Context, conn *sql.DB, schemaName, t } func toLikePattern(pattern string) string { - pattern = strings.ReplaceAll(pattern, "*", "%") - return strings.ReplaceAll(pattern, "?", "_") + var b strings.Builder + b.Grow(len(pattern)) + for i := 0; i < len(pattern); i++ { + switch pattern[i] { + case '\\', '%', '_': + b.WriteByte('\\') + b.WriteByte(pattern[i]) + case '*': + b.WriteByte('%') + case '?': + b.WriteByte('_') + default: + b.WriteByte(pattern[i]) + } + } + return b.String() } diff --git a/internal/db/pg/driver.go b/internal/db/pg/driver.go index 3f224a9e..a322a69b 100644 --- a/internal/db/pg/driver.go +++ b/internal/db/pg/driver.go @@ -63,22 +63,31 @@ func (d *Driver) Open(ctx context.Context, opts db.ConnOptions) (*sql.DB, *error func buildDSN(opts db.ConnOptions) string { parts := []string{} if opts.Host != "" { - parts = append(parts, fmt.Sprintf("host=%s", opts.Host)) + parts = append(parts, formatPGParam("host", opts.Host)) } if opts.Port != 0 { parts = append(parts, fmt.Sprintf("port=%d", opts.Port)) } if opts.User != "" { - parts = append(parts, fmt.Sprintf("user=%s", opts.User)) + parts = append(parts, formatPGParam("user", opts.User)) } if opts.Password != "" { - parts = append(parts, fmt.Sprintf("password=%s", opts.Password)) + parts = append(parts, formatPGParam("password", opts.Password)) } if opts.Database != "" { - parts = append(parts, fmt.Sprintf("dbname=%s", opts.Database)) + parts = append(parts, formatPGParam("dbname", opts.Database)) } for k, v := range opts.Params { - parts = append(parts, fmt.Sprintf("%s=%s", k, v)) + parts = append(parts, formatPGParam(k, v)) } return strings.Join(parts, " ") } + +func formatPGParam(key, val string) string { + if strings.ContainsAny(val, " \t\n\r'\\=") { + escaped := strings.ReplaceAll(val, `\`, `\\`) + escaped = strings.ReplaceAll(escaped, `'`, `\'`) + return fmt.Sprintf("%s='%s'", key, escaped) + } + return fmt.Sprintf("%s=%s", key, val) +} diff --git a/internal/db/pg/driver_test.go b/internal/db/pg/driver_test.go index 0ce7ee83..e06eb221 100644 --- a/internal/db/pg/driver_test.go +++ b/internal/db/pg/driver_test.go @@ -93,6 +93,16 @@ func TestBuildDSN(t *testing.T) { }, expected: []string{"sslmode=disable", "pool_max_conns=10"}, }, + { + name: "with special characters and injection attempt", + opts: db.ConnOptions{ + Host: "localhost", + User: "user", + Password: `my'secret\pw`, + Database: "mydb sslmode=disable", + }, + expected: []string{`password='my\'secret\\pw'`, `dbname='mydb sslmode=disable'`}, + }, } for _, tt := range tests { @@ -107,6 +117,15 @@ func TestBuildDSN(t *testing.T) { } } +func TestToLikePattern(t *testing.T) { + if got := toLikePattern("user_roles*"); got != `user\_roles%` { + t.Fatalf("toLikePattern(user_roles*) = %q, want %q", got, `user\_roles%`) + } + if got := toLikePattern("a?b%c"); got != `a_b\%c` { + t.Fatalf("toLikePattern(a?b%%c) = %q, want %q", got, `a_b\%c`) + } +} + func containsSubstring(s, substr string) bool { return len(substr) == 0 || (len(s) >= len(substr) && findSubstring(s, substr)) } diff --git a/internal/db/pg/schema.go b/internal/db/pg/schema.go index 000814ad..ab7c01dc 100644 --- a/internal/db/pg/schema.go +++ b/internal/db/pg/schema.go @@ -38,7 +38,12 @@ func (d *Driver) ListTables(ctx context.Context, conn *sql.DB, opts db.SchemaOpt // DescribeTable returns the schema details for a single PostgreSQL table. func (d *Driver) DescribeTable(ctx context.Context, conn *sql.DB, opts db.TableDescribeOptions) (*db.Table, *errors.XError) { - table, xe := d.loadTableSummary(ctx, conn, opts.Schema, opts.Name) + schemaName := strings.TrimSpace(opts.Schema) + if schemaName == "" { + schemaName = "public" + } + + table, xe := d.loadTableSummary(ctx, conn, schemaName, opts.Name) if xe != nil { return nil, xe } @@ -51,7 +56,7 @@ func (d *Driver) DescribeTable(ctx context.Context, conn *sql.DB, opts db.TableD g, gctx := errgroup.WithContext(ctx) g.Go(func() error { - result, xe := d.getColumns(gctx, conn, opts.Schema, opts.Name) + result, xe := d.getColumns(gctx, conn, schemaName, opts.Name) if xe != nil { return xe } @@ -59,7 +64,7 @@ func (d *Driver) DescribeTable(ctx context.Context, conn *sql.DB, opts db.TableD return nil }) g.Go(func() error { - result, xe := d.getIndexes(gctx, conn, opts.Schema, opts.Name) + result, xe := d.getIndexes(gctx, conn, schemaName, opts.Name) if xe != nil { return xe } @@ -67,7 +72,7 @@ func (d *Driver) DescribeTable(ctx context.Context, conn *sql.DB, opts db.TableD return nil }) g.Go(func() error { - result, xe := d.getForeignKeys(gctx, conn, opts.Schema, opts.Name) + result, xe := d.getForeignKeys(gctx, conn, schemaName, opts.Name) if xe != nil { return xe } @@ -329,22 +334,22 @@ func (d *Driver) getIndexes(ctx context.Context, conn *sql.DB, schemaName, table func (d *Driver) getForeignKeys(ctx context.Context, conn *sql.DB, schemaName, tableName string) ([]db.ForeignKey, *errors.XError) { const query = ` SELECT - tc.constraint_name, - kcu.column_name, - ccu.table_name AS referenced_table, - ccu.column_name AS referenced_column, - kcu.ordinal_position - FROM information_schema.table_constraints tc - JOIN information_schema.key_column_usage kcu - ON tc.constraint_name = kcu.constraint_name - AND tc.table_schema = kcu.table_schema - JOIN information_schema.constraint_column_usage ccu - ON tc.constraint_name = ccu.constraint_name - AND tc.table_schema = ccu.table_schema - WHERE tc.constraint_type = 'FOREIGN KEY' - AND tc.table_schema = $1 - AND tc.table_name = $2 - ORDER BY tc.constraint_name, kcu.ordinal_position + con.conname AS constraint_name, + att.attname AS column_name, + ref_cls.relname AS referenced_table, + ref_att.attname AS referenced_column, + u.ord AS ordinal_position + FROM pg_constraint con + JOIN pg_class cls ON cls.oid = con.conrelid + JOIN pg_namespace nsp ON nsp.oid = cls.relnamespace + JOIN pg_class ref_cls ON ref_cls.oid = con.confrelid + CROSS JOIN LATERAL unnest(con.conkey, con.confkey) WITH ORDINALITY AS u(attnum, ref_attnum, ord) + JOIN pg_attribute att ON att.attrelid = con.conrelid AND att.attnum = u.attnum + JOIN pg_attribute ref_att ON ref_att.attrelid = con.confrelid AND ref_att.attnum = u.ref_attnum + WHERE con.contype = 'f' + AND nsp.nspname = $1 + AND cls.relname = $2 + ORDER BY con.conname, u.ord ` rows, err := conn.QueryContext(ctx, query, schemaName, tableName) @@ -391,6 +396,20 @@ func (d *Driver) getForeignKeys(ctx context.Context, conn *sql.DB, schemaName, t } func toLikePattern(pattern string) string { - pattern = strings.ReplaceAll(pattern, "*", "%") - return strings.ReplaceAll(pattern, "?", "_") + var b strings.Builder + b.Grow(len(pattern)) + for i := 0; i < len(pattern); i++ { + switch pattern[i] { + case '\\', '%', '_': + b.WriteByte('\\') + b.WriteByte(pattern[i]) + case '*': + b.WriteByte('%') + case '?': + b.WriteByte('_') + default: + b.WriteByte(pattern[i]) + } + } + return b.String() } diff --git a/internal/db/query.go b/internal/db/query.go index abea0a8e..9ee1325a 100644 --- a/internal/db/query.go +++ b/internal/db/query.go @@ -147,12 +147,12 @@ func scanRows(rows *sql.Rows, maxRows int) (*QueryResult, *errors.XError) { } result := &QueryResult{Columns: cols, Rows: make([]map[string]any, 0)} + vals := make([]any, len(cols)) + ptrs := make([]any, len(cols)) + for i := range vals { + ptrs[i] = &vals[i] + } for rows.Next() { - vals := make([]any, len(cols)) - ptrs := make([]any, len(cols)) - for i := range vals { - ptrs[i] = &vals[i] - } if err := rows.Scan(ptrs...); err != nil { return nil, errors.Wrap(errors.CodeDBExecFailed, "failed to scan row", nil, err) } diff --git a/internal/db/readonly.go b/internal/db/readonly.go index 3f071861..a12499c9 100644 --- a/internal/db/readonly.go +++ b/internal/db/readonly.go @@ -1,6 +1,7 @@ package db import ( + "fmt" "strings" "unicode" @@ -269,7 +270,7 @@ func advanceStringOrComment(s string, i *int) bool { } func hasLineCommentPrefix(s string, i int) bool { - return s[i] == '-' && i+1 < len(s) && s[i+1] == '-' + return s[i] == '#' || (s[i] == '-' && i+1 < len(s) && s[i+1] == '-') } func hasBlockCommentPrefix(s string, i int) bool { @@ -297,6 +298,10 @@ func skipBlockCommentBody(s string, i *int) bool { func skipDoubledQuoteLiteral(s string, i *int, quote byte) bool { *i++ for *i < len(s) { + if s[*i] == '\\' && *i+1 < len(s) { + *i += 2 + continue + } if s[*i] != quote { *i++ continue @@ -345,7 +350,7 @@ func stripLeadingCommentsAndSpace(s string) string { for { s = strings.TrimLeftFunc(s, unicode.IsSpace) s = strings.TrimPrefix(s, "\ufeff") - if strings.HasPrefix(s, "--") { + if strings.HasPrefix(s, "--") || strings.HasPrefix(s, "#") { if i := strings.IndexByte(s, '\n'); i >= 0 { s = s[i+1:] continue @@ -381,6 +386,12 @@ func tokenize(sql string) ([]SQLToken, error) { sqlLen := len(sql) for i < sqlLen { + // UTF-8 BOM header + if strings.HasPrefix(sql[i:], "\ufeff") { + i += len("\ufeff") + continue + } + r := rune(sql[i]) // Skip whitespace @@ -389,14 +400,8 @@ func tokenize(sql string) ([]SQLToken, error) { continue } - // BOM header - if r == '\ufeff' { - i++ - continue - } - - // Line comment -- - if r == '-' && i+1 < sqlLen && sql[i+1] == '-' { + // Line comment -- or # (MySQL) + if r == '#' || (r == '-' && i+1 < sqlLen && sql[i+1] == '-') { // Skip to end of line for i < sqlLen && sql[i] != '\n' { i++ @@ -408,19 +413,27 @@ func tokenize(sql string) ([]SQLToken, error) { if r == '/' && i+1 < sqlLen && sql[i+1] == '*' { // Skip to */ i += 2 + closed := false for i < sqlLen-1 { if sql[i] == '*' && sql[i+1] == '/' { i += 2 + closed = true break } i++ } + if !closed { + return nil, fmt.Errorf("unclosed block comment") + } continue } // String literal '...' (MySQL/PostgreSQL with escape support) if r == '\'' { - str, newIdx := parseString(sql, i, '\'') + str, newIdx, closed := parseStringWithState(sql, i, '\'') + if !closed { + return nil, fmt.Errorf("unclosed string literal") + } tokens = append(tokens, SQLToken{Type: TokenString, Value: str}) i = newIdx continue @@ -428,7 +441,10 @@ func tokenize(sql string) ([]SQLToken, error) { // String literal "..." (PostgreSQL/ANSI standard) if r == '"' { - str, newIdx := parseString(sql, i, '"') + str, newIdx, closed := parseStringWithState(sql, i, '"') + if !closed { + return nil, fmt.Errorf("unclosed quoted identifier or string") + } tokens = append(tokens, SQLToken{Type: TokenString, Value: str}) i = newIdx continue @@ -436,7 +452,10 @@ func tokenize(sql string) ([]SQLToken, error) { // Backtick `...` (MySQL identifier) if r == '`' { - str, newIdx := parseString(sql, i, '`') + str, newIdx, closed := parseStringWithState(sql, i, '`') + if !closed { + return nil, fmt.Errorf("unclosed backtick identifier") + } tokens = append(tokens, SQLToken{Type: TokenIdentifier, Value: str}) i = newIdx continue @@ -506,6 +525,11 @@ func tokenize(sql string) ([]SQLToken, error) { // parseString parses a quoted string, handling escape sequences func parseString(sql string, start int, quote rune) (string, int) { + str, idx, _ := parseStringWithState(sql, start, quote) + return str, idx +} + +func parseStringWithState(sql string, start int, quote rune) (string, int, bool) { i := start + 1 // skip opening quote sqlLen := len(sql) var result strings.Builder @@ -520,20 +544,23 @@ func parseString(sql string, start int, quote rune) (string, int) { continue } // End of string - return result.String(), i + 1 + return result.String(), i + 1, true } - // Handle standard escape \' or '' - if r == '\\' && i+1 < sqlLen && rune(sql[i+1]) == quote { - result.WriteRune(quote) - i += 2 - continue + // Handle backslash escape sequences (\', \", \\, etc.) for single/double quotes + if quote != '`' && r == '\\' && i+1 < sqlLen { + next := rune(sql[i+1]) + if next == quote || next == '\\' { + result.WriteRune(next) + i += 2 + continue + } } result.WriteRune(r) i++ } // Unclosed string - return result.String(), i + return result.String(), i, false } // parseDollarQuotedString parses PostgreSQL dollar-quoted strings $tag$...$tag$ diff --git a/internal/db/readonly_test.go b/internal/db/readonly_test.go index 27477067..c6563513 100644 --- a/internal/db/readonly_test.go +++ b/internal/db/readonly_test.go @@ -177,6 +177,14 @@ func TestIsReadOnlySQL_MultipleStatements(t *testing.T) { // 注释中的分号不应被误认为多语句 {"SELECT 1 /* ; comment */ FROM t", true}, {"-- select 2;\nSELECT 1", true}, + {"# mysql comment;\nSELECT 1", true}, + {"SELECT 1 # update comment", true}, + + // 反斜杠与注释多语句逃逸拦截 + {`SELECT 'abc\\'; DROP TABLE users; -- '`, false}, + {"SELECT 1 # '\n; DROP TABLE users; -- '", false}, + {"SELECT 'unclosed string", false}, + {"SELECT 1 /* unclosed comment", false}, } for _, tc := range cases { diff --git a/internal/errors/exitcode.go b/internal/errors/exitcode.go index c999b913..08a016e4 100644 --- a/internal/errors/exitcode.go +++ b/internal/errors/exitcode.go @@ -24,7 +24,7 @@ const ( func ExitCodeFor(code Code) ExitCode { switch code { - case CodeCfgNotFound, CodeCfgInvalid, CodeSecretNotFound: + case CodeCfgNotFound, CodeCfgInvalid, CodeSecretNotFound, CodeAuthRequired, CodeAuthInvalid: return ExitConfig case CodeSSHAuthFailed, CodeSSHHostKeyMismatch, CodeSSHDialFailed, CodeDBDriverUnsupported, CodeDBConnectFailed, CodeDBAuthFailed: diff --git a/internal/errors/guidance.go b/internal/errors/guidance.go index e01d737c..41e40438 100644 --- a/internal/errors/guidance.go +++ b/internal/errors/guidance.go @@ -52,10 +52,28 @@ func guidanceFor(xe *XError) map[string]any { return dbExecGuidance(xe) case CodeDBConnectFailed, CodeDBAuthFailed: return connectGuidance(xe) + case CodeDBDriverUnsupported: + return map[string]any{ + detailCategory: "config", + detailRetryable: false, + detailHint: "Unsupported database driver; set profile `db` to `mysql` or `pg`.", + } case CodeSSHDialFailed, CodeSSHAuthFailed, CodeSSHHostKeyMismatch: return sshGuidance(xe) case CodeCfgNotFound, CodeCfgInvalid, CodeSecretNotFound: return configGuidance(xe) + case CodePortInUse: + return map[string]any{ + detailCategory: string(CategoryConnection), + detailRetryable: false, + detailHint: "Local port is already in use; specify a different port or `--local-port 0` for auto-assignment.", + } + case CodeAuthRequired, CodeAuthInvalid: + return map[string]any{ + detailCategory: string(CategoryAuthFailed), + detailRetryable: false, + detailHint: "Provide a valid `Authorization: Bearer ` header matching the configured auth token.", + } default: return nil } diff --git a/internal/mcp/query_result.go b/internal/mcp/query_result.go index aae7f2f8..1cdac5eb 100644 --- a/internal/mcp/query_result.go +++ b/internal/mcp/query_result.go @@ -36,11 +36,11 @@ func applyMCPResponseByteLimit(result *db.QueryResult, maxBytes int, effectiveMa } func mcpPayloadSize(result *db.QueryResult) int { - payload, err := json.Marshal(map[string]any{ + payload, err := json.MarshalIndent(map[string]any{ "ok": true, "schema_version": 1, "data": result, - }) + }, "", " ") if err != nil { return 0 } @@ -48,21 +48,23 @@ func mcpPayloadSize(result *db.QueryResult) int { } func binarySearchRowFit(result *db.QueryResult, maxBytes int) int { + truncatedReason := db.AppendTruncatedReason(result.TruncatedReason, db.TruncatedReasonMaxResponseBytes) low, high := 0, len(result.Rows) for low < high { mid := (low + high + 1) / 2 trial := &db.QueryResult{ Columns: result.Columns, Rows: result.Rows[:mid], - Truncated: result.Truncated, + Truncated: true, RowCount: mid, MaxRows: result.MaxRows, MaxRowsRequested: result.MaxRowsRequested, MaxRowsLimitApplied: result.MaxRowsLimitApplied, - TruncatedReason: result.TruncatedReason, + TruncatedReason: truncatedReason, MaxResponseBytes: maxBytes, Hint: result.Hint, } + db.RefreshTruncationHint(trial) if mcpPayloadSize(trial) <= maxBytes { low = mid } else { diff --git a/internal/mcp/tools.go b/internal/mcp/tools.go index 22c9fdf5..4256ee84 100644 --- a/internal/mcp/tools.go +++ b/internal/mcp/tools.go @@ -3,6 +3,7 @@ package mcp import ( "context" "encoding/json" + "sort" "time" "github.com/google/jsonschema-go/jsonschema" @@ -30,13 +31,16 @@ type ProfileShowInput struct { // ServerOptions configures MCP server behavior passed from the CLI entrypoint. type ServerOptions struct { - UnsafeAllowWrite bool // server-level write opt-in (dual auth with profile) + UnsafeAllowWrite bool // server-level write opt-in (dual auth with profile) + Attrs map[string]string // session attributes recorded in stats } // ToolHandler manages MCP tools type ToolHandler struct { config *config.File stats stats.StatsConfig + statsStore *stats.Store + attrs map[string]string serverAllowsWrite bool } @@ -48,19 +52,26 @@ func NewToolHandler(cfg *config.File, st stats.StatsConfig, opts ServerOptions) SSHProxies: map[string]config.SSHProxy{}, } } + var store *stats.Store + if st.Enabled { + store = stats.NewStore(st.FilePath) + } return &ToolHandler{ config: cfg, stats: st, + statsStore: store, + attrs: opts.Attrs, serverAllowsWrite: opts.UnsafeAllowWrite, } } -// getProfileNames returns a list of available profile names +// getProfileNames returns a sorted list of available profile names func (h *ToolHandler) getProfileNames() []string { names := make([]string, 0, len(h.config.Profiles)) for name := range h.config.Profiles { names = append(names, name) } + sort.Strings(names) return names } @@ -203,11 +214,12 @@ func (h *ToolHandler) Query(ctx context.Context, req *mcp.CallToolRequest, input return h.successResult(result) } -// ProfileList lists all profiles +// ProfileList lists all profiles in deterministic order func (h *ToolHandler) ProfileList(ctx context.Context, req *mcp.CallToolRequest, input struct{}) (*mcp.CallToolResult, any, error) { - profiles := make([]config.ProfileInfo, 0, len(h.config.Profiles)) - for name, p := range h.config.Profiles { - profiles = append(profiles, config.ProfileToInfo(name, p)) + names := h.getProfileNames() + profiles := make([]config.ProfileInfo, 0, len(names)) + for _, name := range names { + profiles = append(profiles, config.ProfileToInfo(name, h.config.Profiles[name])) } return h.successResult(map[string]any{"profiles": profiles}) } @@ -232,10 +244,10 @@ func (h *ToolHandler) ProfileShow(ctx context.Context, req *mcp.CallToolRequest, "allow_plaintext": profile.AllowPlaintext, } if p.DSN != "" { - result["dsn"] = "***" + result["dsn"] = config.MaskSecretForDisplay(p.DSN) } if p.Password != "" { - result["password"] = "***" + result["password"] = config.MaskSecretForDisplay(p.Password) } if profile.SSHProxy != "" { result["ssh_proxy"] = profile.SSHProxy @@ -293,13 +305,17 @@ func (h *ToolHandler) recordMCPStats(cmd, profile string, ok bool, duration time if !h.stats.Enabled { return } - store := stats.NewStore(h.stats.FilePath) + store := h.statsStore + if store == nil { + store = stats.NewStore(h.stats.FilePath) + } r := &stats.Record{ Timestamp: time.Now(), Cmd: cmd, Profile: profile, OK: ok, DurationMs: duration.Milliseconds(), + Attrs: h.attrs, } if xe != nil { r.ErrorCode = string(xe.Code) @@ -308,4 +324,8 @@ func (h *ToolHandler) recordMCPStats(cmd, profile string, ok bool, duration time r.SQL = sql } _ = store.Append(r) + if h.stats.RetentionDays > 0 { + _, _ = store.Cleanup(h.stats.RetentionDays) + } } + diff --git a/internal/mcp/write.go b/internal/mcp/write.go index a9eea2b3..99e48b68 100644 --- a/internal/mcp/write.go +++ b/internal/mcp/write.go @@ -1,7 +1,7 @@ package mcp // WriteAllowed reports whether MCP query tool may bypass read-only protections. -// Dual authorization matches CLI/TUI: both the MCP server entrypoint and the +// Dual authorization matches CLI: both the MCP server entrypoint and the // profile must explicitly opt in. func WriteAllowed(serverAllowsWrite, profileAllowsWrite bool) bool { return serverAllowsWrite && profileAllowsWrite diff --git a/internal/ssh/client.go b/internal/ssh/client.go index 9964220c..9dd42aa5 100644 --- a/internal/ssh/client.go +++ b/internal/ssh/client.go @@ -108,7 +108,7 @@ func (c *Client) DialContext(ctx context.Context, network, addr string) (net.Con if c.client == nil { return nil, fmt.Errorf("ssh client is not connected") } - return c.client.Dial(network, addr) + return c.client.DialContext(ctx, network, addr) } // Close closes the SSH connection. diff --git a/internal/ssh/reconnect.go b/internal/ssh/reconnect.go index d19f2b97..ab7b3a5d 100644 --- a/internal/ssh/reconnect.go +++ b/internal/ssh/reconnect.go @@ -240,6 +240,15 @@ func (rd *ReconnectDialer) finishReconnect(newClient *Client) { rd.mu.Lock() defer rd.mu.Unlock() + if rd.closed { + if newClient != nil { + _ = newClient.Close() + } + rd.reconnecting = false + close(rd.reconnectCh) + return + } + if newClient != nil { rd.client = newClient rd.emitStatus(StatusReconnected, "ssh reconnected successfully", nil) @@ -248,9 +257,7 @@ func (rd *ReconnectDialer) finishReconnect(newClient *Client) { // Always restart keepalive so health monitoring continues even after failure. // On success, it monitors the new connection; on failure, it will detect // the nil/dead client and trigger another reconnect attempt. - if !rd.closed { - rd.startKeepaliveLocked() - } + rd.startKeepaliveLocked() rd.reconnecting = false close(rd.reconnectCh) @@ -299,7 +306,15 @@ func (rd *ReconnectDialer) keepaliveLoop(ctx context.Context, interval time.Dura closed := rd.closed rd.mu.Unlock() - if closed || client == nil { + if closed { + return + } + if client == nil { + go func() { + if _, reconnErr := rd.reconnect(); reconnErr != nil { + log.Printf("[ssh] keepalive-triggered reconnect failed: %v", reconnErr) + } + }() return } diff --git a/internal/stats/store.go b/internal/stats/store.go index 4c2fa5ee..482166a8 100644 --- a/internal/stats/store.go +++ b/internal/stats/store.go @@ -79,7 +79,10 @@ func (s *Store) Append(r *Record) error { func (s *Store) Load() ([]*Record, error) { s.mu.Lock() defer s.mu.Unlock() + return s.loadLocked() +} +func (s *Store) loadLocked() ([]*Record, error) { f, err := os.Open(s.path) if err != nil { if os.IsNotExist(err) { @@ -126,7 +129,10 @@ func (s *Store) Cleanup(retentionDays int) (int, error) { return 0, nil } - records, err := s.Load() + s.mu.Lock() + defer s.mu.Unlock() + + records, err := s.loadLocked() if err != nil { return 0, err } @@ -146,15 +152,11 @@ func (s *Store) Cleanup(retentionDays int) (int, error) { return 0, nil } - // Rewrite file with kept records - s.mu.Lock() - defer s.mu.Unlock() - if err := os.MkdirAll(filepath.Dir(s.path), 0o700); err != nil { return 0, err } - f, err := os.Create(s.path) + f, err := os.OpenFile(s.path, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o600) if err != nil { return 0, err } @@ -169,3 +171,4 @@ func (s *Store) Cleanup(retentionDays int) (int, error) { return removed, f.Close() } + diff --git a/internal/web/handler.go b/internal/web/handler.go index bb648556..d127601e 100644 --- a/internal/web/handler.go +++ b/internal/web/handler.go @@ -2,6 +2,7 @@ package web import ( "context" + "crypto/subtle" "encoding/json" "fmt" "io" @@ -35,6 +36,7 @@ type HandlerOptions struct { AuthToken string Assets fs.FS Stats stats.StatsConfig + Attrs map[string]string } type handler struct { @@ -46,6 +48,8 @@ type handler struct { authToken string assets fs.FS stats stats.StatsConfig + statsStore *stats.Store + attrs map[string]string } type queryRequest struct { @@ -70,6 +74,8 @@ func NewHandler(opts HandlerOptions) http.Handler { authToken: opts.AuthToken, assets: assets, stats: opts.Stats, + statsStore: stats.NewStore(opts.Stats.FilePath), + attrs: opts.Attrs, } mux := http.NewServeMux() @@ -91,20 +97,42 @@ func NewHandler(opts HandlerOptions) http.Handler { return mux } -func (h *handler) withAuth(next http.Handler) http.Handler { - if !h.authRequired { - return next +func isCrossOriginRequest(r *http.Request) bool { + if strings.EqualFold(strings.TrimSpace(r.Header.Get("Sec-Fetch-Site")), "cross-site") { + return true + } + origin := strings.TrimSpace(r.Header.Get("Origin")) + if origin == "" { + return false + } + if origin == "null" { + return true } + u, err := url.Parse(origin) + if err != nil || u.Host == "" { + return true + } + return r.Host != "" && !strings.EqualFold(u.Host, r.Host) +} + +func (h *handler) withAuth(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - authHeader := strings.TrimSpace(r.Header.Get("Authorization")) - if authHeader == "" { - writeError(w, http.StatusUnauthorized, errors.New(errors.CodeAuthRequired, "authorization token is required", nil)) + if isCrossOriginRequest(r) { + writeError(w, http.StatusForbidden, errors.New(errors.CodeAuthInvalid, "cross-origin request blocked", nil)) return } - const prefix = "Bearer " - if !strings.HasPrefix(authHeader, prefix) || strings.TrimSpace(strings.TrimPrefix(authHeader, prefix)) != h.authToken { - writeError(w, http.StatusUnauthorized, errors.New(errors.CodeAuthInvalid, "authorization token is invalid", nil)) - return + if h.authRequired { + authHeader := strings.TrimSpace(r.Header.Get("Authorization")) + if authHeader == "" { + writeError(w, http.StatusUnauthorized, errors.New(errors.CodeAuthRequired, "authorization token is required", nil)) + return + } + const prefix = "Bearer " + token := strings.TrimSpace(strings.TrimPrefix(authHeader, prefix)) + if !strings.HasPrefix(authHeader, prefix) || subtle.ConstantTimeCompare([]byte(token), []byte(h.authToken)) != 1 { + writeError(w, http.StatusUnauthorized, errors.New(errors.CodeAuthInvalid, "authorization token is invalid", nil)) + return + } } next.ServeHTTP(w, r) }) @@ -468,11 +496,15 @@ func (h *handler) recordWebStats(cmd, profile string, ok bool, duration time.Dur if !h.stats.Enabled { return } - store := stats.NewStore(h.stats.FilePath) + store := h.statsStore + if store == nil { + store = stats.NewStore(h.stats.FilePath) + } r := &stats.Record{ Timestamp: time.Now(), Cmd: cmd, Profile: profile, + Attrs: h.attrs, OK: ok, DurationMs: duration.Milliseconds(), } @@ -483,6 +515,9 @@ func (h *handler) recordWebStats(cmd, profile string, ok bool, duration time.Dur r.SQL = sql } _ = store.Append(r) + if h.stats.RetentionDays > 0 { + _, _ = store.Cleanup(h.stats.RetentionDays) + } } // IsLoopbackAddr reports whether the listen address is bound only to loopback. @@ -519,6 +554,7 @@ func (h *handler) handleConfigGet(w http.ResponseWriter, r *http.Request) { "ssh_proxies": safe.SSHProxies, "mcp": safe.MCP, "web": safe.Web, + "stats": safe.Stats, }) } @@ -553,8 +589,9 @@ func (h *handler) handleConfigSaveProfile(w http.ResponseWriter, r *http.Request writeMethodNotAllowed(w) return } + defer r.Body.Close() var req configProfileRequest - if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + if err := json.NewDecoder(io.LimitReader(r.Body, 1<<20)).Decode(&req); err != nil { writeError(w, http.StatusBadRequest, errors.Wrap(errors.CodeCfgInvalid, "invalid JSON payload", nil, err)) return } @@ -598,8 +635,9 @@ func (h *handler) handleConfigSaveSSHProxy(w http.ResponseWriter, r *http.Reques writeMethodNotAllowed(w) return } + defer r.Body.Close() var req configSSHProxyRequest - if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + if err := json.NewDecoder(io.LimitReader(r.Body, 1<<20)).Decode(&req); err != nil { writeError(w, http.StatusBadRequest, errors.Wrap(errors.CodeCfgInvalid, "invalid JSON payload", nil, err)) return } @@ -638,11 +676,12 @@ func (h *handler) handleConfigTestProfile(w http.ResponseWriter, r *http.Request writeMethodNotAllowed(w) return } + defer r.Body.Close() var req struct { Name string `json:"name"` Profile config.Profile `json:"profile"` } - if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + if err := json.NewDecoder(io.LimitReader(r.Body, 1<<20)).Decode(&req); err != nil { writeError(w, http.StatusBadRequest, errors.Wrap(errors.CodeCfgInvalid, "invalid JSON payload", nil, err)) return } @@ -684,7 +723,9 @@ func (h *handler) handleConfigTestProfile(w http.ResponseWriter, r *http.Request profile.SSHConfig.IdentityFile = filepath.Clean(profile.SSHConfig.IdentityFile) } - result, xe := app.TestProfileConnection(r.Context(), profile, h.allowPlaintext, h.skipHostKeyCheck) + ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second) + defer cancel() + result, xe := app.TestProfileConnection(ctx, profile, h.allowPlaintext, h.skipHostKeyCheck) if xe != nil { writeError(w, statusCodeFor(xe.Code), xe) return @@ -697,11 +738,12 @@ func (h *handler) handleConfigTestSSHProxy(w http.ResponseWriter, r *http.Reques writeMethodNotAllowed(w) return } + defer r.Body.Close() var req struct { Name string `json:"name"` SSHProxy config.SSHProxy `json:"ssh_proxy"` } - if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + if err := json.NewDecoder(io.LimitReader(r.Body, 1<<20)).Decode(&req); err != nil { writeError(w, http.StatusBadRequest, errors.Wrap(errors.CodeCfgInvalid, "invalid JSON payload", nil, err)) return } @@ -725,7 +767,9 @@ func (h *handler) handleConfigTestSSHProxy(w http.ResponseWriter, r *http.Reques proxy.IdentityFile = filepath.Clean(proxy.IdentityFile) } - result, xe := app.TestSSHProxyConnection(r.Context(), proxy, h.allowPlaintext, h.skipHostKeyCheck) + ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second) + defer cancel() + result, xe := app.TestSSHProxyConnection(ctx, proxy, h.allowPlaintext, h.skipHostKeyCheck) if xe != nil { writeError(w, statusCodeFor(xe.Code), xe) return diff --git a/internal/web/handler_test.go b/internal/web/handler_test.go index 1bf5df73..3953c312 100644 --- a/internal/web/handler_test.go +++ b/internal/web/handler_test.go @@ -814,3 +814,33 @@ ssh_proxies: t.Fatalf("profile show leaked password: %s", profileRec.Body.String()) } } + +func TestHandler_CrossOriginBlocked(t *testing.T) { + handler := NewHandler(HandlerOptions{ + AuthRequired: false, + }) + + req := httptest.NewRequest(http.MethodPost, "http://127.0.0.1:8788/api/v1/config/profiles", strings.NewReader(`{"name":"p","profile":{"db":"mysql"}}`)) + req.Header.Set("Origin", "https://evil.example.com") + rec := httptest.NewRecorder() + handler.ServeHTTP(rec, req) + if rec.Code != http.StatusForbidden { + t.Fatalf("expected 403 for cross-origin Origin header, got %d", rec.Code) + } + + req2 := httptest.NewRequest(http.MethodPost, "http://127.0.0.1:8788/api/v1/query", strings.NewReader(`{"profile":"dev","sql":"SELECT 1"}`)) + req2.Header.Set("Sec-Fetch-Site", "cross-site") + rec2 := httptest.NewRecorder() + handler.ServeHTTP(rec2, req2) + if rec2.Code != http.StatusForbidden { + t.Fatalf("expected 403 for Sec-Fetch-Site: cross-site, got %d", rec2.Code) + } + + reqSame := httptest.NewRequest(http.MethodGet, "http://127.0.0.1:8788/api/v1/config", nil) + reqSame.Header.Set("Origin", "http://127.0.0.1:8788") + recSame := httptest.NewRecorder() + handler.ServeHTTP(recSame, reqSame) + if recSame.Code != http.StatusOK { + t.Fatalf("expected 200 for same-origin request, got %d", recSame.Code) + } +} diff --git a/internal/web/server.go b/internal/web/server.go index 80386653..cc544499 100644 --- a/internal/web/server.go +++ b/internal/web/server.go @@ -27,7 +27,7 @@ func NewServer(listener net.Listener, handler http.Handler) *Server { Handler: handler, ReadHeaderTimeout: 15 * time.Second, ReadTimeout: 30 * time.Second, - WriteTimeout: 30 * time.Second, + WriteTimeout: 120 * time.Second, IdleTimeout: 120 * time.Second, }, } diff --git a/internal/web/server_test.go b/internal/web/server_test.go index 19287454..75cf0cc9 100644 --- a/internal/web/server_test.go +++ b/internal/web/server_test.go @@ -234,7 +234,7 @@ func TestServerTimeouts(t *testing.T) { t.Errorf("expected ReadHeaderTimeout %v, got %v", expectedRead, server.server.ReadHeaderTimeout) } - expectedWrite := 30 * time.Second + expectedWrite := 120 * time.Second if server.server.WriteTimeout != expectedWrite { t.Errorf("expected WriteTimeout %v, got %v", expectedWrite, server.server.WriteTimeout) } diff --git a/tests/e2e/README.md b/tests/e2e/README.md index 4726d100..45732b87 100644 --- a/tests/e2e/README.md +++ b/tests/e2e/README.md @@ -71,7 +71,6 @@ go test -v -tags=e2e -coverprofile=coverage.txt ./tests/e2e/... - 配置文件验证 ### 其他入口 -- AI TUI 命令与初始状态(`ai_test.go`) - config 命令(`config_test.go`) - schema dump(`schema_test.go`) - 使用统计与全局 attr(`stats_test.go`) diff --git a/webui/dist/.keep b/webui/dist/.keep new file mode 100644 index 00000000..e69de29b diff --git a/webui/src/App.svelte b/webui/src/App.svelte index 94a59030..133171a9 100644 --- a/webui/src/App.svelte +++ b/webui/src/App.svelte @@ -56,6 +56,7 @@ schemaLoading={ui.schemaLoading} onProfileChange={(profileName) => ui.selectProfile(profileName)} onThemeChange={(mode) => ui.setThemeMode(mode)} + onTokenChange={(token) => ui.setAuthToken(token)} onOpenConfig={() => ui.openConfigModal()} onOpenShortcuts={() => ui.openShortcutsModal()} /> @@ -156,6 +157,9 @@ columns={ui.columns} rows={ui.processedRows} rowCount={ui.rowCount} + truncated={ui.queryTruncated} + maxRows={ui.queryMaxRows} + truncationHint={ui.queryTruncationHint} sortColumn={ui.sortColumn} sortDirection={ui.sortDirection} resultFilter={ui.resultFilter} diff --git a/webui/src/lib/components/ConfigModal.svelte b/webui/src/lib/components/ConfigModal.svelte index 6fc43145..e1b9abaa 100644 --- a/webui/src/lib/components/ConfigModal.svelte +++ b/webui/src/lib/components/ConfigModal.svelte @@ -58,6 +58,7 @@ if (key && fullConfig?.profiles?.[key]) { const p = fullConfig.profiles[key]; profileForm = { + ...p, db: p.db ?? p.DB ?? 'mysql', host: p.host ?? p.Host ?? '127.0.0.1', port: p.port ?? p.Port ?? ((p.db ?? p.DB) === 'pg' ? 5432 : 3306), @@ -92,6 +93,7 @@ if (key && fullConfig?.ssh_proxies?.[key]) { const sp = fullConfig.ssh_proxies[key]; proxyForm = { + ...sp, host: sp.host ?? sp.Host ?? '', port: sp.port ?? sp.Port ?? 22, user: sp.user ?? sp.User ?? '', @@ -138,6 +140,11 @@ formError = 'Profile name is required'; return; } + const isExisting = Boolean(fullConfig?.profiles?.[key]); + if (!isExisting && profileForm.password === '***') { + formError = 'Please enter the password for the new profile (cannot copy masked "***")'; + return; + } isSubmitting = true; formError = ''; try { @@ -192,6 +199,11 @@ formError = 'SSH Proxy name is required'; return; } + const isExisting = Boolean(fullConfig?.ssh_proxies?.[key]); + if (!isExisting && proxyForm.passphrase === '***') { + formError = 'Please enter the passphrase for the new SSH proxy (cannot copy masked "***")'; + return; + } isSubmitting = true; formError = ''; try { diff --git a/webui/src/lib/components/Navbar.svelte b/webui/src/lib/components/Navbar.svelte index f2093c03..423756a6 100644 --- a/webui/src/lib/components/Navbar.svelte +++ b/webui/src/lib/components/Navbar.svelte @@ -10,6 +10,7 @@ schemaLoading = false, onProfileChange, onThemeChange, + onTokenChange, onOpenConfig, onOpenShortcuts } = $props(); @@ -96,6 +97,17 @@
+ {#if authRequired} + onTokenChange?.(e.currentTarget.value)} + /> + {/if} +
{#if columns.length > 0} diff --git a/webui/src/lib/result-grid.js b/webui/src/lib/result-grid.js index baf74d0a..65682cd0 100644 --- a/webui/src/lib/result-grid.js +++ b/webui/src/lib/result-grid.js @@ -180,7 +180,6 @@ export function formatResultCellValue(value) { const kind = detectValueKind(value); const previewText = buildPreviewText(value, kind); const fullText = buildFullText(value, kind); - const highlightedHtml = kind === 'json' ? highlightJson(fullText) : ''; return { kind, @@ -188,7 +187,7 @@ export function formatResultCellValue(value) { previewText, previewDisplay: previewText.length > PREVIEW_LENGTH ? `${previewText.slice(0, PREVIEW_LENGTH - 1)}…` : previewText, fullText, - highlightedHtml, + highlightedHtml: '', tooltipText: fullText.length > TOOLTIP_LENGTH ? `${fullText.slice(0, TOOLTIP_LENGTH - 1)}…` : fullText, isEmptyString: kind === 'string' && value === '', isLong: previewText.length > PREVIEW_LENGTH || /\n/.test(fullText) @@ -200,7 +199,8 @@ export function buildSelectedResultCell({ rowIndex, columnName, value }) { return { rowIndex, columnName, - ...formatted + ...formatted, + highlightedHtml: formatted.kind === 'json' ? highlightJson(formatted.fullText) : '' }; } diff --git a/webui/src/lib/web-ui.svelte.js b/webui/src/lib/web-ui.svelte.js index 2bea207b..e2031bed 100644 --- a/webui/src/lib/web-ui.svelte.js +++ b/webui/src/lib/web-ui.svelte.js @@ -154,6 +154,9 @@ export class WebUIController { resultFilter = $state(''); sortColumn = $state(''); sortDirection = $state('asc'); // 'asc' | 'desc' + queryTruncated = $state(false); + queryMaxRows = $state(null); + queryTruncationHint = $state(''); rowCount = $derived(this.rows.length); tableCount = $derived(this.schemaTables.length); @@ -255,6 +258,9 @@ export class WebUIController { setAuthToken(token) { this.authToken = token; sessionStorage.setItem('xsql-web-auth-token', token.trim()); + if (this.authRequired && token.trim() && this.profiles.length === 0) { + void this.initialize(); + } } setSidebarWidth(width) { @@ -667,15 +673,18 @@ export class WebUIController { this.pageLoading = true; this.errorMessage = ''; try { - const [health, profileData] = await Promise.all([ - this.api('/api/v1/health'), - this.api('/api/v1/profiles') - ]); + const health = await this.api('/api/v1/health'); this.authRequired = Boolean(health.auth_required); if (!this.selectedProfile && typeof health.initial_profile === 'string') { this.selectedProfile = health.initial_profile; } + if (this.authRequired && !this.authToken.trim()) { + this.showToast('Authentication required: enter Bearer token in the top bar', 'info', 4000); + return; + } + + const profileData = await this.api('/api/v1/profiles'); this.profiles = profileData.profiles || []; this.configPath = profileData.config_path || ''; if (!this.selectedProfile && this.profiles.length > 0) { @@ -688,7 +697,9 @@ export class WebUIController { this.pageLoading = false; } - await this.loadTables(); + if (!this.authRequired || this.authToken.trim()) { + await this.loadTables(); + } } async loadTables() { @@ -769,6 +780,9 @@ export class WebUIController { this.resultFilter = ''; this.sortColumn = ''; this.sortDirection = 'asc'; + this.queryTruncated = false; + this.queryMaxRows = null; + this.queryTruncationHint = ''; const startTime = performance.now(); let queryError = null; @@ -784,6 +798,9 @@ export class WebUIController { returnedRows = data.rows || []; this.columns = returnedColumns; this.rows = returnedRows; + this.queryTruncated = Boolean(data.truncated); + this.queryMaxRows = data.max_rows ?? null; + this.queryTruncationHint = data.hint || ''; this.activeTab = 'results'; } catch (error) { queryError = error.message; From 2e99968a8c4a835b708d0d402afe6edbabcc3736 Mon Sep 17 00:00:00 2001 From: x_zhuo <12474586+zx06@users.noreply.github.com> Date: Fri, 6 Nov 2026 11:20:08 +0000 Subject: [PATCH 2/3] chore: fix golangci-lint issues, deduplicate code, and improve test coverage --- cmd/xsql/root.go | 1 - cmd/xsql/stats.go | 1 - cmd/xsql/stats_test.go | 49 +++++++++ internal/app/app.go | 175 +++++++++++-------------------- internal/app/service_test.go | 10 ++ internal/config/write_test.go | 11 ++ internal/db/mysql/schema.go | 106 +++---------------- internal/db/pg/schema.go | 105 +++---------------- internal/db/readonly.go | 7 +- internal/db/readonly_test.go | 33 +++--- internal/db/schema.go | 110 +++++++++++++++++++ internal/db/schema_test.go | 46 ++++++++ internal/errors/guidance_test.go | 23 ++++ internal/mcp/tools.go | 1 - internal/mcp/tools_test.go | 12 +++ internal/ssh/reconnect_test.go | 17 +++ internal/stats/store.go | 1 - internal/web/handler.go | 22 ++-- internal/web/handler_test.go | 10 ++ 19 files changed, 401 insertions(+), 339 deletions(-) diff --git a/cmd/xsql/root.go b/cmd/xsql/root.go index 9598a67b..44de1681 100644 --- a/cmd/xsql/root.go +++ b/cmd/xsql/root.go @@ -113,4 +113,3 @@ func loadStatsConfig(configPath string) stats.StatsConfig { } return st } - diff --git a/cmd/xsql/stats.go b/cmd/xsql/stats.go index 5b84ce7a..b8462312 100644 --- a/cmd/xsql/stats.go +++ b/cmd/xsql/stats.go @@ -200,4 +200,3 @@ func recordCmdStats(cmd string, profile string, ok bool, start time.Duration, er _, _ = store.Cleanup(GlobalConfig.Stats.RetentionDays) } } - diff --git a/cmd/xsql/stats_test.go b/cmd/xsql/stats_test.go index 0063eb62..52ca5a0b 100644 --- a/cmd/xsql/stats_test.go +++ b/cmd/xsql/stats_test.go @@ -347,3 +347,52 @@ func TestNewStatsResetCommand(t *testing.T) { t.Error("expected stats file to be removed") } } + +func TestStatsFormatAndRetentionCleanup(t *testing.T) { + dir := t.TempDir() + statsPath := filepath.Join(dir, "stats.jsonl") + GlobalConfig.Stats.FilePath = statsPath + GlobalConfig.Stats.RetentionDays = 7 + defer func() { + GlobalConfig.Stats.RetentionDays = 0 + GlobalConfig.FormatStr = "auto" + }() + + store := stats.NewStore(statsPath) + _ = store.Append(&stats.Record{ + Timestamp: time.Now(), + Cmd: "query", + Profile: "dev", + OK: true, + DurationMs: 12, + }) + + for _, fmtStr := range []string{"json", "yaml"} { + GlobalConfig.FormatStr = fmtStr + var buf bytes.Buffer + w := output.New(&buf, &buf) + if err := runStats(&StatsFlags{}, &w); err != nil { + t.Fatalf("runStats(%s): %v", fmtStr, err) + } + if err := runStatsLog(&StatsLogFlags{Limit: 10}, &w); err != nil { + t.Fatalf("runStatsLog(%s): %v", fmtStr, err) + } + } +} + +func TestLoadStatsConfigEnvVars(t *testing.T) { + dir := t.TempDir() + t.Setenv("XSQL_WORKDIR", dir) + t.Setenv("XSQL_HOMEDIR", dir) + t.Setenv("XSQL_STATS_ENABLED", "1") + t.Setenv("XSQL_STATS_LOG_SQL", "true") + st := loadStatsConfig("") + if !st.Enabled || !st.LogSQL { + t.Fatalf("expected stats enabled and log_sql true from env, got %+v", st) + } + GlobalConfig.Stats = st + GlobalConfig.Stats.FilePath = filepath.Join(dir, "stats.jsonl") + GlobalConfig.Stats.RetentionDays = 7 + recordCmdStats("query", "dev", true, 5*time.Millisecond, "", "SELECT 1") + GlobalConfig.Stats.RetentionDays = 0 +} diff --git a/internal/app/app.go b/internal/app/app.go index 047f90d4..de3bb16a 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -23,125 +23,68 @@ func (a App) BuildSpec() spec.Spec { {Name: "format", Shorthand: "f", Env: "XSQL_FORMAT", Default: "auto", Description: "Output format: json|yaml|table|csv|auto"}, {Name: "attr", Env: "XSQL_ATTR", Default: "", Description: "Attribute key=value pair (repeatable)"}, } + connFlags := []spec.FlagSpec{ + {Name: "allow-plaintext", Default: "false", Description: "Allow plaintext secrets in config"}, + {Name: "ssh-skip-known-hosts-check", Default: "false", Description: "Skip SSH known_hosts check (dangerous)"}, + } + webFlags := append([]spec.FlagSpec{ + {Name: "addr", Default: "127.0.0.1:8788", Env: "XSQL_WEB_HTTP_ADDR", Description: "Web HTTP listen address"}, + {Name: "auth-token", Default: "", Env: "XSQL_WEB_HTTP_AUTH_TOKEN", Description: "Bearer auth token required for non-loopback addresses"}, + }, connFlags...) + statsJSONFlag := spec.FlagSpec{Name: "json", Default: "false", Description: "Output as JSON"} + + cmd := func(name, desc string, extra ...spec.FlagSpec) spec.CommandSpec { + flags := make([]spec.FlagSpec, 0, len(globalFlags)+len(extra)) + flags = append(flags, globalFlags...) + flags = append(flags, extra...) + return spec.CommandSpec{Name: name, Description: desc, Flags: flags} + } + return spec.Spec{ SchemaVersion: output.SchemaVersion, Commands: []spec.CommandSpec{ - { - Name: "spec", - Description: "Export tool spec for AI/agents", - Flags: globalFlags, - }, - { - Name: "version", - Description: "Print version information", - Flags: globalFlags, - }, - { - Name: "query", - Description: "Execute a read-only SQL query", - Flags: append(globalFlags, - spec.FlagSpec{Name: "unsafe-allow-write", Default: "false", Description: "Allow writes when profile unsafe_allow_write is true"}, - spec.FlagSpec{Name: "allow-plaintext", Default: "false", Description: "Allow plaintext secrets in config"}, - spec.FlagSpec{Name: "ssh-skip-known-hosts-check", Default: "false", Description: "Skip SSH known_hosts check (dangerous)"}, - spec.FlagSpec{Name: "max-rows", Env: "XSQL_MAX_ROWS", Default: "1000", Description: "Maximum rows to return (0 = unlimited)"}, - spec.FlagSpec{Name: "query-timeout", Default: "30", Description: "Query timeout in seconds"}, - ), - }, - { - Name: "profile list", - Description: "List all configured profiles", - Flags: globalFlags, - }, - { - Name: "profile show", - Description: "Show profile details (passwords are masked)", - Flags: globalFlags, - }, - { - Name: "schema dump", - Description: "Dump database schema (tables, columns, indexes, foreign keys)", - Flags: append(globalFlags, - spec.FlagSpec{Name: "table", Default: "", Description: "Table name filter (supports * and ? wildcards)"}, - spec.FlagSpec{Name: "include-system", Default: "false", Description: "Include system tables"}, - spec.FlagSpec{Name: "allow-plaintext", Default: "false", Description: "Allow plaintext secrets in config"}, - spec.FlagSpec{Name: "ssh-skip-known-hosts-check", Default: "false", Description: "Skip SSH known_hosts check (dangerous)"}, - spec.FlagSpec{Name: "schema-timeout", Default: "60", Description: "Schema dump timeout in seconds"}, - ), - }, - { - Name: "config init", - Description: "Create a template configuration file", - Flags: append(globalFlags, - spec.FlagSpec{Name: "path", Default: "", Description: "Config file path (default: $HOME/.config/xsql/xsql.yaml)"}, - ), - }, - { - Name: "config set", - Description: "Set a configuration value (e.g., profile.dev.host localhost)", - Flags: globalFlags, - }, - { - Name: "mcp server", - Description: "Start MCP server for AI assistant integration", - Flags: append(globalFlags, - spec.FlagSpec{Name: "transport", Env: "XSQL_MCP_TRANSPORT", Default: "stdio", Description: "MCP transport: stdio|streamable_http"}, - spec.FlagSpec{Name: "http-addr", Env: "XSQL_MCP_HTTP_ADDR", Default: "127.0.0.1:8787", Description: "Streamable HTTP listen address"}, - spec.FlagSpec{Name: "http-auth-token", Env: "XSQL_MCP_HTTP_AUTH_TOKEN", Default: "", Description: "Streamable HTTP auth token (required for streamable_http)"}, - spec.FlagSpec{Name: "unsafe-allow-write", Env: "XSQL_MCP_UNSAFE_ALLOW_WRITE", Default: "false", Description: "Allow writes when profile unsafe_allow_write is true"}, - ), - }, - { - Name: "proxy", - Description: "Start a port forwarding proxy (replaces ssh -L)", - Flags: append(globalFlags, - spec.FlagSpec{Name: "local-port", Default: "0", Description: "Local port to listen on (0 for auto-assign)"}, - spec.FlagSpec{Name: "local-host", Default: "127.0.0.1", Description: "Local host to bind to"}, - spec.FlagSpec{Name: "allow-plaintext", Default: "false", Description: "Allow plaintext secrets in config"}, - spec.FlagSpec{Name: "ssh-skip-known-hosts-check", Default: "false", Description: "Skip SSH known_hosts check (dangerous)"}, - ), - }, - { - Name: "serve", - Description: "Start the local web management server", - Flags: append(globalFlags, - spec.FlagSpec{Name: "addr", Default: "127.0.0.1:8788", Env: "XSQL_WEB_HTTP_ADDR", Description: "Web HTTP listen address"}, - spec.FlagSpec{Name: "auth-token", Default: "", Env: "XSQL_WEB_HTTP_AUTH_TOKEN", Description: "Bearer auth token required for non-loopback addresses"}, - spec.FlagSpec{Name: "allow-plaintext", Default: "false", Description: "Allow plaintext secrets in config"}, - spec.FlagSpec{Name: "ssh-skip-known-hosts-check", Default: "false", Description: "Skip SSH known_hosts check (dangerous)"}, - ), - }, - { - Name: "web", - Description: "Start the local web management server and open a browser", - Flags: append(globalFlags, - spec.FlagSpec{Name: "addr", Default: "127.0.0.1:8788", Env: "XSQL_WEB_HTTP_ADDR", Description: "Web HTTP listen address"}, - spec.FlagSpec{Name: "auth-token", Default: "", Env: "XSQL_WEB_HTTP_AUTH_TOKEN", Description: "Bearer auth token required for non-loopback addresses"}, - spec.FlagSpec{Name: "allow-plaintext", Default: "false", Description: "Allow plaintext secrets in config"}, - spec.FlagSpec{Name: "ssh-skip-known-hosts-check", Default: "false", Description: "Skip SSH known_hosts check (dangerous)"}, - ), - }, - { - Name: "stats", - Description: "Show usage statistics", - Flags: append(globalFlags, - spec.FlagSpec{Name: "json", Default: "false", Description: "Output as JSON"}, - ), - }, - { - Name: "stats log", - Description: "Show detailed stats log", - Flags: append(globalFlags, - spec.FlagSpec{Name: "json", Default: "false", Description: "Output as JSON"}, - spec.FlagSpec{Name: "limit", Default: "100", Description: "Maximum number of records to show"}, - ), - }, - { - Name: "stats reset", - Description: "Reset usage statistics", - Flags: append(globalFlags, - spec.FlagSpec{Name: "json", Default: "false", Description: "Output as JSON"}, - ), - }, + cmd("spec", "Export tool spec for AI/agents"), + cmd("version", "Print version information"), + cmd("query", "Execute a read-only SQL query", + spec.FlagSpec{Name: "unsafe-allow-write", Default: "false", Description: "Allow writes when profile unsafe_allow_write is true"}, + connFlags[0], + connFlags[1], + spec.FlagSpec{Name: "max-rows", Env: "XSQL_MAX_ROWS", Default: "1000", Description: "Maximum rows to return (0 = unlimited)"}, + spec.FlagSpec{Name: "query-timeout", Default: "30", Description: "Query timeout in seconds"}, + ), + cmd("profile list", "List all configured profiles"), + cmd("profile show", "Show profile details (passwords are masked)"), + cmd("schema dump", "Dump database schema (tables, columns, indexes, foreign keys)", + spec.FlagSpec{Name: "table", Default: "", Description: "Table name filter (supports * and ? wildcards)"}, + spec.FlagSpec{Name: "include-system", Default: "false", Description: "Include system tables"}, + connFlags[0], + connFlags[1], + spec.FlagSpec{Name: "schema-timeout", Default: "60", Description: "Schema dump timeout in seconds"}, + ), + cmd("config init", "Create a template configuration file", + spec.FlagSpec{Name: "path", Default: "", Description: "Config file path (default: $HOME/.config/xsql/xsql.yaml)"}, + ), + cmd("config set", "Set a configuration value (e.g., profile.dev.host localhost)"), + cmd("mcp server", "Start MCP server for AI assistant integration", + spec.FlagSpec{Name: "transport", Env: "XSQL_MCP_TRANSPORT", Default: "stdio", Description: "MCP transport: stdio|streamable_http"}, + spec.FlagSpec{Name: "http-addr", Env: "XSQL_MCP_HTTP_ADDR", Default: "127.0.0.1:8787", Description: "Streamable HTTP listen address"}, + spec.FlagSpec{Name: "http-auth-token", Env: "XSQL_MCP_HTTP_AUTH_TOKEN", Default: "", Description: "Streamable HTTP auth token (required for streamable_http)"}, + spec.FlagSpec{Name: "unsafe-allow-write", Env: "XSQL_MCP_UNSAFE_ALLOW_WRITE", Default: "false", Description: "Allow writes when profile unsafe_allow_write is true"}, + ), + cmd("proxy", "Start a port forwarding proxy (replaces ssh -L)", + spec.FlagSpec{Name: "local-port", Default: "0", Description: "Local port to listen on (0 for auto-assign)"}, + spec.FlagSpec{Name: "local-host", Default: "127.0.0.1", Description: "Local host to bind to"}, + connFlags[0], + connFlags[1], + ), + cmd("serve", "Start the local web management server", webFlags...), + cmd("web", "Start the local web management server and open a browser", webFlags...), + cmd("stats", "Show usage statistics", statsJSONFlag), + cmd("stats log", "Show detailed stats log", + statsJSONFlag, + spec.FlagSpec{Name: "limit", Default: "100", Description: "Maximum number of records to show"}, + ), + cmd("stats reset", "Reset usage statistics", statsJSONFlag), }, ErrorCodes: errors.AllCodes(), } diff --git a/internal/app/service_test.go b/internal/app/service_test.go index 6ec973f5..f4ac19f4 100644 --- a/internal/app/service_test.go +++ b/internal/app/service_test.go @@ -1118,3 +1118,13 @@ func TestTestSSHProxyConnection_Branches(t *testing.T) { t.Fatal("expected error connecting to closed port") } } + +func TestQuery_ReadOnlyBlockedBeforeConnect(t *testing.T) { + _, xe := Query(context.Background(), QueryRequest{ + Profile: config.Profile{DB: "mysql", Host: "127.0.0.1", Port: 1}, + SQL: "DROP TABLE users", + }) + if xe == nil || xe.Code != errors.CodeROBlocked { + t.Fatalf("expected CodeROBlocked before connecting, got %v", xe) + } +} diff --git a/internal/config/write_test.go b/internal/config/write_test.go index 12b61c48..54207f5e 100644 --- a/internal/config/write_test.go +++ b/internal/config/write_test.go @@ -264,6 +264,9 @@ func TestSetConfigValue(t *testing.T) { "ssh_proxy": "bastion", "unsafe_allow_write": "true", "allow_plaintext": "true", + "query_timeout": "25", + "schema_timeout": "75", + "max_rows": "500", } for field, value := range fields { @@ -287,6 +290,14 @@ func TestSetConfigValue(t *testing.T) { if !p.AllowPlaintext { t.Error("allow_plaintext should be true") } + if p.QueryTimeout != 25 || p.SchemaTimeout != 75 || p.MaxRows != 500 { + t.Errorf("unexpected numeric fields: query_timeout=%d schema_timeout=%d max_rows=%d", p.QueryTimeout, p.SchemaTimeout, p.MaxRows) + } + for _, badField := range []string{"query_timeout", "schema_timeout", "max_rows"} { + if xe := SetConfigValue(path, "profile.test."+badField, "notanint"); xe == nil { + t.Errorf("expected error for invalid %s", badField) + } + } }) t.Run("set all ssh_proxy fields", func(t *testing.T) { diff --git a/internal/db/mysql/schema.go b/internal/db/mysql/schema.go index ce1d0845..bff27c64 100644 --- a/internal/db/mysql/schema.go +++ b/internal/db/mysql/schema.go @@ -4,9 +4,6 @@ import ( "context" "database/sql" "sort" - "strings" - - "golang.org/x/sync/errgroup" "github.com/zx06/xsql/internal/db" "github.com/zx06/xsql/internal/errors" @@ -47,45 +44,19 @@ func (d *Driver) DescribeTable(ctx context.Context, conn *sql.DB, opts db.TableD return nil, xe } - var ( - columns []db.Column - indexes []db.Index - fks []db.ForeignKey + return db.PopulateTableDetails( + ctx, + table, + func(gctx context.Context) ([]db.Column, *errors.XError) { + return d.getColumns(gctx, conn, schemaName, opts.Name) + }, + func(gctx context.Context) ([]db.Index, *errors.XError) { + return d.getIndexes(gctx, conn, schemaName, opts.Name) + }, + func(gctx context.Context) ([]db.ForeignKey, *errors.XError) { + return d.getForeignKeys(gctx, conn, schemaName, opts.Name) + }, ) - - g, gctx := errgroup.WithContext(ctx) - g.Go(func() error { - result, xe := d.getColumns(gctx, conn, schemaName, opts.Name) - if xe != nil { - return xe - } - columns = result - return nil - }) - g.Go(func() error { - result, xe := d.getIndexes(gctx, conn, schemaName, opts.Name) - if xe != nil { - return xe - } - indexes = result - return nil - }) - g.Go(func() error { - result, xe := d.getForeignKeys(gctx, conn, schemaName, opts.Name) - if xe != nil { - return xe - } - fks = result - return nil - }) - if err := g.Wait(); err != nil { - return nil, errors.AsOrWrap(err) - } - - table.Columns = columns - table.Indexes = indexes - table.ForeignKeys = fks - return table, nil } func currentDatabase(ctx context.Context, conn *sql.DB) (string, *errors.XError) { @@ -291,58 +262,9 @@ func (d *Driver) getForeignKeys(ctx context.Context, conn *sql.DB, schemaName, t } defer rows.Close() - fkMap := make(map[string]*db.ForeignKey) - for rows.Next() { - var constraintName, columnName, refTable, refColumn string - var ordinalPosition int - if err := rows.Scan(&constraintName, &columnName, &refTable, &refColumn, &ordinalPosition); err != nil { - return nil, errors.Wrap(errors.CodeDBExecFailed, "failed to scan foreign key row", nil, err) - } - - if fk, exists := fkMap[constraintName]; exists { - fk.Columns = append(fk.Columns, columnName) - fk.ReferencedColumns = append(fk.ReferencedColumns, refColumn) - } else { - fkMap[constraintName] = &db.ForeignKey{ - Name: constraintName, - Columns: []string{columnName}, - ReferencedTable: refTable, - ReferencedColumns: []string{refColumn}, - } - } - } - if err := rows.Err(); err != nil { - return nil, errors.Wrap(errors.CodeDBExecFailed, "rows iteration error", nil, err) - } - - names := make([]string, 0, len(fkMap)) - for name := range fkMap { - names = append(names, name) - } - sort.Strings(names) - - fks := make([]db.ForeignKey, 0, len(names)) - for _, name := range names { - fks = append(fks, *fkMap[name]) - } - return fks, nil + return db.ScanForeignKeyRows(rows) } func toLikePattern(pattern string) string { - var b strings.Builder - b.Grow(len(pattern)) - for i := 0; i < len(pattern); i++ { - switch pattern[i] { - case '\\', '%', '_': - b.WriteByte('\\') - b.WriteByte(pattern[i]) - case '*': - b.WriteByte('%') - case '?': - b.WriteByte('_') - default: - b.WriteByte(pattern[i]) - } - } - return b.String() + return db.ToLikePattern(pattern) } diff --git a/internal/db/pg/schema.go b/internal/db/pg/schema.go index ab7c01dc..eadf4af4 100644 --- a/internal/db/pg/schema.go +++ b/internal/db/pg/schema.go @@ -6,8 +6,6 @@ import ( "sort" "strings" - "golang.org/x/sync/errgroup" - "github.com/zx06/xsql/internal/db" "github.com/zx06/xsql/internal/errors" ) @@ -48,45 +46,19 @@ func (d *Driver) DescribeTable(ctx context.Context, conn *sql.DB, opts db.TableD return nil, xe } - var ( - columns []db.Column - indexes []db.Index - fks []db.ForeignKey + return db.PopulateTableDetails( + ctx, + table, + func(gctx context.Context) ([]db.Column, *errors.XError) { + return d.getColumns(gctx, conn, schemaName, opts.Name) + }, + func(gctx context.Context) ([]db.Index, *errors.XError) { + return d.getIndexes(gctx, conn, schemaName, opts.Name) + }, + func(gctx context.Context) ([]db.ForeignKey, *errors.XError) { + return d.getForeignKeys(gctx, conn, schemaName, opts.Name) + }, ) - - g, gctx := errgroup.WithContext(ctx) - g.Go(func() error { - result, xe := d.getColumns(gctx, conn, schemaName, opts.Name) - if xe != nil { - return xe - } - columns = result - return nil - }) - g.Go(func() error { - result, xe := d.getIndexes(gctx, conn, schemaName, opts.Name) - if xe != nil { - return xe - } - indexes = result - return nil - }) - g.Go(func() error { - result, xe := d.getForeignKeys(gctx, conn, schemaName, opts.Name) - if xe != nil { - return xe - } - fks = result - return nil - }) - if err := g.Wait(); err != nil { - return nil, errors.AsOrWrap(err) - } - - table.Columns = columns - table.Indexes = indexes - table.ForeignKeys = fks - return table, nil } func currentDatabase(ctx context.Context, conn *sql.DB) (string, *errors.XError) { @@ -358,58 +330,9 @@ func (d *Driver) getForeignKeys(ctx context.Context, conn *sql.DB, schemaName, t } defer rows.Close() - fkMap := make(map[string]*db.ForeignKey) - for rows.Next() { - var constraintName, columnName, refTable, refColumn string - var ordinalPosition int - if err := rows.Scan(&constraintName, &columnName, &refTable, &refColumn, &ordinalPosition); err != nil { - return nil, errors.Wrap(errors.CodeDBExecFailed, "failed to scan foreign key row", nil, err) - } - - if fk, exists := fkMap[constraintName]; exists { - fk.Columns = append(fk.Columns, columnName) - fk.ReferencedColumns = append(fk.ReferencedColumns, refColumn) - } else { - fkMap[constraintName] = &db.ForeignKey{ - Name: constraintName, - Columns: []string{columnName}, - ReferencedTable: refTable, - ReferencedColumns: []string{refColumn}, - } - } - } - if err := rows.Err(); err != nil { - return nil, errors.Wrap(errors.CodeDBExecFailed, "rows iteration error", nil, err) - } - - names := make([]string, 0, len(fkMap)) - for name := range fkMap { - names = append(names, name) - } - sort.Strings(names) - - fks := make([]db.ForeignKey, 0, len(names)) - for _, name := range names { - fks = append(fks, *fkMap[name]) - } - return fks, nil + return db.ScanForeignKeyRows(rows) } func toLikePattern(pattern string) string { - var b strings.Builder - b.Grow(len(pattern)) - for i := 0; i < len(pattern); i++ { - switch pattern[i] { - case '\\', '%', '_': - b.WriteByte('\\') - b.WriteByte(pattern[i]) - case '*': - b.WriteByte('%') - case '?': - b.WriteByte('_') - default: - b.WriteByte(pattern[i]) - } - } - return b.String() + return db.ToLikePattern(pattern) } diff --git a/internal/db/readonly.go b/internal/db/readonly.go index a12499c9..a2e2a04d 100644 --- a/internal/db/readonly.go +++ b/internal/db/readonly.go @@ -523,12 +523,7 @@ func tokenize(sql string) ([]SQLToken, error) { return tokens, nil } -// parseString parses a quoted string, handling escape sequences -func parseString(sql string, start int, quote rune) (string, int) { - str, idx, _ := parseStringWithState(sql, start, quote) - return str, idx -} - +// parseStringWithState parses a quoted string, handling escape sequences and reporting closure state. func parseStringWithState(sql string, start int, quote rune) (string, int, bool) { i := start + 1 // skip opening quote sqlLen := len(sql) diff --git a/internal/db/readonly_test.go b/internal/db/readonly_test.go index c6563513..e1d6ccc3 100644 --- a/internal/db/readonly_test.go +++ b/internal/db/readonly_test.go @@ -363,9 +363,9 @@ func BenchmarkIsReadOnlySQL_ComplexCTE(b *testing.B) { func TestUnwrapOuterParenthesizedSQL(t *testing.T) { cases := []struct { - input string - want string - wantOK bool + input string + want string + wantOK bool }{ {"(SELECT 1)", "SELECT 1", true}, {"( SELECT 1 )", "SELECT 1", true}, @@ -417,23 +417,6 @@ func TestAdvanceStringOrComment(t *testing.T) { } } -func TestParseString_Escapes(t *testing.T) { - got, idx := parseString(`'a''b'`, 0, '\'') - if got != "a'b" || idx != 6 { - t.Fatalf("doubled quote: got %q idx=%d", got, idx) - } - - got, idx = parseString(`'a\'b'`, 0, '\'') - if got != "a'b" || idx != 6 { - t.Fatalf("backslash escape: got %q idx=%d", got, idx) - } - - got, idx = parseString(`"x""y"`, 0, '"') - if got != `x"y` || idx != 6 { - t.Fatalf("double-quote escape: got %q idx=%d", got, idx) - } -} - func TestStripLeadingCommentsAndSpace(t *testing.T) { cases := []struct { input string @@ -599,3 +582,13 @@ func assertIsReadOnlySQL(t *testing.T, cases []readOnlySQLCase) { } } } + +func TestReadOnlyEdgeCases_BOMAndQuotes(t *testing.T) { + assertIsReadOnlySQL(t, []readOnlySQLCase{ + {"\ufeffSELECT 1", true}, + {"SELECT 1 # comment at eof", true}, + {`SELECT "col\"name", "col\\2" FROM t`, true}, + {`SELECT "unclosed_ident`, false}, + {"SELECT `unclosed_backtick", false}, + }) +} diff --git a/internal/db/schema.go b/internal/db/schema.go index d7867f5a..f5e12521 100644 --- a/internal/db/schema.go +++ b/internal/db/schema.go @@ -3,6 +3,8 @@ package db import ( "context" "database/sql" + "sort" + "strings" "golang.org/x/sync/errgroup" @@ -187,3 +189,111 @@ func DumpSchema(ctx context.Context, driverName string, db *sql.DB, opts SchemaO return info, nil } + +// PopulateTableDetails concurrently loads columns, indexes, and foreign keys for a table. +func PopulateTableDetails( + ctx context.Context, + table *Table, + getCols func(context.Context) ([]Column, *errors.XError), + getIdxs func(context.Context) ([]Index, *errors.XError), + getFKs func(context.Context) ([]ForeignKey, *errors.XError), +) (*Table, *errors.XError) { + var ( + columns []Column + indexes []Index + fks []ForeignKey + ) + + g, gctx := errgroup.WithContext(ctx) + g.Go(func() error { + res, xe := getCols(gctx) + if xe != nil { + return xe + } + columns = res + return nil + }) + g.Go(func() error { + res, xe := getIdxs(gctx) + if xe != nil { + return xe + } + indexes = res + return nil + }) + g.Go(func() error { + res, xe := getFKs(gctx) + if xe != nil { + return xe + } + fks = res + return nil + }) + if err := g.Wait(); err != nil { + return nil, errors.AsOrWrap(err) + } + + table.Columns = columns + table.Indexes = indexes + table.ForeignKeys = fks + return table, nil +} + +// ScanForeignKeyRows scans ordered foreign key rows into sorted ForeignKey structs. +func ScanForeignKeyRows(rows *sql.Rows) ([]ForeignKey, *errors.XError) { + fkMap := make(map[string]*ForeignKey) + for rows.Next() { + var constraintName, columnName, refTable, refColumn string + var ordinalPosition int + if err := rows.Scan(&constraintName, &columnName, &refTable, &refColumn, &ordinalPosition); err != nil { + return nil, errors.Wrap(errors.CodeDBExecFailed, "failed to scan foreign key row", nil, err) + } + + if fk, exists := fkMap[constraintName]; exists { + fk.Columns = append(fk.Columns, columnName) + fk.ReferencedColumns = append(fk.ReferencedColumns, refColumn) + } else { + fkMap[constraintName] = &ForeignKey{ + Name: constraintName, + Columns: []string{columnName}, + ReferencedTable: refTable, + ReferencedColumns: []string{refColumn}, + } + } + } + if err := rows.Err(); err != nil { + return nil, errors.Wrap(errors.CodeDBExecFailed, "rows iteration error", nil, err) + } + + names := make([]string, 0, len(fkMap)) + for name := range fkMap { + names = append(names, name) + } + sort.Strings(names) + + fks := make([]ForeignKey, 0, len(names)) + for _, name := range names { + fks = append(fks, *fkMap[name]) + } + return fks, nil +} + +// ToLikePattern converts wildcard patterns (* and ?) into SQL LIKE patterns while escaping literal \, %, and _. +func ToLikePattern(pattern string) string { + var b strings.Builder + b.Grow(len(pattern)) + for i := 0; i < len(pattern); i++ { + switch pattern[i] { + case '\\', '%', '_': + b.WriteByte('\\') + b.WriteByte(pattern[i]) + case '*': + b.WriteByte('%') + case '?': + b.WriteByte('_') + default: + b.WriteByte(pattern[i]) + } + } + return b.String() +} diff --git a/internal/db/schema_test.go b/internal/db/schema_test.go index 95284b04..abca1fc7 100644 --- a/internal/db/schema_test.go +++ b/internal/db/schema_test.go @@ -415,3 +415,49 @@ func (d *mockSchemaExplorerDriver) DescribeTable(ctx context.Context, db *sql.DB table := d.tables[key] return &table, nil } + +func TestToLikePattern(t *testing.T) { + cases := map[string]string{ + "users": "users", + "user*": "user%", + "user_?": `user\_` + "_", + `100%\test*`: `100\%\\test%`, + } + for in, want := range cases { + if got := ToLikePattern(in); got != want { + t.Fatalf("ToLikePattern(%q) = %q, want %q", in, got, want) + } + } +} + +func TestPopulateTableDetails(t *testing.T) { + ctx := context.Background() + okCols := func(context.Context) ([]Column, *errors.XError) { + return []Column{{Name: "id", Type: "int"}}, nil + } + okIdxs := func(context.Context) ([]Index, *errors.XError) { + return []Index{{Name: "idx_id", Columns: []string{"id"}}}, nil + } + okFKs := func(context.Context) ([]ForeignKey, *errors.XError) { + return []ForeignKey{{Name: "fk_id", Columns: []string{"id"}}}, nil + } + + tbl, xe := PopulateTableDetails(ctx, &Table{Schema: "public", Name: "users"}, okCols, okIdxs, okFKs) + if xe != nil { + t.Fatalf("PopulateTableDetails failed: %v", xe) + } + if len(tbl.Columns) != 1 || len(tbl.Indexes) != 1 || len(tbl.ForeignKeys) != 1 { + t.Fatalf("unexpected populated table: %+v", tbl) + } + + errFn := errors.New(errors.CodeDBExecFailed, "mock failure", nil) + if _, xe := PopulateTableDetails(ctx, &Table{}, func(context.Context) ([]Column, *errors.XError) { return nil, errFn }, okIdxs, okFKs); xe == nil { + t.Fatal("expected error from getCols") + } + if _, xe := PopulateTableDetails(ctx, &Table{}, okCols, func(context.Context) ([]Index, *errors.XError) { return nil, errFn }, okFKs); xe == nil { + t.Fatal("expected error from getIdxs") + } + if _, xe := PopulateTableDetails(ctx, &Table{}, okCols, okIdxs, func(context.Context) ([]ForeignKey, *errors.XError) { return nil, errFn }); xe == nil { + t.Fatal("expected error from getFKs") + } +} diff --git a/internal/errors/guidance_test.go b/internal/errors/guidance_test.go index d84d2764..8dd210f3 100644 --- a/internal/errors/guidance_test.go +++ b/internal/errors/guidance_test.go @@ -183,6 +183,29 @@ func TestMergeDetails_NilBase(t *testing.T) { } } +func TestAdditionalGuidanceAndExitCodes(t *testing.T) { + cases := []struct { + code Code + expectSub string + expectExit ExitCode + }{ + {CodeDBDriverUnsupported, "mysql", ExitCode(3)}, + {CodePortInUse, "port", ExitInternal}, + {CodeAuthRequired, "Bearer", ExitConfig}, + {CodeAuthInvalid, "Bearer", ExitConfig}, + } + for _, tc := range cases { + xe := New(tc.code, "test error", nil) + hint, _ := xe.Details["hint"].(string) + if !containsFold(hint, tc.expectSub) { + t.Errorf("code %s hint = %q, want substring %q", tc.code, hint, tc.expectSub) + } + if got := ExitCodeFor(tc.code); got != tc.expectExit { + t.Errorf("ExitCodeFor(%s) = %v, want %v", tc.code, got, tc.expectExit) + } + } +} + func containsFold(s, sub string) bool { return strings.Contains(strings.ToLower(s), strings.ToLower(sub)) } diff --git a/internal/mcp/tools.go b/internal/mcp/tools.go index 4256ee84..b8c44e41 100644 --- a/internal/mcp/tools.go +++ b/internal/mcp/tools.go @@ -328,4 +328,3 @@ func (h *ToolHandler) recordMCPStats(cmd, profile string, ok bool, duration time _, _ = store.Cleanup(h.stats.RetentionDays) } } - diff --git a/internal/mcp/tools_test.go b/internal/mcp/tools_test.go index 43c29fa0..1383f30e 100644 --- a/internal/mcp/tools_test.go +++ b/internal/mcp/tools_test.go @@ -880,3 +880,15 @@ func TestProfileList_EmptyProfiles(t *testing.T) { t.Fatalf("expected empty profiles list, got: %s", text) } } + +func TestRecordStats_WithRetentionAndLogSQL(t *testing.T) { + cfg := &config.File{Profiles: map[string]config.Profile{"dev": {DB: "mysql"}}} + statsCfg := stats.StatsConfig{ + Enabled: true, + FilePath: t.TempDir() + "/mcp_stats.jsonl", + LogSQL: true, + RetentionDays: 7, + } + handler := NewToolHandler(cfg, statsCfg, ServerOptions{}) + handler.recordMCPStats("query", "dev", false, 0, errors.New(errors.CodeROBlocked, "blocked", nil), "DROP TABLE x") +} diff --git a/internal/ssh/reconnect_test.go b/internal/ssh/reconnect_test.go index 2a7031f0..6d42ad8a 100644 --- a/internal/ssh/reconnect_test.go +++ b/internal/ssh/reconnect_test.go @@ -820,3 +820,20 @@ func TestReconnectDialer_RealSSH_DialThroughTunnel(t *testing.T) { t.Errorf("echo mismatch: got %q, want %q", buf, msg) } } + +func TestReconnectDialer_FinishReconnectWhenClosed(t *testing.T) { + rd := &ReconnectDialer{ + closed: true, + reconnecting: true, + reconnectCh: make(chan struct{}), + } + c := &Client{} + c.alive.Store(true) + rd.finishReconnect(c) + if c.alive.Load() { + t.Error("expected newClient to be closed when dialer was already closed") + } + if rd.reconnecting { + t.Error("expected reconnecting to be false") + } +} diff --git a/internal/stats/store.go b/internal/stats/store.go index 482166a8..59366855 100644 --- a/internal/stats/store.go +++ b/internal/stats/store.go @@ -171,4 +171,3 @@ func (s *Store) Cleanup(retentionDays int) (int, error) { return removed, f.Close() } - diff --git a/internal/web/handler.go b/internal/web/handler.go index d127601e..9a8083ad 100644 --- a/internal/web/handler.go +++ b/internal/web/handler.go @@ -584,15 +584,22 @@ func (h *handler) parseConfigDeleteName(w http.ResponseWriter, r *http.Request, return name, true } -func (h *handler) handleConfigSaveProfile(w http.ResponseWriter, r *http.Request) { +func decodeConfigSaveBody(w http.ResponseWriter, r *http.Request, dst any) bool { if r.Method != http.MethodPost && r.Method != http.MethodPut { writeMethodNotAllowed(w) - return + return false } + if err := json.NewDecoder(io.LimitReader(r.Body, 1<<20)).Decode(dst); err != nil { + writeError(w, http.StatusBadRequest, errors.Wrap(errors.CodeCfgInvalid, "invalid JSON payload", nil, err)) + return false + } + return true +} + +func (h *handler) handleConfigSaveProfile(w http.ResponseWriter, r *http.Request) { defer r.Body.Close() var req configProfileRequest - if err := json.NewDecoder(io.LimitReader(r.Body, 1<<20)).Decode(&req); err != nil { - writeError(w, http.StatusBadRequest, errors.Wrap(errors.CodeCfgInvalid, "invalid JSON payload", nil, err)) + if !decodeConfigSaveBody(w, r, &req) { return } name := strings.TrimSpace(req.Name) @@ -631,14 +638,9 @@ type configSSHProxyRequest struct { } func (h *handler) handleConfigSaveSSHProxy(w http.ResponseWriter, r *http.Request) { - if r.Method != http.MethodPost && r.Method != http.MethodPut { - writeMethodNotAllowed(w) - return - } defer r.Body.Close() var req configSSHProxyRequest - if err := json.NewDecoder(io.LimitReader(r.Body, 1<<20)).Decode(&req); err != nil { - writeError(w, http.StatusBadRequest, errors.Wrap(errors.CodeCfgInvalid, "invalid JSON payload", nil, err)) + if !decodeConfigSaveBody(w, r, &req) { return } name := strings.TrimSpace(req.Name) diff --git a/internal/web/handler_test.go b/internal/web/handler_test.go index 3953c312..0a1d4c0a 100644 --- a/internal/web/handler_test.go +++ b/internal/web/handler_test.go @@ -843,4 +843,14 @@ func TestHandler_CrossOriginBlocked(t *testing.T) { if recSame.Code != http.StatusOK { t.Fatalf("expected 200 for same-origin request, got %d", recSame.Code) } + + for _, badOrigin := range []string{"null", "://invalid-url", "https://"} { + reqBad := httptest.NewRequest(http.MethodGet, "http://127.0.0.1:8788/api/v1/config", nil) + reqBad.Header.Set("Origin", badOrigin) + recBad := httptest.NewRecorder() + handler.ServeHTTP(recBad, reqBad) + if recBad.Code != http.StatusForbidden { + t.Fatalf("expected 403 for Origin=%q, got %d", badOrigin, recBad.Code) + } + } } From b72085f82bfbd4376d5b10f1d02c4e9bf51cffa7 Mon Sep 17 00:00:00 2001 From: x_zhuo <12474586+zx06@users.noreply.github.com> Date: Fri, 6 Nov 2026 11:27:54 +0000 Subject: [PATCH 3/3] refactor(db): extract DescribeTableWithDetails to eliminate SonarCloud duplication --- internal/db/mysql/schema.go | 20 +------------- internal/db/pg/schema.go | 20 +------------- internal/db/query_readonly_test.go | 16 ++++++------ internal/db/schema.go | 29 +++++++++++++++++++++ internal/db/schema_test.go | 21 +++++++++++++++ internal/errors/dbclassify_test.go | 22 ++++++++-------- internal/mcp/schema_tools_test.go | 6 ++--- internal/proxy/proxy_test.go | 2 -- tests/e2e/mcp_test.go | 2 +- tests/integration/app_query_test.go | 2 +- tests/integration/error_guidance_test.go | 14 +++++----- tests/integration/readonly_db_layer_test.go | 2 +- 12 files changed, 84 insertions(+), 72 deletions(-) diff --git a/internal/db/mysql/schema.go b/internal/db/mysql/schema.go index bff27c64..fe85b9c6 100644 --- a/internal/db/mysql/schema.go +++ b/internal/db/mysql/schema.go @@ -38,25 +38,7 @@ func (d *Driver) DescribeTable(ctx context.Context, conn *sql.DB, opts db.TableD if schemaName == "" { schemaName = database } - - table, xe := d.loadTableSummary(ctx, conn, schemaName, opts.Name) - if xe != nil { - return nil, xe - } - - return db.PopulateTableDetails( - ctx, - table, - func(gctx context.Context) ([]db.Column, *errors.XError) { - return d.getColumns(gctx, conn, schemaName, opts.Name) - }, - func(gctx context.Context) ([]db.Index, *errors.XError) { - return d.getIndexes(gctx, conn, schemaName, opts.Name) - }, - func(gctx context.Context) ([]db.ForeignKey, *errors.XError) { - return d.getForeignKeys(gctx, conn, schemaName, opts.Name) - }, - ) + return db.DescribeTableWithDetails(ctx, conn, schemaName, opts.Name, d.loadTableSummary, d.getColumns, d.getIndexes, d.getForeignKeys) } func currentDatabase(ctx context.Context, conn *sql.DB) (string, *errors.XError) { diff --git a/internal/db/pg/schema.go b/internal/db/pg/schema.go index eadf4af4..968732c4 100644 --- a/internal/db/pg/schema.go +++ b/internal/db/pg/schema.go @@ -40,25 +40,7 @@ func (d *Driver) DescribeTable(ctx context.Context, conn *sql.DB, opts db.TableD if schemaName == "" { schemaName = "public" } - - table, xe := d.loadTableSummary(ctx, conn, schemaName, opts.Name) - if xe != nil { - return nil, xe - } - - return db.PopulateTableDetails( - ctx, - table, - func(gctx context.Context) ([]db.Column, *errors.XError) { - return d.getColumns(gctx, conn, schemaName, opts.Name) - }, - func(gctx context.Context) ([]db.Index, *errors.XError) { - return d.getIndexes(gctx, conn, schemaName, opts.Name) - }, - func(gctx context.Context) ([]db.ForeignKey, *errors.XError) { - return d.getForeignKeys(gctx, conn, schemaName, opts.Name) - }, - ) + return db.DescribeTableWithDetails(ctx, conn, schemaName, opts.Name, d.loadTableSummary, d.getColumns, d.getIndexes, d.getForeignKeys) } func currentDatabase(ctx context.Context, conn *sql.DB) (string, *errors.XError) { diff --git a/internal/db/query_readonly_test.go b/internal/db/query_readonly_test.go index e0417fc9..3c4f0e71 100644 --- a/internal/db/query_readonly_test.go +++ b/internal/db/query_readonly_test.go @@ -12,14 +12,14 @@ import ( func TestNormalizeDBType(t *testing.T) { cases := map[string]string{ - "mysql": "mysql", - "MYSQL": "mysql", - "mariadb": "mysql", - "pg": "pg", - "postgres": "pg", - "postgresql": "pg", - " PG ": "pg", - "custom": "custom", + "mysql": "mysql", + "MYSQL": "mysql", + "mariadb": "mysql", + "pg": "pg", + "postgres": "pg", + "postgresql": "pg", + " PG ": "pg", + "custom": "custom", } for in, want := range cases { if got := normalizeDBType(in); got != want { diff --git a/internal/db/schema.go b/internal/db/schema.go index f5e12521..1e162078 100644 --- a/internal/db/schema.go +++ b/internal/db/schema.go @@ -239,6 +239,35 @@ func PopulateTableDetails( return table, nil } +// DescribeTableWithDetails loads a table summary and concurrently populates its columns, indexes, and foreign keys. +func DescribeTableWithDetails( + ctx context.Context, + conn *sql.DB, + schemaName, tableName string, + loadSummary func(context.Context, *sql.DB, string, string) (*Table, *errors.XError), + getCols func(context.Context, *sql.DB, string, string) ([]Column, *errors.XError), + getIdxs func(context.Context, *sql.DB, string, string) ([]Index, *errors.XError), + getFKs func(context.Context, *sql.DB, string, string) ([]ForeignKey, *errors.XError), +) (*Table, *errors.XError) { + table, xe := loadSummary(ctx, conn, schemaName, tableName) + if xe != nil { + return nil, xe + } + return PopulateTableDetails( + ctx, + table, + func(gctx context.Context) ([]Column, *errors.XError) { + return getCols(gctx, conn, schemaName, tableName) + }, + func(gctx context.Context) ([]Index, *errors.XError) { + return getIdxs(gctx, conn, schemaName, tableName) + }, + func(gctx context.Context) ([]ForeignKey, *errors.XError) { + return getFKs(gctx, conn, schemaName, tableName) + }, + ) +} + // ScanForeignKeyRows scans ordered foreign key rows into sorted ForeignKey structs. func ScanForeignKeyRows(rows *sql.Rows) ([]ForeignKey, *errors.XError) { fkMap := make(map[string]*ForeignKey) diff --git a/internal/db/schema_test.go b/internal/db/schema_test.go index abca1fc7..d1784136 100644 --- a/internal/db/schema_test.go +++ b/internal/db/schema_test.go @@ -460,4 +460,25 @@ func TestPopulateTableDetails(t *testing.T) { if _, xe := PopulateTableDetails(ctx, &Table{}, okCols, okIdxs, func(context.Context) ([]ForeignKey, *errors.XError) { return nil, errFn }); xe == nil { t.Fatal("expected error from getFKs") } + + tbl2, xe := DescribeTableWithDetails( + ctx, + nil, + "public", + "users", + func(_ context.Context, _ *sql.DB, s, n string) (*Table, *errors.XError) { + return &Table{Schema: s, Name: n}, nil + }, + func(context.Context, *sql.DB, string, string) ([]Column, *errors.XError) { return okCols(ctx) }, + func(context.Context, *sql.DB, string, string) ([]Index, *errors.XError) { return okIdxs(ctx) }, + func(context.Context, *sql.DB, string, string) ([]ForeignKey, *errors.XError) { return okFKs(ctx) }, + ) + if xe != nil || tbl2.Name != "users" || len(tbl2.Columns) != 1 { + t.Fatalf("DescribeTableWithDetails failed: %v %+v", xe, tbl2) + } + if _, xe := DescribeTableWithDetails(ctx, nil, "public", "users", func(context.Context, *sql.DB, string, string) (*Table, *errors.XError) { + return nil, errFn + }, nil, nil, nil); xe == nil { + t.Fatal("expected error from loadSummary") + } } diff --git a/internal/errors/dbclassify_test.go b/internal/errors/dbclassify_test.go index 40fbb0e1..6b3763ac 100644 --- a/internal/errors/dbclassify_test.go +++ b/internal/errors/dbclassify_test.go @@ -57,17 +57,17 @@ func TestClassifyMySQLError(t *testing.T) { number uint16 want classifyWant }{ - "unknown_table": {1146, classifyWant{CategoryUnknownTable, "1146", "mysql_errno", false, "schema_list_tables"}}, - "unknown_db": {1049, classifyWant{CategoryUnknownTable, "1049", "mysql_errno", false, "schema dump"}}, - "unknown_column": {1054, classifyWant{CategoryUnknownColumn, "1054", "mysql_errno", false, "schema dump"}}, - "syntax": {1064, classifyWant{CategorySyntaxError, "1064", "mysql_errno", false, "syntax"}}, - "auth_failed": {1045, classifyWant{CategoryAuthFailed, "1045", "mysql_errno", false, "keyring"}}, - "permission": {1142, classifyWant{CategoryPermissionDenied, "1142", "mysql_errno", false, "privileges"}}, - "read_only_tx": {1792, classifyWant{CategoryReadOnlyViolation, "1792", "mysql_errno", false, "unsafe_allow_write"}}, - "duplicate_key": {1062, classifyWant{CategoryDuplicateKey, "1062", "mysql_errno", false, "Duplicate"}}, - "connection": {2003, classifyWant{CategoryConnection, "2003", "mysql_errno", true, "MySQL"}}, - "timeout": {1205, classifyWant{CategoryTimeout, "1205", "mysql_errno", true, "LIMIT"}}, - "other": {9999, classifyWant{CategoryOther, "9999", "mysql_errno", false, "native_code"}}, + "unknown_table": {1146, classifyWant{CategoryUnknownTable, "1146", "mysql_errno", false, "schema_list_tables"}}, + "unknown_db": {1049, classifyWant{CategoryUnknownTable, "1049", "mysql_errno", false, "schema dump"}}, + "unknown_column": {1054, classifyWant{CategoryUnknownColumn, "1054", "mysql_errno", false, "schema dump"}}, + "syntax": {1064, classifyWant{CategorySyntaxError, "1064", "mysql_errno", false, "syntax"}}, + "auth_failed": {1045, classifyWant{CategoryAuthFailed, "1045", "mysql_errno", false, "keyring"}}, + "permission": {1142, classifyWant{CategoryPermissionDenied, "1142", "mysql_errno", false, "privileges"}}, + "read_only_tx": {1792, classifyWant{CategoryReadOnlyViolation, "1792", "mysql_errno", false, "unsafe_allow_write"}}, + "duplicate_key": {1062, classifyWant{CategoryDuplicateKey, "1062", "mysql_errno", false, "Duplicate"}}, + "connection": {2003, classifyWant{CategoryConnection, "2003", "mysql_errno", true, "MySQL"}}, + "timeout": {1205, classifyWant{CategoryTimeout, "1205", "mysql_errno", true, "LIMIT"}}, + "other": {9999, classifyWant{CategoryOther, "9999", "mysql_errno", false, "native_code"}}, } for name, tc := range cases { t.Run(name, func(t *testing.T) { diff --git a/internal/mcp/schema_tools_test.go b/internal/mcp/schema_tools_test.go index 96e74702..b067bd65 100644 --- a/internal/mcp/schema_tools_test.go +++ b/internal/mcp/schema_tools_test.go @@ -406,9 +406,9 @@ func assertToolError(t *testing.T, result *mcp.CallToolResult, code, messageCont t.Fatalf("expected message %q in %s", messageContains, text) } var envelope struct { - OK bool `json:"ok"` - SchemaVersion int `json:"schema_version"` - Error map[string]any `json:"error"` + OK bool `json:"ok"` + SchemaVersion int `json:"schema_version"` + Error map[string]any `json:"error"` } if err := json.Unmarshal([]byte(text), &envelope); err != nil { t.Fatalf("invalid error json: %v", err) diff --git a/internal/proxy/proxy_test.go b/internal/proxy/proxy_test.go index 27425fab..44febf72 100644 --- a/internal/proxy/proxy_test.go +++ b/internal/proxy/proxy_test.go @@ -877,5 +877,3 @@ func TestProxy_AcceptConnections_ContextDoneDuringBackoff(t *testing.T) { t.Fatal("acceptConnections should terminate upon context cancellation during backoff") } } - - diff --git a/tests/e2e/mcp_test.go b/tests/e2e/mcp_test.go index de38142d..f735f461 100644 --- a/tests/e2e/mcp_test.go +++ b/tests/e2e/mcp_test.go @@ -17,8 +17,8 @@ import ( "time" _ "github.com/go-sql-driver/mysql" - "github.com/modelcontextprotocol/go-sdk/mcp" _ "github.com/jackc/pgx/v5/stdlib" + "github.com/modelcontextprotocol/go-sdk/mcp" ) // TestMCPServer_Startup tests that MCP server starts correctly and returns tools list diff --git a/tests/integration/app_query_test.go b/tests/integration/app_query_test.go index 39a1553e..671984e9 100644 --- a/tests/integration/app_query_test.go +++ b/tests/integration/app_query_test.go @@ -25,7 +25,7 @@ func TestAppQuery_TruncationHint_MySQL(t *testing.T) { DB: "mysql", DSN: dsn, }, - SQL: `WITH RECURSIVE seq AS (SELECT 1 AS n UNION ALL SELECT n+1 FROM seq WHERE n < 8) SELECT n FROM seq`, + SQL: `WITH RECURSIVE seq AS (SELECT 1 AS n UNION ALL SELECT n+1 FROM seq WHERE n < 8) SELECT n FROM seq`, MaxRows: 3, TruncationHint: app.QueryTruncationHint, }) diff --git a/tests/integration/error_guidance_test.go b/tests/integration/error_guidance_test.go index b97c671f..d4605c75 100644 --- a/tests/integration/error_guidance_test.go +++ b/tests/integration/error_guidance_test.go @@ -18,13 +18,13 @@ import ( ) type errorGuidanceEngine struct { - label string - driver string - dsnEnv string - dbType string - dsn string - badDSN func(string) string - authHintSub string + label string + driver string + dsnEnv string + dbType string + dsn string + badDSN func(string) string + authHintSub string } type errorGuidanceScenario struct { diff --git a/tests/integration/readonly_db_layer_test.go b/tests/integration/readonly_db_layer_test.go index d22bf775..eeee5fb0 100644 --- a/tests/integration/readonly_db_layer_test.go +++ b/tests/integration/readonly_db_layer_test.go @@ -9,9 +9,9 @@ import ( "time" "github.com/zx06/xsql/internal/db" - "github.com/zx06/xsql/internal/errors" _ "github.com/zx06/xsql/internal/db/mysql" // register MySQL driver for db.Get("mysql") _ "github.com/zx06/xsql/internal/db/pg" // register PostgreSQL driver for db.Get("pg") + "github.com/zx06/xsql/internal/errors" ) type readonlyTxCase struct {