-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathv8_js.rs
More file actions
519 lines (453 loc) · 18.3 KB
/
v8_js.rs
File metadata and controls
519 lines (453 loc) · 18.3 KB
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
use crate::rules::common::{RequestInfo, RuleResponse};
use crate::rules::console_log;
use crate::rules::{EvaluationResult, RuleEngineTrait};
use async_trait::async_trait;
use hyper::Method;
use std::sync::Arc;
use tokio::sync::Mutex;
use tracing::{debug, info, warn};
pub struct V8JsRuleEngine {
js_code: String,
#[allow(dead_code)]
runtime: Arc<Mutex<()>>, // Placeholder for V8 runtime management
}
impl V8JsRuleEngine {
pub fn new(js_code: String) -> Result<Self, Box<dyn std::error::Error>> {
// Initialize V8 platform once and keep it alive for the lifetime of the program
use std::sync::OnceLock;
static V8_PLATFORM: OnceLock<v8::SharedRef<v8::Platform>> = OnceLock::new();
V8_PLATFORM.get_or_init(|| {
let platform = v8::new_default_platform(0, false).make_shared();
v8::V8::initialize_platform(platform.clone());
v8::V8::initialize();
platform
});
// Compile the JavaScript to check for syntax errors
{
let mut isolate = v8::Isolate::new(v8::CreateParams::default());
let handle_scope = &mut v8::HandleScope::new(&mut isolate);
let context = v8::Context::new(handle_scope, Default::default());
let context_scope = &mut v8::ContextScope::new(handle_scope, context);
let source =
v8::String::new(context_scope, &js_code).ok_or("Failed to create V8 string")?;
v8::Script::compile(context_scope, source, None)
.ok_or("Failed to compile JavaScript expression")?;
}
info!("V8 JavaScript rule engine initialized");
Ok(Self {
js_code,
runtime: Arc::new(Mutex::new(())),
})
}
pub fn execute(
&self,
method: &Method,
url: &str,
requester_ip: &str,
) -> (bool, Option<String>, Option<u64>) {
let request_info = match RequestInfo::from_request(method, url, requester_ip) {
Ok(info) => info,
Err(e) => {
warn!("Failed to parse request info: {}", e);
return (false, Some("Invalid request format".to_string()), None);
}
};
match self.create_and_execute(&request_info) {
Ok(result) => result,
Err(e) => {
warn!("JavaScript execution failed: {}", e);
(false, Some("JavaScript execution failed".to_string()), None)
}
}
}
/// Convert a V8 value to a response string that can be parsed by RuleResponse
fn value_to_response_string(
context_scope: &mut v8::ContextScope<v8::HandleScope>,
global: v8::Local<v8::Object>,
value: v8::Local<v8::Value>,
) -> Result<String, Box<dyn std::error::Error>> {
if value.is_object() && !value.is_null() && !value.is_undefined() {
// Object - stringify it to JSON using JSON.stringify()
let json_key = v8::String::new(context_scope, "JSON").unwrap();
let stringify_key = v8::String::new(context_scope, "stringify").unwrap();
let json_obj = global
.get(context_scope, json_key.into())
.and_then(|v| v.to_object(context_scope))
.ok_or("Failed to get JSON object")?;
let stringify_fn = json_obj
.get(context_scope, stringify_key.into())
.and_then(|v| v8::Local::<v8::Function>::try_from(v).ok())
.ok_or("Failed to get JSON.stringify function")?;
// Call JSON.stringify(value)
stringify_fn
.call(context_scope, json_obj.into(), &[value])
.and_then(|v| v.to_string(context_scope))
.map(|s| s.to_rust_string_lossy(context_scope))
.ok_or_else(|| "Failed to stringify value".into())
} else if value.is_boolean() {
// Boolean - convert to "true" or "false" string
Ok(if value.boolean_value(context_scope) {
"true".to_string()
} else {
"false".to_string()
})
} else if value.is_string() {
// String - use as-is (will be treated as deny message)
value
.to_string(context_scope)
.map(|s| s.to_rust_string_lossy(context_scope))
.ok_or_else(|| "Failed to convert string".into())
} else {
// Other types - default to "false"
Ok("false".to_string())
}
}
#[allow(clippy::type_complexity)]
fn execute_with_isolate(
isolate: &mut v8::OwnedIsolate,
js_code: &str,
request_info: &RequestInfo,
) -> Result<(bool, Option<String>, Option<u64>), Box<dyn std::error::Error>> {
let handle_scope = &mut v8::HandleScope::new(isolate);
let context = v8::Context::new(handle_scope, Default::default());
let context_scope = &mut v8::ContextScope::new(handle_scope, context);
// Set up console object with debug, log, info, warn, error methods
console_log::setup_console(context_scope);
let global = context.global(context_scope);
// Serialize RequestInfo to JSON - this is the exact same JSON sent to proc
let json_request = serde_json::to_string(&request_info)
.map_err(|e| format!("Failed to serialize request: {}", e))?;
// Parse the JSON in V8 to create the 'r' object
let json_str = v8::String::new(context_scope, &json_request)
.ok_or("Failed to create V8 string for JSON")?;
let json_key = v8::String::new(context_scope, "JSON").unwrap();
let parse_key = v8::String::new(context_scope, "parse").unwrap();
let json_obj = global
.get(context_scope, json_key.into())
.ok_or("Failed to get JSON object")?
.to_object(context_scope)
.ok_or("JSON is not an object")?;
let parse_fn = json_obj
.get(context_scope, parse_key.into())
.ok_or("Failed to get JSON.parse")?;
let parse_fn = v8::Local::<v8::Function>::try_from(parse_fn)
.map_err(|_| "JSON.parse is not a function")?;
// Call JSON.parse to create the request object
let r_obj = parse_fn
.call(context_scope, json_obj.into(), &[json_str.into()])
.ok_or("Failed to parse JSON")?;
// Set the parsed object as 'r' in the global scope
let r_key = v8::String::new(context_scope, "r").unwrap();
global.set(context_scope, r_key.into(), r_obj);
// Execute the JavaScript expression
let source = v8::String::new(context_scope, js_code).ok_or("Failed to create V8 string")?;
let script = v8::Script::compile(context_scope, source, None)
.ok_or("Failed to compile JavaScript expression")?;
// Execute the expression
let result = script
.run(context_scope)
.ok_or("Expression evaluation failed")?;
// Convert the V8 result to a JSON string for consistent parsing
// This ensures perfect parity with the proc engine response handling
let response_str = Self::value_to_response_string(context_scope, global, result)?;
// Use the common RuleResponse parser - exact same logic as proc engine
let rule_response = RuleResponse::from_string(&response_str);
let (allowed, message, max_tx_bytes) = rule_response.to_evaluation_result();
debug!(
"JS rule returned {} for {} {}",
if allowed { "ALLOW" } else { "DENY" },
request_info.method,
request_info.url
);
if let Some(ref msg) = message {
debug!("Deny message: {}", msg);
}
Ok((allowed, message, max_tx_bytes))
}
#[allow(clippy::type_complexity)]
fn create_and_execute(
&self,
request_info: &RequestInfo,
) -> Result<(bool, Option<String>, Option<u64>), Box<dyn std::error::Error>> {
// Create a new isolate for each execution (simpler approach)
let mut isolate = v8::Isolate::new(v8::CreateParams::default());
Self::execute_with_isolate(&mut isolate, &self.js_code, request_info)
}
}
#[async_trait]
impl RuleEngineTrait for V8JsRuleEngine {
async fn evaluate(&self, method: Method, url: &str, requester_ip: &str) -> EvaluationResult {
// Run the JavaScript evaluation in a blocking task to avoid
// issues with V8's single-threaded nature
let method_clone = method.clone();
let url_clone = url.to_string();
let ip_clone = requester_ip.to_string();
// Clone self to move into the closure
let self_clone = Self {
js_code: self.js_code.clone(),
runtime: self.runtime.clone(),
};
let (allowed, context, max_tx_bytes) = tokio::task::spawn_blocking(move || {
self_clone.execute(&method_clone, &url_clone, &ip_clone)
})
.await
.unwrap_or_else(|e| {
warn!("Failed to spawn V8 evaluation task: {}", e);
(false, Some("Evaluation failed".to_string()), None)
});
if allowed {
let mut result = EvaluationResult::allow();
if let Some(ctx) = context {
result = result.with_context(ctx);
}
if let Some(bytes) = max_tx_bytes {
result = result.with_max_tx_bytes(bytes);
}
result
} else {
let mut result = EvaluationResult::deny();
if let Some(ctx) = context {
result = result.with_context(ctx);
}
result
}
}
fn name(&self) -> &str {
"v8_js"
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn test_v8_js_allow() {
let engine = V8JsRuleEngine::new("true".to_string()).unwrap();
let result = engine
.evaluate(Method::GET, "https://example.com", "127.0.0.1")
.await;
assert!(matches!(result.action, crate::rules::Action::Allow));
}
#[tokio::test]
async fn test_v8_js_deny() {
let engine = V8JsRuleEngine::new("false".to_string()).unwrap();
let result = engine
.evaluate(Method::GET, "https://example.com", "127.0.0.1")
.await;
assert!(matches!(result.action, crate::rules::Action::Deny));
}
#[tokio::test]
async fn test_v8_js_with_request_info() {
let engine = V8JsRuleEngine::new("r.host === 'example.com'".to_string()).unwrap();
let result = engine
.evaluate(Method::GET, "https://example.com/path", "127.0.0.1")
.await;
assert!(matches!(result.action, crate::rules::Action::Allow));
}
#[tokio::test]
async fn test_v8_js_object_response_allow() {
let engine = V8JsRuleEngine::new("({allow: true})".to_string()).unwrap();
let result = engine
.evaluate(Method::GET, "https://example.com", "127.0.0.1")
.await;
assert!(matches!(result.action, crate::rules::Action::Allow));
assert_eq!(result.context, None); // No message when allowing
}
#[tokio::test]
async fn test_v8_js_object_response_deny() {
let engine =
V8JsRuleEngine::new("({allow: false, deny_message: 'Blocked by policy'})".to_string())
.unwrap();
let result = engine
.evaluate(Method::POST, "https://example.com", "127.0.0.1")
.await;
assert!(matches!(result.action, crate::rules::Action::Deny));
assert_eq!(result.context, Some("Blocked by policy".to_string()));
}
#[tokio::test]
async fn test_v8_js_conditional_object() {
let engine = V8JsRuleEngine::new(
"r.method === 'POST' ? {deny_message: 'POST not allowed'} : true".to_string(),
)
.unwrap();
// Test POST (should deny with message)
let result = engine
.evaluate(Method::POST, "https://example.com", "127.0.0.1")
.await;
assert!(matches!(result.action, crate::rules::Action::Deny));
assert_eq!(result.context, Some("POST not allowed".to_string()));
// Test GET (should allow)
let result = engine
.evaluate(Method::GET, "https://example.com", "127.0.0.1")
.await;
assert!(matches!(result.action, crate::rules::Action::Allow));
assert_eq!(result.context, None);
}
#[tokio::test]
async fn test_v8_js_shorthand_deny_message() {
// Test shorthand: {deny_message: "reason"} implies allow: false
let engine =
V8JsRuleEngine::new("({deny_message: 'Shorthand denial'})".to_string()).unwrap();
let result = engine
.evaluate(Method::GET, "https://example.com", "127.0.0.1")
.await;
assert!(matches!(result.action, crate::rules::Action::Deny));
assert_eq!(result.context, Some("Shorthand denial".to_string()));
}
#[tokio::test]
async fn test_request_field_access() {
use crate::rules::Action;
// Test accessing various fields of the request
let test_cases = vec![
(
"r.method === 'GET'",
Method::GET,
"https://example.com",
true,
),
(
"r.method === 'POST'",
Method::GET,
"https://example.com",
false,
),
(
"r.host === 'example.com'",
Method::GET,
"https://example.com/test",
true,
),
(
"r.host === 'other.com'",
Method::GET,
"https://example.com/test",
false,
),
(
"r.path === '/test'",
Method::GET,
"https://example.com/test",
true,
),
(
"r.path.startsWith('/api')",
Method::GET,
"https://example.com/api/v1",
true,
),
(
"r.path.startsWith('/api')",
Method::GET,
"https://example.com/v1/api",
false,
),
];
for (js_code, method, url, expected_allow) in test_cases {
let engine = V8JsRuleEngine::new(js_code.to_string()).unwrap();
let result = engine.evaluate(method, url, "127.0.0.1").await;
assert_eq!(
matches!(result.action, Action::Allow),
expected_allow,
"Expression '{}' should {} request to {}",
js_code,
if expected_allow { "allow" } else { "deny" },
url
);
}
}
#[tokio::test]
async fn test_object_response() {
use crate::rules::Action;
// Test returning an object with allow/deny and message
let js_code = r#"
if (r.host === 'blocked.com') {
({ allow: false, deny_message: `Host ${r.host} is blocked` })
} else {
({ allow: true })
}
"#;
let engine = V8JsRuleEngine::new(js_code.to_string()).unwrap();
// Test allowed request
let result = engine
.evaluate(Method::GET, "https://example.com/test", "127.0.0.1")
.await;
assert!(matches!(result.action, Action::Allow));
assert_eq!(result.context, None);
// Test denied request with message
let result = engine
.evaluate(Method::GET, "https://blocked.com/test", "127.0.0.1")
.await;
assert!(matches!(result.action, Action::Deny));
assert_eq!(
result.context,
Some("Host blocked.com is blocked".to_string())
);
}
#[tokio::test]
async fn test_complex_logic() {
use crate::rules::Action;
let js_code = r#"
// Allow GitHub and GitLab
const allowed_hosts = ['github.com', 'gitlab.com'];
// Block certain paths
const blocked_paths = ['/admin', '/config'];
if (blocked_paths.some(p => r.path.startsWith(p))) {
({ deny_message: 'Access to administrative paths denied' })
} else if (allowed_hosts.includes(r.host)) {
true
} else {
false
}
"#;
let engine = V8JsRuleEngine::new(js_code.to_string()).unwrap();
// Test allowed hosts
let result = engine
.evaluate(Method::GET, "https://github.com/repo", "127.0.0.1")
.await;
assert!(matches!(result.action, Action::Allow));
let result = engine
.evaluate(Method::GET, "https://gitlab.com/project", "127.0.0.1")
.await;
assert!(matches!(result.action, Action::Allow));
// Test blocked paths
let result = engine
.evaluate(Method::GET, "https://github.com/admin", "127.0.0.1")
.await;
assert!(matches!(result.action, Action::Deny));
assert_eq!(
result.context,
Some("Access to administrative paths denied".to_string())
);
// Test non-allowed host
let result = engine
.evaluate(Method::GET, "https://example.com/test", "127.0.0.1")
.await;
assert!(matches!(result.action, Action::Deny));
}
#[tokio::test]
async fn test_concurrent_evaluation() {
use crate::rules::Action;
use std::sync::Arc;
// Test that multiple evaluations can run concurrently
let engine = Arc::new(V8JsRuleEngine::new("r.host === 'example.com'".to_string()).unwrap());
let mut tasks = vec![];
for i in 0..10 {
let engine_clone = engine.clone();
let host = if i % 2 == 0 {
"example.com"
} else {
"other.com"
};
let should_allow = i % 2 == 0;
tasks.push(tokio::spawn(async move {
let result = engine_clone
.evaluate(Method::GET, &format!("https://{}/path", host), "127.0.0.1")
.await;
(should_allow, matches!(result.action, Action::Allow))
}));
}
for task in tasks {
let (should_allow, did_allow) = task.await.unwrap();
assert_eq!(should_allow, did_allow);
}
}
}