regorus 0.9.0

A fast, lightweight Rego (OPA policy language) interpreter
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using System;
using System.Runtime.InteropServices;
using System.Text;
using Regorus.Internal;


#nullable enable
namespace Regorus
{
    /// <summary>
    /// C# Wrapper for the Regorus engine.
    /// This class is not thread-safe. For multithreaded use, prefer cloning after adding policies and data to an instance.
    /// Cloning is cheap and involves only incrementing reference counts for shared immutable objects like parsed policies,
    /// data etc. Mutable state is deep copied as needed.
    /// </summary>
    public unsafe sealed class Engine : IDisposable
    {
        private RegorusEngineHandle? _handle;
        private int _isDisposed;

        public Engine()
        {
            _handle = RegorusEngineHandle.Create();
        }

        public static void SetFallbackExecutionTimerConfig(ExecutionTimerConfig config)
        {
            var nativeConfig = config.ToNative();
            CheckAndDropResult(Regorus.Internal.API.regorus_set_fallback_execution_timer_config(nativeConfig));
        }

        public static void ClearFallbackExecutionTimerConfig()
        {
            CheckAndDropResult(Regorus.Internal.API.regorus_clear_fallback_execution_timer_config());
        }

        public void Dispose()
        {
            Dispose(disposing: true);

            // This object will be cleaned up by the Dispose method.
            // Therefore, call GC.SuppressFinalize to
            // take this object off the finalization queue
            // and prevent finalization code for this object
            // from executing a second time.
            GC.SuppressFinalize(this);
        }

        // Dispose(bool disposing) executes in two distinct scenarios.
        // If disposing equals true, the method has been called directly
        // or indirectly by a user's code. Managed and unmanaged resources
        // can be disposed.
        // If disposing equals false, the method has been called by the
        // runtime from inside the finalizer and you should not reference
        // other objects. Only unmanaged resources can be disposed.
        void Dispose(bool disposing)
        {
            if (System.Threading.Interlocked.CompareExchange(ref _isDisposed, 1, 0) == 0)
            {
                _handle?.Dispose();
                _handle = null;
            }
        }

        private Engine(RegorusEngineHandle handle)
        {
            _handle = handle ?? throw new ArgumentNullException(nameof(handle));
        }

        public Engine Clone()
        {
            ThrowIfDisposed();
            return UseHandle(enginePtr =>
            {
                unsafe
                {
                    var clonePtr = Regorus.Internal.API.regorus_engine_clone((Regorus.Internal.RegorusEngine*)enginePtr);
                    if (clonePtr is null)
                    {
                        throw new InvalidOperationException("Failed to clone Regorus engine.");
                    }

                    var handle = RegorusEngineHandle.FromPointer((IntPtr)clonePtr);
                    return new Engine(handle);
                }
            });
        }

        public void SetStrictBuiltinErrors(bool strict)
        {
            ThrowIfDisposed();
            UseHandle(enginePtr =>
            {
                unsafe
                {
                    CheckAndDropResult(Regorus.Internal.API.regorus_engine_set_strict_builtin_errors((Regorus.Internal.RegorusEngine*)enginePtr, strict));
                }
            });
        }

        public void SetExecutionTimerConfig(ExecutionTimerConfig config)
        {
            ThrowIfDisposed();
            var nativeConfig = config.ToNative();
            UseHandle(enginePtr =>
            {
                unsafe
                {
                    var localConfig = nativeConfig;
                    CheckAndDropResult(Regorus.Internal.API.regorus_engine_set_execution_timer_config((Regorus.Internal.RegorusEngine*)enginePtr, &localConfig));
                }
            });
        }

        public void ClearExecutionTimerConfig()
        {
            ThrowIfDisposed();
            UseHandle(enginePtr =>
            {
                unsafe
                {
                    CheckAndDropResult(Regorus.Internal.API.regorus_engine_clear_execution_timer_config((Regorus.Internal.RegorusEngine*)enginePtr));
                }
            });
        }
        public string? AddPolicy(string path, string rego)
        {
            ThrowIfDisposed();
            return Utf8Marshaller.WithUtf8(path, pathPtr =>
                Utf8Marshaller.WithUtf8(rego, regoPtr =>
                {
                    unsafe
                    {
                        return UseHandle(enginePtr =>
                        {
                            unsafe
                            {
                                return CheckAndDropResult(Regorus.Internal.API.regorus_engine_add_policy((Regorus.Internal.RegorusEngine*)enginePtr, (byte*)pathPtr, (byte*)regoPtr));
                            }
                        });
                    }
                }));
        }

        public void SetRegoV0(bool enable)
        {
            ThrowIfDisposed();
            UseHandle(enginePtr =>
            {
                unsafe
                {
                    CheckAndDropResult(Regorus.Internal.API.regorus_engine_set_rego_v0((Regorus.Internal.RegorusEngine*)enginePtr, enable));
                }
            });
        }

        public string? AddPolicyFromFile(string path)
        {
            ThrowIfDisposed();
            return Utf8Marshaller.WithUtf8(path, pathPtr =>
            {
                unsafe
                {
                    return UseHandle(enginePtr =>
                    {
                        unsafe
                        {
                            return CheckAndDropResult(Regorus.Internal.API.regorus_engine_add_policy_from_file((Regorus.Internal.RegorusEngine*)enginePtr, (byte*)pathPtr));
                        }
                    });
                }
            });

        }

        public void AddDataJson(string data)
        {
            ThrowIfDisposed();
            Utf8Marshaller.WithUtf8(data, dataPtr =>
            {
                unsafe
                {
                    UseHandle(enginePtr =>
                    {
                        unsafe
                        {
                            CheckAndDropResult(Regorus.Internal.API.regorus_engine_add_data_json((Regorus.Internal.RegorusEngine*)enginePtr, (byte*)dataPtr));
                        }
                    });
                }
            });

        }

        public void AddDataFromJsonFile(string path)
        {
            ThrowIfDisposed();
            Utf8Marshaller.WithUtf8(path, pathPtr =>
            {
                unsafe
                {
                    UseHandle(enginePtr =>
                    {
                        unsafe
                        {
                            CheckAndDropResult(Regorus.Internal.API.regorus_engine_add_data_from_json_file((Regorus.Internal.RegorusEngine*)enginePtr, (byte*)pathPtr));
                        }
                    });
                }
            });

        }

        public void SetInputJson(string input)
        {
            ThrowIfDisposed();
            Utf8Marshaller.WithUtf8(input, inputPtr =>
            {
                unsafe
                {
                    UseHandle(enginePtr =>
                    {
                        unsafe
                        {
                            CheckAndDropResult(Regorus.Internal.API.regorus_engine_set_input_json((Regorus.Internal.RegorusEngine*)enginePtr, (byte*)inputPtr));
                        }
                    });
                }
            });
        }

        public void SetInputFromJsonFile(string path)
        {
            ThrowIfDisposed();
            Utf8Marshaller.WithUtf8(path, pathPtr =>
            {
                unsafe
                {
                    UseHandle(enginePtr =>
                    {
                        unsafe
                        {
                            CheckAndDropResult(Regorus.Internal.API.regorus_engine_set_input_from_json_file((Regorus.Internal.RegorusEngine*)enginePtr, (byte*)pathPtr));
                        }
                    });
                }
            });
        }

        public string? EvalQuery(string query)
        {
            ThrowIfDisposed();
            return Utf8Marshaller.WithUtf8(query, queryPtr =>
            {
                unsafe
                {
                    return UseHandle(enginePtr =>
                    {
                        unsafe
                        {
                            return CheckAndDropResult(Regorus.Internal.API.regorus_engine_eval_query((Regorus.Internal.RegorusEngine*)enginePtr, (byte*)queryPtr));
                        }
                    });
                }
            });
        }

        public string? EvalRule(string rule)
        {
            ThrowIfDisposed();
            return Utf8Marshaller.WithUtf8(rule, rulePtr =>
            {
                unsafe
                {
                    return UseHandle(enginePtr =>
                    {
                        unsafe
                        {
                            return CheckAndDropResult(Regorus.Internal.API.regorus_engine_eval_rule((Regorus.Internal.RegorusEngine*)enginePtr, (byte*)rulePtr));
                        }
                    });
                }
            });
        }

        public void SetEnableCoverage(bool enable)
        {
            ThrowIfDisposed();
            UseHandle(enginePtr =>
            {
                unsafe
                {
                    CheckAndDropResult(Regorus.Internal.API.regorus_engine_set_enable_coverage((Regorus.Internal.RegorusEngine*)enginePtr, enable));
                }
            });
        }

        public void ClearCoverageData()
        {
            ThrowIfDisposed();
            UseHandle(enginePtr =>
            {
                unsafe
                {
                    CheckAndDropResult(Regorus.Internal.API.regorus_engine_clear_coverage_data((Regorus.Internal.RegorusEngine*)enginePtr));
                }
            });
        }

        public string? GetCoverageReport()
        {
            ThrowIfDisposed();
            return UseHandle(enginePtr =>
            {
                unsafe
                {
                    return CheckAndDropResult(Regorus.Internal.API.regorus_engine_get_coverage_report((Regorus.Internal.RegorusEngine*)enginePtr));
                }
            });
        }

        public string? GetCoverageReportPretty()
        {
            ThrowIfDisposed();
            return UseHandle(enginePtr =>
            {
                unsafe
                {
                    return CheckAndDropResult(Regorus.Internal.API.regorus_engine_get_coverage_report_pretty((Regorus.Internal.RegorusEngine*)enginePtr));
                }
            });
        }

        public void SetGatherPrints(bool enable)
        {
            ThrowIfDisposed();
            UseHandle(enginePtr =>
            {
                unsafe
                {
                    CheckAndDropResult(Regorus.Internal.API.regorus_engine_set_gather_prints((Regorus.Internal.RegorusEngine*)enginePtr, enable));
                }
            });
        }

        public string? TakePrints()
        {
            ThrowIfDisposed();
            return UseHandle(enginePtr =>
            {
                unsafe
                {
                    return CheckAndDropResult(Regorus.Internal.API.regorus_engine_take_prints((Regorus.Internal.RegorusEngine*)enginePtr));
                }
            });
        }

        public string? GetAstAsJson()
        {
            ThrowIfDisposed();
            return UseHandle(enginePtr =>
            {
                unsafe
                {
                    return CheckAndDropResult(Regorus.Internal.API.regorus_engine_get_ast_as_json((Regorus.Internal.RegorusEngine*)enginePtr));
                }
            });
        }

        public string? GetPolicyPackageNames()
        {
            ThrowIfDisposed();
            return UseHandle(enginePtr =>
            {
                unsafe
                {
                    return CheckAndDropResult(Regorus.Internal.API.regorus_engine_get_policy_package_names((Regorus.Internal.RegorusEngine*)enginePtr));
                }
            });
        }

        public string? GetPolicyParameters()
        {
            ThrowIfDisposed();
            return UseHandle(enginePtr =>
            {
                unsafe
                {
                    return CheckAndDropResult(Regorus.Internal.API.regorus_engine_get_policy_parameters((Regorus.Internal.RegorusEngine*)enginePtr));
                }
            });
        }

    private static string? StringFromUtf8(IntPtr ptr)
        {

#if NETSTANDARD2_1
			return Marshal.PtrToStringUTF8(ptr);
#else
            int len = 0;
            while (Marshal.ReadByte(ptr, len) != 0) { ++len; }
            byte[] buffer = new byte[len];
            Marshal.Copy(ptr, buffer, 0, buffer.Length);
            return Encoding.UTF8.GetString(buffer);
#endif
        }

    private static string? CheckAndDropResult(Regorus.Internal.RegorusResult result)
        {
            try
            {
                if (result.status != Regorus.Internal.RegorusStatus.Ok)
                {
                    var message = Utf8Marshaller.FromUtf8(result.error_message);
                    throw result.status.CreateException(message);
                }

                return result.data_type switch
                {
                    Regorus.Internal.RegorusDataType.String => Utf8Marshaller.FromUtf8(result.output),
                    Regorus.Internal.RegorusDataType.Boolean => result.bool_value.ToString().ToLowerInvariant(),
                    Regorus.Internal.RegorusDataType.Integer => result.int_value.ToString(),
                    Regorus.Internal.RegorusDataType.None => null,
                    _ => Utf8Marshaller.FromUtf8(result.output)
                };
            }
            finally
            {
                Regorus.Internal.API.regorus_result_drop(result);
            }
        }

        private void ThrowIfDisposed()
        {
            if (_isDisposed != 0 || _handle is null || _handle.IsClosed)
            {
                throw new ObjectDisposedException(nameof(Engine));
            }
        }

        internal RegorusEngineHandle GetHandleForUse()
        {
            var handle = _handle;
            if (handle is null || handle.IsClosed || handle.IsInvalid)
            {
                throw new ObjectDisposedException(nameof(Engine));
            }
            return handle;
        }

        internal void UseHandle(Action<IntPtr> action)
        {
            UseHandle<object?>(handlePtr =>
            {
                action(handlePtr);
                return null;
            });
        }

        internal T UseHandle<T>(Func<IntPtr, T> func)
        {
            var handle = GetHandleForUse();
            bool addedRef = false;
            try
            {
                handle.DangerousAddRef(ref addedRef);
                var pointer = handle.DangerousGetHandle();
                if (pointer == IntPtr.Zero)
                {
                    throw new ObjectDisposedException(nameof(Engine));
                }

                return func(pointer);
            }
            finally
            {
                if (addedRef)
                {
                    handle.DangerousRelease();
                }
            }
        }

        internal T UseHandleForInterop<T>(Func<IntPtr, T> func)
        {
            return UseHandle(func);
        }

    }
}