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

            
21
use nomiscript::HostFnSpec;
22
use wasmtime::Linker;
23

            
24
use 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).
31
pub 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]
82
13497
pub fn render_compiler_specs() -> Vec<HostFnSpec> {
83
13497
    super::all_compiler_specs()
84
13497
        .into_iter()
85
944790
        .filter(|spec| {
86
944790
            RENDER_NATIVE_ALLOWLIST.contains(&spec.nomi_name.to_ascii_lowercase().as_str())
87
944790
        })
88
        .collect()
89
13497
}
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).
102
6611
pub fn link_render(linker: &mut Linker<SessionData>) -> wasmtime::Result<()> {
103
6611
    super::meta::register(linker)?;
104
6611
    super::env_io::register_silent(linker)?;
105
6611
    super::raise::register(linker)?;
106
6611
    super::catch_each::register(linker)?;
107
6611
    super::account::register_readonly(linker)?;
108
6611
    super::commodity::register_readonly(linker)?;
109
6611
    super::report::register_readonly(linker)?;
110
6611
    super::split::register_readonly(linker)?;
111
6611
    super::tag::register_readonly(linker)?;
112
6611
    super::transaction::register_readonly(linker)?;
113
6611
    super::template::register(linker)?;
114
6611
    Ok(())
115
6611
}
116

            
117
#[cfg(test)]
118
mod tests {
119
    use crate::session::SessionData;
120
    use crate::wasm::{EngineOpts, build_engine};
121
    use std::collections::BTreeSet;
122
    use wasmtime::Linker;
123

            
124
25
    fn render_linker() -> (Linker<SessionData>, wasmtime::Store<SessionData>) {
125
25
        let engine = build_engine(EngineOpts::baseline().with_fuel()).expect("engine");
126
25
        let mut linker: Linker<SessionData> = Linker::new(&engine);
127
25
        super::link_render(&mut linker).expect("link_render");
128
25
        let store = dummy_store(&engine);
129
25
        (linker, store)
130
25
    }
131

            
132
    /// Whether the render linker has a host fn bound at `nomi.<import>`.
133
24
    fn render_binds(import: &str) -> bool {
134
24
        let (linker, mut store) = render_linker();
135
24
        linker.get(&mut store, "nomi", import).is_ok()
136
24
    }
137

            
138
    /// Import names bound under `nomi` that are not the always-linked infra.
139
1
    fn bound_domain_imports() -> BTreeSet<String> {
140
1
        let (linker, mut store) = render_linker();
141
1
        linker
142
1
            .iter(&mut store)
143
33
            .filter(|(module, _, _)| *module == "nomi")
144
31
            .map(|(_, name, _)| name.to_string())
145
31
            .filter(|name| !INFRA_IMPORTS.contains(&name.as_str()))
146
            .collect()
147
1
    }
148

            
149
    const INFRA_IMPORTS: &[&str] = &["__nomi_raise", "__nomi_catch_each"];
150

            
151
25
    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
25
        wasmtime::Store::new(
156
25
            engine,
157
25
            SessionData::for_render(
158
25
                ScriptCtx::new(Uuid::nil()),
159
25
                Arc::new(Mutex::new(String::new())),
160
25
            ),
161
25
        )
162
25
    }
163

            
164
    #[test]
165
1
    fn render_linker_does_not_bind_mutators_or_secrets() {
166
1
        for dangerous in [
167
1
            "transaction_create_transaction",
168
1
            "transaction_delete_transaction",
169
1
            "account_create_account",
170
1
            "account_merge_accounts",
171
1
            "account_set_account_tag",
172
1
            "account_clear_account_tag",
173
1
            "commodity_create_commodity",
174
1
            "commodity_set_commodity_tag",
175
1
            "commodity_clear_commodity_tag",
176
1
            "split_set_split_tag",
177
1
            "config_get_config",
178
1
            "config_set_config",
179
1
            "config_list_config",
180
1
            "forms_form_descriptor",
181
1
            "forms_form_options",
182
1
            "forms_load_form",
183
1
            "forms_submit_form",
184
1
            "forms_merge_preview",
185
1
            "ssh_key_remove_ssh_key",
186
1
            "tag_delete_tag",
187
1
            "template_store_delete_template",
188
1
            "script_store_delete_script",
189
1
            "script_store_run_script",
190
1
            "report_report_csv",
191
1
        ] {
192
24
            assert!(
193
24
                !render_binds(dangerous),
194
                "render linker must NOT bind dangerous import '{dangerous}'"
195
            );
196
        }
197
1
    }
198

            
199
    #[test]
200
1
    fn render_linker_binds_exactly_the_allowlist() {
201
1
        let specced: BTreeSet<String> = super::render_compiler_specs()
202
1
            .into_iter()
203
29
            .filter(|spec| spec.import_module == "nomi")
204
29
            .map(|spec| spec.import_name)
205
            .collect();
206
1
        assert_eq!(bound_domain_imports(), specced);
207
1
    }
208
}