rpc/natives/render.rs
1//! Restricted render-only native surface for template evaluation.
2//!
3//! Templates are per-user nomiscript source that must NOT be able to mutate
4//! data or read secrets — above all the per-user JWT private key reachable via
5//! `get-config` (Slice B places it in the same per-user DB the eval channel
6//! reads). The render surface is therefore a strict WHITELIST applied at BOTH
7//! levels:
8//!
9//! * [`render_compiler_specs`] — the compiler only knows the allowlisted
10//! read-only financial natives plus the draft natives, so a template that
11//! names anything else is a COMPILE error (it never reaches the linker).
12//! * [`link_render`] — the linker registers only the infra natives, the
13//! allowlisted read fns, and the draft natives. The secret/auth
14//! modules (`config`, `user`, `ssh_key`) and every mutator are NOT linked
15//! at all, so even a hypothetical compiler-spec leak has nothing to call.
16//!
17//! Whitelist, not blacklist: a newly added native is excluded by default and
18//! must be explicitly added here, so a future sensitive native cannot silently
19//! become reachable from templates.
20
21use nomiscript::HostFnSpec;
22use wasmtime::Linker;
23
24use crate::session::SessionData;
25
26/// The only non-draft natives a template may call: read-only financial lookups,
27/// pure value conversion, and the session-user-id accessor. Every entry is
28/// verified read-only — no mutator, no config/secret reader, no auth surface.
29/// `convert-commodity` only reads the prices table (verified: it issues
30/// `SELECT … prices …`, never a write).
31pub const RENDER_NATIVE_ALLOWLIST: &[&str] = &[
32 // Infra / meta. NOTE: `get-version`/`get-build-date` are deliberately
33 // excluded — they live in the `config` module alongside the catastrophic
34 // `get-config`, and `link_render` never registers that module. Keeping them
35 // off the allowlist means the entire config surface stays unlinked, so the
36 // secret reader has nothing to bind to even if a spec leaked. Templates have
37 // no use for build metadata anyway.
38 "rpc-protocol-version",
39 "rpc-session-user-id",
40 // Account reads.
41 "account-count",
42 "list-accounts",
43 "get-account",
44 "get-balance",
45 "get-account-commodities",
46 "account-balance",
47 "list-accounts-for-manage",
48 "get-account-for-manage",
49 // Commodity reads + pure conversion.
50 "list-commodities",
51 "get-commodity",
52 "convert-commodity",
53 // Transaction reads.
54 "list-transactions",
55 "get-transaction",
56 "get-transaction-tag",
57 // Tag reads.
58 "list-tags",
59 // Split reads.
60 "list-splits",
61 "list-splits-by-transaction",
62 "get-split-tag",
63 "get-split-tags",
64 // Reports (read-only).
65 "balance-report",
66 "activity-report",
67 "category-breakdown",
68 // Draft natives (render-only side effects into the accumulator).
69 "set-draft-note",
70 "set-draft-date",
71 "draft-split",
72 "draft-tag",
73 "draft-split-tag",
74];
75
76/// Compiler specs the render surface exposes: the allowlisted subset of
77/// [`all_compiler_specs`](super::all_compiler_specs). Filtering the single
78/// canonical registry (rather than hand-maintaining a parallel list) keeps the
79/// render surface in lock-step with the org source — a renamed native drops out
80/// automatically rather than silently mismatching the linker.
81#[must_use]
82pub fn render_compiler_specs() -> Vec<HostFnSpec> {
83 super::all_compiler_specs()
84 .into_iter()
85 .filter(|spec| {
86 RENDER_NATIVE_ALLOWLIST.contains(&spec.nomi_name.to_ascii_lowercase().as_str())
87 })
88 .collect()
89}
90
91/// Links ONLY the render-safe host fns onto `linker`: infra, the allowlisted
92/// read fns, and the draft natives. The dual gate is FULL here — a dangerous
93/// native is blocked at both levels. First, the `config`, `user`, and `ssh_key`
94/// modules are never registered at all (the secret/credential/auth surface has
95/// nothing to bind to). Second, the account/commodity/report/split/tag/transaction
96/// mutators and the unlisted reads are excluded by linking each module's
97/// `register_readonly` variant, which holds only allowlisted natives (pinned by
98/// a test), so those imports are never bound either. So even a hypothetical
99/// compiler-spec leak finds no linked target.
100/// `env.log` is bound as a silent no-op (the import must resolve, but template
101/// output is discarded).
102pub fn link_render(linker: &mut Linker<SessionData>) -> wasmtime::Result<()> {
103 super::meta::register(linker)?;
104 super::env_io::register_silent(linker)?;
105 super::raise::register(linker)?;
106 super::catch_each::register(linker)?;
107 super::account::register_readonly(linker)?;
108 super::commodity::register_readonly(linker)?;
109 super::report::register_readonly(linker)?;
110 super::split::register_readonly(linker)?;
111 super::tag::register_readonly(linker)?;
112 super::transaction::register_readonly(linker)?;
113 super::template::register(linker)?;
114 Ok(())
115}
116
117#[cfg(test)]
118mod tests {
119 use crate::session::SessionData;
120 use crate::wasm::{EngineOpts, build_engine};
121 use std::collections::BTreeSet;
122 use wasmtime::Linker;
123
124 fn render_linker() -> (Linker<SessionData>, wasmtime::Store<SessionData>) {
125 let engine = build_engine(EngineOpts::baseline().with_fuel()).expect("engine");
126 let mut linker: Linker<SessionData> = Linker::new(&engine);
127 super::link_render(&mut linker).expect("link_render");
128 let store = dummy_store(&engine);
129 (linker, store)
130 }
131
132 /// Whether the render linker has a host fn bound at `nomi.<import>`.
133 fn render_binds(import: &str) -> bool {
134 let (linker, mut store) = render_linker();
135 linker.get(&mut store, "nomi", import).is_ok()
136 }
137
138 /// Import names bound under `nomi` that are not the always-linked infra.
139 fn bound_domain_imports() -> BTreeSet<String> {
140 let (linker, mut store) = render_linker();
141 linker
142 .iter(&mut store)
143 .filter(|(module, _, _)| *module == "nomi")
144 .map(|(_, name, _)| name.to_string())
145 .filter(|name| !INFRA_IMPORTS.contains(&name.as_str()))
146 .collect()
147 }
148
149 const INFRA_IMPORTS: &[&str] = &["__nomi_raise", "__nomi_catch_each"];
150
151 fn dummy_store(engine: &wasmtime::Engine) -> wasmtime::Store<SessionData> {
152 use crate::ctx::ScriptCtx;
153 use std::sync::{Arc, Mutex};
154 use uuid::Uuid;
155 wasmtime::Store::new(
156 engine,
157 SessionData::for_render(
158 ScriptCtx::new(Uuid::nil()),
159 Arc::new(Mutex::new(String::new())),
160 ),
161 )
162 }
163
164 #[test]
165 fn render_linker_does_not_bind_mutators_or_secrets() {
166 for dangerous in [
167 "transaction_create_transaction",
168 "transaction_delete_transaction",
169 "account_create_account",
170 "account_merge_accounts",
171 "account_set_account_tag",
172 "account_clear_account_tag",
173 "commodity_create_commodity",
174 "commodity_set_commodity_tag",
175 "commodity_clear_commodity_tag",
176 "split_set_split_tag",
177 "config_get_config",
178 "config_set_config",
179 "config_list_config",
180 "forms_form_descriptor",
181 "forms_form_options",
182 "forms_load_form",
183 "forms_submit_form",
184 "forms_merge_preview",
185 "ssh_key_remove_ssh_key",
186 "tag_delete_tag",
187 "template_store_delete_template",
188 "script_store_delete_script",
189 "script_store_run_script",
190 "report_report_csv",
191 ] {
192 assert!(
193 !render_binds(dangerous),
194 "render linker must NOT bind dangerous import '{dangerous}'"
195 );
196 }
197 }
198
199 #[test]
200 fn render_linker_binds_exactly_the_allowlist() {
201 let specced: BTreeSet<String> = super::render_compiler_specs()
202 .into_iter()
203 .filter(|spec| spec.import_module == "nomi")
204 .map(|spec| spec.import_name)
205 .collect();
206 assert_eq!(bound_domain_imports(), specced);
207 }
208}