Elffuss BraidHub

kikocis/utopia public

2d1966ff85f5 · 7.2 KiBRawPermalink
1//! 问数查询引擎:trait 接缝(BlobStore 同手法)+ 引擎无关的安全闸。
2//!
3//! 引擎按协议族扩,不按产品名扩:postgres(本文件)→ mysql 线协议族(白捡
4//! TiDB/OceanBase/Doris/StarRocks)→ HTTP 族(ClickHouse、Trino——后者一个顶起
5//! Iceberg/Delta/Hive 整个湖仓生态)。挂载模型与注册表引擎无关,加引擎零迁移。
6//!
7//! 安全闸(纵深防御,不信任模型):
8//! 1. sqlparser 解析:仅放行单条 SELECT/WITH(含 CTE),拒绝 DML/DDL/多语句/SELECT INTO
9//! 2. 强制外包一层 LIMIT(cap+1 探测截断)
10//! 3. 会话级只读 + 语句超时(引擎各自的机制,parser 万一漏网也写不进去)
11//! 4. 结果统一为 JSON Lines(各引擎都有原生 JSON 行输出,也是模型最好消化的格式)
12
13use sqlparser::ast::Statement;
14use sqlparser::dialect::PostgreSqlDialect;
15use sqlparser::parser::Parser;
16use sqlx::postgres::PgPoolOptions;
17use sqlx::Row;
18use std::time::Duration;
19
20/// 行数上限(外包 LIMIT cap+1,第 201 行只用来判断截断)。
21pub const ROW_CAP: usize = 200;
22const STATEMENT_TIMEOUT_SECS: u32 = 10;
23
24pub struct QueryResult {
25 /// 每行一个 JSON 对象文本(键序 = 查询列序)
26 pub rows: Vec<String>,
27 pub truncated: bool,
28}
29
30#[derive(Debug)]
31pub struct SchemaColumn {
32 pub schema: String,
33 pub table: String,
34 pub column: String,
35 pub data_type: String,
36 pub comment: Option<String>,
37}
38
39#[async_trait::async_trait]
40pub trait QueryEngine: Send + Sync {
41 async fn test(&self) -> anyhow::Result<()>;
42 async fn fetch_schema(&self) -> anyhow::Result<Vec<SchemaColumn>>;
43 /// 执行已过闸的 SELECT。实现自身仍需强制只读会话与超时(纵深防御)。
44 async fn execute(&self, sql: &str) -> anyhow::Result<QueryResult>;
45}
46
47/// 引擎工厂。conn 凭据只在服务端流转。
48pub fn engine_for(engine: &str, conn: &str) -> anyhow::Result<Box<dyn QueryEngine>> {
49 match engine {
50 "postgres" => Ok(Box::new(PostgresEngine {
51 conn: conn.to_string(),
52 })),
53 other => anyhow::bail!("Unsupported engine: {other}"),
54 }
55}
56
57/// 安全闸第 1 层:解析并校验,返回规整后的语句文本。
58pub fn guard_sql(sql: &str) -> anyhow::Result<String> {
59 let cleaned = sql.trim().trim_end_matches(';').trim();
60 if cleaned.is_empty() {
61 anyhow::bail!("Empty SQL");
62 }
63 let statements = Parser::parse_sql(&PostgreSqlDialect {}, cleaned)
64 .map_err(|e| anyhow::anyhow!("SQL parse error: {e}"))?;
65 if statements.len() != 1 {
66 anyhow::bail!("Exactly one statement is allowed");
67 }
68 match &statements[0] {
69 Statement::Query(_) => Ok(cleaned.to_string()),
70 other => anyhow::bail!(
71 "Read-only: only SELECT/WITH queries are allowed (got {})",
72 statement_kind(other)
73 ),
74 }
75}
76
77fn statement_kind(s: &Statement) -> &'static str {
78 match s {
79 Statement::Insert { .. } => "INSERT",
80 Statement::Update { .. } => "UPDATE",
81 Statement::Delete { .. } => "DELETE",
82 Statement::Drop { .. } => "DROP",
83 Statement::CreateTable { .. } | Statement::CreateView { .. } => "CREATE",
84 Statement::AlterTable { .. } => "ALTER",
85 Statement::Truncate { .. } => "TRUNCATE",
86 Statement::Copy { .. } => "COPY",
87 _ => "a non-SELECT statement",
88 }
89}
90
91// ---------------------------------------------------------------------------
92// Postgres 族(顺带覆盖 Greenplum/Timescale 等 PG 兼容系)
93// ---------------------------------------------------------------------------
94
95pub struct PostgresEngine {
96 conn: String,
97}
98
99impl PostgresEngine {
100 async fn pool(&self) -> anyhow::Result<sqlx::PgPool> {
101 Ok(PgPoolOptions::new()
102 .max_connections(1)
103 .acquire_timeout(Duration::from_secs(5))
104 .connect(&self.conn)
105 .await?)
106 }
107}
108
109#[async_trait::async_trait]
110impl QueryEngine for PostgresEngine {
111 async fn test(&self) -> anyhow::Result<()> {
112 let pool = self.pool().await?;
113 sqlx::query("SELECT 1").execute(&pool).await?;
114 pool.close().await;
115 Ok(())
116 }
117
118 async fn fetch_schema(&self) -> anyhow::Result<Vec<SchemaColumn>> {
119 let pool = self.pool().await?;
120 let rows: Vec<(String, String, String, String, Option<String>)> = sqlx::query_as(
121 "SELECT c.table_schema, c.table_name, c.column_name,
122 c.data_type, pgd.description
123 FROM information_schema.columns c
124 LEFT JOIN pg_catalog.pg_statio_all_tables st
125 ON st.schemaname = c.table_schema AND st.relname = c.table_name
126 LEFT JOIN pg_catalog.pg_description pgd
127 ON pgd.objoid = st.relid AND pgd.objsubid = c.ordinal_position
128 WHERE c.table_schema NOT IN ('pg_catalog', 'information_schema')
129 ORDER BY c.table_schema, c.table_name, c.ordinal_position",
130 )
131 .fetch_all(&pool)
132 .await?;
133 pool.close().await;
134 Ok(rows
135 .into_iter()
136 .map(|(schema, table, column, data_type, comment)| SchemaColumn {
137 schema,
138 table,
139 column,
140 data_type,
141 comment,
142 })
143 .collect())
144 }
145
146 async fn execute(&self, sql: &str) -> anyhow::Result<QueryResult> {
147 let pool = self.pool().await?;
148 // 纵深防御第 3 层:会话级只读 + 超时(parser 漏网也写不进去、跑不死库)
149 sqlx::query("SET default_transaction_read_only = on")
150 .execute(&pool)
151 .await?;
152 sqlx::query(&format!(
153 "SET statement_timeout = '{STATEMENT_TIMEOUT_SECS}s'"
154 ))
155 .execute(&pool)
156 .await?;
157 // 第 2 层:外包 LIMIT;row_to_json 让 PG 全权处理类型→JSON(文本键序保留列序)
158 let wrapped = format!(
159 "SELECT row_to_json(_q)::text AS _j FROM ( {sql} ) AS _q LIMIT {}",
160 ROW_CAP + 1
161 );
162 let fetched = sqlx::query(&wrapped).fetch_all(&pool).await?;
163 pool.close().await;
164
165 let truncated = fetched.len() > ROW_CAP;
166 let rows = fetched
167 .into_iter()
168 .take(ROW_CAP)
169 .map(|r| r.try_get::<String, _>("_j").unwrap_or_else(|_| "{}".into()))
170 .collect();
171 Ok(QueryResult { rows, truncated })
172 }
173}
174
175#[cfg(test)]
176mod tests {
177 use super::guard_sql;
178
179 #[test]
180 fn allows_select_and_cte() {
181 assert!(guard_sql("SELECT region, sum(amount) FROM orders GROUP BY 1").is_ok());
182 assert!(guard_sql("WITH t AS (SELECT 1 AS x) SELECT * FROM t;").is_ok());
183 }
184
185 #[test]
186 fn rejects_writes_and_ddl() {
187 for bad in [
188 "UPDATE orders SET amount = 0",
189 "DELETE FROM orders",
190 "INSERT INTO orders (region) VALUES ('east')",
191 "DROP TABLE orders",
192 "TRUNCATE orders",
193 "CREATE TABLE t (id int)",
194 "ALTER TABLE orders ADD COLUMN x int",
195 ] {
196 assert!(guard_sql(bad).is_err(), "should reject: {bad}");
197 }
198 }
199
200 #[test]
201 fn rejects_multi_statement() {
202 assert!(guard_sql("SELECT 1; DROP TABLE orders").is_err());
203 assert!(guard_sql("").is_err());
204 }
205}