raisfast 0.2.23

The last backend you'll ever need. Rust-powered headless CMS with built-in blog, ecommerce, wallet, payment and 4 plugin engines.
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
//! Lua host functions — engine binding layer
//!
//! Only responsible for binding the shared business logic of
//! [`HostContext`](super::host_common::HostContext) to the `PLUGIN_HOST_GLOBAL` property
//! of the Lua global table.

use std::sync::Arc;

use mlua::{Lua, LuaSerdeExt};

use crate::config::app::AppConfig;
use crate::constants::PLUGIN_HOST_GLOBAL;
use crate::db::Pool;
use crate::plugins::Permissions;
use crate::plugins::host_common::HostContext;

/// Register host functions into the Lua global scope.
pub fn register_host_functions(
    lua: &Lua,
    config: Arc<AppConfig>,
    plugin_id: String,
    permissions: Permissions,
    pool: Option<Pool>,
    event_bus: Option<crate::eventbus::EventBus>,
) -> anyhow::Result<()> {
    let globals = lua.globals();
    let host = lua.create_table()?;

    let mut hc_inner = HostContext::new("lua", config, plugin_id, permissions, pool);
    if let Some(bus) = event_bus {
        hc_inner.set_event_bus(bus);
    }
    let host_ctx = Arc::new(hc_inner);

    let hc = host_ctx.clone();
    let log_fn = lua.create_function(move |_, (level, msg): (String, String)| {
        hc.log(&level, &msg);
        Ok(())
    })?;
    host.set("log", log_fn)?;

    let hc = host_ctx.clone();
    let get_config_fn = lua.create_function(move |lua, key: String| match hc.get_config(&key) {
        Some(val) => Ok(mlua::Value::String(lua.create_string(&val)?)),
        None => Ok(mlua::Value::Nil),
    })?;
    host.set("getConfig", get_config_fn)?;

    let hc = host_ctx.clone();
    let http_get_fn = lua.create_function(move |lua, url: String| {
        Ok(mlua::Value::String(lua.create_string(hc.http_get(&url))?))
    })?;
    host.set("httpGet", http_get_fn)?;

    let hc = host_ctx.clone();
    let http_post_fn = lua.create_function(move |lua, (url, body): (String, String)| {
        Ok(mlua::Value::String(
            lua.create_string(hc.http_post(&url, &body))?,
        ))
    })?;
    host.set("httpPost", http_post_fn)?;

    let hc = host_ctx.clone();
    let get_data_fn = lua.create_function(move |lua, key: String| match hc.get_data(&key) {
        Some(val) => Ok(mlua::Value::String(lua.create_string(&val)?)),
        None => Ok(mlua::Value::Nil),
    })?;
    host.set("getData", get_data_fn)?;

    let hc = host_ctx.clone();
    let set_data_fn = lua
        .create_function(move |_, (key, value): (String, String)| Ok(hc.set_data(&key, &value)))?;
    host.set("setData", set_data_fn)?;

    let hc = host_ctx.clone();
    let get_post_fn = lua.create_function(move |lua, slug: String| match hc.get_post(&slug) {
        Some(json) => Ok(mlua::Value::String(lua.create_string(&json)?)),
        None => Ok(mlua::Value::Nil),
    })?;
    host.set("getPost", get_post_fn)?;

    let hc = host_ctx.clone();
    let db_query_fn = lua.create_function(move |lua, (sql, params): (String, String)| {
        Ok(mlua::Value::String(
            lua.create_string(hc.db_query(&sql, &params))?,
        ))
    })?;
    host.set("dbQuery", db_query_fn)?;

    let hc = host_ctx.clone();
    let db_execute_fn = lua.create_function(move |lua, (sql, params): (String, String)| {
        Ok(mlua::Value::String(
            lua.create_string(hc.db_execute(&sql, &params))?,
        ))
    })?;
    host.set("dbExecute", db_execute_fn)?;

    let hc = host_ctx.clone();
    let db_begin_fn = lua.create_function(move |lua, ()| {
        Ok(mlua::Value::String(lua.create_string(hc.db_begin())?))
    })?;
    host.set("dbBegin", db_begin_fn)?;

    let hc = host_ctx.clone();
    let db_commit_fn = lua.create_function(move |lua, ()| {
        Ok(mlua::Value::String(lua.create_string(hc.db_commit())?))
    })?;
    host.set("dbCommit", db_commit_fn)?;

    let hc = host_ctx.clone();
    let db_rollback_fn = lua.create_function(move |lua, ()| {
        Ok(mlua::Value::String(lua.create_string(hc.db_rollback())?))
    })?;
    host.set("dbRollback", db_rollback_fn)?;

    let hc = host_ctx.clone();
    let db_insert_fn = lua.create_function(
        move |lua, (table, data, options): (String, String, String)| {
            Ok(mlua::Value::String(
                lua.create_string(hc.db_insert(&table, &data, &options))?,
            ))
        },
    )?;
    host.set("dbInsert", db_insert_fn)?;

    let hc = host_ctx.clone();
    let db_fetch_one_fn = lua.create_function(
        move |lua, (table, r#where, options): (String, String, String)| {
            Ok(mlua::Value::String(lua.create_string(
                hc.db_fetch_one(&table, &r#where, &options),
            )?))
        },
    )?;
    host.set("dbFetchOne", db_fetch_one_fn)?;

    let hc = host_ctx.clone();
    let db_fetch_all_fn = lua.create_function(
        move |lua, (table, r#where, options): (String, String, String)| {
            Ok(mlua::Value::String(lua.create_string(
                hc.db_fetch_all(&table, &r#where, &options),
            )?))
        },
    )?;
    host.set("dbFetchAll", db_fetch_all_fn)?;

    let hc = host_ctx.clone();
    let db_update_fn = lua.create_function(
        move |lua, (table, data, r#where, options): (String, String, String, String)| {
            Ok(mlua::Value::String(lua.create_string(
                hc.db_update(&table, &data, &r#where, &options),
            )?))
        },
    )?;
    host.set("dbUpdate", db_update_fn)?;

    let hc = host_ctx.clone();
    let db_delete_fn = lua.create_function(
        move |lua, (table, r#where, options): (String, String, String)| {
            Ok(mlua::Value::String(
                lua.create_string(hc.db_delete(&table, &r#where, &options))?,
            ))
        },
    )?;
    host.set("dbDelete", db_delete_fn)?;

    let hc = host_ctx.clone();
    let db_count_fn = lua.create_function(
        move |lua, (table, r#where, options): (String, String, String)| {
            Ok(mlua::Value::String(
                lua.create_string(hc.db_count(&table, &r#where, &options))?,
            ))
        },
    )?;
    host.set("dbCount", db_count_fn)?;

    let hc = host_ctx.clone();
    let db_increment_fn = lua.create_function(
        move |lua, (table, columns, r#where, options): (String, String, String, String)| {
            Ok(mlua::Value::String(lua.create_string(
                hc.db_increment(&table, &columns, &r#where, &options),
            )?))
        },
    )?;
    host.set("dbIncrement", db_increment_fn)?;

    let hc = host_ctx.clone();
    let db_sum_fn = lua.create_function(
        move |lua, (table, column, r#where, options): (String, String, String, String)| {
            Ok(mlua::Value::String(lua.create_string(
                hc.db_sum(&table, &column, &r#where, &options),
            )?))
        },
    )?;
    host.set("dbSum", db_sum_fn)?;

    let hc = host_ctx.clone();
    let db_group_by_fn = lua.create_function(move |lua, (table, options): (String, String)| {
        Ok(mlua::Value::String(
            lua.create_string(hc.db_group_by(&table, &options))?,
        ))
    })?;
    host.set("dbGroupBy", db_group_by_fn)?;

    let hc = host_ctx.clone();
    let vfs_read_fn = lua.create_function(move |lua, path: String| match hc.vfs_read(&path) {
        Ok(content) => Ok(mlua::Value::String(lua.create_string(&content)?)),
        Err(_) => Ok(mlua::Value::Nil),
    })?;
    host.set("vfsRead", vfs_read_fn)?;

    let hc = host_ctx.clone();
    let vfs_write_fn = lua.create_function(move |_, (path, content): (String, String)| {
        Ok(hc.vfs_write(&path, &content).is_ok())
    })?;
    host.set("vfsWrite", vfs_write_fn)?;

    let hc = host_ctx.clone();
    let vfs_delete_fn =
        lua.create_function(move |_, path: String| Ok(hc.vfs_delete(&path).is_ok()))?;
    host.set("vfsDelete", vfs_delete_fn)?;

    let hc = host_ctx.clone();
    let vfs_exists_fn =
        lua.create_function(move |_lua, path: String| match hc.vfs_exists(&path) {
            Ok(true) => Ok(mlua::Value::Boolean(true)),
            Ok(false) => Ok(mlua::Value::Boolean(false)),
            Err(_) => Ok(mlua::Value::Nil),
        })?;
    host.set("vfsExists", vfs_exists_fn)?;

    let hc = host_ctx.clone();
    let vfs_list_fn = lua.create_function(move |lua, path: String| match hc.vfs_list(&path) {
        Ok(entries) => {
            let tbl = lua.create_table()?;
            for (i, entry) in entries.into_iter().enumerate() {
                tbl.set(i + 1, entry)?;
            }
            Ok(mlua::Value::Table(tbl))
        }
        Err(_) => Ok(mlua::Value::Nil),
    })?;
    host.set("vfsList", vfs_list_fn)?;

    let hc = host_ctx.clone();
    let vfs_stat_fn = lua.create_function(move |lua, path: String| match hc.vfs_stat(&path) {
        Ok(json) => Ok(mlua::Value::String(lua.create_string(&json)?)),
        Err(_) => Ok(mlua::Value::Nil),
    })?;
    host.set("vfsStat", vfs_stat_fn)?;

    let hc = host_ctx.clone();
    let emit_event_fn = lua.create_function(move |lua, (event_type, data): (String, String)| {
        Ok(mlua::Value::String(
            lua.create_string(hc.emit_event(&event_type, &data))?,
        ))
    })?;
    host.set("emitEvent", emit_event_fn)?;

    let hc = host_ctx.clone();
    let new_id_fn = lua.create_function(move |lua, ()| -> mlua::Result<mlua::String> {
        lua.create_string(hc.new_uuid())
    })?;
    host.set("newId", new_id_fn)?;

    let hc = host_ctx.clone();
    let db_ph_fn = lua.create_function(move |lua, idx: usize| -> mlua::Result<mlua::String> {
        lua.create_string(hc.db_ph(idx))
    })?;
    host.set("dbPh", db_ph_fn)?;

    let json_encode_fn =
        lua.create_function(move |lua, val: mlua::Value| -> mlua::Result<String> {
            let json_val: serde_json::Value = lua.from_value(val)?;
            serde_json::to_string(&json_val)
                .map_err(|e| mlua::Error::runtime(format!("json encode error: {e}")))
        })?;
    host.set("jsonEncode", json_encode_fn)?;

    let json_decode_fn =
        lua.create_function(move |lua, json_str: String| -> mlua::Result<mlua::Value> {
            let json_val: serde_json::Value = serde_json::from_str(&json_str)
                .map_err(|e| mlua::Error::runtime(format!("json decode error: {e}")))?;
            lua.to_value(&json_val)
        })?;
    host.set("jsonDecode", json_decode_fn)?;

    globals.set(PLUGIN_HOST_GLOBAL, host)?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    fn make_test_config() -> Arc<AppConfig> {
        Arc::new(AppConfig::test_defaults())
    }

    fn create_sandboxed_lua() -> Lua {
        Lua::new_with(
            mlua::StdLib::TABLE | mlua::StdLib::STRING | mlua::StdLib::MATH,
            mlua::LuaOptions::default(),
        )
        .unwrap()
    }

    #[test]
    fn register_host_functions_in_context() {
        let lua = create_sandboxed_lua();
        let config = make_test_config();
        let perms = Permissions::default();
        register_host_functions(&lua, config, "test-plugin".into(), perms, None, None).unwrap();

        let globals = lua.globals();
        let host: mlua::Table = globals.get(PLUGIN_HOST_GLOBAL).unwrap();

        let log_fn: mlua::Function = host.get("log").unwrap();
        let _: () = log_fn.call(("info", "test")).unwrap();

        let get_cfg_fn: mlua::Function = host.get("getConfig").unwrap();
        let result: mlua::Value = get_cfg_fn.call(("some.key",)).unwrap();
        assert!(result.is_nil());
    }

    #[test]
    fn host_get_config_returns_known_values() {
        let lua = create_sandboxed_lua();
        let config = make_test_config();
        let perms = Permissions {
            config: vec!["app.*".into()],
            ..Permissions::default()
        };
        register_host_functions(&lua, config, "test-plugin".into(), perms, None, None).unwrap();

        let globals = lua.globals();
        let host: mlua::Table = globals.get(PLUGIN_HOST_GLOBAL).unwrap();
        let get_cfg_fn: mlua::Function = host.get("getConfig").unwrap();

        let env: String = get_cfg_fn.call(("app.env",)).unwrap();
        assert_eq!(env, "test");

        let port: String = get_cfg_fn.call(("app.port",)).unwrap();
        assert_eq!(port, "9898");

        let unknown: mlua::Value = get_cfg_fn.call(("nonexistent.key",)).unwrap();
        assert!(unknown.is_nil());
    }

    #[test]
    fn host_http_get_blocked_without_permission() {
        let lua = create_sandboxed_lua();
        let config = make_test_config();
        let perms = Permissions::default();
        register_host_functions(&lua, config, "test-plugin".into(), perms, None, None).unwrap();

        let globals = lua.globals();
        let host: mlua::Table = globals.get(PLUGIN_HOST_GLOBAL).unwrap();
        let http_fn: mlua::Function = host.get("httpGet").unwrap();

        let result: String = http_fn.call(("https://evil.com",)).unwrap();
        assert!(result.contains("not allowed"));
    }

    #[test]
    fn host_http_post_blocked_without_permission() {
        let lua = create_sandboxed_lua();
        let config = make_test_config();
        let perms = Permissions::default();
        register_host_functions(&lua, config, "test-plugin".into(), perms, None, None).unwrap();

        let globals = lua.globals();
        let host: mlua::Table = globals.get(PLUGIN_HOST_GLOBAL).unwrap();
        let http_fn: mlua::Function = host.get("httpPost").unwrap();

        let result: String = http_fn.call(("https://evil.com", "{}")).unwrap();
        assert!(result.contains("not allowed"));
    }

    #[test]
    fn host_get_data_returns_nil_without_pool() {
        let lua = create_sandboxed_lua();
        let config = make_test_config();
        let perms = Permissions::default();
        register_host_functions(&lua, config, "test-plugin".into(), perms, None, None).unwrap();

        let globals = lua.globals();
        let host: mlua::Table = globals.get(PLUGIN_HOST_GLOBAL).unwrap();
        let get_data_fn: mlua::Function = host.get("getData").unwrap();

        let result: mlua::Value = get_data_fn.call(("some.key",)).unwrap();
        assert!(result.is_nil());
    }

    #[test]
    fn host_set_data_returns_false_without_pool() {
        let lua = create_sandboxed_lua();
        let config = make_test_config();
        let perms = Permissions::default();
        register_host_functions(&lua, config, "test-plugin".into(), perms, None, None).unwrap();

        let globals = lua.globals();
        let host: mlua::Table = globals.get(PLUGIN_HOST_GLOBAL).unwrap();
        let set_data_fn: mlua::Function = host.get("setData").unwrap();

        let result: bool = set_data_fn.call(("key", "val")).unwrap();
        assert!(!result);
    }

    #[test]
    fn host_get_post_returns_nil_without_pool() {
        let lua = create_sandboxed_lua();
        let config = make_test_config();
        let perms = Permissions::default();
        register_host_functions(&lua, config, "test-plugin".into(), perms, None, None).unwrap();

        let globals = lua.globals();
        let host: mlua::Table = globals.get(PLUGIN_HOST_GLOBAL).unwrap();
        let get_post_fn: mlua::Function = host.get("getPost").unwrap();

        let result: mlua::Value = get_post_fn.call(("some-slug",)).unwrap();
        assert!(result.is_nil());
    }

    #[test]
    fn host_db_query_returns_error_without_pool() {
        let lua = create_sandboxed_lua();
        let config = make_test_config();
        let perms = Permissions::default();
        register_host_functions(&lua, config, "test-plugin".into(), perms, None, None).unwrap();

        let globals = lua.globals();
        let host: mlua::Table = globals.get(PLUGIN_HOST_GLOBAL).unwrap();
        let db_fn: mlua::Function = host.get("dbQuery").unwrap();

        let result: String = db_fn.call(("SELECT 1", "[]")).unwrap();
        assert!(result.contains("no database access"));
    }

    #[test]
    fn host_db_query_rejects_non_select() {
        let lua = create_sandboxed_lua();
        let config = make_test_config();
        let perms = Permissions::default();
        register_host_functions(&lua, config, "test-plugin".into(), perms, None, None).unwrap();

        let globals = lua.globals();
        let host: mlua::Table = globals.get(PLUGIN_HOST_GLOBAL).unwrap();
        let db_fn: mlua::Function = host.get("dbQuery").unwrap();

        let result: String = db_fn.call(("DELETE FROM posts", "[]")).unwrap();
        assert!(result.contains("only SELECT"));
    }

    #[test]
    fn host_all_functions_registered() {
        let lua = create_sandboxed_lua();
        let config = make_test_config();
        let perms = Permissions::default();
        register_host_functions(&lua, config, "test-plugin".into(), perms, None, None).unwrap();

        let globals = lua.globals();
        let host: mlua::Table = globals.get(PLUGIN_HOST_GLOBAL).unwrap();
        for name in [
            "log",
            "getConfig",
            "httpGet",
            "httpPost",
            "getData",
            "setData",
            "getPost",
            "dbQuery",
            "dbExecute",
            "dbBegin",
            "dbCommit",
            "dbRollback",
            "dbPh",
            "vfsRead",
            "vfsWrite",
            "vfsDelete",
            "vfsExists",
            "vfsList",
            "vfsStat",
        ] {
            let _: mlua::Function = host.get(name).unwrap();
        }
    }
}