forked from microsoft/regorus
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlib.rs
More file actions
654 lines (584 loc) · 19.9 KB
/
Copy pathlib.rs
File metadata and controls
654 lines (584 loc) · 19.9 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
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
use anyhow::{anyhow, Result};
use core::num::{NonZeroU32, NonZeroUsize};
use pyo3::exceptions::PyTypeError;
use pyo3::prelude::*;
use pyo3::types::*;
use pyo3::IntoPyObjectExt;
use std::collections::{BTreeMap, BTreeSet};
use ::regorus::languages::rego::compiler::Compiler;
use ::regorus::rvm::program::{
generate_assembly_listing, generate_tabular_assembly_listing, AssemblyListingConfig,
DeserializationResult, Program as RvmProgram,
};
use ::regorus::rvm::vm::{ExecutionMode, RegoVM};
use ::regorus::{compile_policy_with_entrypoint, PolicyModule, Rc, Value};
use std::sync::Arc;
/// Regorus engine.
#[pyclass(unsendable)]
pub struct Engine {
engine: ::regorus::Engine,
}
/// RVM program wrapper.
#[pyclass(unsendable)]
pub struct Program {
program: Arc<RvmProgram>,
}
/// RVM runtime wrapper.
#[pyclass(unsendable)]
pub struct Rvm {
vm: RegoVM,
}
impl Default for Engine {
fn default() -> Self {
Self::new()
}
}
fn from(ob: &Bound<'_, PyAny>) -> Result<Value, PyErr> {
// dicts
Ok(if let Ok(dict) = ob.cast::<PyDict>() {
let mut map = BTreeMap::new();
for (k, v) in dict {
map.insert(from(&k)?, from(&v)?);
}
map.into()
}
// set
else if let Ok(pset) = ob.cast::<PySet>() {
let mut set = BTreeSet::new();
for v in pset {
set.insert(from(&v)?);
}
set.into()
}
// frozen set
else if let Ok(pfset) = ob.cast::<PyFrozenSet>() {
//
let mut set = BTreeSet::new();
for v in pfset {
set.insert(from(&v)?);
}
set.into()
}
// lists and tuples
else if let Ok(plist) = ob.cast::<PyList>() {
let mut array = Vec::new();
for v in plist {
array.push(from(&v)?);
}
array.into()
} else if let Ok(ptuple) = ob.cast::<PyTuple>() {
let mut array = Vec::new();
for v in ptuple {
array.push(from(&v)?);
}
array.into()
}
// String
else if let Ok(s) = ob.extract::<String>() {
s.into()
}
// Boolean
else if let Ok(b) = ob.extract::<bool>() {
b.into()
}
// Numeric
else if let Ok(v) = ob.extract::<i64>() {
v.into()
} else if let Ok(v) = ob.extract::<u64>() {
v.into()
} else if let Ok(v) = ob.extract::<f64>() {
v.into()
}
// None
else if ob.cast::<PyNone>().is_ok() {
Value::Null
}
// Anything that is a sequence
else if let Ok(pseq) = ob.cast::<PySequence>() {
let mut array = Vec::new();
for i in 0..pseq.len()? {
array.push(from(&pseq.get_item(i)?)?);
}
array.into()
}
// Anything that is a map
else if let Ok(pmap) = ob.cast::<PyMapping>() {
let mut map = BTreeMap::new();
let keys = pmap.keys()?;
let values = pmap.values()?;
for i in 0..keys.len() {
let key = keys.get_item(i)?;
let value = values.get_item(i)?;
map.insert(from(&key)?, from(&value)?);
}
map.into()
} else {
return Err(PyErr::new::<PyTypeError, _>(
"object cannot be converted to RegoValue",
));
})
}
fn to(mut v: Value, py: Python<'_>) -> Result<Py<PyAny>> {
let obj = match v {
Value::Null => None::<u64>.into_bound_py_any(py),
// TODO: Revisit this mapping
Value::Undefined => None::<u64>.into_bound_py_any(py),
Value::Bool(b) => b.into_bound_py_any(py),
Value::String(s) => s.into_bound_py_any(py),
Value::Number(_) => {
if v.as_number()?.is_integer() {
if let Ok(u) = v.as_u64() {
u.into_bound_py_any(py)
} else {
v.as_i64()?.into_bound_py_any(py)
}
} else if let Ok(f) = v.as_f64() {
f.into_bound_py_any(py)
} else {
// fallback
v.as_f64()?.into_bound_py_any(py)
}
}
Value::Array(_) => {
let list = PyList::empty(py);
for v in std::mem::take(v.as_array_mut()?) {
list.append(to(v, py)?)?;
}
list.into_bound_py_any(py)
}
Value::Set(_) => {
let set = PySet::empty(py)?;
for item in v.set_ref()?.iter() {
set.add(to(item.clone(), py)?)?;
}
set.into_bound_py_any(py)
}
Value::Object(_) => {
let dict = PyDict::new(py);
for (k, val) in v.object_ref()?.iter() {
dict.set_item(to(k.clone(), py)?, to(val.clone(), py)?)?;
}
dict.into_bound_py_any(py)
}
};
match obj {
Ok(v) => Ok(v.into()),
Err(e) => Err(anyhow!("{e}")),
}
}
#[pymethods]
impl Engine {
/// Construct a new Engine
#[new]
pub fn new() -> Self {
Self {
engine: ::regorus::Engine::new(),
}
}
/// Turn on rego v0.
///
/// Regorus now defaults to v1.
///
/// * `enable`: Whether to enable/disable v0.
pub fn set_rego_v0(&mut self, enable: bool) {
self.engine.set_rego_v0(enable)
}
/// Add a policy
///
/// The policy is parsed into AST.
///
/// * `path`: A filename to be associated with the policy.
/// * `rego`: Rego policy.
pub fn add_policy(&mut self, path: String, rego: String) -> Result<String> {
self.engine.add_policy(path, rego)
}
/// Add a policy from given file.
///
/// The policy is parsed into AST.
///
/// * `path`: Path to the policy file.
pub fn add_policy_from_file(&mut self, path: String) -> Result<String> {
self.engine.add_policy_from_file(path)
}
/// Get the list of packages defined by loaded policies.
///
pub fn get_packages(&self) -> Result<Vec<String>> {
self.engine.get_packages()
}
/// Get the list of policies.
///
pub fn get_policies(&self) -> Result<String> {
Ok(serde_json::to_string_pretty(
&self.engine.get_policies_as_json()?,
)?)
}
/// Add policy data.
///
/// * `data`: Rego value. A Rego value is a number, bool, string, None
/// or a list/set/map whose items themselves are Rego values.
pub fn add_data(&mut self, data: &Bound<'_, PyAny>) -> Result<()> {
let data = from(data)?;
self.engine.add_data(data)
}
/// Add policy data.
///
/// * `data`: JSON encoded value to be used as policy data.
pub fn add_data_json(&mut self, data: String) -> Result<()> {
let data = Value::from_json_str(&data)?;
self.engine.add_data(data)
}
/// Add policy data from file.
///
/// * `path`: Path to JSON policy data.
pub fn add_data_from_json_file(&mut self, path: String) -> Result<()> {
let data = Value::from_json_file(path)?;
self.engine.add_data(data)
}
/// Clear policy data.
pub fn clear_data(&mut self) -> Result<()> {
self.engine.clear_data();
Ok(())
}
/// Set input.
///
/// * `input`: Rego value. A Rego value is a number, bool, string, None
/// or a list/set/map whose items themselves are Rego values.
pub fn set_input(&mut self, input: &Bound<'_, PyAny>) -> Result<()> {
let input = from(input)?;
self.engine.set_input(input);
Ok(())
}
/// Set input.
///
/// * `input`: JSON encoded value to be used as input to query.
pub fn set_input_json(&mut self, input: String) -> Result<()> {
let input = Value::from_json_str(&input)?;
self.engine.set_input(input);
Ok(())
}
/// Set input.
///
/// * `path`: Path to JSON input data.
pub fn set_input_from_json_file(&mut self, path: String) -> Result<()> {
let input = Value::from_json_file(path)?;
self.engine.set_input(input);
Ok(())
}
/// Evaluate query.
///
/// * `query`: Rego expression to be evaluate.
pub fn eval_query(&mut self, query: String, py: Python<'_>) -> Result<Py<PyAny>> {
let results = self.engine.eval_query(query, false)?;
let rlist = PyList::empty(py);
for result in results.result.into_iter() {
let rdict = PyDict::new(py);
let elist = PyList::empty(py);
for expr in result.expressions.into_iter() {
let edict = PyDict::new(py);
edict.set_item("value", to(expr.value, py)?)?;
edict.set_item("text", expr.text.as_ref())?;
let ldict = PyDict::new(py);
ldict.set_item("row", expr.location.row)?;
ldict.set_item("col", expr.location.col)?;
edict.set_item("location", ldict)?;
elist.append(edict)?;
}
rdict.set_item("expressions", elist)?;
rdict.set_item("bindings", to(result.bindings, py)?)?;
rlist.append(rdict)?;
}
let dict = PyDict::new(py);
dict.set_item("result", rlist)?;
Ok(dict.into())
}
/// Evaluate query. Returns result as JSON.
///
/// * `query`: Rego expression to be evaluate.
pub fn eval_query_as_json(&mut self, query: String) -> Result<String> {
let results = self.engine.eval_query(query, false)?;
serde_json::to_string_pretty(&results).map_err(|e| anyhow!("{e}"))
}
/// Evaluate rule.
///
/// * `rule`: Full path to the rule.
pub fn eval_rule(&mut self, rule: String, py: Python<'_>) -> Result<Py<PyAny>> {
to(self.engine.eval_rule(rule)?, py)
}
/// Evaluate rule and return value as json.
///
/// * `rule`: Full path to the rule.
pub fn eval_rule_as_json(&mut self, rule: String) -> Result<String> {
let v = self.engine.eval_rule(rule)?;
v.to_json_str()
}
/// Registers a custom Python function as a Rego extension.
///
/// This allows you to define functions in Python that can be called directly
/// from your Rego policies. The Python function will be called synchronously
/// during policy evaluation.
///
/// Arguments passed from Rego are automatically converted to their corresponding
/// Python types. The return value is converted back to a Rego value.
///
/// * `path`: Full path to the function as it will be used in Rego.
/// * `nargs`: The number of arguments the function expects.
/// * `extension`: The Python function to execute. Must accept exactly `nargs` arguments.
///
/// Note: When the engine is cloned, extensions share the same Python callable reference
/// rather than being deep-copied. Stateful callables will share state across clones.
pub fn add_extension(&mut self, path: String, nargs: u8, extension: Py<PyAny>) -> Result<()> {
Python::attach(|py| {
if !extension.bind(py).is_callable() {
return Err(anyhow!("extension '{}' must be callable", path));
}
Ok(())
})?;
let func_ref = Arc::new(extension);
let path_clone = path.clone();
let extension_impl = move |args: Vec<Value>| -> Result<Value, anyhow::Error> {
Python::attach(|py| {
let py_args_vec: Result<Vec<Py<PyAny>>> =
args.into_iter().map(|arg| to(arg, py)).collect();
let py_args = PyTuple::new(py, py_args_vec?)?;
let py_result = func_ref.call1(py, py_args).map_err(|e| {
anyhow!("extension '{}' raises Python error: {}", path_clone, e)
})?;
let rego_result = from(&py_result.into_bound(py))?;
Ok(rego_result)
})
};
self.engine
.add_extension(path, nargs, Box::new(extension_impl))
}
/// Set the policy length limits used when loading policies.
///
/// * `max_col`: Maximum column width per line.
/// * `max_file_bytes`: Maximum policy file size in bytes.
/// * `max_lines`: Maximum number of lines per policy file.
#[pyo3(signature = (*, max_col, max_file_bytes, max_lines))]
pub fn set_policy_length_config(
&mut self,
max_col: u32,
max_file_bytes: usize,
max_lines: usize,
) -> Result<()> {
self.engine
.set_policy_length_config(::regorus::PolicyLengthConfig {
max_col: NonZeroU32::new(max_col)
.ok_or_else(|| anyhow!("max_col must be non-zero"))?,
max_file_bytes: NonZeroUsize::new(max_file_bytes)
.ok_or_else(|| anyhow!("max_file_bytes must be non-zero"))?,
max_lines: NonZeroUsize::new(max_lines)
.ok_or_else(|| anyhow!("max_lines must be non-zero"))?,
});
Ok(())
}
/// Clear the policy length configuration, reverting to defaults.
pub fn clear_policy_length_config(&mut self) {
self.engine.clear_policy_length_config();
}
/// Enable code coverage
///
/// * `enable`: Whether to enable coverage or not.
pub fn set_enable_coverage(&mut self, enable: bool) {
self.engine.set_enable_coverage(enable)
}
/// Get coverage report as json.
///
#[cfg(feature = "coverage")]
pub fn get_coverage_report_as_json(&self) -> Result<String> {
let report = self.engine.get_coverage_report()?;
serde_json::to_string_pretty(&report).map_err(|e| anyhow!("{e}"))
}
/// Get coverage report as pretty printable string.
///
#[cfg(feature = "coverage")]
pub fn get_coverage_report_pretty(&self) -> Result<String> {
self.engine.get_coverage_report()?.to_string_pretty()
}
/// Clear coverage data.
///
#[cfg(feature = "coverage")]
pub fn clear_coverage_data(&mut self) {
self.engine.clear_coverage_data();
}
/// Gather print statements instead of printing to stderr.
///
pub fn set_gather_prints(&mut self, b: bool) {
self.engine.set_gather_prints(b)
}
/// Take gathered prints.
///
pub fn take_prints(&mut self) -> Result<Vec<String>> {
self.engine.take_prints()
}
/// Clone a [`Engine`]
///
/// To avoid having to parse same policy again, the engine can be cloned
/// after policies and data have been added.
fn clone(&self) -> Self {
Self {
engine: self.engine.clone(),
}
}
/// Get AST of policies.
///
#[cfg(feature = "ast")]
pub fn get_ast_as_json(&self) -> Result<String> {
self.engine.get_ast_as_json()
}
}
#[pymethods]
impl Program {
/// Compile an RVM program from modules and entry points.
#[staticmethod]
pub fn compile_from_modules(
data_json: String,
modules: Vec<(String, String)>,
entry_points: Vec<String>,
) -> Result<Self> {
if entry_points.is_empty() {
return Err(anyhow!("entry_points must contain at least one entry"));
}
let data = Value::from_json_str(&data_json)?;
let policy_modules: Vec<PolicyModule> = modules
.into_iter()
.map(|(id, content)| PolicyModule {
id: Rc::from(id.as_str()),
content: Rc::from(content.as_str()),
})
.collect();
let entry_points_ref: Vec<&str> = entry_points.iter().map(|s| s.as_str()).collect();
let entry_rule = Rc::from(entry_points_ref[0]);
let compiled = compile_policy_with_entrypoint(data, &policy_modules, entry_rule)?;
let program = Compiler::compile_from_policy(&compiled, &entry_points_ref)?;
Ok(Self { program })
}
/// Deserialize an RVM program from binary data.
#[staticmethod]
pub fn deserialize_binary(data: Vec<u8>) -> Result<(Self, bool)> {
let (program, is_partial) =
match RvmProgram::deserialize_binary(&data).map_err(|e: String| anyhow!(e))? {
DeserializationResult::Complete(program) => (program, false),
DeserializationResult::Partial(program) => (program, true),
};
Ok((
Self {
program: Arc::new(program),
},
is_partial,
))
}
/// Serialize a program to binary format.
pub fn serialize_binary(&self) -> Result<Vec<u8>> {
self.program
.serialize_binary()
.map_err(|e: String| anyhow!(e))
}
/// Generate a readable assembly listing.
pub fn generate_listing(&self) -> Result<String> {
Ok(generate_assembly_listing(
self.program.as_ref(),
&AssemblyListingConfig::default(),
))
}
/// Generate a tabular assembly listing.
pub fn generate_tabular_listing(&self) -> Result<String> {
Ok(generate_tabular_assembly_listing(
self.program.as_ref(),
&AssemblyListingConfig::default(),
))
}
}
impl Default for Rvm {
fn default() -> Self {
Self::new()
}
}
#[pymethods]
impl Rvm {
#[new]
pub fn new() -> Self {
Self { vm: RegoVM::new() }
}
/// Load an RVM program into the VM.
pub fn load_program(&mut self, program: &Program) -> Result<()> {
self.vm.load_program(program.program.clone());
Ok(())
}
/// Set data JSON for the VM.
pub fn set_data_json(&mut self, data_json: String) -> Result<()> {
let data = Value::from_json_str(&data_json)?;
self.vm.set_data(data)?;
Ok(())
}
/// Set input JSON for the VM.
pub fn set_input_json(&mut self, input_json: String) -> Result<()> {
let input = Value::from_json_str(&input_json)?;
self.vm.set_input(input);
Ok(())
}
/// Set execution mode (0 = run-to-completion, 1 = suspendable).
pub fn set_execution_mode(&mut self, mode: u8) -> Result<()> {
let mode = match mode {
0 => ExecutionMode::RunToCompletion,
1 => ExecutionMode::Suspendable,
_ => return Err(anyhow!("invalid execution mode")),
};
self.vm.set_execution_mode(mode);
Ok(())
}
/// Execute the program and return the JSON result.
pub fn execute(&mut self) -> Result<String> {
self.vm.execute()?.to_json_str()
}
/// Execute an entry point by name and return the JSON result.
pub fn execute_entry_point(&mut self, entry_point: String) -> Result<String> {
self.vm
.execute_entry_point_by_name(&entry_point)?
.to_json_str()
}
/// Resume execution with an optional JSON value.
pub fn resume(&mut self, resume_json: Option<String>) -> Result<String> {
let value = if let Some(json) = resume_json {
Some(Value::from_json_str(&json)?)
} else {
None
};
self.vm.resume(value)?.to_json_str()
}
/// Get the execution state as a string.
pub fn get_execution_state(&self) -> Result<String> {
Ok(format!("{:?}", self.vm.execution_state()))
}
}
/// Configure the global pattern caches used by `regex.*` and `glob.*` builtins.
///
/// * `regex`: Maximum cached compiled regex patterns (default 256, 0 = disabled).
/// * `glob`: Maximum cached compiled glob matchers (default 128, 0 = disabled).
#[cfg(feature = "cache")]
#[pyfunction]
#[pyo3(signature = (*, regex = 256, glob = 128))]
fn set_cache_config(regex: usize, glob: usize) {
::regorus::cache::configure(::regorus::cache::Config { regex, glob });
}
/// Clear all entries from every pattern cache.
#[cfg(feature = "cache")]
#[pyfunction]
fn clear_cache() {
::regorus::cache::clear();
}
#[pymodule]
pub fn regorus(_py: Python<'_>, m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<crate::Engine>()?;
m.add_class::<crate::Program>()?;
m.add_class::<crate::Rvm>()?;
#[cfg(feature = "cache")]
{
m.add_function(wrap_pyfunction!(set_cache_config, m)?)?;
m.add_function(wrap_pyfunction!(clear_cache, m)?)?;
}
Ok(())
}