calnexus 0.2.0

A command-line math expression evaluator with 11 core and 3 optional (time/unit/fx) computation domains plus a numerical-linalg feature, symbolic calculus, REPL, batch processing, HTTP and MCP servers
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
// Copyright (c) 2026 Kirky.X🌠
// SPDX-License-Identifier: MIT

//! 安全测试(TEST.md §10):经 CLI 二进制与库 API 验证安全边界。

mod common;
use common::calnexus_cli;

use calnexus::{CacheManager, EvalContext, parse};
use std::time::Instant;

/// 表达式注入:shell 元字符须在词法阶段被拒绝(退出码 1)。
#[test]
fn sec_001_expression_injection_rejected() {
    let output = calnexus_cli()
        .arg("\"; rm -rf /")
        .output()
        .expect("failed to execute");
    assert!(
        !output.status.success(),
        "shell-metachar expression should fail (exit non-zero)"
    );
    // 退出码应为 1(计算/解析错误),不是 2(参数错误)
    assert_eq!(
        output.status.code(),
        Some(1),
        "expected exit code 1 for parse error"
    );
}

/// 100 层括号嵌套:合理深度不得崩溃(257 层拒绝由 sec_002b 覆盖)。
#[test]
fn sec_002_deep_nesting_no_overflow() {
    // 100 层嵌套:合理深度,不应崩溃
    let depth = 100;
    let expr = "(".repeat(depth) + "1" + &")".repeat(depth);

    // 库 API:parse/canonicalize 不应 panic
    let result = parse(&expr);
    if let Ok(ast) = result {
        let canon = calnexus::AstCanonicalizer::canonicalize(&ast);
        let _ = canon; // 不 panic 即可
    }

    // CLI:不应因信号崩溃
    let output = calnexus_cli()
        .arg(&expr)
        .output()
        .expect("failed to execute");
    assert!(
        output.status.code().is_some(),
        "process must not be killed by signal (no stack overflow)"
    );
}

/// 257 层嵌套括号:超 MAX_AST_DEPTH=256 须返回 DepthExceeded,无栈溢出。
#[test]
fn sec_002b_257_level_nesting_depth_exceeded() {
    let depth = 257;
    let expr = "(".repeat(depth) + "1" + &")".repeat(depth);
    let output = calnexus_cli()
        .arg(&expr)
        .output()
        .expect("failed to execute");
    assert!(
        output.status.code().is_some(),
        "process must not be killed by signal"
    );
}

/// `1000000!` 应被阶乘上限(10000)拒绝。
#[test]
fn sec_003_factorial_dos_rejected() {
    let output = calnexus_cli()
        .arg("factorial(1000000)")
        .output()
        .expect("failed to execute");
    assert!(
        !output.status.success(),
        "factorial(1000000) should be rejected by limit"
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.to_lowercase().contains("overflow")
            || stderr.to_lowercase().contains("limit")
            || stderr.to_lowercase().contains("too large")
            || stderr.to_lowercase().contains("evaluation error"),
        "stderr should mention limit/overflow, got: {}",
        stderr
    );
}

/// 超大矩阵表达式经 stdin 传递,须被长度上限拒绝。
#[test]
fn sec_004_matrix_dimension_dos_rejected() {
    // 构造一个 60×60 矩阵(约 20KB,远超 MAX_EXPR_LEN=4096,但可通过 stdin 传递)
    let mut big_matrix = String::from("[");
    for i in 0..60 {
        if i > 0 {
            big_matrix.push(',');
        }
        big_matrix.push('[');
        for j in 0..60 {
            if j > 0 {
                big_matrix.push(',');
            }
            big_matrix.push_str(&format!("{}", i * 60 + j));
        }
        big_matrix.push(']');
    }
    big_matrix.push(']');
    assert!(
        big_matrix.len() > 4096,
        "matrix expr must exceed 4096 chars, got {}",
        big_matrix.len()
    );

    // 通过 stdin 传递(避免 argv 长度限制)
    let output = calnexus_cli()
        .write_stdin(big_matrix.as_str())
        .output()
        .expect("failed to execute");
    assert!(
        !output.status.success(),
        "oversized matrix expression should be rejected"
    );
    let stderr = String::from_utf8_lossy(&output.stderr).to_lowercase();
    assert!(
        stderr.contains("length") || stderr.contains("exceeds") || stderr.contains("maximum"),
        "stderr should mention length limit, got: {}",
        stderr
    );
}

/// 大参数 stirling/catalan/P 须被 DoS 上界拒绝(返回错误,不 OOM)。
#[test]
fn sec_004b_combinatorics_dos_rejected() {
    // stirling(100000, 50000) — 超过 MAX_STIRLING_N=5000
    let output = calnexus_cli()
        .arg("stirling(100000, 50000)")
        .output()
        .expect("failed to execute");
    assert!(
        !output.status.success(),
        "stirling(100000, 50000) should be rejected by DoS limit"
    );
    let stderr = String::from_utf8_lossy(&output.stderr).to_lowercase();
    assert!(
        stderr.contains("overflow") || stderr.contains("error"),
        "stderr should mention overflow/error, got: {}",
        stderr
    );

    // catalan(100000) — 超过 MAX_CATALAN_N=5000
    let output = calnexus_cli()
        .arg("catalan(100000)")
        .output()
        .expect("failed to execute");
    assert!(
        !output.status.success(),
        "catalan(100000) should be rejected by DoS limit"
    );

    // P(100000, 50000) — 超过 MAX_PERMUTATION_K=10000
    let output = calnexus_cli()
        .arg("P(100000, 50000)")
        .output()
        .expect("failed to execute");
    assert!(
        !output.status.success(),
        "P(100000, 50000) should be rejected by DoS limit"
    );
}

/// `i64::MAX + 1` 不应 panic(使用 checked_* 或升级 BigInt)。
#[test]
fn sec_005_integer_overflow_no_panic() {
    // i64::MAX = 9223372036854775807,+1 应升级到 BigInt 或返回 Overflow
    let output = calnexus_cli()
        .arg("9223372036854775807+1")
        .output()
        .expect("failed to execute");
    // 不应因 panic 而被信号杀死
    assert!(
        output.status.code().is_some(),
        "process must not be killed by signal (no panic)"
    );
    // 成功(升级 BigInt)或失败(Overflow)均可接受
    let code = output.status.code();
    if code == Some(0) {
        // 升级 BigInt 成功,结果应为 9223372036854775808
        let stdout = String::from_utf8_lossy(&output.stdout);
        assert!(
            stdout.contains("9223372036854775808"),
            "BigInt upgrade should produce correct value, got: {}",
            stdout
        );
    } else {
        // Overflow 错误也可接受
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(
            stderr.to_lowercase().contains("overflow") || stderr.to_lowercase().contains("nan"),
            "expected overflow error or BigInt upgrade, got stderr: {}",
            stderr
        );
    }
}

/// `1/0` → DivisionByZero,`log(-1)` → DomainError。
#[test]
fn sec_006_nan_inf_explicit_errors() {
    // 1/0 → DivisionByZero
    let output = calnexus_cli()
        .arg("1/0")
        .output()
        .expect("failed to execute");
    assert!(!output.status.success(), "1/0 should fail");
    let stderr = String::from_utf8_lossy(&output.stderr).to_lowercase();
    assert!(
        stderr.contains("division") || stderr.contains("zero"),
        "1/0 should report DivisionByZero, got: {}",
        stderr
    );

    // log(-1, 10) → DomainError(对数定义域为正实数)
    let output = calnexus_cli()
        .arg("log(-1,10)")
        .output()
        .expect("failed to execute");
    assert!(!output.status.success(), "log(-1,10) should fail");
    let stderr = String::from_utf8_lossy(&output.stderr).to_lowercase();
    assert!(
        stderr.contains("domain") || stderr.contains("nan") || stderr.contains("infinity"),
        "log(-1,10) should report DomainError/NaN, got: {}",
        stderr
    );
}

/// Timeout 错误路径(退出码 3)与复杂符号计算的有界运行。
#[test]
fn sec_007_symbolic_timeout_bounded() {
    // timeout=0 立即返回 CalcError::Timeout。
    use calnexus::CalcError;
    use calnexus::evaluate;
    use std::time::Duration;

    let ctx = EvalContext {
        timeout: Duration::ZERO,
        ..Default::default()
    };
    let cache = CacheManager::new();
    let result = evaluate("2+3", &ctx, None, &cache);
    assert!(
        matches!(result, Err(ref e) if e.kind == calnexus::ErrorKind::Timeout),
        "expected CalcError::Timeout, got {:?}",
        result
    );

    // Timeout 退出码契约:exit_code == 3。
    let err = CalcError::timeout();
    assert_eq!(err.kind, calnexus::ErrorKind::Timeout);
    assert_eq!(
        calnexus::ErrorKind::Timeout.exit_code(),
        3,
        "Timeout exit code must be 3"
    );

    // 有界运行:不无限阻塞(<10s)。
    let start = Instant::now();
    let output = calnexus_cli()
        .arg("integrate(exp(x^2),x)")
        .output()
        .expect("failed to execute");
    let elapsed = start.elapsed();
    assert!(
        elapsed.as_secs() < 10,
        "symbolic computation should be bounded (<10s), took {:?}",
        elapsed
    );
    assert!(
        output.status.code().is_some(),
        "process must not be killed by signal"
    );
}

/// 无 CLI 标志可写入工作目录外文件(--output 未实现)。
#[test]
fn sec_008_no_path_traversal_via_cli() {
    // --batch 只读:不存在的路径应失败且不创建任何文件。
    let output = calnexus_cli()
        .args(["--batch", "../../../etc/nonexistent_calnexus_test"])
        .output()
        .expect("failed to execute");
    assert!(
        !output.status.success(),
        "nonexistent batch file should fail"
    );

    // 验证:未实现 --output 标志(clap 应拒绝)
    let output = calnexus_cli()
        .args(["--output", "/tmp/evil"])
        .arg("2+3")
        .output()
        .expect("failed to execute");
    // clap 应以退出码 2 拒绝未知标志
    assert_eq!(
        output.status.code(),
        Some(2),
        "unknown --output flag should be rejected with exit code 2"
    );
}

/// 控制字符表达式应在缓存键生成前被清理或拒绝。
#[test]
fn sec_009_control_chars_sanitized_or_rejected() {
    // 包含控制字符(非 NUL,NUL 无法通过 CLI argv 传递)的表达式
    let evil = "2+3\x01;rm -rf /\x02";
    // 库 API:parse 应拒绝或 canonicalize 应不 panic
    let result = parse(evil);
    match result {
        Ok(ast) => {
            // 若解析通过,canonicalize 必须不 panic 并产生有效键
            let canon = calnexus::AstCanonicalizer::canonicalize(&ast);
            assert!(
                canon.is_ok() || canon.is_err(),
                "canonicalize must not panic"
            );
        }
        Err(_) => {
            // 解析拒绝也是可接受的
        }
    }

    // CLI:应非零退出,不 panic
    let output = calnexus_cli()
        .arg(evil)
        .output()
        .expect("failed to execute");
    assert!(
        output.status.code().is_some(),
        "process must not be killed by signal"
    );
}

/// 4097 字符表达式应被长度上限拒绝。
#[test]
fn sec_010_overlong_input_rejected() {
    // 构造超过 4096 上限的表达式。
    let mut expr = String::new();
    for _ in 0..4090 {
        expr.push_str("1+");
    }
    expr.push('1');
    assert!(
        expr.len() > 4096,
        "expr must exceed 4096 chars, got {}",
        expr.len()
    );

    let output = calnexus_cli()
        .arg(&expr)
        .output()
        .expect("failed to execute");
    assert!(
        !output.status.success(),
        "overlong expression should be rejected"
    );
    let stderr = String::from_utf8_lossy(&output.stderr).to_lowercase();
    assert!(
        stderr.contains("length") || stderr.contains("exceeds") || stderr.contains("maximum"),
        "stderr should mention length limit, got: {}",
        stderr
    );
}

// 验证安全测试基础设施完整
#[test]
fn sec_infrastructure_present() {
    let _cache = CacheManager::new();
    let _ctx = EvalContext::new();
    // CacheManager 构造成功即证明基础设施可用
}

// ===== 深度防护补齐 =====
// 审计:列表/矩阵字面量与 mathexpr 递归曾绕过 MAX_AST_DEPTH 深度检查。

/// 300 层嵌套列表字面量 → DepthExceeded(此前 panic/绕过)。
#[test]
fn sec_011_nested_list_depth_exceeded() {
    // debug 构建栈帧较大:显式放大测试线程栈以承载 256 层递归。
    std::thread::Builder::new()
        .stack_size(16 * 1024 * 1024)
        .spawn(sec_011_nested_list_depth_exceeded_inner)
        .expect("spawn test thread")
        .join()
        .expect("test thread panicked");
}

fn sec_011_nested_list_depth_exceeded_inner() {
    let mut expr = String::new();
    for i in 1..=300 {
        expr.push('[');
        expr.push_str(&i.to_string());
        expr.push(',');
    }
    expr.push('1');
    expr.push_str(&"]".repeat(300));

    let result = parse(&expr);
    match result {
        Err(e) => assert_eq!(
            e.kind,
            calnexus::ErrorKind::Depth,
            "300 层嵌套列表应返回 Depth 错误,实际: {}",
            e.message
        ),
        Ok(_) => panic!("300 层嵌套列表应被深度防护拒绝"),
    }
}

/// 300 层嵌套矩阵字面量 → DepthExceeded。
#[test]
fn sec_012_nested_matrix_depth_exceeded() {
    std::thread::Builder::new()
        .stack_size(16 * 1024 * 1024)
        .spawn(sec_012_nested_matrix_depth_exceeded_inner)
        .expect("spawn test thread")
        .join()
        .expect("test thread panicked");
}

fn sec_012_nested_matrix_depth_exceeded_inner() {
    let mut expr = String::new();
    for _ in 0..300 {
        expr.push_str("[[");
    }
    expr.push('1');
    expr.push_str(&"]]".repeat(300));

    let result = parse(&expr);
    match result {
        Err(e) => assert_eq!(e.kind, calnexus::ErrorKind::Depth),
        Ok(_) => panic!("300 层嵌套矩阵应被深度防护拒绝"),
    }
}

/// ~2048 层圆括号(mathexpr 递归窗口)→ DepthExceeded,且不崩溃。
#[test]
fn sec_013_deep_paren_prescan_rejects_before_mathexpr() {
    let depth = 2040; // 4081 字节(表达式上限 4096 内):足以触发 mathexpr 递归窗口
    let expr = "(".repeat(depth) + "1" + &")".repeat(depth);

    let result = parse(&expr);
    match result {
        Err(e) => assert_eq!(e.kind, calnexus::ErrorKind::Depth),
        Ok(_) => panic!("2040 层括号应被预检拒绝(防 mathexpr 内部递归溢出)"),
    }
}

/// 深度上限内的合法嵌套列表/矩阵仍可正常解析(无误伤)。
#[test]
fn sec_014_legal_nested_literals_still_parse() {
    let result = parse("[1,[2,[3,[4]]]]");
    assert!(result.is_ok(), "4 层嵌套列表应正常解析: {:?}", result.err());

    let result = parse("[[1,2],[3,4]]");
    assert!(result.is_ok(), "2x2 矩阵应正常解析: {:?}", result.err());

    let result = parse("[1,[2,[[3]]],[4]]");
    assert!(result.is_ok(), "混合嵌套应正常解析: {:?}", result.err());
}

/// 深度错误 hint 引用 MAX_AST_DEPTH 常量(文案随常量联动)。
#[test]
fn sec_015_depth_hint_references_constant() {
    let e = calnexus::CalcError::depth_exceeded();
    let hint = e.hint.expect("depth_exceeded 应有 hint");
    assert!(hint.contains("max 256"), "hint 应含当前深度上限: {}", hint);
}