gravityfile-plugin 0.4.0

Lua plugin system for gravityfile
Documentation
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
//! Lua runtime implementation.

use std::collections::HashMap;
use std::path::Path;

use mlua::{Function, Lua, MultiValue, Table, Value as LuaValue};

use crate::config::{PluginConfig, PluginMetadata};
use crate::hooks::{Hook, HookContext, HookResult, Notice, NoticeLevel};
use crate::runtime::{BoxFuture, HOOK_NAMES, IsolatedContext, PluginHandle, PluginRuntime};
use crate::sandbox::SandboxConfig;
use crate::types::{PluginError, PluginResult, Value};

use super::bindings;
use super::convert::{context_to_lua, lua_to_value, value_to_lua};
use super::isolate::LuaIsolatedContext;

/// A loaded Lua plugin.
struct LoadedLuaPlugin {
    /// Plugin name/id.
    name: String,

    /// The plugin's module table.
    module: mlua::RegistryKey,

    /// Plugin metadata.
    metadata: PluginMetadata,

    /// Hooks implemented by this plugin.
    hooks: Vec<String>,
}

/// Lua plugin runtime.
pub struct LuaRuntime {
    /// The main Lua state.
    lua: Lua,

    /// Loaded plugins by handle.
    plugins: HashMap<PluginHandle, LoadedLuaPlugin>,

    /// Next plugin handle ID.
    next_handle: usize,

    /// Runtime configuration.
    config: Option<PluginConfig>,

    /// Sandbox configuration used to gate filesystem API access.
    sandbox: SandboxConfig,

    /// Notices raised with `gf.notify` during the current hook call.
    notices: std::sync::Arc<std::sync::Mutex<Vec<Notice>>>,

    /// Whether the runtime has been initialized.
    initialized: bool,
}

impl LuaRuntime {
    /// Create a new Lua runtime.
    pub fn new() -> PluginResult<Self> {
        let lua = Lua::new();

        // Disable potentially dangerous standard library functions
        {
            let globals = lua.globals();
            let map_err = |e: mlua::Error| PluginError::LoadError {
                name: "lua".into(),
                message: e.to_string(),
            };
            globals.set("loadfile", LuaValue::Nil).map_err(map_err)?;
            globals
                .set("dofile", LuaValue::Nil)
                .map_err(|e| PluginError::LoadError {
                    name: "lua".into(),
                    message: e.to_string(),
                })?;
            globals
                .set("load", LuaValue::Nil)
                .map_err(|e| PluginError::LoadError {
                    name: "lua".into(),
                    message: e.to_string(),
                })?;
            globals
                .set("os", LuaValue::Nil)
                .map_err(|e| PluginError::LoadError {
                    name: "lua".into(),
                    message: e.to_string(),
                })?;
            globals
                .set("io", LuaValue::Nil)
                .map_err(|e| PluginError::LoadError {
                    name: "lua".into(),
                    message: e.to_string(),
                })?;
            globals
                .set("debug", LuaValue::Nil)
                .map_err(|e| PluginError::LoadError {
                    name: "lua".into(),
                    message: e.to_string(),
                })?;
            globals
                .set("require", LuaValue::Nil)
                .map_err(|e| PluginError::LoadError {
                    name: "lua".into(),
                    message: e.to_string(),
                })?;
            globals
                .set("package", LuaValue::Nil)
                .map_err(|e| PluginError::LoadError {
                    name: "lua".into(),
                    message: e.to_string(),
                })?;
            // Disable string.dump to prevent bytecode extraction
            if let Ok(string_table) = globals.get::<mlua::Table>("string") {
                string_table.set("dump", LuaValue::Nil).ok();
            }
        }

        Ok(Self {
            lua,
            plugins: HashMap::new(),
            next_handle: 0,
            config: None,
            sandbox: SandboxConfig::default(),
            notices: Default::default(),
            initialized: false,
        })
    }

    /// Initialize the Lua runtime with the gravityfile API.
    fn init_api(&self) -> PluginResult<()> {
        let globals = self.lua.globals();

        // Create the 'gf' namespace (gravityfile API)
        let gf = self
            .lua
            .create_table()
            .map_err(|e| PluginError::LoadError {
                name: "lua".into(),
                message: format!("Failed to create gf table: {}", e),
            })?;

        // Add version info
        gf.set("version", env!("CARGO_PKG_VERSION"))
            .map_err(|e| PluginError::LoadError {
                name: "lua".into(),
                message: e.to_string(),
            })?;

        // Add logging functions
        let log_info = self
            .lua
            .create_function(|_, msg: String| {
                tracing::info!(target: "plugin", "{}", msg);
                Ok(())
            })
            .map_err(|e| PluginError::LoadError {
                name: "lua".into(),
                message: e.to_string(),
            })?;
        gf.set("log_info", log_info).ok();

        let log_warn = self
            .lua
            .create_function(|_, msg: String| {
                tracing::warn!(target: "plugin", "{}", msg);
                Ok(())
            })
            .map_err(|e| PluginError::LoadError {
                name: "lua".into(),
                message: e.to_string(),
            })?;
        gf.set("log_warn", log_warn).ok();

        let log_error = self
            .lua
            .create_function(|_, msg: String| {
                tracing::error!(target: "plugin", "{}", msg);
                Ok(())
            })
            .map_err(|e| PluginError::LoadError {
                name: "lua".into(),
                message: e.to_string(),
            })?;
        gf.set("log_error", log_error).ok();

        // gf.notify(message, level): shown by the explorer once the hook
        // returns. Bounded per call so a plugin cannot flood the screen.
        let notices = std::sync::Arc::clone(&self.notices);
        let notify = self
            .lua
            .create_function(move |_, (message, level): (String, Option<String>)| {
                let level = NoticeLevel::parse(level.as_deref().unwrap_or("info"));
                let mut notices = notices.lock().unwrap_or_else(|poison| poison.into_inner());
                if notices.len() < Notice::MAX_PER_CALL {
                    notices.push(Notice::new(level, &message));
                }
                Ok(())
            })
            .map_err(|e| PluginError::LoadError {
                name: "lua".into(),
                message: e.to_string(),
            })?;
        gf.set("notify", notify).ok();

        globals.set("gf", gf).map_err(|e| PluginError::LoadError {
            name: "lua".into(),
            message: e.to_string(),
        })?;

        // Create the 'fs' namespace (filesystem API), gated by the runtime sandbox.
        let fs = bindings::create_fs_api(&self.lua, Some(self.sandbox.clone()))?;
        globals.set("fs", fs).map_err(|e| PluginError::LoadError {
            name: "lua".into(),
            message: e.to_string(),
        })?;

        Ok(())
    }

    /// Convert a Hook to a Lua table.
    fn hook_to_lua(&self, lua: &Lua, hook: &Hook) -> mlua::Result<Table> {
        let table = lua.create_table()?;

        // Serialize hook to JSON then to Lua table
        let json = serde_json::to_string(hook).map_err(mlua::Error::external)?;
        let json_val: serde_json::Value =
            serde_json::from_str(&json).map_err(mlua::Error::external)?;

        fn json_to_lua(lua: &Lua, val: &serde_json::Value) -> mlua::Result<LuaValue> {
            match val {
                serde_json::Value::Null => Ok(LuaValue::Nil),
                serde_json::Value::Bool(b) => Ok(LuaValue::Boolean(*b)),
                serde_json::Value::Number(n) => {
                    if let Some(i) = n.as_i64() {
                        Ok(LuaValue::Integer(i))
                    } else {
                        Ok(LuaValue::Number(n.as_f64().unwrap_or(0.0)))
                    }
                }
                serde_json::Value::String(s) => Ok(LuaValue::String(lua.create_string(s)?)),
                serde_json::Value::Array(arr) => {
                    let t = lua.create_table()?;
                    for (i, v) in arr.iter().enumerate() {
                        t.set(i + 1, json_to_lua(lua, v)?)?;
                    }
                    Ok(LuaValue::Table(t))
                }
                serde_json::Value::Object(obj) => {
                    let t = lua.create_table()?;
                    for (k, v) in obj {
                        t.set(k.as_str(), json_to_lua(lua, v)?)?;
                    }
                    Ok(LuaValue::Table(t))
                }
            }
        }

        if let serde_json::Value::Object(obj) = json_val {
            for (k, v) in obj {
                table.set(k.as_str(), json_to_lua(lua, &v)?)?;
            }
        }

        Ok(table)
    }

    /// Run `f` under a CPU watchdog: an instruction-count hook aborts execution
    /// once the wall-clock deadline (from the sandbox timeout) passes. This
    /// bounds runaway plugins on the shared Lua state without requiring the state
    /// to be `Send` (so we avoid `spawn_blocking`). A timeout surfaces as an
    /// execution error from the wrapped Lua call.
    fn with_deadline<T>(&self, f: impl FnOnce() -> PluginResult<T>) -> PluginResult<T> {
        use std::time::{Duration, Instant};

        let timeout_ms = self.sandbox.timeout_ms;
        if timeout_ms == 0 {
            return f();
        }

        let Some(deadline) = Instant::now().checked_add(Duration::from_millis(timeout_ms)) else {
            return f();
        };
        let _ = self.lua.set_hook(
            mlua::HookTriggers::new().every_nth_instruction(100_000),
            move |_lua, _debug| {
                if Instant::now() >= deadline {
                    Err(mlua::Error::external("plugin execution timed out"))
                } else {
                    Ok(mlua::VmState::Continue)
                }
            },
        );
        let result = f();
        self.lua.remove_hook();
        result
    }
}

impl PluginRuntime for LuaRuntime {
    fn name(&self) -> &'static str {
        "lua"
    }

    fn file_extensions(&self) -> &'static [&'static str] {
        &[".lua"]
    }

    fn init(&mut self, config: &PluginConfig) -> PluginResult<()> {
        if self.initialized {
            return Ok(());
        }

        // Build a sandbox from plugin config settings. The default grants the
        // Read permission but no paths; wiring the configured roots is what makes
        // the filesystem API actually usable (and scoped).
        self.sandbox = SandboxConfig {
            timeout_ms: config.default_timeout_ms,
            max_memory: config.max_memory_mb.saturating_mul(1024 * 1024),
            allow_network: config.allow_network,
            allowed_read_paths: config.fs_read_roots.clone(),
            ..SandboxConfig::default()
        };

        // Bound memory on the shared Lua state so a runaway plugin can't OOM the
        // whole TUI. 0 means "unlimited" in our config; only set a real cap.
        if self.sandbox.max_memory > 0 {
            let _ = self.lua.set_memory_limit(self.sandbox.max_memory);
        }

        self.config = Some(config.clone());
        self.init_api()?;
        self.initialized = true;

        Ok(())
    }

    fn load_plugin(&mut self, id: &str, source: &Path) -> PluginResult<PluginHandle> {
        // Read the plugin source
        let code = crate::runtime::read_plugin_source(source)?;

        // Load and execute the plugin
        let chunk = self.lua.load(&code).set_name(id);

        let module: Table = chunk.eval().map_err(|e| PluginError::LoadError {
            name: id.to_string(),
            message: e.to_string(),
        })?;

        // Detect which hooks are implemented, using the shared canonical list
        // so Lua plugins can register every hook the host dispatches.
        let mut hooks = vec![];
        for hook_name in HOOK_NAMES {
            if module.contains_key(*hook_name).unwrap_or(false) {
                hooks.push(hook_name.to_string());
            }
        }

        // Store in registry
        let key = self
            .lua
            .create_registry_value(module)
            .map_err(|e| PluginError::LoadError {
                name: id.to_string(),
                message: e.to_string(),
            })?;

        let handle = PluginHandle::new(self.next_handle);
        self.next_handle += 1;

        // Create default metadata (would normally come from plugin.toml)
        let metadata = PluginMetadata {
            name: id.to_string(),
            runtime: "lua".to_string(),
            ..Default::default()
        };

        self.plugins.insert(
            handle,
            LoadedLuaPlugin {
                name: id.to_string(),
                module: key,
                metadata,
                hooks,
            },
        );

        Ok(handle)
    }

    fn unload_plugin(&mut self, handle: PluginHandle) -> PluginResult<()> {
        if let Some(plugin) = self.plugins.remove(&handle) {
            self.lua.remove_registry_value(plugin.module).ok();
        }
        Ok(())
    }

    fn get_metadata(&self, handle: PluginHandle) -> Option<&PluginMetadata> {
        self.plugins.get(&handle).map(|p| &p.metadata)
    }

    fn has_hook(&self, handle: PluginHandle, hook_name: &str) -> bool {
        self.plugins
            .get(&handle)
            .map(|p| p.hooks.contains(&hook_name.to_string()))
            .unwrap_or(false)
    }

    fn call_hook_sync(
        &self,
        handle: PluginHandle,
        hook: &Hook,
        ctx: &HookContext,
    ) -> PluginResult<HookResult> {
        let take_notices = || {
            std::mem::take(
                &mut *self
                    .notices
                    .lock()
                    .unwrap_or_else(|poison| poison.into_inner()),
            )
        };
        take_notices();
        let plugin = self
            .plugins
            .get(&handle)
            .ok_or_else(|| PluginError::NotFound {
                path: std::path::PathBuf::new(),
            })?;

        let module: Table =
            self.lua
                .registry_value(&plugin.module)
                .map_err(|e| PluginError::ExecutionError {
                    name: plugin.name.clone(),
                    message: e.to_string(),
                })?;

        let hook_name = hook.name();
        let func: Function = match module.get(hook_name) {
            Ok(f) => f,
            Err(_) => return Ok(HookResult::default()),
        };

        // Convert hook and context to Lua
        let hook_table =
            self.hook_to_lua(&self.lua, hook)
                .map_err(|e| PluginError::ExecutionError {
                    name: plugin.name.clone(),
                    message: e.to_string(),
                })?;

        let context_table =
            context_to_lua(&self.lua, ctx).map_err(|e| PluginError::ExecutionError {
                name: plugin.name.clone(),
                message: e.to_string(),
            })?;

        // Call the function under the CPU/time watchdog.
        let result: LuaValue = self.with_deadline(|| {
            func.call((module.clone(), hook_table, context_table))
                .map_err(|e| PluginError::ExecutionError {
                    name: plugin.name.clone(),
                    message: e.to_string(),
                })
        })?;

        // Convert result
        let mut hook_result = HookResult::ok();
        hook_result.notices = take_notices();
        if let LuaValue::Table(t) = result {
            if let Ok(prevent) = t.get::<bool>("prevent_default")
                && prevent
            {
                hook_result = hook_result.prevent_default();
            }
            if let Ok(stop) = t.get::<bool>("stop_propagation")
                && stop
            {
                hook_result = hook_result.stop_propagation();
            }
            if let Ok(val) = t.get::<LuaValue>("value") {
                hook_result.value = Some(lua_to_value(val));
            }
        }

        Ok(hook_result)
    }

    fn call_hook_async<'a>(
        &'a self,
        handle: PluginHandle,
        hook: &'a Hook,
        ctx: &'a HookContext,
    ) -> BoxFuture<'a, PluginResult<HookResult>> {
        // The main Lua state is shared with synchronous render hooks, so calls
        // remain serialized. `with_deadline` enforces the VM instruction/time
        // budget even though this future resolves synchronously.
        Box::pin(async move { self.call_hook_sync(handle, hook, ctx) })
    }

    fn call_method<'a>(
        &'a self,
        handle: PluginHandle,
        method: &'a str,
        args: Vec<Value>,
    ) -> BoxFuture<'a, PluginResult<Value>> {
        Box::pin(async move {
            let plugin = self
                .plugins
                .get(&handle)
                .ok_or_else(|| PluginError::NotFound {
                    path: std::path::PathBuf::new(),
                })?;

            let module: Table = self.lua.registry_value(&plugin.module).map_err(|e| {
                PluginError::ExecutionError {
                    name: plugin.name.clone(),
                    message: e.to_string(),
                }
            })?;

            let func: Function = module
                .get(method)
                .map_err(|e| PluginError::ExecutionError {
                    name: plugin.name.clone(),
                    message: format!("Method '{}' not found: {}", method, e),
                })?;

            // Convert args to Lua
            let lua_args: Vec<LuaValue> = args
                .iter()
                .map(|v| value_to_lua(&self.lua, v))
                .collect::<Result<_, _>>()
                .map_err(|e| PluginError::ExecutionError {
                    name: plugin.name.clone(),
                    message: e.to_string(),
                })?;

            let result: LuaValue = self.with_deadline(|| {
                func.call(MultiValue::from_vec(
                    std::iter::once(LuaValue::Table(module))
                        .chain(lua_args)
                        .collect(),
                ))
                .map_err(|e| PluginError::ExecutionError {
                    name: plugin.name.clone(),
                    message: e.to_string(),
                })
            })?;

            Ok(lua_to_value(result))
        })
    }

    fn create_isolated_context(
        &self,
        sandbox: &SandboxConfig,
    ) -> PluginResult<Box<dyn IsolatedContext>> {
        Ok(Box::new(LuaIsolatedContext::new(sandbox.clone())?))
    }

    fn loaded_plugins(&self) -> Vec<PluginHandle> {
        self.plugins.keys().copied().collect()
    }

    fn shutdown(&mut self) -> PluginResult<()> {
        self.plugins.clear();
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::hooks::{Hook, HookContext};
    use std::io::Write as _;

    fn load(rt: &mut LuaRuntime, source: &str) -> PluginHandle {
        let mut file = tempfile::NamedTempFile::new().unwrap();
        file.write_all(source.as_bytes()).unwrap();
        rt.load_plugin("test", file.path()).unwrap()
    }

    #[test]
    fn notices_return_with_the_hook_result_bounded_and_per_call() {
        let mut rt = lua_runtime(1000);
        let handle = load(
            &mut rt,
            r#"
            local M = {}
            function M.on_startup(self, hook)
                gf.notify("started", "warn")
                gf.notify(string.rep("x", 2000))
                for i = 1, 20 do gf.notify("more " .. i, "error") end
            end
            function M.on_shutdown(self, hook) end
            return M
            "#,
        );
        let started = rt
            .call_hook_sync(handle, &Hook::OnStartup, &HookContext::new())
            .unwrap();
        assert_eq!(started.notices.len(), Notice::MAX_PER_CALL);
        assert_eq!(
            started.notices[0],
            Notice::new(NoticeLevel::Warn, "started")
        );
        assert_eq!(started.notices[1].level, NoticeLevel::Info);
        assert_eq!(started.notices[1].message.len(), Notice::MAX_BYTES);
        let quiet = rt
            .call_hook_sync(handle, &Hook::OnShutdown, &HookContext::new())
            .unwrap();
        assert!(quiet.notices.is_empty(), "notices do not carry over");
    }

    #[test]
    fn hooks_receive_the_context() {
        let mut rt = lua_runtime(1000);
        let handle = load(
            &mut rt,
            r#"
            local M = {}
            function M.on_navigate(self, hook, ctx)
                return { value = ctx.view_root .. "|" .. ctx.theme .. "|" .. ctx.selected .. "|" .. hook.to }
            end
            return M
            "#,
        );
        let mut context = HookContext::new()
            .with_view_root("/home/me".into())
            .with_theme("nord");
        context.set("selected", "notes.txt");
        let hook = Hook::OnNavigate {
            from: "/home".into(),
            to: "/home/me".into(),
        };
        let result = rt.call_hook_sync(handle, &hook, &context).unwrap();
        assert_eq!(
            result.value,
            Some(Value::String("/home/me|nord|notes.txt|/home/me".into()))
        );
    }

    fn lua_runtime(timeout_ms: u64) -> LuaRuntime {
        let mut rt = LuaRuntime::new().unwrap();
        let cfg = PluginConfig {
            default_timeout_ms: timeout_ms,
            ..PluginConfig::default()
        };
        rt.init(&cfg).unwrap();
        rt
    }

    #[test]
    fn deadline_aborts_infinite_loop_hook() {
        let mut rt = lua_runtime(50);

        let mut file = tempfile::NamedTempFile::new().unwrap();
        // on_startup is a sync hook; the body loops forever and must be aborted
        // by the instruction-count deadline watchdog rather than hanging.
        write!(
            file,
            "local M = {{}}\nfunction M.on_startup(self, hook) while true do end end\nreturn M\n"
        )
        .unwrap();

        let handle = rt.load_plugin("loopy", file.path()).unwrap();
        assert!(rt.has_hook(handle, "on_startup"));

        let start = std::time::Instant::now();
        let res = rt.call_hook_sync(handle, &Hook::OnStartup, &HookContext::new());

        assert!(res.is_err(), "runaway hook should abort, got {res:?}");
        assert!(
            start.elapsed().as_secs() < 5,
            "watchdog should abort promptly, took {:?}",
            start.elapsed()
        );
    }

    #[test]
    fn normal_hook_runs_under_deadline() {
        let mut rt = lua_runtime(1000);

        let mut file = tempfile::NamedTempFile::new().unwrap();
        write!(
            file,
            "local M = {{}}\nfunction M.on_startup(self, hook) return {{ handled = true }} end\nreturn M\n"
        )
        .unwrap();

        let handle = rt.load_plugin("calm", file.path()).unwrap();
        let res = rt
            .call_hook_sync(handle, &Hook::OnStartup, &HookContext::new())
            .unwrap();
        assert!(res.is_ok());
    }
}