opa_wasm/types.rs
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
// Copyright 2022-2024 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! Type wrappers to help with interacting with the OPA WASM module
use std::ffi::CStr;
use anyhow::{bail, Context, Result};
use serde::Deserialize;
use wasmtime::{AsContext, AsContextMut, Instance, Memory};
/// An entrypoint ID, as returned by the `entrypoints` export, and given to the
/// `opa_eval_ctx_set_entrypoint` exports
#[derive(Debug, Deserialize, Clone)]
#[serde(transparent)]
pub struct EntrypointId(pub(crate) i32);
/// The ID of a builtin, as returned by the `builtins` export, and passed to the
/// `opa_builtin*` imports
#[derive(Debug, Deserialize, Clone)]
#[serde(transparent)]
pub struct BuiltinId(pub(crate) i32);
/// A value stored on the WASM heap, as used by the `opa_value_*` exports
#[derive(Debug)]
pub struct Value(pub(crate) i32);
/// A generic value on the WASM memory
#[derive(Debug)]
pub struct Addr(pub(crate) i32);
/// A heap allocation on the WASM memory
#[derive(Debug)]
pub struct Heap {
/// The pointer to the start of the heap allocation
pub(crate) ptr: i32,
/// The length of the heap allocation
pub(crate) len: i32,
/// Whether the heap allocation has been freed
pub(crate) freed: bool,
}
impl Heap {
/// Get the end of the heap allocation
pub const fn end(&self) -> i32 {
self.ptr + self.len
}
/// Calculate the number of pages this heap allocation occupies
pub fn pages(&self) -> u64 {
let page_size = 64 * 1024;
let addr = self.end();
let page = addr / page_size;
// This is safe as the heap pointers will never be negative. We use i32 for
// convenience to avoid having to cast all the time.
#[allow(clippy::expect_used)]
if addr % page_size > 0 { page + 1 } else { page }
.try_into()
.expect("invalid heap address")
}
}
impl Drop for Heap {
fn drop(&mut self) {
if !self.freed {
tracing::warn!("forgot to free heap allocation");
self.freed = true;
}
}
}
/// A null-terminated string on the WASM memory
#[derive(Debug)]
pub struct NulStr(pub(crate) i32);
impl NulStr {
/// Read the null-terminated string from the WASM memory
pub fn read<'s, T: AsContext>(&self, store: &'s T, memory: &Memory) -> Result<&'s CStr> {
let mem = memory.data(store);
let start: usize = self.0.try_into().context("invalid address")?;
let mem = mem.get(start..).context("memory address out of bounds")?;
let nul = mem
.iter()
.position(|c| *c == 0)
.context("malformed string")?;
let mem = mem
.get(..=nul)
.context("issue while extracting nul-terminated string")?;
let res = CStr::from_bytes_with_nul(mem)?;
Ok(res)
}
}
/// The address of the evaluation context, used by the `opa_eval_ctx_*` exports
#[derive(Debug)]
pub struct Ctx(pub(crate) i32);
/// An error returned by the OPA module
#[derive(Debug, thiserror::Error)]
pub enum OpaError {
/// Unrecoverable internal error
#[error("Unrecoverable internal error")]
Internal,
/// Invalid value type was encountered
#[error("Invalid value type was encountered")]
InvalidType,
/// Invalid object path reference
#[error("Invalid object path reference")]
InvalidPath,
/// Unrecognized error code
#[error("Unrecognized error code: {0}")]
Other(i32),
}
impl OpaError {
/// Convert an error code to an `OpaError`
pub(crate) fn from_code(code: i32) -> Result<(), OpaError> {
match code {
0 => Ok(()),
1 => Err(Self::Internal),
2 => Err(Self::InvalidType),
3 => Err(Self::InvalidPath),
x => Err(Self::Other(x)),
}
}
}
/// Represents the ABI version of a WASM OPA module
#[derive(Debug, Clone, Copy)]
pub enum AbiVersion {
/// Version 1.0
V1_0,
/// Version 1.1
V1_1,
/// Version 1.2
V1_2,
/// Version >1.2, <2.0
V1_2Plus(i32),
}
impl AbiVersion {
/// Get the ABI version out of an instanciated WASM policy
///
/// # Errors
///
/// Returns an error if the WASM module lacks ABI version information
pub(crate) fn from_instance<T: Send>(
mut store: impl AsContextMut<Data = T>,
instance: &Instance,
) -> Result<Self> {
let abi_version = instance
.get_global(&mut store, "opa_wasm_abi_version")
.context("missing global opa_wasm_abi_version")?
.get(&mut store)
.i32()
.context("opa_wasm_abi_version is not an i32")?;
let abi_minor_version = instance
.get_global(&mut store, "opa_wasm_abi_minor_version")
.context("missing global opa_wasm_abi_minor_version")?
.get(&mut store)
.i32()
.context("opa_wasm_abi_minor_version is not an i32")?;
Self::new(abi_version, abi_minor_version)
}
/// Create a new ABI version out of the minor and major version numbers.
fn new(major: i32, minor: i32) -> Result<Self> {
match (major, minor) {
(1, 0) => Ok(Self::V1_0),
(1, 1) => Ok(Self::V1_1),
(1, 2) => Ok(Self::V1_2),
(1, n @ 2..) => Ok(Self::V1_2Plus(n)),
(major, minor) => bail!("unsupported ABI version {}.{}", major, minor),
}
}
/// Check if this ABI version has support for the `eval` fastpath
#[must_use]
pub(crate) const fn has_eval_fastpath(self) -> bool {
matches!(self, Self::V1_2 | Self::V1_2Plus(_))
}
}
impl std::fmt::Display for AbiVersion {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
AbiVersion::V1_0 => write!(f, "1.0"),
AbiVersion::V1_1 => write!(f, "1.1"),
AbiVersion::V1_2 => write!(f, "1.2"),
AbiVersion::V1_2Plus(n) => write!(f, "1.{n} (1.2+ compatible)"),
}
}
}