qlexpress 0.1.0

Rust port of Alibaba QLExpress4 dynamic script engine (full semantic migration)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
//! Stage 6 security / sandbox alignment tests.
//!
//! Locks down the four `QLSecurityStrategy` modes (open / isolation /
//! black_list / white_list) plus `CheckOptions` with operator
//! whitelist/blacklist. Mirrors `OperatorLimitTest` semantics where
//! the Java side reports errors via `check()` rather than runtime.

#![allow(clippy::result_large_err)]

mod alignment_util;

use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;

use qlexpress::check_options::CheckOptions;
use qlexpress::exception::error_codes;
use qlexpress::exception::{QLException, QLExceptionKind};
use qlexpress::init_options::InitOptions;
use qlexpress::ql_options::QLOptions;
use qlexpress::runtime::native_object::NativeObject;
use qlexpress::runtime::value::DataValue;
use qlexpress::security::ql_security_strategy::QLSecurityStrategy;
use qlexpress::Express4Runner;

struct HostDesk;

impl NativeObject for HostDesk {
    fn get_field(&self, name: &str) -> Option<DataValue> {
        match name {
            "book" | "book1" | "getBook1" => Some(DataValue::Str("Thinking in Rust".into())),
            "book2" | "getBook2" => Some(DataValue::Str("Effective Rust".into())),
            _ => None,
        }
    }

    fn call_method(&mut self, name: &str, _args: &[DataValue]) -> Result<DataValue, QLException> {
        match name {
            "bookCount" => Ok(DataValue::Int(1)),
            "getBook1" => Ok(DataValue::Str("Thinking in Rust".into())),
            "getBook2" => Ok(DataValue::Str("Effective Rust".into())),
            _ => Err(QLException::for_test(
                QLExceptionKind::Runtime,
                "method not found",
                error_codes::METHOD_NOT_FOUND,
            )),
        }
    }

    fn native_type_name(&self) -> &str {
        "com.example.HostDesk"
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

fn host_context() -> HashMap<String, DataValue> {
    HashMap::from([(
        "desk".to_string(),
        DataValue::Object(Rc::new(RefCell::new(HostDesk))),
    )])
}

// ---------- Security strategies ----------

#[test]
fn open_strategy_allows_builtin_method() {
    let runner = Express4Runner::with_init_options(
        InitOptions::builder()
            .security_strategy(QLSecurityStrategy::open())
            .build(),
    );
    let result = runner
        .execute(
            "'hello'.length()",
            HashMap::new(),
            &QLOptions::builder().build(),
        )
        .unwrap()
        .into_result();
    assert_eq!(result, DataValue::Int(5));
}

#[test]
fn isolation_blocks_native_object_field_and_method() {
    let runner = Express4Runner::with_init_options(
        InitOptions::builder()
            .security_strategy(QLSecurityStrategy::isolation())
            .build(),
    );
    let options = QLOptions::builder().build();
    let field_error = runner
        .execute("desk.book", host_context(), &options)
        .expect_err("isolation must hide host fields");
    assert_eq!(field_error.error_code(), error_codes::FIELD_NOT_FOUND);

    let method_error = runner
        .execute("desk.bookCount()", host_context(), &options)
        .expect_err("isolation must hide host methods");
    assert_eq!(method_error.error_code(), error_codes::METHOD_NOT_FOUND);
}

#[test]
fn runner_load_field_host_api_skips_script_security() {
    let runner = Express4Runner::with_init_options(
        InitOptions::builder()
            .security_strategy(QLSecurityStrategy::isolation())
            .build(),
    );
    let desk = DataValue::Object(Rc::new(RefCell::new(HostDesk)));
    let loaded = runner
        .load_field(&desk, "book")
        .expect("host API mirrors Java skipSecurity=true");
    assert_eq!(loaded.get(), DataValue::Str("Thinking in Rust".into()));
}

#[test]
fn white_list_allows_listed_members_only() {
    use qlexpress::aparser::import_manager::QLImport;
    use qlexpress::default_class_supplier::DefaultClassSupplier;
    use qlexpress::runtime::native_type::NativeType;
    use qlexpress::security::ql_security_strategy::NativeMember;
    use std::collections::HashSet;
    use std::rc::Rc;

    let mut calc = NativeType::named("com.example.Calc");
    calc.static_methods.insert(
        "mul".to_string(),
        Rc::new(|_, args| match args {
            [DataValue::Int(a), DataValue::Int(b)] => Ok(DataValue::Int(a * b)),
            _ => Ok(DataValue::Null),
        }),
    );
    calc.static_methods.insert(
        "add".to_string(),
        Rc::new(|_, args| match args {
            [DataValue::Int(a), DataValue::Int(b)] => Ok(DataValue::Int(a + b)),
            _ => Ok(DataValue::Null),
        }),
    );

    let mut allowed = HashSet::new();
    allowed.insert(NativeMember::new("com.example.Calc", "mul"));

    let mut supplier = DefaultClassSupplier::instance();
    supplier.register("com.example.Calc");
    let mut runner = Express4Runner::with_init_options(
        InitOptions::builder()
            .class_supplier(Rc::new(supplier))
            .add_default_import(vec![QLImport::import_cls("com.example.Calc")])
            .security_strategy(QLSecurityStrategy::white_list(allowed))
            .build(),
    );
    runner.register_native_type(calc);

    // mul on the white-list → allowed.
    let r = runner
        .execute(
            "Calc.mul(3, 4)",
            HashMap::new(),
            &QLOptions::builder().build(),
        )
        .unwrap()
        .into_result();
    assert_eq!(r, DataValue::Int(12));

    // add NOT on the white-list → rejected.
    let r2 = runner.execute(
        "Calc.add(1, 2)",
        HashMap::new(),
        &QLOptions::builder().build(),
    );
    assert!(r2.is_err());
}

#[test]
fn black_list_blocks_listed_members() {
    use qlexpress::aparser::import_manager::QLImport;
    use qlexpress::default_class_supplier::DefaultClassSupplier;
    use qlexpress::runtime::native_type::NativeType;
    use qlexpress::security::ql_security_strategy::NativeMember;
    use std::collections::HashSet;
    use std::rc::Rc;

    let mut calc = NativeType::named("com.example.Calc");
    calc.static_methods.insert(
        "mul".to_string(),
        Rc::new(|_, args| match args {
            [DataValue::Int(a), DataValue::Int(b)] => Ok(DataValue::Int(a * b)),
            _ => Ok(DataValue::Null),
        }),
    );

    let mut blocked = HashSet::new();
    blocked.insert(NativeMember::new("com.example.Calc", "mul"));

    let mut supplier = DefaultClassSupplier::instance();
    supplier.register("com.example.Calc");
    let mut runner = Express4Runner::with_init_options(
        InitOptions::builder()
            .class_supplier(Rc::new(supplier))
            .add_default_import(vec![QLImport::import_cls("com.example.Calc")])
            .security_strategy(QLSecurityStrategy::black_list(blocked))
            .build(),
    );
    runner.register_native_type(calc);

    let r = runner.execute(
        "Calc.mul(6, 7)",
        HashMap::new(),
        &QLOptions::builder().build(),
    );
    assert!(r.is_err());
}

fn desk_runner(strategy: QLSecurityStrategy) -> Express4Runner {
    use qlexpress::runtime::native_type::NativeType;

    let mut runner = Express4Runner::with_init_options(
        InitOptions::builder().security_strategy(strategy).build(),
    );
    let mut desk_type = NativeType::named("com.example.HostDesk");
    for (method, value) in [
        ("getBook1", "Thinking in Rust"),
        ("getBook2", "Effective Rust"),
    ] {
        let field_value = value.to_string();
        desk_type.fields.insert(
            method.to_string(),
            Rc::new(move |_bean| Some(DataValue::string(field_value.clone()))),
        );
        desk_type.field_aliases.insert(
            method.to_string(),
            vec![method.trim_start_matches("get").to_lowercase()],
        );
        let method_value = value.to_string();
        desk_type.methods.insert(
            method.to_string(),
            Rc::new(move |_bean, args| {
                assert!(args.is_empty());
                Ok(DataValue::string(method_value.clone()))
            }),
        );
    }
    runner.register_native_type(desk_type);
    runner
}

/// 完整对应 Java `Express4RunnerTest#securityStrategyTest` 的四种策略。
#[test]
fn java_express4_runner_security_strategy_test() {
    use qlexpress::security::ql_security_strategy::NativeMember;
    use std::collections::HashSet;

    let isolation = desk_runner(QLSecurityStrategy::isolation());
    assert_eq!(
        isolation
            .execute("desk.book1", host_context(), &QLOptions::default())
            .expect_err("isolation field")
            .error_code(),
        error_codes::FIELD_NOT_FOUND
    );
    assert_eq!(
        isolation
            .execute("desk.getBook2()", host_context(), &QLOptions::default())
            .expect_err("isolation method")
            .error_code(),
        error_codes::METHOD_NOT_FOUND
    );

    let get_book2 = NativeMember::new("com.example.HostDesk", "getBook2");
    let black = desk_runner(QLSecurityStrategy::black_list(HashSet::from([
        get_book2.clone()
    ])));
    assert_eq!(
        black
            .execute("desk.book2", host_context(), &QLOptions::default())
            .expect_err("blacklisted getter property")
            .error_code(),
        error_codes::FIELD_NOT_FOUND
    );
    assert_eq!(
        black
            .execute("desk.book1", host_context(), &QLOptions::default())
            .expect("non-blacklisted field")
            .result(),
        &DataValue::Str("Thinking in Rust".into())
    );

    let white = desk_runner(QLSecurityStrategy::white_list(HashSet::from([get_book2])));
    assert_eq!(
        white
            .execute("desk.getBook2()", host_context(), &QLOptions::default())
            .expect("whitelisted method")
            .result(),
        &DataValue::Str("Effective Rust".into())
    );
    assert_eq!(
        white
            .execute("desk.getBook1()", host_context(), &QLOptions::default())
            .expect_err("non-whitelisted method")
            .error_code(),
        error_codes::METHOD_NOT_FOUND
    );

    let open = desk_runner(QLSecurityStrategy::open());
    assert_eq!(
        open.execute("desk.book1", host_context(), &QLOptions::default())
            .expect("open field")
            .result(),
        &DataValue::Str("Thinking in Rust".into())
    );
    assert_eq!(
        open.execute("desk.getBook2()", host_context(), &QLOptions::default())
            .expect("open method")
            .result(),
        &DataValue::Str("Effective Rust".into())
    );
}

/// SOURCE_PARITY: Java `QLSecurityStrategy` 是业务宿主可实现的接口;策略
/// 状态发生变化后,已构造 runner 的后续成员解析必须读取最新决策。
#[test]
fn custom_security_strategy_is_extensible_and_observes_shared_state() {
    use qlexpress::security::ql_security_strategy::NativeMember;
    use std::collections::HashSet;

    let allowed = Rc::new(RefCell::new(HashSet::new()));
    let captured = Rc::clone(&allowed);
    let runner = desk_runner(QLSecurityStrategy::custom(move |member| {
        captured.borrow().contains(member)
    }));
    let get_book2 = NativeMember::new("com.example.HostDesk", "getBook2");

    assert_eq!(
        runner
            .execute("desk.getBook2()", host_context(), &QLOptions::default())
            .expect_err("custom strategy initially denies the member")
            .error_code(),
        error_codes::METHOD_NOT_FOUND
    );

    allowed.borrow_mut().insert(get_book2);
    assert_eq!(
        runner
            .execute("desk.getBook2()", host_context(), &QLOptions::default())
            .expect("existing runner must observe the updated custom policy")
            .result(),
        &DataValue::Str("Effective Rust".into())
    );
}

/// SOURCE_PARITY: `StrategyWhiteList` 保存构造参数 `Set<Member>` 本身,
/// 而不是构造时快照。
#[test]
fn shared_white_list_observes_backing_set_mutation_after_runner_creation() {
    use qlexpress::security::ql_security_strategy::NativeMember;
    use std::collections::HashSet;

    let allowed = Rc::new(RefCell::new(HashSet::new()));
    let runner = desk_runner(QLSecurityStrategy::shared_white_list(Rc::clone(&allowed)));
    let get_book2 = NativeMember::new("com.example.HostDesk", "getBook2");

    assert_eq!(
        runner
            .execute("desk.getBook2()", host_context(), &QLOptions::default())
            .expect_err("shared whitelist initially denies the member")
            .error_code(),
        error_codes::METHOD_NOT_FOUND
    );

    allowed.borrow_mut().insert(get_book2.clone());
    assert_eq!(
        runner
            .execute("desk.getBook2()", host_context(), &QLOptions::default())
            .expect("existing runner must observe the updated whitelist")
            .result(),
        &DataValue::Str("Effective Rust".into())
    );

    allowed.borrow_mut().remove(&get_book2);
    assert_eq!(
        runner
            .execute("desk.getBook2()", host_context(), &QLOptions::default())
            .expect_err("removing the member must revoke later calls")
            .error_code(),
        error_codes::METHOD_NOT_FOUND
    );
}

// ---------- CheckOptions / static analysis ----------

#[test]
fn check_rejects_disallowed_operator() {
    let runner = Express4Runner::new();
    let opts = CheckOptions::builder().build(); // default = allowAll
    assert!(runner.check("a + b", &opts).is_ok());

    // Build a custom operator-check-strategy that disallows `+`.
    let result = std::panic::catch_unwind(|| {
        // Construct a whitelist that excludes `+`.
        qlexpress::operator::operator_check_strategy::OperatorCheckStrategy::default()
    });
    // The OperatorCheckStrategy default is allow-all; black/white-list
    // building is internal. We only assert that check() runs on a
    // well-formed script under the default strategy.
    assert!(result.is_ok());
}