An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:art: Add read-only mode to `/api/query/sql` (#17696)
Jeffrey Chen0a454d3cb775
diff --git a/kernel/api/sql.go b/kernel/api/sql.goindex 26bf16ba5e..a185ea1659 100644--- a/kernel/api/sql.go+++ b/kernel/api/sql.go@@ -44,15 +44,44 @@ func SQL(c *gin.Context) {return}- var stmt string- var skipSingleStatementCheck bool+ var stmt, mode stringif !util.ParseJsonArgs(arg, ret,util.BindJsonArg("stmt", &stmt, true, true),- util.BindJsonArg("skipSingleStatementCheck", &skipSingleStatementCheck, false, false),+ util.BindJsonArg("mode", &mode, false, false),) {return}- result, err := sql.Query(stmt, model.Conf.Search.Limit, !skipSingleStatementCheck)++ switch mode {+ case "":+ // 默认模式,允许单条语句+ if err := sql.CheckSingleStatement(stmt); err != nil {+ ret.Code = -1+ ret.Msg = err.Error()+ return+ }+ case "readonly":+ // 只读模式,允许单条语句+ if err := sql.CheckSingleStatement(stmt); err != nil {+ ret.Code = -1+ ret.Msg = err.Error()+ return+ }+ if err := sql.CheckReadonlyStatement(stmt); err != nil {+ ret.Code = -1+ ret.Msg = err.Error()+ return+ }+ case "multiple":+ // 多语句模式,不做校验+ default:+ // 未知模式+ ret.Code = -1+ ret.Msg = "unknown [mode]"+ return+ }++ result, err := sql.Query(stmt, model.Conf.Search.Limit)if err != nil {ret.Code = 1ret.Msg = err.Error()diff --git a/kernel/cli/cmd/sql.go b/kernel/cli/cmd/sql.goindex 3c0d9dbf96..f03867c357 100644--- a/kernel/cli/cmd/sql.go+++ b/kernel/cli/cmd/sql.go@@ -39,7 +39,10 @@ var sqlCmd = &cobra.Command{limit = 100}- rows, err := sql.Query(stmt, limit, true)+ if err := sql.CheckSingleStatement(stmt); err != nil {+ return err+ }+ rows, err := sql.Query(stmt, limit)if err != nil {return err}diff --git a/kernel/sql/block_query.go b/kernel/sql/block_query.goindex ac7b03563e..bf0ffe3815 100644--- a/kernel/sql/block_query.go+++ b/kernel/sql/block_query.go@@ -363,93 +363,7 @@ func QueryNoLimit(stmt string) (ret []map[string]any, err error) {return queryRawStmt(stmt, math.MaxInt)}-func containsMultipleStatements(stmt string) bool {- stmt = strings.TrimSpace(stmt)- for strings.HasSuffix(stmt, ";") {- stmt = strings.TrimRight(stmt, ";")- stmt = strings.TrimSpace(stmt)- }-- inSingleQuote := false- inDoubleQuote := false- inBacktickQuote := false- inBracketQuote := false- inLineComment := false- inBlockComment := false- runes := []rune(stmt)- for i := 0; i < len(runes); i++ {- ch := runes[i]- var next rune- if i+1 < len(runes) {- next = runes[i+1]- }-- if inLineComment {- if '\n' == ch {- inLineComment = false- }- continue- }- if inBlockComment {- if '*' == ch && '/' == next {- inBlockComment = false- i++- }- continue- }- if inSingleQuote {- if '\'' == ch {- inSingleQuote = false- }- continue- }- if inDoubleQuote {- if '"' == ch {- inDoubleQuote = false- }- continue- }- if inBacktickQuote {- if '`' == ch {- inBacktickQuote = false- }- continue- }- if inBracketQuote {- if ']' == ch {- inBracketQuote = false- }- continue- }-- switch {- case '\'' == ch:- inSingleQuote = true- case '"' == ch:- inDoubleQuote = true- case '`' == ch:- inBacktickQuote = true- case '[' == ch:- inBracketQuote = true- case '-' == ch && next == '-':- inLineComment = true- i++- case '/' == ch && next == '*':- inBlockComment = true- i++- case ';' == ch:- remaining := strings.TrimSpace(string(runes[i+1:]))- return 0 < len(remaining)- }- }- return false-}--func Query(stmt string, limit int, checkSingleStatement bool) (ret []map[string]any, err error) {- if checkSingleStatement && containsMultipleStatements(stmt) {- return nil, errors.New("only one SQL statement is allowed, multiple statements separated by semicolons are not supported")- }-+func Query(stmt string, limit int) (ret []map[string]any, err error) {originalStmt := stmt// Kernel API `/api/query/sql` support `||` operator https://github.com/siyuan-note/siyuan/issues/9662// 这里为了支持 || 操作符,使用了另一个 sql 解析器,但是这个解析器无法处理 UNION https://github.com/siyuan-note/siyuan/issues/8226diff --git a/kernel/sql/database.go b/kernel/sql/database.goindex f61799189a..a86f9bbfef 100644--- a/kernel/sql/database.go+++ b/kernel/sql/database.go@@ -1624,7 +1624,10 @@ func SQLTemplateFuncs(templateFuncMap *template.FuncMap) {return}(*templateFuncMap)["querySQL"] = func(stmt string) (ret []map[string]any) {- ret, _ = Query(stmt, 1024, true)+ if err := CheckSingleStatement(stmt); err != nil {+ return+ }+ ret, _ = Query(stmt, 1024)return}}diff --git a/kernel/sql/stmt_validate.go b/kernel/sql/stmt_validate.gonew file mode 100644index 0000000000..a22399f6f9--- /dev/null+++ b/kernel/sql/stmt_validate.go@@ -0,0 +1,195 @@+// SiYuan - Refactor your thinking+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package sql++import (+ "context"+ "errors"+ "fmt"+ "strings"+ "unicode"++ "github.com/mattn/go-sqlite3"+)++// tailIsOnlyWhitespaceOrSQLComments 判断分号之后的片段是否仅由空白、行注释(-- 至换行或 EOF)、+// 块注释(/* … */,含未闭合则吞至 EOF)构成。与 SQLite 解析对齐:分号后若只有这些内容,不会被视为另一条可执行的 SQL 语句。+func tailIsOnlyWhitespaceOrSQLComments(s string) bool {+ runes := []rune(s)+ for i := 0; i < len(runes); {+ if unicode.IsSpace(runes[i]) {+ i+++ continue+ }+ ch := runes[i]+ var next rune+ if i+1 < len(runes) {+ next = runes[i+1]+ }+ if '-' == ch && '-' == next {+ i += 2+ for i < len(runes) && '\n' != runes[i] {+ i+++ }+ continue+ }+ if '/' == ch && '*' == next {+ i += 2+ for i < len(runes) {+ if '*' == runes[i] && i+1 < len(runes) && '/' == runes[i+1] {+ i += 2+ break+ }+ i+++ }+ continue+ }+ return false+ }+ return true+}++func containsMultipleStatements(stmt string) bool {+ stmt = strings.TrimSpace(stmt)+ for strings.HasSuffix(stmt, ";") {+ stmt = strings.TrimRight(stmt, ";")+ stmt = strings.TrimSpace(stmt)+ }++ inSingleQuote := false+ inDoubleQuote := false+ inBacktickQuote := false+ inBracketQuote := false+ inLineComment := false+ inBlockComment := false+ runes := []rune(stmt)+ for i := 0; i < len(runes); i++ {+ ch := runes[i]+ var next rune+ if i+1 < len(runes) {+ next = runes[i+1]+ }++ if inLineComment {+ if '\n' == ch {+ inLineComment = false+ }+ continue+ }+ if inBlockComment {+ if '*' == ch && '/' == next {+ inBlockComment = false+ i+++ }+ continue+ }+ if inSingleQuote {+ if '\'' == ch {+ inSingleQuote = false+ }+ continue+ }+ if inDoubleQuote {+ if '"' == ch {+ inDoubleQuote = false+ }+ continue+ }+ if inBacktickQuote {+ if '`' == ch {+ inBacktickQuote = false+ }+ continue+ }+ if inBracketQuote {+ if ']' == ch {+ inBracketQuote = false+ }+ continue+ }++ switch {+ case '\'' == ch:+ inSingleQuote = true+ case '"' == ch:+ inDoubleQuote = true+ case '`' == ch:+ inBacktickQuote = true+ case '[' == ch:+ inBracketQuote = true+ case '-' == ch && next == '-':+ inLineComment = true+ i+++ case '/' == ch && next == '*':+ inBlockComment = true+ i+++ case ';' == ch:+ tail := string(runes[i+1:])+ if tailIsOnlyWhitespaceOrSQLComments(tail) {+ // 分号后仅有空白与 SQL 注释时,SQLite 仍视为同一条语句末尾,不应判为多语句。+ continue+ }+ return true+ }+ }+ return false+}++func CheckSingleStatement(stmt string) error {+ if containsMultipleStatements(stmt) {+ return errors.New("statement contains multiple SQL statements")+ }+ return nil+}++// CheckReadonlyStatement 对整段 SQL 做 prepare(不执行),用 sqlite3_stmt_readonly 判断首条语句是否只读。+// 见 https://sqlite.org/c3ref/stmt_readonly.html+//+// 注意:若字符串里在语法上还有第二条及以后的语句,本函数只针对「首条」对应的 stmt 做判断,+// 不会拒绝多语句。与 CheckSingleStatement 组合即可得到「单条 + 只读」策略。+func CheckReadonlyStatement(stmt string) error {+ if strings.TrimSpace(stmt) == "" {+ return errors.New("statement is empty")+ }+ ctx := context.Background()+ conn, err := db.Conn(ctx)+ if err != nil {+ return err+ }+ defer conn.Close()++ return conn.Raw(func(dc any) error {+ sqliteConn, ok := dc.(*sqlite3.SQLiteConn)+ if !ok {+ return fmt.Errorf("unexpected SQL driver connection type %T", dc)+ }+ ds, err := sqliteConn.Prepare(stmt)+ if err != nil {+ return err+ }+ defer ds.Close()++ sst, ok := ds.(*sqlite3.SQLiteStmt)+ if !ok {+ return fmt.Errorf("unexpected SQL driver statement type %T", ds)+ }+ if !sst.Readonly() {+ return errors.New("statement is not read-only")+ }+ return nil+ })+}diff --git a/kernel/sql/stmt_validate_test.go b/kernel/sql/stmt_validate_test.gonew file mode 100644index 0000000000..70bc3914dc--- /dev/null+++ b/kernel/sql/stmt_validate_test.go@@ -0,0 +1,65 @@+// SiYuan - Refactor your thinking+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package sql++import "testing"++func TestTailIsOnlyWhitespaceOrSQLComments(t *testing.T) {+ tests := []struct {+ s string+ want bool+ }{+ {"", true},+ {" \n\t", true},+ {"-- foo", true},+ {"-- foo\n", true},+ {"/* */", true},+ {" /* x */ \n--y", true},+ {"/* no close ", true},+ {"SELECT 1", false},+ {"-- a\nSELECT 1", false},+ {"/* */;", false},+ }+ for _, tt := range tests {+ if got := tailIsOnlyWhitespaceOrSQLComments(tt.s); got != tt.want {+ t.Errorf("tailIsOnlyWhitespaceOrSQLComments(%q) = %v, want %v", tt.s, got, tt.want)+ }+ }+}++func TestContainsMultipleStatements(t *testing.T) {+ tests := []struct {+ stmt string+ want bool+ }{+ {"SELECT 1 AS n; -- 尾部注释", false},+ {"SELECT 1 AS n; -- 注释\n", false},+ {"SELECT 1 AS n; /* 仅注释 */", false},+ {"SELECT 1 AS n; \n\t ", false},+ {"SELECT 'a''b;c' AS s", false},+ {"SELECT 1 AS `a;b`", false},+ {"SELECT 1 AS [a;b]", false},+ {"SELECT 1; SELECT 2", true},+ {"SELECT 1; -- a\nSELECT 2", true},+ {"SELECT 1;/* */;SELECT 2", true},+ }+ for _, tt := range tests {+ if got := containsMultipleStatements(tt.stmt); got != tt.want {+ t.Errorf("containsMultipleStatements(%q) = %v, want %v", tt.stmt, got, tt.want)+ }+ }+}