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

            
17
use std::sync::{Arc, Mutex};
18

            
19
use nomiscript::{Compiler, Program, Reader, SymbolTable};
20
use scripting::runtime::{EngineError, classify_runtime_error};
21
use thiserror::Error;
22
use wasmtime::{AnyRef, Linker, Rooted, Store, Val};
23

            
24
use crate::ctx::ScriptCtx;
25
use crate::draft::TransactionDraft;
26
use crate::envelope::ErrorCode;
27
use crate::host_failure::is_host_failure;
28
use crate::session::SessionData;
29
use crate::session::payload::restore_host_condition;
30
use crate::wasm::{EngineOpts, build_engine};
31

            
32
const RENDER_EPOCH_TICKS: u64 = 1;
33

            
34
#[derive(Debug, Error)]
35
pub 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

            
55
impl TemplateError {
56
    /// True for failures the template author did not cause and must not see.
57
    #[must_use]
58
1610
    pub fn is_internal(&self) -> bool {
59
1610
        matches!(self, Self::Engine(_) | Self::Host(_) | Self::Unavailable(_))
60
1610
    }
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).
67
6428
pub fn compile_template(source: &str) -> Result<Vec<u8>, TemplateError> {
68
6428
    let (_, bytes) = compile_render_program(source)?;
69
4980
    Ok(bytes)
70
6428
}
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.
77
3060
pub fn validate_source(source: &str) -> Result<(), String> {
78
3060
    compile_template(source)
79
3060
        .map(drop)
80
484
        .map_err(|err| format!("Template does not compile: {err}"))
81
3060
}
82

            
83
6428
fn compile_render_program(source: &str) -> Result<(Program, Vec<u8>), TemplateError> {
84
6428
    let host_fns = crate::natives::render_compiler_specs();
85
6428
    let mut symbols = SymbolTable::with_builtins();
86
6428
    symbols.register_host_fns(&host_fns);
87
6428
    crate::host_prelude::load(&mut symbols)
88
        .map_err(|err| TemplateError::Compile(format!("host prelude: {err}")))?;
89
6428
    let mut compiler = Compiler::with_host_fns(host_fns);
90
6428
    let program = Reader::parse(source).map_err(|err| TemplateError::Compile(err.to_string()))?;
91
5624
    let (bytes, _ty) = compiler
92
5624
        .compile_eval_with_type(&program, &mut symbols)
93
644
        .map_err(|err| TemplateError::Compile(err.to_string()))?;
94
4980
    Ok((program, bytes))
95
6428
}
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.
101
6588
pub async fn render_template(
102
6588
    ctx: &ScriptCtx,
103
6588
    source: &str,
104
6588
) -> Result<TransactionDraft, TemplateError> {
105
6588
    let host_fns = crate::natives::render_compiler_specs();
106
6588
    let mut symbols = SymbolTable::with_builtins();
107
6588
    symbols.register_host_fns(&host_fns);
108
6588
    crate::host_prelude::load(&mut symbols)
109
        .map_err(|err| TemplateError::Compile(format!("host prelude: {err}")))?;
110
6588
    let mut compiler = Compiler::with_host_fns(host_fns);
111
6588
    let program = Reader::parse(source).map_err(|err| TemplateError::Compile(err.to_string()))?;
112

            
113
6586
    let engine = build_engine(EngineOpts::baseline().with_fuel())
114
        .map_err(|err| TemplateError::Engine(err.to_string()))?;
115
6586
    let mut linker: Linker<SessionData> = Linker::new(&engine);
116
6586
    crate::natives::link_render(&mut linker)
117
        .map_err(|err| TemplateError::Engine(err.to_string()))?;
118

            
119
6586
    let output = Arc::new(Mutex::new(String::new()));
120
    let mut store: Store<SessionData> =
121
6586
        Store::new(&engine, SessionData::for_render(ctx.clone(), output));
122
6586
    store
123
6586
        .set_fuel(ctx.limits.fuel)
124
        .map_err(|err| TemplateError::Engine(err.to_string()))?;
125
6586
    store.set_epoch_deadline(RENDER_EPOCH_TICKS);
126

            
127
6586
    for form in program.exprs {
128
29703
        let single = Program::new(vec![form]);
129
29703
        let (bytes, _ty) = compiler
130
29703
            .compile_eval_with_type(&single, &mut symbols)
131
            .map_err(|err| TemplateError::Compile(err.to_string()))?;
132
29703
        let module = scripting::runtime::compile_module(&engine, &bytes)
133
            .map_err(|err| TemplateError::Engine(err.to_string()))?;
134
29703
        let instance = linker
135
29703
            .instantiate_async(&mut store, &module)
136
29703
            .await
137
            .map_err(|err| TemplateError::Engine(classify_engine(&err)))?;
138
29703
        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
29703
        let mut results = [Val::AnyRef(None)];
142
29703
        func.call_async(&mut store, &[], &mut results)
143
29703
            .await
144
802
            .map_err(|err| runtime_error(&err))?;
145
28901
        let _: Option<Rooted<AnyRef>> = match results[0] {
146
28901
            Val::AnyRef(a) => a,
147
            _ => None,
148
        };
149
    }
150

            
151
5784
    Ok(store.into_data().into_draft().unwrap_or_default())
152
6588
}
153

            
154
807
fn runtime_error(err: &wasmtime::Error) -> TemplateError {
155
807
    let engine = restore_host_condition(classify_runtime_error(err));
156
807
    let unavailable = matches!(
157
807
        &engine,
158
324
        EngineError::HostCondition { code, .. } if code == ErrorCode::UNAVAILABLE
159
    );
160
807
    let message = engine_message(engine);
161
807
    if unavailable {
162
161
        return TemplateError::Unavailable(message);
163
646
    }
164
646
    if is_host_failure(err) {
165
1
        return TemplateError::Host(message);
166
645
    }
167
645
    TemplateError::Runtime(message)
168
807
}
169

            
170
fn classify_engine(err: &wasmtime::Error) -> String {
171
    engine_message(restore_host_condition(classify_runtime_error(err)))
172
}
173

            
174
807
fn engine_message(engine: EngineError) -> String {
175
807
    match engine {
176
482
        EngineError::ScriptRaised { code, message, .. } => format!("{code}: {message}"),
177
325
        other => other.to_string(),
178
    }
179
807
}
180

            
181
#[cfg(test)]
182
mod tests;