opa/
lib.rs

1#![warn(clippy::pedantic)]
2
3use serde::{de::DeserializeOwned, Serialize};
4
5#[cfg(feature = "bundle")]
6pub mod bundle;
7
8#[cfg(feature = "http")]
9pub mod http;
10
11#[cfg(any(feature = "wasmtime-cranelift", feature = "wasmtime-aot"))]
12pub mod wasm;
13
14#[cfg(feature = "build")]
15pub mod build;
16
17/// A helper trait for defining strongly-typed input/decision pairs
18/// for given policies.
19pub trait PolicyDecision {
20    /// A `.` or `/` separated path to the policy decision.
21    const POLICY_PATH: &'static str;
22
23    /// The input type for the decision.
24    type Input: Serialize;
25
26    /// The output type expected to be returned by OPA.
27    type Output: DeserializeOwned;
28}
29
30/// Include a bundle built at compile-time.
31///
32/// # Example
33///
34/// Build the policy with `opa`:
35///
36/// ```rust,ignore
37/// opa::build::policy("example")
38///     .add_source("./example.rego")
39///     .add_entrypoint("example.project_permissions")
40///     .compile()
41///     .unwrap();
42/// ```
43///
44/// Then include the bundle:
45///
46/// ```rust,ignore
47/// let bundle = include_policy!("example");
48/// ```
49///
50#[cfg(all(feature = "bundle", feature = "build"))]
51#[macro_export]
52macro_rules! include_policy {
53    ($name:literal) => {{
54        let mut bundle = $crate::bundle::Bundle::from_bytes(include_bytes!(concat!(
55            env!("OUT_DIR"),
56            "/opa/",
57            $name,
58            ".tar.gz"
59        )))
60        .unwrap();
61
62        $crate::include_aot!($name, bundle);
63
64        bundle
65    }};
66}
67
68#[doc(hidden)]
69pub mod private {
70    pub use bytes;
71}
72
73#[cfg(all(feature = "build", feature = "wasmtime-aot"))]
74#[doc(hidden)]
75#[macro_export]
76macro_rules! include_aot {
77    ($name:literal, $bundle:ident) => {
78        let b = include_bytes!(concat!(env!("OUT_DIR"), "/opa/", $name, ".cwasm"));
79        
80        if !b.is_empty() {
81            // SAFETY: The WASM module was compiled by
82            // this library in a build script, so it is correct.
83            unsafe { $bundle.set_wasmtime_bytes($crate::private::bytes::Bytes::from(&b[..])) }
84        }
85    };
86}
87
88#[cfg(all(feature = "build", not(feature = "wasmtime-aot")))]
89#[doc(hidden)]
90#[macro_export]
91macro_rules! include_aot {
92    ($name:literal, $bundle:ident) => {};
93}