jsdet-core 0.1.0

Core WASM-sandboxed JavaScript detonation engine
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
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
//! VulnIR producer implementation for jsdet.
//!
//! This module converts jsdet observations and execution results into
//! VulnIR graph representations for security analysis.
//!
//! # Example
//!
//! ```
//! use jsdet_core::{ExecutionResult, JsdetProducer};
//! use jsdet_core::vulnir_producer::to_vulnir_graph;
//!
//! let result = ExecutionResult {
//!     observations: vec![],
//!     scripts_executed: 1,
//!     errors: vec![],
//!     duration_us: 1000,
//!     timed_out: false,
//! };
//!
//! let producer = JsdetProducer::new("jsdet-core", "1.0.0");
//! let graph = to_vulnir_graph(&result, &producer);
//! ```

use petgraph::graph::NodeIndex;
use vulnir::{
    ConfidenceValue, Evidence, Producer, ProducerKind, Provenance, SourceLocation, VulnEdge,
    VulnIRGraph, VulnNode, VulnProducer,
};

use crate::observation::{Observation, Value};
use crate::sandbox::ExecutionResult;

/// Producer identity for jsdet VulnIR emission.
///
/// Implements the `VulnProducer` trait to provide stable identity
/// for all VulnIR graphs produced by jsdet.
#[derive(Debug, Clone)]
pub struct JsdetProducer {
    producer: Producer,
}

impl JsdetProducer {
    /// Creates a new jsdet producer with the given name and version.
    #[must_use]
    pub fn new(name: impl Into<String>, version: impl Into<String>) -> Self {
        Self {
            producer: Producer::new(name, ProducerKind::Dynamic).with_version(version),
        }
    }

    /// Creates a producer with default identity.
    #[must_use]
    pub fn default_producer() -> Self {
        Self::new("jsdet-core", env!("CARGO_PKG_VERSION"))
    }

    /// Creates a provenance record for a node or edge.
    fn create_provenance(&self, location: Option<SourceLocation>) -> Provenance {
        let mut prov = Provenance::new(self.producer.clone());
        prov.location = location;
        prov
    }

    /// Creates evidence from an observation.
    fn create_evidence(&self, details: impl Into<String>) -> Evidence {
        Evidence::new(
            self.producer.name.clone(),
            details,
            1.0, // High confidence for dynamic observations
            true,
        )
    }
}

impl VulnProducer for JsdetProducer {
    fn producer(&self) -> Producer {
        self.producer.clone()
    }
}

impl Default for JsdetProducer {
    fn default() -> Self {
        Self::default_producer()
    }
}

/// Converts an ExecutionResult into a VulnIR graph.
///
/// This function processes all observations in the execution result and
/// creates appropriate VulnIR nodes and edges:
///
/// - `DynamicCodeExec` (eval, Function) → `Capability` node with `code-execution` resource
/// - `ApiCall` for require/import → `TrustBoundary` node with `module-import` source_type
/// - `NetworkRequest` (fetch, XHR) → `Capability` node with `network` resource
/// - `ApiCall` for fs operations → `Capability` node with `filesystem` resource
/// - Taint flows → `TaintReach` edges between nodes
///
/// # Arguments
///
/// * `result` - The execution result containing observations
/// * `producer` - The producer identity for provenance
///
/// # Returns
///
/// A `VulnIRGraph` representing the security-relevant behavior
#[must_use]
pub fn to_vulnir_graph(
    result: &ExecutionResult,
    producer: &JsdetProducer,
) -> VulnIRGraph<VulnNode, VulnEdge> {
    let mut graph = VulnIRGraph::new();
    let mut node_indices: Vec<NodeIndex> = Vec::new();

    // First pass: create nodes for all observations
    for (idx, obs) in result.observations.iter().enumerate() {
        let node_idx = observation_to_node(&mut graph, obs, idx, producer);
        if let Some(idx) = node_idx {
            node_indices.push(idx);
        }
    }

    // Second pass: create edges for taint flows between nodes
    create_taint_edges(&mut graph, &result.observations, &node_indices, producer);

    graph
}

/// Converts a single observation into a VulnIR node.
///
/// Returns `Some(NodeIndex)` if the observation maps to a node,
/// `None` if the observation doesn't have a security-relevant representation.
fn observation_to_node(
    graph: &mut VulnIRGraph<VulnNode, VulnEdge>,
    obs: &Observation,
    idx: usize,
    producer: &JsdetProducer,
) -> Option<NodeIndex> {
    match obs {
        // eval, Function constructor → Capability node (code-execution)
        Observation::DynamicCodeExec {
            source,
            code_preview,
        } => {
            let source_type = match source {
                crate::observation::DynamicCodeSource::Eval => "eval",
                crate::observation::DynamicCodeSource::Function => "function-constructor",
                crate::observation::DynamicCodeSource::SetTimeoutString => "settimeout-string",
                crate::observation::DynamicCodeSource::SetIntervalString => "setinterval-string",
                crate::observation::DynamicCodeSource::ImportScripts => "importscripts",
            };

            let node = VulnNode::Capability {
                id: format!("dynamic-code-exec-{idx}"),
                resource: "code-execution".to_string(),
                permission: "execute".to_string(),
                target: Some(code_preview.chars().take(100).collect()),
                arguments: vec![source_type.to_string()],
                duration_ns: None,
                provenance: vec![producer.create_provenance(Some(SourceLocation {
                    file: None,
                    artifact: None,
                    line: None,
                    column: None,
                }))],
                metadata: Default::default(),
            };

            Some(graph.add_node(node))
        }

        // Network requests → Capability node (network)
        Observation::NetworkRequest {
            url,
            method,
            headers: _,
            body: _,
        } => {
            let node = VulnNode::Capability {
                id: format!("network-request-{idx}"),
                resource: "network".to_string(),
                permission: method.to_lowercase(),
                target: Some(url.clone()),
                arguments: vec![],
                duration_ns: None,
                provenance: vec![producer.create_provenance(Some(SourceLocation {
                    file: None,
                    artifact: None,
                    line: None,
                    column: None,
                }))],
                metadata: Default::default(),
            };

            Some(graph.add_node(node))
        }

        // API calls - may be module imports, filesystem operations, or code execution
        Observation::ApiCall {
            api,
            args,
            result: _,
        } => {
            if is_code_execution(api) {
                // eval, setTimeout with string, etc. → Capability node (code-execution)
                let code_preview = args
                    .first()
                    .and_then(|v| v.as_str())
                    .map(|s| s.chars().take(100).collect())
                    .unwrap_or_else(|| "<empty>".to_string());

                let node = VulnNode::Capability {
                    id: format!("dynamic-code-exec-{idx}"),
                    resource: "code-execution".to_string(),
                    permission: "execute".to_string(),
                    target: Some(code_preview),
                    arguments: vec![api.clone()],
                    duration_ns: None,
                    provenance: vec![producer.create_provenance(Some(SourceLocation {
                        file: None,
                        artifact: None,
                        line: None,
                        column: None,
                    }))],
                    metadata: Default::default(),
                };

                Some(graph.add_node(node))
            } else if is_module_import(api) {
                // require/import → TrustBoundary node
                let module_name = extract_module_name(api, args);

                let node = VulnNode::TrustBoundary {
                    id: format!("module-import-{idx}"),
                    description: format!("Module import: {module_name}"),
                    source_type: "module-import".to_string(),
                    confidence: ConfidenceValue::from(1.0),
                    taint_id: None,
                    created_ns: None,
                    provenance: vec![producer.create_provenance(Some(SourceLocation {
                        file: None,
                        artifact: None,
                        line: None,
                        column: None,
                    }))],
                    metadata: Default::default(),
                };

                Some(graph.add_node(node))
            } else if is_filesystem_operation(api) {
                // fs.readFile/writeFile → Capability node (filesystem)
                let permission = if api.contains("read") || api.contains("readdir") {
                    "read"
                } else if api.contains("write") {
                    "write"
                } else {
                    "access"
                };

                let target = args.first().and_then(|v| v.as_str()).map(String::from);

                let node = VulnNode::Capability {
                    id: format!("filesystem-{idx}"),
                    resource: "filesystem".to_string(),
                    permission: permission.to_string(),
                    target,
                    arguments: vec![api.clone()],
                    duration_ns: None,
                    provenance: vec![producer.create_provenance(Some(SourceLocation {
                        file: None,
                        artifact: None,
                        line: None,
                        column: None,
                    }))],
                    metadata: Default::default(),
                };

                Some(graph.add_node(node))
            } else {
                None
            }
        }

        // DOM mutations may indicate XSS or other injections
        Observation::DomMutation {
            kind,
            target,
            detail,
        } => {
            let _description = format!("DOM {kind:?} on {target}: {detail}");

            let node = VulnNode::Capability {
                id: format!("dom-mutation-{idx}"),
                resource: "dom-manipulation".to_string(),
                permission: "modify".to_string(),
                target: Some(target.clone()),
                arguments: vec![format!("{kind:?}"), detail.clone()],
                duration_ns: None,
                provenance: vec![producer.create_provenance(Some(SourceLocation {
                    file: None,
                    artifact: None,
                    line: None,
                    column: None,
                }))],
                metadata: Default::default(),
            };

            Some(graph.add_node(node))
        }

        // Cookie access → TrustBoundary (data crossing boundary)
        Observation::CookieAccess {
            operation,
            name,
            value: _,
        } => {
            let description = format!("Cookie {operation:?}: {name}");

            let node = VulnNode::TrustBoundary {
                id: format!("cookie-access-{idx}"),
                description,
                source_type: "cookie-access".to_string(),
                confidence: ConfidenceValue::from(1.0),
                taint_id: None,
                created_ns: None,
                provenance: vec![producer.create_provenance(Some(SourceLocation {
                    file: None,
                    artifact: None,
                    line: None,
                    column: None,
                }))],
                metadata: Default::default(),
            };

            Some(graph.add_node(node))
        }

        // WebAssembly instantiation
        Observation::WasmInstantiation {
            module_size,
            import_names,
            export_names,
        } => {
            let node = VulnNode::Capability {
                id: format!("wasm-instantiation-{idx}"),
                resource: "webassembly".to_string(),
                permission: "instantiate".to_string(),
                target: Some(format!("{module_size} bytes")),
                arguments: vec![
                    format!("imports: {:?}", import_names),
                    format!("exports: {:?}", export_names),
                ],
                duration_ns: None,
                provenance: vec![producer.create_provenance(Some(SourceLocation {
                    file: None,
                    artifact: None,
                    line: None,
                    column: None,
                }))],
                metadata: Default::default(),
            };

            Some(graph.add_node(node))
        }

        // Context messages indicate cross-context communication
        Observation::ContextMessage {
            from_context,
            to_context,
            payload,
        } => {
            let description = format!("Message from {from_context} to {to_context}: {payload}");

            let node = VulnNode::TrustBoundary {
                id: format!("context-message-{idx}"),
                description,
                source_type: "cross-context".to_string(),
                confidence: ConfidenceValue::from(1.0),
                taint_id: None,
                created_ns: None,
                provenance: vec![producer.create_provenance(Some(SourceLocation {
                    file: None,
                    artifact: None,
                    line: None,
                    column: None,
                }))],
                metadata: Default::default(),
            };

            Some(graph.add_node(node))
        }

        // Other observations don't map to VulnIR nodes directly
        _ => None,
    }
}

/// Creates TaintReach edges between nodes based on taint flow observations.
fn create_taint_edges(
    graph: &mut VulnIRGraph<VulnNode, VulnEdge>,
    observations: &[Observation],
    node_indices: &[NodeIndex],
    producer: &JsdetProducer,
) {
    for obs in observations {
        if let Observation::ApiCall { api, args, .. } = obs {
            // Check if any arguments are tainted
            let tainted_positions: Vec<usize> = args
                .iter()
                .enumerate()
                .filter(|(_, v)| is_value_tainted(v))
                .map(|(idx, _)| idx)
                .collect();

            if !tainted_positions.is_empty() && !node_indices.is_empty() {
                // Find or create a source node (first tainted argument source)
                // and a sink node (this API call)
                // For simplicity, we connect the last node to this observation's node
                // This is a simplified taint flow representation

                let evidence = vec![producer.create_evidence(format!(
                    "Tainted data reached sink '{api}' at argument positions {:?}",
                    tainted_positions
                ))];

                // Try to find a previous capability or trust boundary as source
                // and connect to a sink capability
                if node_indices.len() >= 2 {
                    let source_idx = node_indices[node_indices.len() - 2];
                    let sink_idx = node_indices[node_indices.len() - 1];

                    let edge = VulnEdge::TaintReach {
                        path: format!("{api}<-arg[{tainted_positions:?}]"),
                        confidence: ConfidenceValue::from(1.0),
                        observed_dynamically: true,
                        transform_chain: vec![],
                        evidence,
                    };

                    graph.add_edge(source_idx, sink_idx, edge);
                }
            }
        }
    }
}

/// Checks if a value is tainted.
fn is_value_tainted(value: &Value) -> bool {
    match value {
        Value::String(_, label) | Value::Json(_, label) => label.is_tainted(),
        _ => false,
    }
}

/// Checks if an API call is a code execution operation.
fn is_code_execution(api: &str) -> bool {
    api == "eval"
        || api == "Function"
        || api == "setTimeout"
        || api == "setInterval"
        || api == "importScripts"
        || api.contains("executeScript")
        || api.contains("execScript")
}

/// Checks if an API call is a module import operation.
fn is_module_import(api: &str) -> bool {
    api == "require"
        || api == "import"
        || api.starts_with("module.require")
        || api.contains("__webpack_require__")
        || api.contains("dynamicImport")
}

/// Extracts the module name from import arguments.
fn extract_module_name(api: &str, args: &[Value]) -> String {
    if let Some(first_arg) = args.first()
        && let Some(s) = first_arg.as_str()
    {
        return s.to_string();
    }
    api.to_string()
}

/// Checks if an API call is a filesystem operation.
fn is_filesystem_operation(api: &str) -> bool {
    api.starts_with("fs.")
        || api.starts_with("node:fs")
        || api.contains("readFile")
        || api.contains("writeFile")
        || api.contains("readdir")
        || api.contains("unlink")
        || api.contains("mkdir")
        || api.contains("rmdir")
}

/// Extension trait for ExecutionResult to provide VulnIR conversion.
pub trait ToVulnIR {
    /// Converts this execution result to a VulnIR graph.
    ///
    /// Uses the default jsdet producer identity.
    fn to_vulnir_graph(&self) -> VulnIRGraph<VulnNode, VulnEdge>;

    /// Converts this execution result to a VulnIR graph with a custom producer.
    fn to_vulnir_graph_with_producer(
        &self,
        producer: &JsdetProducer,
    ) -> VulnIRGraph<VulnNode, VulnEdge>;
}

impl ToVulnIR for ExecutionResult {
    fn to_vulnir_graph(&self) -> VulnIRGraph<VulnNode, VulnEdge> {
        let producer = JsdetProducer::default_producer();
        to_vulnir_graph(self, &producer)
    }

    fn to_vulnir_graph_with_producer(
        &self,
        producer: &JsdetProducer,
    ) -> VulnIRGraph<VulnNode, VulnEdge> {
        to_vulnir_graph(self, producer)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::observation::{DynamicCodeSource, Observation, TaintLabel, Value};
    use vulnir::VulnIRGraphExt;

    #[test]
    fn eval_produces_capability_node() {
        let result = ExecutionResult {
            observations: vec![Observation::DynamicCodeExec {
                source: DynamicCodeSource::Eval,
                code_preview: "console.log('test')".to_string(),
            }],
            scripts_executed: 1,
            errors: vec![],
            duration_us: 1000,
            timed_out: false,
        };

        let graph = result.to_vulnir_graph();

        assert_eq!(graph.node_count(), 1);
        assert_eq!(graph.edge_count(), 0);

        // Check it's a Capability node with code-execution resource
        let attack_surface = graph.attack_surface();
        assert!(attack_surface.is_empty()); // Capabilities are not attack surfaces
    }

    #[test]
    fn require_produces_trust_boundary_node() {
        let result = ExecutionResult {
            observations: vec![Observation::ApiCall {
                api: "require".to_string(),
                args: vec![Value::string("fs")],
                result: Value::Null,
            }],
            scripts_executed: 1,
            errors: vec![],
            duration_us: 1000,
            timed_out: false,
        };

        let graph = result.to_vulnir_graph();

        assert_eq!(graph.node_count(), 1);
        assert_eq!(graph.edge_count(), 0);

        // Check it's a TrustBoundary node (attack surface)
        let attack_surface = graph.attack_surface();
        assert_eq!(attack_surface.len(), 1);
    }

    #[test]
    fn network_and_eval_produces_taint_reach_edge() {
        let result = ExecutionResult {
            observations: vec![
                Observation::NetworkRequest {
                    url: "https://evil.com/payload".to_string(),
                    method: "GET".to_string(),
                    headers: vec![],
                    body: None,
                },
                Observation::ApiCall {
                    api: "eval".to_string(),
                    args: vec![Value::tainted_string(
                        "console.log('pwned')",
                        TaintLabel::new(1),
                    )],
                    result: Value::Null,
                },
            ],
            scripts_executed: 1,
            errors: vec![],
            duration_us: 1000,
            timed_out: false,
        };

        let graph = result.to_vulnir_graph();

        // Should have 2 nodes: network capability and the eval call
        assert_eq!(graph.node_count(), 2);

        // Should have 1 taint reach edge
        assert_eq!(graph.edge_count(), 1);
    }

    #[test]
    fn empty_result_produces_empty_graph() {
        let result = ExecutionResult {
            observations: vec![],
            scripts_executed: 0,
            errors: vec![],
            duration_us: 0,
            timed_out: false,
        };

        let graph = result.to_vulnir_graph();

        assert_eq!(graph.node_count(), 0);
        assert_eq!(graph.edge_count(), 0);
    }

    #[test]
    fn filesystem_operations_produce_capability_nodes() {
        let result = ExecutionResult {
            observations: vec![Observation::ApiCall {
                api: "fs.readFileSync".to_string(),
                args: vec![Value::string("/etc/passwd")],
                result: Value::Null,
            }],
            scripts_executed: 1,
            errors: vec![],
            duration_us: 1000,
            timed_out: false,
        };

        let graph = result.to_vulnir_graph();

        assert_eq!(graph.node_count(), 1);

        // Check the node is a filesystem capability
        let caps = graph.reachable_capabilities(NodeIndex::new(0));
        assert_eq!(caps.len(), 1);
    }

    #[test]
    fn jsdet_producer_trait_implementation() {
        let producer = JsdetProducer::new("test-producer", "1.0.0");
        let p = producer.producer();

        assert_eq!(p.name, "test-producer");
        assert_eq!(p.version, Some("1.0.0".to_string()));
        assert_eq!(p.kind, ProducerKind::Dynamic);
    }

    #[test]
    fn custom_producer_used_in_graph() {
        let result = ExecutionResult {
            observations: vec![Observation::DynamicCodeExec {
                source: DynamicCodeSource::Function,
                code_preview: "return 1".to_string(),
            }],
            scripts_executed: 1,
            errors: vec![],
            duration_us: 1000,
            timed_out: false,
        };

        let producer = JsdetProducer::new("custom-scanner", "2.0.0");
        let graph = result.to_vulnir_graph_with_producer(&producer);

        assert_eq!(graph.node_count(), 1);
    }
}