Skip to main content

rpc/
template.rs

1//! Template render entry point.
2//!
3//! A template is per-user nomiscript source that pre-fills a transaction draft.
4//! [`compile_template`] validates source against the restricted render compiler
5//! surface (a template naming any non-allowlisted native is a compile error).
6//! [`render_template`] runs it under [`link_render`](crate::natives::link_render)
7//! — a linker that registers only the read-only financial natives and the draft
8//! natives, never the config/user/ssh secret surface — and returns the
9//! accumulated [`TransactionDraft`].
10//!
11//! Both gates (compiler whitelist + linker omission) are load-bearing for token
12//! security: Slice B keeps the per-user JWT private key in the same per-user DB
13//! the eval channel reads, so an escape here would let a template exfiltrate the
14//! signing key. The whitelist test suite (`tests/`) is treated as a security
15//! gate.
16
17use std::sync::{Arc, Mutex};
18
19use nomiscript::{Compiler, Program, Reader, SymbolTable};
20use scripting::runtime::{EngineError, classify_runtime_error};
21use thiserror::Error;
22use wasmtime::{AnyRef, Linker, Rooted, Store, Val};
23
24use crate::ctx::ScriptCtx;
25use crate::draft::TransactionDraft;
26use crate::envelope::ErrorCode;
27use crate::host_failure::is_host_failure;
28use crate::session::SessionData;
29use crate::session::payload::restore_host_condition;
30use crate::wasm::{EngineOpts, build_engine};
31
32const RENDER_EPOCH_TICKS: u64 = 1;
33
34#[derive(Debug, Error)]
35pub enum TemplateError {
36    /// Source failed to parse or referenced a native outside the render
37    /// whitelist (or any other compile error).
38    #[error("template compile error: {0}")]
39    Compile(String),
40    /// The wasm engine / instantiation failed.
41    #[error("template engine error: {0}")]
42    Engine(String),
43    /// A draft native trapped at runtime (bad arg, missing entity, …).
44    #[error("template render error: {0}")]
45    Runtime(String),
46    /// A native failed on host infrastructure (database, config, server), not
47    /// because of the script.
48    #[error("template host failure: {0}")]
49    Host(String),
50    /// A native could not reach the database right now; rendering again may succeed.
51    #[error("template unavailable: {0}")]
52    Unavailable(String),
53}
54
55impl TemplateError {
56    /// True for failures the template author did not cause and must not see.
57    #[must_use]
58    pub fn is_internal(&self) -> bool {
59        matches!(self, Self::Engine(_) | Self::Host(_) | Self::Unavailable(_))
60    }
61}
62
63/// Compiles `source` against the restricted render surface, returning the wasm
64/// bytes. A template that names a non-allowlisted native fails here with a
65/// [`TemplateError::Compile`] — this is the first half of the security gate
66/// (the compiler simply doesn't know the dangerous natives exist).
67pub fn compile_template(source: &str) -> Result<Vec<u8>, TemplateError> {
68    let (_, bytes) = compile_render_program(source)?;
69    Ok(bytes)
70}
71
72/// [`compile_template`] as the one save-time check: the refusal message for a
73/// source that does not compile against the render surface.
74///
75/// # Errors
76/// The message of the compile failure.
77pub fn validate_source(source: &str) -> Result<(), String> {
78    compile_template(source)
79        .map(drop)
80        .map_err(|err| format!("Template does not compile: {err}"))
81}
82
83fn compile_render_program(source: &str) -> Result<(Program, Vec<u8>), TemplateError> {
84    let host_fns = crate::natives::render_compiler_specs();
85    let mut symbols = SymbolTable::with_builtins();
86    symbols.register_host_fns(&host_fns);
87    crate::host_prelude::load(&mut symbols)
88        .map_err(|err| TemplateError::Compile(format!("host prelude: {err}")))?;
89    let mut compiler = Compiler::with_host_fns(host_fns);
90    let program = Reader::parse(source).map_err(|err| TemplateError::Compile(err.to_string()))?;
91    let (bytes, _ty) = compiler
92        .compile_eval_with_type(&program, &mut symbols)
93        .map_err(|err| TemplateError::Compile(err.to_string()))?;
94    Ok((program, bytes))
95}
96
97/// Renders `source` for `ctx`'s user, returning the accumulated draft. Runs the
98/// program form-by-form under the render linker (read-only financial natives +
99/// draft natives only). The final value of each form is ignored; only the draft
100/// side effects matter.
101pub async fn render_template(
102    ctx: &ScriptCtx,
103    source: &str,
104) -> Result<TransactionDraft, TemplateError> {
105    let host_fns = crate::natives::render_compiler_specs();
106    let mut symbols = SymbolTable::with_builtins();
107    symbols.register_host_fns(&host_fns);
108    crate::host_prelude::load(&mut symbols)
109        .map_err(|err| TemplateError::Compile(format!("host prelude: {err}")))?;
110    let mut compiler = Compiler::with_host_fns(host_fns);
111    let program = Reader::parse(source).map_err(|err| TemplateError::Compile(err.to_string()))?;
112
113    let engine = build_engine(EngineOpts::baseline().with_fuel())
114        .map_err(|err| TemplateError::Engine(err.to_string()))?;
115    let mut linker: Linker<SessionData> = Linker::new(&engine);
116    crate::natives::link_render(&mut linker)
117        .map_err(|err| TemplateError::Engine(err.to_string()))?;
118
119    let output = Arc::new(Mutex::new(String::new()));
120    let mut store: Store<SessionData> =
121        Store::new(&engine, SessionData::for_render(ctx.clone(), output));
122    store
123        .set_fuel(ctx.limits.fuel)
124        .map_err(|err| TemplateError::Engine(err.to_string()))?;
125    store.set_epoch_deadline(RENDER_EPOCH_TICKS);
126
127    for form in program.exprs {
128        let single = Program::new(vec![form]);
129        let (bytes, _ty) = compiler
130            .compile_eval_with_type(&single, &mut symbols)
131            .map_err(|err| TemplateError::Compile(err.to_string()))?;
132        let module = scripting::runtime::compile_module(&engine, &bytes)
133            .map_err(|err| TemplateError::Engine(err.to_string()))?;
134        let instance = linker
135            .instantiate_async(&mut store, &module)
136            .await
137            .map_err(|err| TemplateError::Engine(classify_engine(&err)))?;
138        let func = instance.get_func(&mut store, "nomi-eval").ok_or_else(|| {
139            TemplateError::Engine("render module missing nomi-eval export".to_string())
140        })?;
141        let mut results = [Val::AnyRef(None)];
142        func.call_async(&mut store, &[], &mut results)
143            .await
144            .map_err(|err| runtime_error(&err))?;
145        let _: Option<Rooted<AnyRef>> = match results[0] {
146            Val::AnyRef(a) => a,
147            _ => None,
148        };
149    }
150
151    Ok(store.into_data().into_draft().unwrap_or_default())
152}
153
154fn runtime_error(err: &wasmtime::Error) -> TemplateError {
155    let engine = restore_host_condition(classify_runtime_error(err));
156    let unavailable = matches!(
157        &engine,
158        EngineError::HostCondition { code, .. } if code == ErrorCode::UNAVAILABLE
159    );
160    let message = engine_message(engine);
161    if unavailable {
162        return TemplateError::Unavailable(message);
163    }
164    if is_host_failure(err) {
165        return TemplateError::Host(message);
166    }
167    TemplateError::Runtime(message)
168}
169
170fn classify_engine(err: &wasmtime::Error) -> String {
171    engine_message(restore_host_condition(classify_runtime_error(err)))
172}
173
174fn engine_message(engine: EngineError) -> String {
175    match engine {
176        EngineError::ScriptRaised { code, message, .. } => format!("{code}: {message}"),
177        other => other.to_string(),
178    }
179}
180
181#[cfg(test)]
182mod tests;