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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
use crate::impl_rule;
use crate::rules::common::{make_finding, walk_tree};
use crate::{Language, Severity};
use regex::Regex;
/// Returns `true` if a tree-sitter `string` node contains interpolation
/// children (i.e., `#{}` segments). Plain string literals like `"ls -la"`
/// return `false`; strings like `"#{cmd}"` return `true`.
fn has_interpolation(string_node: tree_sitter::Node) -> bool {
let mut cursor = string_node.walk();
for child in string_node.children(&mut cursor) {
// tree-sitter-ruby uses "interpolation" for `#{}` segments
if child.kind() == "interpolation" {
return true;
}
}
false
}
// ─── Rule 1: no-eval ──────────────────────────────────────────────────────────
pub struct NoEval;
impl_rule! {
NoEval,
id = "rb/no-eval",
severity = Severity::Critical,
cwe = Some("CWE-95"),
description = "Use of eval or similar dynamic code execution",
language = Language::Ruby,
fn check(_self, source, tree) {
let mut findings = Vec::new();
walk_tree(tree.root_node(), source, &mut |node, src| {
let method_name = match node.kind() {
"call" => node
.child_by_field_name("method")
.map(|m| &src[m.byte_range()]),
"command" => node
.child_by_field_name("name")
.map(|m| &src[m.byte_range()]),
_ => None,
};
if let Some(name) = method_name {
// Only flag eval and instance_eval — class_eval/module_eval are
// standard Ruby metaprogramming patterns used by every framework
if name == "eval" || name == "instance_eval" {
findings.push(make_finding(
_self.id(),
_self.severity(),
_self.cwe(),
&format!(
"{} executes arbitrary code — avoid dynamic evaluation",
name
),
node,
src,
));
}
}
});
findings
}
}
// ─── Rule 2: no-command-injection ─────────────────────────────────────────────
pub struct NoCommandInjection;
impl_rule! {
NoCommandInjection,
id = "rb/no-command-injection",
severity = Severity::Critical,
cwe = Some("CWE-78"),
description = "Potential command injection via system/exec/spawn or backtick execution",
language = Language::Ruby,
fn check(_self, source, tree) {
let mut findings = Vec::new();
walk_tree(tree.root_node(), source, &mut |node, src| {
// Detect backtick/subshell execution
if node.kind() == "subshell" {
findings.push(make_finding(
_self.id(),
_self.severity(),
_self.cwe(),
"Backtick/subshell command execution — risk of command injection",
node,
src,
));
return;
}
let method_name = match node.kind() {
"call" => node
.child_by_field_name("method")
.map(|m| &src[m.byte_range()]),
"command" => node
.child_by_field_name("name")
.map(|m| &src[m.byte_range()]),
_ => None,
};
if let Some(name) = method_name {
if name == "system" || name == "exec" || name == "spawn" {
// Check if the first argument is a plain string literal
// (no interpolation). If so, skip — it's safe.
let first_arg = node
.child_by_field_name("arguments")
.and_then(|a| a.named_child(0))
.or_else(|| {
// For command-style calls like `system "ls"`,
// args are in an argument_list child.
node.named_child(1).and_then(|c| {
if c.kind() == "argument_list" {
c.named_child(0)
} else {
Some(c)
}
})
});
let is_safe_literal = first_arg.is_some_and(|arg| {
// A `string` node without any `string_content` siblings
// that are interpolation is a plain literal.
arg.kind() == "string" && !has_interpolation(arg)
});
if !is_safe_literal {
findings.push(make_finding(
_self.id(),
_self.severity(),
_self.cwe(),
&format!(
"{} called — risk of command injection with dynamic arguments",
name
),
node,
src,
));
}
}
}
// Detect %x strings (parsed as subshell or string node with %x prefix)
if node.kind() == "string" {
let text = &src[node.byte_range()];
if text.starts_with("%x") {
findings.push(make_finding(
_self.id(),
_self.severity(),
_self.cwe(),
"%x command execution — risk of command injection",
node,
src,
));
}
}
});
findings
}
}
// ─── Rule 3: no-sql-injection ─────────────────────────────────────────────────
pub struct NoSqlInjection;
impl_rule! {
NoSqlInjection,
id = "rb/no-sql-injection",
severity = Severity::Critical,
cwe = Some("CWE-89"),
description = "Potential SQL injection via string interpolation in query methods",
language = Language::Ruby,
fn check(_self, source, tree) {
let mut findings = Vec::new();
walk_tree(tree.root_node(), source, &mut |node, src| {
let method_name = match node.kind() {
"call" => node
.child_by_field_name("method")
.map(|m| &src[m.byte_range()]),
"command" => node
.child_by_field_name("name")
.map(|m| &src[m.byte_range()]),
_ => None,
};
if let Some(name) = method_name {
if name == "where" || name == "find_by_sql" || name == "execute" {
// Check if any argument contains string interpolation
let node_text = &src[node.byte_range()];
if node_text.contains("#{") {
findings.push(make_finding(
_self.id(),
_self.severity(),
_self.cwe(),
&format!(
"String interpolation in {} — use parameterized queries to prevent SQL injection",
name
),
node,
src,
));
}
}
}
});
findings
}
}
// ─── Rule 4: no-mass-assignment ───────────────────────────────────────────────
pub struct NoMassAssignment;
impl_rule! {
NoMassAssignment,
id = "rb/no-mass-assignment",
severity = Severity::High,
cwe = Some("CWE-915"),
description = "Mass assignment via permit! allows all parameters",
language = Language::Ruby,
fn check(_self, source, tree) {
let mut findings = Vec::new();
walk_tree(tree.root_node(), source, &mut |node, src| {
if node.kind() == "call" {
if let Some(method) = node.child_by_field_name("method") {
let name = &src[method.byte_range()];
if name == "permit!" {
findings.push(make_finding(
_self.id(),
_self.severity(),
_self.cwe(),
"permit! allows all parameters — use permit(:field1, :field2) to whitelist",
node,
src,
));
}
}
}
});
findings
}
}
// ─── Rule 5: no-unsafe-deserialization ────────────────────────────────────────
pub struct NoUnsafeDeserialization;
impl_rule! {
NoUnsafeDeserialization,
id = "rb/no-unsafe-deserialization",
severity = Severity::Critical,
cwe = Some("CWE-502"),
description = "Unsafe deserialization via Marshal.load or YAML.load",
language = Language::Ruby,
fn check(_self, source, tree) {
let mut findings = Vec::new();
walk_tree(tree.root_node(), source, &mut |node, src| {
if node.kind() == "call" {
if let (Some(receiver), Some(method)) = (
node.child_by_field_name("receiver"),
node.child_by_field_name("method"),
) {
let recv = &src[receiver.byte_range()];
let meth = &src[method.byte_range()];
if (recv == "Marshal" && meth == "load")
|| (recv == "YAML" && (meth == "load" || meth == "unsafe_load"))
{
findings.push(make_finding(
_self.id(),
_self.severity(),
_self.cwe(),
&format!(
"{}.{} can execute arbitrary code — use YAML.safe_load or safer alternatives",
recv, meth
),
node,
src,
));
}
}
}
});
findings
}
}
// ─── Rule 6: no-open-redirect ─────────────────────────────────────────────────
pub struct NoOpenRedirect;
impl_rule! {
NoOpenRedirect,
id = "rb/no-open-redirect",
severity = Severity::High,
cwe = Some("CWE-601"),
description = "Potential open redirect via redirect_to with dynamic argument",
language = Language::Ruby,
fn check(_self, source, tree) {
let mut findings = Vec::new();
walk_tree(tree.root_node(), source, &mut |node, src| {
let is_redirect = match node.kind() {
"call" => node
.child_by_field_name("method")
.map(|m| &src[m.byte_range()] == "redirect_to")
.unwrap_or(false),
"command" => node
.child_by_field_name("name")
.map(|m| &src[m.byte_range()] == "redirect_to")
.unwrap_or(false),
_ => false,
};
if is_redirect {
// Check if the argument is a string literal (safe) or dynamic (unsafe)
let node_text = &src[node.byte_range()];
// If it contains variable interpolation or is not a simple string, flag it
let has_literal_only = node_text.contains("redirect_to \"")
|| node_text.contains("redirect_to '")
|| node_text.contains("redirect_to(\"")
|| node_text.contains("redirect_to('");
if !has_literal_only {
findings.push(make_finding(
_self.id(),
_self.severity(),
_self.cwe(),
"redirect_to with dynamic argument — validate URL to prevent open redirect",
node,
src,
));
}
}
});
findings
}
}
// ─── Rule 7: no-csrf-skip ────────────────────────────────────────────────────
pub struct NoCsrfSkip;
impl_rule! {
NoCsrfSkip,
id = "rb/no-csrf-skip",
severity = Severity::High,
cwe = Some("CWE-352"),
description = "CSRF protection disabled via skip_before_action",
language = Language::Ruby,
fn check(_self, source, tree) {
let mut findings = Vec::new();
walk_tree(tree.root_node(), source, &mut |node, src| {
let method_name = match node.kind() {
"call" => node
.child_by_field_name("method")
.map(|m| &src[m.byte_range()]),
"command" => node
.child_by_field_name("name")
.map(|m| &src[m.byte_range()]),
_ => None,
};
if let Some(name) = method_name {
if name == "skip_before_action" {
let text = &src[node.byte_range()];
if text.contains("verify_authenticity_token") {
findings.push(make_finding(
_self.id(),
_self.severity(),
_self.cwe(),
"skip_before_action :verify_authenticity_token disables CSRF protection",
node,
src,
));
}
}
}
});
findings
}
}
// ─── Rule 8: no-html-safe ─────────────────────────────────────────────────────
pub struct NoHtmlSafe;
impl_rule! {
NoHtmlSafe,
id = "rb/no-html-safe",
severity = Severity::High,
cwe = Some("CWE-79"),
description = "Potential XSS via html_safe or raw()",
language = Language::Ruby,
fn check(_self, source, tree) {
let mut findings = Vec::new();
walk_tree(tree.root_node(), source, &mut |node, src| {
// Detect .html_safe on non-literal receivers
if node.kind() == "call" {
if let Some(method) = node.child_by_field_name("method") {
let name = &src[method.byte_range()];
if name == "html_safe" {
if let Some(receiver) = node.child_by_field_name("receiver") {
// Only flag non-string-literal receivers
if receiver.kind() != "string" {
findings.push(make_finding(
_self.id(),
_self.severity(),
_self.cwe(),
".html_safe on dynamic content — risk of XSS",
node,
src,
));
}
}
}
}
}
// Detect raw() calls
let is_raw = match node.kind() {
"call" => node
.child_by_field_name("method")
.map(|m| &src[m.byte_range()] == "raw")
.unwrap_or(false),
"command" => node
.child_by_field_name("name")
.map(|m| &src[m.byte_range()] == "raw")
.unwrap_or(false),
_ => false,
};
if is_raw {
findings.push(make_finding(
_self.id(),
_self.severity(),
_self.cwe(),
"raw() bypasses HTML escaping — risk of XSS",
node,
src,
));
}
});
findings
}
}
// ─── Rule 9: no-hardcoded-secret ──────────────────────────────────────────────
pub struct NoHardcodedSecret;
impl_rule! {
NoHardcodedSecret,
id = "rb/no-hardcoded-secret",
severity = Severity::High,
cwe = Some("CWE-798"),
description = "Hardcoded secret or credential detected",
language = Language::Ruby,
fn check(_self, source, tree) {
let mut findings = Vec::new();
let secret_pattern =
Regex::new(r"(?i)(password|secret|api_?key|token|auth|credential|private_?key)")
.unwrap();
walk_tree(tree.root_node(), source, &mut |node, src| {
// assignment: variable = "hardcoded"
if node.kind() == "assignment" {
if let (Some(left), Some(right)) = (
node.child_by_field_name("left"),
node.child_by_field_name("right"),
) {
let left_text = &src[left.byte_range()];
if secret_pattern.is_match(left_text) && right.kind() == "string" {
let val = &src[right.byte_range()];
// Strip quotes and check length
let inner = val
.trim_start_matches(['"', '\''])
.trim_end_matches(['"', '\'']);
if inner.len() >= 4 {
findings.push(make_finding(
_self.id(),
_self.severity(),
_self.cwe(),
&format!(
"Hardcoded secret in '{}' — use environment variables",
left_text.trim()
),
node,
src,
));
}
}
}
}
});
findings
}
}
// ─── Rule 10: no-ssrf ────────────────────────────────────────────────────────
pub struct NoSsrf;
impl_rule! {
NoSsrf,
id = "rb/no-ssrf",
severity = Severity::High,
cwe = Some("CWE-918"),
description = "Potential SSRF via dynamic outbound HTTP request URL",
language = Language::Ruby,
fn check(_self, source, tree) {
let mut findings = Vec::new();
walk_tree(tree.root_node(), source, &mut |node, src| {
match node.kind() {
// Calls with a receiver: URI.open(...), Net::HTTP.get(...),
// HTTParty.get(...), Faraday.get(...), RestClient.get(...)
// Also bare calls: open(url), open url
"call" => {
let method = node.child_by_field_name("method");
let receiver = node.child_by_field_name("receiver");
let http_methods = ["get", "post", "put", "patch", "delete", "head"];
let (is_ssrf_call, label) = match (receiver, method) {
(Some(recv_node), Some(meth_node)) => {
let recv = &src[recv_node.byte_range()];
let meth = &src[meth_node.byte_range()];
let matched = (recv == "URI" && meth == "open")
|| (recv == "Net::HTTP" && http_methods.contains(&meth))
|| (recv == "HTTParty" && http_methods.contains(&meth))
|| (recv == "Faraday" && http_methods.contains(&meth))
|| (recv == "RestClient" && http_methods.contains(&meth));
(matched, format!("{}.{}", recv, meth))
}
// Bare call: open url (no receiver, method = "open")
(None, Some(meth_node)) => {
let meth = &src[meth_node.byte_range()];
(meth == "open", "open".to_string())
}
_ => (false, String::new()),
};
if !is_ssrf_call {
return;
}
// Check if the first argument is dynamic (not a string literal)
// Arguments can be in an "arguments" field or as argument_list named child
let first_arg = node
.child_by_field_name("arguments")
.and_then(|a| a.named_child(0))
.or_else(|| {
// For bare calls like `open url`, args are in an argument_list child
node.named_child(1).and_then(|c| {
if c.kind() == "argument_list" {
c.named_child(0)
} else {
Some(c)
}
})
});
if let Some(arg) = first_arg {
if arg.kind() != "string" {
let mut finding = make_finding(
_self.id(),
_self.severity(),
_self.cwe(),
&format!(
"{} called with dynamic URL — validate against an allowlist to prevent SSRF",
label
),
node,
src,
);
finding.fix_suggestion = Some(
"Validate URLs against an allowlist before making HTTP requests"
.to_string(),
);
findings.push(finding);
}
}
}
// Command-style bare calls (e.g. open url without parens)
"command" => {
let Some(name_node) = node.child_by_field_name("name") else {
return;
};
let name = &src[name_node.byte_range()];
if name != "open" {
return;
}
// For command nodes, check if the argument is a string literal
let is_literal = if let Some(arg) = node.named_child(1) {
arg.kind() == "string"
|| (arg.kind() == "argument_list"
&& arg.named_child(0).is_some_and(|a| a.kind() == "string"))
} else {
false
};
if !is_literal {
let mut finding = make_finding(
_self.id(),
_self.severity(),
_self.cwe(),
"open called with dynamic URL — validate against an allowlist to prevent SSRF",
node,
src,
);
finding.fix_suggestion = Some(
"Validate URLs against an allowlist before making HTTP requests"
.to_string(),
);
findings.push(finding);
}
}
_ => {}
}
});
findings
}
}
// ─── Rule 11: no-path-traversal ──────────────────────────────────────────────
pub struct NoPathTraversal;
impl_rule! {
NoPathTraversal,
id = "rb/no-path-traversal",
severity = Severity::High,
cwe = Some("CWE-22"),
description = "Potential path traversal via dynamic file path",
language = Language::Ruby,
fn check(_self, source, tree) {
let mut findings = Vec::new();
walk_tree(tree.root_node(), source, &mut |node, src| {
match node.kind() {
// Calls with a receiver: File.read(...), File.open(...),
// IO.read(...), File.write(...), FileUtils.cp(...)
// Also bare calls: send_file(path), send_file path
"call" => {
let method = node.child_by_field_name("method");
let receiver = node.child_by_field_name("receiver");
let (is_path_sink, label) = match (receiver, method) {
(Some(recv_node), Some(meth_node)) => {
let recv = &src[recv_node.byte_range()];
let meth = &src[meth_node.byte_range()];
let matched = (recv == "File"
&& (meth == "read"
|| meth == "open"
|| meth == "write"
|| meth == "delete"
|| meth == "readlines"
|| meth == "binread"))
|| (recv == "IO" && (meth == "read" || meth == "readlines"))
|| (recv == "FileUtils"
&& (meth == "cp"
|| meth == "mv"
|| meth == "rm"
|| meth == "mkdir_p"));
(matched, format!("{}.{}", recv, meth))
}
// Bare call: send_file path (no receiver)
(None, Some(meth_node)) => {
let meth = &src[meth_node.byte_range()];
(meth == "send_file", "send_file".to_string())
}
_ => (false, String::new()),
};
if !is_path_sink {
return;
}
// Check if the first argument is dynamic (not a string literal)
let first_arg = node
.child_by_field_name("arguments")
.and_then(|a| a.named_child(0))
.or_else(|| {
node.named_child(1).and_then(|c| {
if c.kind() == "argument_list" {
c.named_child(0)
} else {
Some(c)
}
})
});
if let Some(arg) = first_arg {
if arg.kind() != "string" {
let mut finding = make_finding(
_self.id(),
_self.severity(),
_self.cwe(),
&format!(
"{} called with dynamic path — validate to prevent path traversal",
label
),
node,
src,
);
finding.fix_suggestion = Some(
"Validate file paths and ensure they don't escape the intended directory"
.to_string(),
);
findings.push(finding);
}
}
}
// Command-style bare calls (e.g. send_file path without parens)
"command" => {
let Some(name_node) = node.child_by_field_name("name") else {
return;
};
let name = &src[name_node.byte_range()];
if name != "send_file" {
return;
}
let is_literal = if let Some(arg) = node.named_child(1) {
arg.kind() == "string"
|| (arg.kind() == "argument_list"
&& arg.named_child(0).is_some_and(|a| a.kind() == "string"))
} else {
false
};
if !is_literal {
let mut finding = make_finding(
_self.id(),
_self.severity(),
_self.cwe(),
"send_file called with dynamic path — validate to prevent path traversal",
node,
src,
);
finding.fix_suggestion = Some(
"Validate file paths and ensure they don't escape the intended directory"
.to_string(),
);
findings.push(finding);
}
}
_ => {}
}
});
findings
}
}
// ─── Rule 12: no-weak-crypto ──────────────────────────────────────────────────
pub struct NoWeakCrypto;
impl_rule! {
NoWeakCrypto,
id = "rb/no-weak-crypto",
severity = Severity::Medium,
cwe = Some("CWE-327"),
description = "Use of weak cryptographic hash (MD5/SHA1)",
language = Language::Ruby,
fn check(_self, source, tree) {
let mut findings = Vec::new();
walk_tree(tree.root_node(), source, &mut |node, src| {
// Detect Digest::MD5, Digest::SHA1 via scope_resolution nodes
if node.kind() == "scope_resolution" {
let text = &src[node.byte_range()];
if text == "Digest::MD5" || text == "Digest::SHA1" {
let algo = if text.contains("MD5") { "MD5" } else { "SHA1" };
findings.push(make_finding(
_self.id(),
_self.severity(),
_self.cwe(),
&format!(
"{} is cryptographically weak — use SHA-256 or stronger",
algo
),
node,
src,
));
}
}
});
findings
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::rules::Rule;
use tree_sitter::Parser;
fn parse_ruby(source: &str) -> tree_sitter::Tree {
let mut parser = Parser::new();
parser
.set_language(&tree_sitter_ruby::LANGUAGE.into())
.unwrap();
parser.parse(source, None).unwrap()
}
#[allow(dead_code)]
fn dump_tree(node: tree_sitter::Node, src: &str, depth: usize) {
let indent = " ".repeat(depth);
let text = &src[node.byte_range()];
let short = if text.len() > 60 { &text[..60] } else { text };
eprintln!(
"{}kind={:?} named_children={} text={:?}",
indent,
node.kind(),
node.named_child_count(),
short.replace('\n', "\\n")
);
for i in 0..node.named_child_count() {
if let Some(c) = node.named_child(i) {
dump_tree(c, src, depth + 1);
}
}
}
#[test]
fn debug_open_url_tree() {
let source = "open url\nsend_file path\n";
let tree = parse_ruby(source);
dump_tree(tree.root_node(), source, 0);
}
#[test]
fn test_ssrf_detects_all_patterns() {
let source = "URI.open(user_input)\nNet::HTTP.get(user_url)\nHTTParty.get(url)\nFaraday.get(url)\nRestClient.get(url)\nopen url\n";
let tree = parse_ruby(source);
let rule = NoSsrf;
let findings = rule.check(source, &tree);
assert_eq!(
findings.len(),
6,
"Expected 6 SSRF findings, got {}",
findings.len()
);
}
#[test]
fn test_path_traversal_detects_all_patterns() {
let source = "File.read(user_input)\nFile.open(user_input)\nIO.read(user_input)\nFile.write(path, data)\nFileUtils.cp(src, dst)\nsend_file path\n";
let tree = parse_ruby(source);
let rule = NoPathTraversal;
let findings = rule.check(source, &tree);
assert_eq!(
findings.len(),
6,
"Expected 6 path traversal findings, got {}",
findings.len()
);
}
#[test]
fn test_command_injection_skips_plain_string_literal() {
let source = r#"system("ls -la")"#;
let tree = parse_ruby(source);
let rule = NoCommandInjection;
let findings = rule.check(source, &tree);
assert_eq!(
findings.len(),
0,
"system() with a plain string literal should NOT fire"
);
}
#[test]
fn test_command_injection_fires_on_variable() {
let source = "system(user_input)";
let tree = parse_ruby(source);
let rule = NoCommandInjection;
let findings = rule.check(source, &tree);
assert_eq!(
findings.len(),
1,
"system() with a variable argument should fire"
);
}
#[test]
fn test_command_injection_fires_on_interpolated_string() {
let source = r##"system("#{cmd}")"##;
let tree = parse_ruby(source);
let rule = NoCommandInjection;
let findings = rule.check(source, &tree);
assert_eq!(
findings.len(),
1,
"system() with an interpolated string should fire"
);
}
#[test]
fn test_command_injection_skips_exec_with_literal() {
let source = r#"exec("echo hello")"#;
let tree = parse_ruby(source);
let rule = NoCommandInjection;
let findings = rule.check(source, &tree);
assert_eq!(
findings.len(),
0,
"exec() with a plain string literal should NOT fire"
);
}
}