diff --git a/internal/utils/inject.go b/internal/utils/inject.go index 2e53e726..773bb13b 100644 --- a/internal/utils/inject.go +++ b/internal/utils/inject.go @@ -844,15 +844,31 @@ func InjectAndConditions(sql, filter string) string { // Check if WHERE clause exists wherePattern := regexp.MustCompile(`(?i)\bWHERE\b`) - if wherePattern.MatchString(sql) { - // Add filter and wrap existing conditions in parentheses to prevent OR precedence issues - return wherePattern.ReplaceAllString(sql, fmt.Sprintf("WHERE %s AND (", filter)) + ")" + if loc := wherePattern.FindStringIndex(sql); loc != nil { + // Add filter and wrap existing conditions in parentheses to prevent OR precedence issues. + // The wrapping must only apply to the original WHERE expression, not trailing clauses like + // ORDER BY / GROUP BY / LIMIT, otherwise it can generate invalid SQL. + whereExprStart := loc[1] + tailPattern := regexp.MustCompile(`(?i)\b(GROUP BY|ORDER BY|LIMIT|OFFSET|HAVING|FETCH)\b`) + tailLoc := tailPattern.FindStringIndex(sql[whereExprStart:]) + + if tailLoc == nil { + originalWhereExpr := strings.TrimSpace(sql[whereExprStart:]) + return fmt.Sprintf("%sWHERE %s AND (%s)", sql[:loc[0]], filter, originalWhereExpr) + } + + whereExprEnd := whereExprStart + tailLoc[0] + originalWhereExpr := strings.TrimSpace(sql[whereExprStart:whereExprEnd]) + tailClause := strings.TrimLeft(sql[whereExprEnd:], " \t\r\n") + return fmt.Sprintf("%sWHERE %s AND (%s) %s", sql[:loc[0]], filter, originalWhereExpr, tailClause) } // Add new WHERE clause before ORDER BY, GROUP BY, LIMIT, etc. clausePattern := regexp.MustCompile(`(?i)\b(GROUP BY|ORDER BY|LIMIT|OFFSET|HAVING|FETCH)\b`) if loc := clausePattern.FindStringIndex(sql); loc != nil { - return sql[:loc[0]] + fmt.Sprintf(" WHERE %s ", filter) + sql[loc[0]:] + prefix := strings.TrimRight(sql[:loc[0]], " \t\r\n") + suffix := strings.TrimLeft(sql[loc[0]:], " \t\r\n") + return fmt.Sprintf("%s WHERE %s %s", prefix, filter, suffix) } // Add WHERE clause at the end diff --git a/internal/utils/inject_test.go b/internal/utils/inject_test.go index 70f819a4..99202615 100644 --- a/internal/utils/inject_test.go +++ b/internal/utils/inject_test.go @@ -411,3 +411,40 @@ func ExampleValidateSQL() { // Error: High-risk SQL injection pattern detected // Example 3 - Valid: false, Error count: 2 } + +func TestInjectAndConditions(t *testing.T) { + tests := []struct { + name string + sql string + filter string + want string + }{ + { + name: "existing WHERE with ORDER BY", + sql: "SELECT id, title FROM knowledges WHERE parse_status = 'completed' ORDER BY created_at DESC LIMIT 10", + filter: "knowledges.tenant_id = 123", + want: "SELECT id, title FROM knowledges WHERE knowledges.tenant_id = 123 AND (parse_status = 'completed') ORDER BY created_at DESC LIMIT 10", + }, + { + name: "existing WHERE without tail clauses", + sql: "SELECT id FROM knowledges WHERE enable_status = 'enabled'", + filter: "knowledges.deleted_at IS NULL", + want: "SELECT id FROM knowledges WHERE knowledges.deleted_at IS NULL AND (enable_status = 'enabled')", + }, + { + name: "no WHERE with ORDER BY", + sql: "SELECT id FROM knowledges ORDER BY created_at DESC", + filter: "knowledges.tenant_id = 123", + want: "SELECT id FROM knowledges WHERE knowledges.tenant_id = 123 ORDER BY created_at DESC", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := InjectAndConditions(tt.sql, tt.filter) + if got != tt.want { + t.Fatalf("InjectAndConditions() = %q, want %q", got, tt.want) + } + }) + } +}