Skip to main content

rust_store_core/command/
write.rs

1//! 写路径与简单查询计划
2
3use serde_json::{json, Map, Value};
4
5use crate::computes::{apply_defaults_and_computes, FnRegistry};
6use crate::permission::{can_write_schema, evaluate, merge_owner_condition, Context, Doc};
7use crate::rbac::{
8    ensure_write, ensure_write_on_doc, filter_writable_data_overlay, merge_row_condition,
9    probe_condition_fields, WriteAction,
10};
11use crate::schema::{Registry, Schema};
12use crate::types::{
13    has_relation_predicate, is_truthy, validate_condition, validate_condition_shape,
14};
15
16use super::cmd::{cmd_count_documents, cmd_find_one, cmd_insert_one};
17use super::write_links::attach_write_links;
18use super::{ensure_context, ERR_NO_WRITE};
19
20/// 生成插入命令(对应 JS `insert`)
21///
22/// `now` 与 `new_id` 由 Host 提供(core 无时钟与随机源,且这样可让产出确定、便于对拍)。
23pub fn plan_insert(
24    schema_name: &str,
25    registry: &Registry,
26    ctx: Option<&Context>,
27    data: &Value,
28    now: i64,
29    new_id: &str,
30    fn_registry: Option<&dyn FnRegistry>,
31) -> Result<Value, String> {
32    ensure_context(registry, ctx)?;
33    let schema = registry.get(schema_name)?;
34
35    if !can_write_schema(registry.role_rules(), schema, ctx) {
36        return Err(ERR_NO_WRITE.to_string());
37    }
38    // RBAC 表级写判定(deny-wins,叠加于静态白名单之后)
39    ensure_write(registry, schema, ctx, WriteAction::Insert)?;
40
41    let doc = build_insert_doc(registry, schema, ctx, data, now, new_id)?;
42    let doc = Value::Object(doc);
43    // 触发链展开(insert 事件;text2query 档下含触发器即 Err —— A9)
44    let triggers = super::triggers::expand_triggers(registry, ctx, schema_name, "insert")?;
45    let mut plan = json!({
46        "command": cmd_insert_one(schema, &doc),
47        "returns": apply_defaults_and_computes(&doc, schema, fn_registry)?,
48    });
49    // 未配置触发器时不出现 triggers 键(A2 零回归)
50    if !triggers.is_empty() {
51        plan.as_object_mut()
52            .expect("plan_insert:plan 必为对象")
53            .insert("triggers".to_string(), json!(triggers));
54    }
55    // 写链路附接(多落点 schema 才追加 writeLinks;单落点原样返回)
56    attach_write_links(plan, registry, &[schema_name], registry.write_link_policy())
57}
58
59/// insert 文档规范化(对应 JS `insert` 主体):
60/// 权限过滤 → 保留显式 null → 自动 _id / createdBy / 时间戳
61pub(super) fn build_insert_doc(
62    registry: &Registry,
63    schema: &Schema,
64    ctx: Option<&Context>,
65    data: &Value,
66    now: i64,
67    new_id: &str,
68) -> Result<Map<String, Value>, String> {
69    let filtered = match ctx {
70        // RBAC 感知版:静态 writable ∩ RBAC writeFields(无策略时直通静态过滤)
71        Some(_) => filter_writable_data_overlay(registry, schema, ctx, data),
72        None => data.clone(),
73    };
74
75    // 保留显式 null:历史实现把 null 一律剔除(当成缺失),导致「空串/NULL/缺失」三态
76    // 无法区分(F-07),null 字段读回也被吞(H-01)。显式 `null` 应原样落库,SQL 落 NULL。
77    let mut doc: Map<String, Value> = filtered.as_object().cloned().unwrap_or_default();
78
79    // 自动生成 ID(仅在 schema 配了 idPrefix 且未提供有效 _id 时);
80    // 无 idPrefix 且无 _id → 显式报错(缺陷 D-03):静默产出「无 _id 文档」会让
81    // Host 返回 _id=undefined,且 Mongo 自动 ObjectId 会触发跨绑定序列化崩溃
82    if !doc.get("_id").map(is_truthy).unwrap_or(false) {
83        if schema.id_is_autoincrement() {
84            // 阶段2:数据库自增主键 —— doc 不注入 `_id`(SQL INSERT 列白名单来自 doc 键,
85            // 无 `_id` 列即由数据库赋值;PG/SQLite 走 RETURNING 回读、MySQL 走宿主
86            // lastrowid)。Mongo 无自增语义,由宿主 Mongo 执行器对此形态显式报错
87            // (AUTOINCREMENT_NOT_SUPPORTED),禁 ObjectId 静默顶替。
88        } else if !schema.id_prefix.is_empty() {
89            doc.insert("_id".to_string(), json!(new_id));
90        } else {
91            return Err(format!(
92                "schema \"{}\" 未配置 idPrefix 且未提供有效 _id:请显式提供 _id,或为 schema 配置 idPrefix",
93                schema.name
94            ));
95        }
96    }
97
98    // 自动设置 createdBy(creator 权限场景)
99    if has_creator_permission(schema) && !doc.get("createdBy").map(is_truthy).unwrap_or(false) {
100        if let Some(uid) = ctx.and_then(|c| c.user_id.clone()) {
101            doc.insert("createdBy".to_string(), json!(uid));
102        }
103    }
104
105    // 自动时间戳
106    if schema.timestamps {
107        if !doc.get("createdAt").map(is_truthy).unwrap_or(false) {
108            doc.insert("createdAt".to_string(), json!(now));
109        }
110        doc.insert("updatedAt".to_string(), json!(now));
111    }
112    Ok(doc)
113}
114
115/// 判断存在性(对应 JS `exists`)
116pub fn plan_exists(
117    schema_name: &str,
118    registry: &Registry,
119    condition: &Value,
120) -> Result<Value, String> {
121    // 条件拒绝名单(缺陷 D-02)
122    validate_condition(condition)?;
123    let schema = registry.get(schema_name)?;
124    // §11.4(D2):与 pipeline 读路径同码拒绝 U1~U4 形态(数组/对象/点号路径)
125    validate_condition_shape(schema, condition, registry.profile())?;
126    // §9.6 关系聚合谓词无法用标量 `findOne` 表达 → 显式 Err(否则 Mongo 静默给错结果)
127    if has_relation_predicate(schema, condition) {
128        return Err(
129            "exists 不支持关系聚合谓词条件(§9.6):标量查询无法表达关系谓词,\
130             请改用 query 并自行判断是否有结果"
131                .to_string(),
132        );
133    }
134    Ok(cmd_find_one(schema, condition, Some(&json!({ "_id": 1 }))))
135}
136
137/// 统计数量(对应 JS `count`):filter 为 nullish 时用 `{}`
138///
139/// R1:owner(read=creator) 场景下,count 必须注入 `createdBy = ctx.userId`,
140/// 否则非 admin 用户 count 会越权统计全表(E-08)。
141pub fn plan_count(
142    schema_name: &str,
143    registry: &Registry,
144    filter: Option<&Value>,
145    ctx: Option<&Context>,
146) -> Result<Value, String> {
147    if let Some(f) = filter {
148        // 条件拒绝名单(缺陷 D-02)
149        validate_condition(f)?;
150    }
151    let schema = registry.get(schema_name)?;
152    // §11.4(D2):与 pipeline 读路径同码拒绝 U1~U4 形态(数组/对象/点号路径)
153    if let Some(f) = filter {
154        validate_condition_shape(schema, f, registry.profile())?;
155        // §9.6 关系聚合谓词无法用标量 count 表达 → 显式 Err(与 query_with_count 同口径)
156        if has_relation_predicate(schema, f) {
157            return Err(
158                "count 不支持关系聚合谓词条件(§9.6):标量计数无法表达关系谓词,\
159                 请改用 query 并在调用方自行统计"
160                    .to_string(),
161            );
162        }
163    }
164    let base = match filter {
165        None | Some(Value::Null) => json!({}),
166        Some(v) => v.clone(),
167    };
168    // 静态 owner 条件叠加 RBAC 行条件(两引擎 $and,deny-wins)
169    let owner_merged = merge_owner_condition(registry.role_rules(), schema, ctx, Some(base));
170    let filter = merge_row_condition(registry, schema, ctx, "read", owner_merged)
171        .unwrap_or_else(|| json!({}));
172    Ok(cmd_count_documents(schema, &filter))
173}
174
175pub(super) fn has_creator_permission(schema: &Schema) -> bool {
176    let has = |list: &Option<Vec<String>>| {
177        list.as_ref()
178            .map(|l| l.iter().any(|r| r == "creator"))
179            .unwrap_or(false)
180    };
181    has(&schema.read) || has(&schema.write)
182}
183
184// ─── 写权限探针(对应 JS `_checkWritePerm`) ─────────────────
185
186/// creator 写权限的探针状态:
187/// `NotProbed` → 尚未探查(可能返回需要探针的命令)
188/// `NoResult` → 探针无结果(拒绝)
189/// `Found`    → 探针命中的 `{_id, createdBy}` 文档
190#[derive(Debug, Clone, Copy)]
191pub enum Probe<'a> {
192    NotProbed,
193    NoResult,
194    Found(&'a Value),
195}
196
197/// Schema 级写权限检查(对应 JS `_checkWritePerm`):
198/// 拒写清单命中直接拒绝;非写授权时仅 creator 命中才放行(需 Host 先执行探针命令)。
199///
200/// RBAC 叠加(deny-wins):
201/// - 表级:`ensure_write(action)` 在 guest 检查后判定,deny 即拒;
202/// - 行级:`row_condition` 非空(ownerOnly / condition)时**同样需要探针**——
203///   静态放行的路径也要先取 `{_id, 归属键, condition 键}` 再重入判定
204///   ([`ensure_write_on_doc`]),杜绝 ownerOnly 单条更新静默命中他人文档;
205/// - 探针重入(`Probe::Found`)时静态 `evaluate` 与 RBAC 行级判定都过才放行。
206///
207/// `extra_probe_fields`:触发器探针需额外投影的字段(`onFields` ∪ `{{before.*}}`
208/// 引用,见 `command::triggers::before_probe_fields`)。非空时即使权限本不需探针
209/// 也发探针(Host 据探针结果替换 `{{before.*}}` 并判定字段级命中);为空时行为
210/// 与无参版本**逐字节等价**(零回归契约)。
211///
212/// 返回:`Ok(None)` = 放行;`Ok(Some(cmd))` = Host 先执行该 findOne 探针后携
213/// [`Probe::Found`] / [`Probe::NoResult`] 重入;`Err` = 拒绝(Host 映射 PermissionError)。
214#[allow(clippy::too_many_arguments)]
215pub fn check_write_perm(
216    registry: &Registry,
217    schema: &Schema,
218    ctx: Option<&Context>,
219    condition: &Value,
220    deny_msg: &str,
221    probe: Probe,
222    action: WriteAction,
223    extra_probe_fields: &[String],
224) -> Result<Option<Value>, String> {
225    let probe_projection = |extra: &[String]| -> Value {
226        let mut m = Map::new();
227        m.insert("_id".to_string(), json!(1));
228        // 探针必须含归属键(schema.owner_key(),缺省 createdBy):creator 判定 /
229        // ownerOnly 行级检查都从探针文档取归属键,ownerKey='_id' 等自定义键同样命中
230        m.insert(schema.owner_key().to_string(), json!(1));
231        for f in extra {
232            // 仅取 schema 已声明字段(防触发器声明引用未声明键污染投影)
233            if schema.fields.contains_key(f) {
234                m.insert(f.clone(), json!(1));
235            }
236        }
237        Value::Object(m)
238    };
239
240    // 无 ctx(内部调用):权限不设防,但触发器探针(`before` 值供给 / onFields 命中
241    // 判定)**与权限无关**,必须发 —— 否则字段级判定退化为「全命中」,静默放大触发面
242    // (no-op 抑制失效)。投影只含 `_id` + 触发器引用字段(不带 createdBy —— 触发器探针
243    // 无 creator 判定语义,且目标 schema 未声明 createdBy 时 SQL 列不存在)。
244    // 有 ctx 时走下方权限路径:权限探针投影已并入 extra(onFields ∪ before 引用)。
245    if ctx.is_none() {
246        if !extra_probe_fields.is_empty() {
247            if let Probe::NotProbed = probe {
248                let mut m = Map::new();
249                m.insert("_id".to_string(), json!(1));
250                for f in extra_probe_fields {
251                    // 仅取 schema 已声明字段(防触发器声明引用未声明键污染投影)
252                    if schema.fields.contains_key(f) {
253                        m.insert(f.clone(), json!(1));
254                    }
255                }
256                return Ok(Some(cmd_find_one(
257                    schema,
258                    condition,
259                    Some(&Value::Object(m)),
260                )));
261            }
262        }
263        return Ok(None);
264    }
265    let Some(c) = ctx else {
266        unreachable!("上方已处理 ctx.is_none()");
267    };
268    // 拒写清单(默认空——无拒写;原 guest 硬编码随清单化移除,设计 §11.4)
269    let rules = registry.role_rules();
270    if crate::permission::has_any_role(c, &rules.deny_write_roles) {
271        return Err(deny_msg.to_string());
272    }
273    // RBAC 表级写判定(deny-wins;拒绝文案自带 RBAC 标识,不走入参 deny_msg)
274    ensure_write(registry, schema, Some(c), action)?;
275    // RBAC 行级限制是否存在(存在则探针投影需并入 condition 字段键)
276    let rbac_row_restricted =
277        crate::rbac::row_condition(registry, schema, Some(c), action.as_str()).is_some();
278
279    // 探针投影字段全集:RBAC 行级条件字段 ∪ 触发器 onFields / before 引用字段
280    let mut merged = probe_condition_fields(registry, schema, Some(c), action.as_str());
281    for f in extra_probe_fields {
282        if !merged.contains(f) {
283            merged.push(f.clone());
284        }
285    }
286
287    if can_write_schema(registry.role_rules(), schema, Some(c)) {
288        // 静态放行:RBAC 行级受限时仍需探针(否则静默放行越权行更新/删除)
289        if rbac_row_restricted && is_truthy(condition) {
290            return match probe {
291                Probe::NotProbed => Ok(Some(cmd_find_one(
292                    schema,
293                    condition,
294                    Some(&probe_projection(&merged)),
295                ))),
296                Probe::NoResult => Err(deny_msg.to_string()),
297                Probe::Found(doc) => {
298                    ensure_write_on_doc(registry, schema, Some(c), action, doc).map(|_| None)
299                }
300            };
301        }
302        // 触发器需要 before 值 / 字段级命中判定 → 权限本不需探针也发探针
303        // (静态权限已由 can_write_schema 放行;Found 重入直接放行)
304        if !extra_probe_fields.is_empty() {
305            return match probe {
306                Probe::NotProbed => Ok(Some(cmd_find_one(
307                    schema,
308                    condition,
309                    Some(&probe_projection(&merged)),
310                ))),
311                Probe::NoResult => Err(deny_msg.to_string()),
312                Probe::Found(_) => Ok(None),
313            };
314        }
315        return Ok(None);
316    }
317    let creator_only = schema
318        .write
319        .as_ref()
320        .map(|w| w.iter().any(|r| r == "creator"))
321        .unwrap_or(false);
322    if creator_only && is_truthy(condition) {
323        let needs_row_check = rbac_row_restricted;
324        return match probe {
325            Probe::NotProbed => Ok(Some(cmd_find_one(
326                schema,
327                condition,
328                Some(&probe_projection(&merged)),
329            ))),
330            Probe::NoResult => Err(deny_msg.to_string()),
331            Probe::Found(doc) => {
332                if evaluate(
333                    registry.role_rules(),
334                    Some(c),
335                    schema.write.as_deref(),
336                    Doc::Doc(doc),
337                    schema.owner_key(),
338                ) {
339                    if needs_row_check {
340                        // 静态 creator 过 → RBAC 行级再判(两引擎都过才放行)
341                        ensure_write_on_doc(registry, schema, Some(c), action, doc).map(|_| None)
342                    } else {
343                        Ok(None)
344                    }
345                } else {
346                    Err(deny_msg.to_string())
347                }
348            }
349        };
350    }
351    Err(deny_msg.to_string())
352}