folk-plugin-http 0.3.2

HTTP plugin for Folk — accepts connections via hyper and dispatches to PHP workers
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
//! Lua hook pipeline for folk-plugin-http.
//!
//! Hook scripts are pre-compiled to Lua bytecode at startup and executed
//! per-request on a fresh [`mlua::Lua`] VM instance.  Sync hooks run in
//! the request critical path; async hooks fire-and-forget via `tokio::spawn`.

use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, Instant};

use axum::body::Body;
use axum::http::Response;
use mlua::{HookTriggers, Lua, LuaOptions, StdLib, Table, Value as LuaValue, VmState};
use tracing::warn;

use crate::config::{HookConfig, HookErrorBehavior, HookMode};

// ── Public context types ──────────────────────────────────────────────────────

/// Context passed to `request.before` and `request.error` hooks.
#[derive(Debug, Clone)]
pub struct RequestContext {
    pub method: String,
    pub path: String,
    pub query: String,
    pub client_ip: String,
    pub request_id: String,
    /// Mutable in sync hooks — mutations propagate to subsequent hooks.
    pub headers: HashMap<String, String>,
    /// Arbitrary key-value bag, mutable in sync hooks.
    pub extra: HashMap<String, String>,
    /// Error message. Set only for `request.error` hooks.
    pub error: Option<String>,
    /// True when a previous sync hook short-circuited the pipeline.
    pub short_circuited: bool,
}

/// Context passed to `response.headers` and `response.after` hooks.
#[derive(Debug, Clone)]
pub struct ResponseContext {
    pub status: u16,
    /// Mutable in sync hooks — mutations propagate to subsequent hooks.
    pub resp_headers: HashMap<String, String>,
    /// Present only for `response.after` hooks. Raw bytes — no lossy UTF-8 conversion.
    pub body: Option<Vec<u8>>,
    /// True when a previous sync hook short-circuited the pipeline.
    pub short_circuited: bool,
}

// ── Hook result ───────────────────────────────────────────────────────────────

/// Outcome of running a hook stage.
pub enum HookResult {
    /// Continue normal processing.
    Continue,
    /// A sync hook returned a short-circuit response.
    ShortCircuit(Response<Body>),
}

// ── Internals ─────────────────────────────────────────────────────────────────

struct CompiledHook {
    config: HookConfig,
    /// Pre-compiled Lua bytecode.
    bytecode: Vec<u8>,
}

// ── HookEngine ────────────────────────────────────────────────────────────────

/// Holds all pre-compiled hooks for the lifetime of the server.
#[derive(Clone)]
pub struct HookEngine {
    hooks: Arc<Vec<CompiledHook>>,
}

impl HookEngine {
    /// Compile all hook scripts.  Scripts that fail to compile are skipped with
    /// a WARN log; the server starts normally regardless.
    pub fn new(configs: &[HookConfig]) -> Self {
        let mut compiled = Vec::with_capacity(configs.len());
        for cfg in configs {
            match compile_script(cfg) {
                Ok(bytecode) => compiled.push(CompiledHook {
                    config: cfg.clone(),
                    bytecode,
                }),
                Err(e) => {
                    warn!(
                        event = %cfg.event,
                        script = %cfg.lua.display(),
                        error = %e,
                        "lua hook script failed to compile — skipping"
                    );
                }
            }
        }
        Self {
            hooks: Arc::new(compiled),
        }
    }

    /// Run `request.before` hooks.
    pub fn run_request_before(&self, ctx: &mut RequestContext) -> HookResult {
        self.run_request_stage("request.before", ctx)
    }

    /// Run `request.error` hooks — all spawned as async; no short-circuit.
    pub fn run_request_error(&self, ctx: &RequestContext) {
        for hook in self
            .hooks
            .iter()
            .filter(|h| h.config.event == "request.error")
        {
            let bytecode = hook.bytecode.clone();
            let ctx_clone = ctx.clone();
            let timeout = Duration::from_millis(hook.config.timeout_ms);
            tokio::spawn(async move {
                if let Err(e) = exec_request_hook(&bytecode, &ctx_clone, timeout) {
                    warn!(error = %e, "lua request.error hook failed");
                }
            });
        }
    }

    /// Run `response.headers` hooks.
    pub fn run_response_headers(&self, ctx: &mut ResponseContext) -> HookResult {
        self.run_response_stage("response.headers", ctx)
    }

    /// Run `response.after` hooks.
    pub fn run_response_after(&self, ctx: &mut ResponseContext) -> HookResult {
        self.run_response_stage("response.after", ctx)
    }

    /// Returns true when at least one compiled hook is registered for `event`.
    pub fn has_event(&self, event: &str) -> bool {
        self.hooks.iter().any(|h| h.config.event == event)
    }

    // ── Internal stage runners ────────────────────────────────────────────────

    fn run_request_stage(&self, event: &str, ctx: &mut RequestContext) -> HookResult {
        let hooks: Vec<_> = self
            .hooks
            .iter()
            .filter(|h| h.config.event == event)
            .collect();

        let (sync_hooks, async_hooks): (Vec<_>, Vec<_>) = hooks
            .into_iter()
            .partition(|h| h.config.mode == HookMode::Sync);

        let mut sc_response: Option<Response<Body>> = None;

        for hook in &sync_hooks {
            if sc_response.is_some() {
                break;
            }
            let timeout = Duration::from_millis(hook.config.timeout_ms);
            match exec_request_hook_mut(&hook.bytecode, ctx, timeout) {
                Ok(Some(resp)) => {
                    ctx.short_circuited = true;
                    sc_response = Some(resp);
                }
                Ok(None) => {}
                Err(e) => {
                    warn!(
                        event = event,
                        script = %hook.config.lua.display(),
                        error = %e,
                        "lua sync hook error"
                    );
                    if hook.config.on_error == HookErrorBehavior::FailClosed {
                        return HookResult::ShortCircuit(internal_error_response());
                    }
                }
            }
        }

        // Spawn async hooks with a read-only snapshot (taken after sync phase).
        let ctx_snap = ctx.clone();
        for hook in async_hooks {
            let bytecode = hook.bytecode.clone();
            let snap = ctx_snap.clone();
            let timeout = Duration::from_millis(hook.config.timeout_ms);
            tokio::spawn(async move {
                if let Err(e) = exec_request_hook(&bytecode, &snap, timeout) {
                    warn!(error = %e, "lua async request hook failed");
                }
            });
        }

        match sc_response {
            Some(resp) => HookResult::ShortCircuit(resp),
            None => HookResult::Continue,
        }
    }

    fn run_response_stage(&self, event: &str, ctx: &mut ResponseContext) -> HookResult {
        let hooks: Vec<_> = self
            .hooks
            .iter()
            .filter(|h| h.config.event == event)
            .collect();

        let (sync_hooks, async_hooks): (Vec<_>, Vec<_>) = hooks
            .into_iter()
            .partition(|h| h.config.mode == HookMode::Sync);

        let mut sc_response: Option<Response<Body>> = None;

        for hook in &sync_hooks {
            if sc_response.is_some() {
                break;
            }
            let timeout = Duration::from_millis(hook.config.timeout_ms);
            match exec_response_hook_mut(&hook.bytecode, ctx, timeout) {
                Ok(Some(resp)) => {
                    ctx.short_circuited = true;
                    sc_response = Some(resp);
                }
                Ok(None) => {}
                Err(e) => {
                    warn!(
                        event = event,
                        script = %hook.config.lua.display(),
                        error = %e,
                        "lua sync response hook error"
                    );
                    if hook.config.on_error == HookErrorBehavior::FailClosed {
                        return HookResult::ShortCircuit(internal_error_response());
                    }
                }
            }
        }

        let ctx_snap = ctx.clone();
        for hook in async_hooks {
            let bytecode = hook.bytecode.clone();
            let snap = ctx_snap.clone();
            let timeout = Duration::from_millis(hook.config.timeout_ms);
            tokio::spawn(async move {
                if let Err(e) = exec_response_hook(&bytecode, &snap, timeout) {
                    warn!(error = %e, "lua async response hook failed");
                }
            });
        }

        match sc_response {
            Some(resp) => HookResult::ShortCircuit(resp),
            None => HookResult::Continue,
        }
    }
}

// ── Script compilation ────────────────────────────────────────────────────────

fn compile_script(cfg: &HookConfig) -> Result<Vec<u8>, String> {
    let source =
        std::fs::read_to_string(&cfg.lua).map_err(|e| format!("read {:?}: {e}", cfg.lua))?;
    let lua = make_lua()?;
    let func = lua
        .load(&source)
        .into_function()
        .map_err(|e| format!("compile {:?}: {e}", cfg.lua))?;
    // dump() returns Vec<u8> directly in mlua 0.10
    Ok(func.dump(false))
}

fn make_lua() -> Result<Lua, String> {
    // Safe subset — no io, os, debug, package, coroutine.
    Lua::new_with(
        StdLib::TABLE | StdLib::STRING | StdLib::MATH | StdLib::UTF8,
        LuaOptions::default(),
    )
    .map_err(|e| format!("lua init: {e}"))
}

// ── Per-request execution helpers ─────────────────────────────────────────────

/// Execute bytecode with an immutable RequestContext.  Used for async hooks.
fn exec_request_hook(
    bytecode: &[u8],
    ctx: &RequestContext,
    timeout: Duration,
) -> Result<Option<Response<Body>>, String> {
    let lua = make_lua()?;
    install_timeout(&lua, timeout)?;

    let t = build_request_table(&lua, ctx)?;
    lua.globals().set("ctx", t).map_err(|e| e.to_string())?;

    let func = lua
        .load(bytecode)
        .into_function()
        .map_err(|e| e.to_string())?;
    let result: LuaValue = func.call(()).map_err(|e| e.to_string())?;
    response_from_lua(result)
}

/// Execute bytecode with a mutable RequestContext — mutations to headers/extra
/// are written back into `ctx` so subsequent sync hooks see them.
fn exec_request_hook_mut(
    bytecode: &[u8],
    ctx: &mut RequestContext,
    timeout: Duration,
) -> Result<Option<Response<Body>>, String> {
    let lua = make_lua()?;
    install_timeout(&lua, timeout)?;

    let t = build_request_table(&lua, ctx)?;
    lua.globals().set("ctx", t).map_err(|e| e.to_string())?;

    let func = lua
        .load(bytecode)
        .into_function()
        .map_err(|e| e.to_string())?;
    let result: LuaValue = func.call(()).map_err(|e| e.to_string())?;

    // Write back mutations.
    let ctx_global: Table = lua.globals().get("ctx").map_err(|e| e.to_string())?;
    let headers_table: Table = ctx_global.get("headers").map_err(|e| e.to_string())?;
    ctx.headers = lua_table_to_map(&headers_table)?;
    let extra_table: Table = ctx_global.get("extra").map_err(|e| e.to_string())?;
    ctx.extra = lua_table_to_map(&extra_table)?;

    response_from_lua(result)
}

/// Execute bytecode with an immutable ResponseContext.  Used for async hooks.
fn exec_response_hook(
    bytecode: &[u8],
    ctx: &ResponseContext,
    timeout: Duration,
) -> Result<Option<Response<Body>>, String> {
    let lua = make_lua()?;
    install_timeout(&lua, timeout)?;

    let t = build_response_table(&lua, ctx)?;
    lua.globals().set("ctx", t).map_err(|e| e.to_string())?;

    let func = lua
        .load(bytecode)
        .into_function()
        .map_err(|e| e.to_string())?;
    let result: LuaValue = func.call(()).map_err(|e| e.to_string())?;
    response_from_lua(result)
}

/// Execute bytecode with a mutable ResponseContext — mutations to resp_headers
/// and body are written back.
fn exec_response_hook_mut(
    bytecode: &[u8],
    ctx: &mut ResponseContext,
    timeout: Duration,
) -> Result<Option<Response<Body>>, String> {
    let lua = make_lua()?;
    install_timeout(&lua, timeout)?;

    let t = build_response_table(&lua, ctx)?;
    lua.globals().set("ctx", t).map_err(|e| e.to_string())?;

    let func = lua
        .load(bytecode)
        .into_function()
        .map_err(|e| e.to_string())?;
    let result: LuaValue = func.call(()).map_err(|e| e.to_string())?;

    // Write back mutations.
    let ctx_global: Table = lua.globals().get("ctx").map_err(|e| e.to_string())?;
    let rh_table: Table = ctx_global.get("resp_headers").map_err(|e| e.to_string())?;
    ctx.resp_headers = lua_table_to_map(&rh_table)?;

    if ctx.body.is_some() {
        // Only write back body if it was present (response.after event).
        // Use mlua::String to preserve raw bytes — avoids any UTF-8 conversion.
        let new_body: Option<mlua::String> = ctx_global.get("body").ok();
        ctx.body = new_body.map(|s| s.as_bytes().to_vec());
    }

    response_from_lua(result)
}

// ── Table builders ────────────────────────────────────────────────────────────

fn build_request_table(lua: &Lua, ctx: &RequestContext) -> Result<Table, String> {
    let t = lua.create_table().map_err(|e| e.to_string())?;
    t.set("method", ctx.method.as_str())
        .map_err(|e| e.to_string())?;
    t.set("path", ctx.path.as_str())
        .map_err(|e| e.to_string())?;
    t.set("query", ctx.query.as_str())
        .map_err(|e| e.to_string())?;
    t.set("client_ip", ctx.client_ip.as_str())
        .map_err(|e| e.to_string())?;
    t.set("request_id", ctx.request_id.as_str())
        .map_err(|e| e.to_string())?;
    t.set("short_circuited", ctx.short_circuited)
        .map_err(|e| e.to_string())?;
    let headers = map_to_lua_table(lua, &ctx.headers)?;
    t.set("headers", headers).map_err(|e| e.to_string())?;
    let extra = map_to_lua_table(lua, &ctx.extra)?;
    t.set("extra", extra).map_err(|e| e.to_string())?;
    if let Some(ref err) = ctx.error {
        t.set("error", err.as_str()).map_err(|e| e.to_string())?;
    }
    Ok(t)
}

fn build_response_table(lua: &Lua, ctx: &ResponseContext) -> Result<Table, String> {
    let t = lua.create_table().map_err(|e| e.to_string())?;
    t.set("status", ctx.status).map_err(|e| e.to_string())?;
    t.set("short_circuited", ctx.short_circuited)
        .map_err(|e| e.to_string())?;
    let rh = map_to_lua_table(lua, &ctx.resp_headers)?;
    t.set("resp_headers", rh).map_err(|e| e.to_string())?;
    if let Some(ref body) = ctx.body {
        // Lua strings are byte strings — binary bodies pass through without corruption.
        let lua_str = lua.create_string(body).map_err(|e| e.to_string())?;
        t.set("body", lua_str).map_err(|e| e.to_string())?;
    }
    Ok(t)
}

// ── Small utilities ───────────────────────────────────────────────────────────

fn install_timeout(lua: &Lua, timeout: Duration) -> Result<(), String> {
    let start = Instant::now();
    lua.set_hook(
        HookTriggers::new().every_nth_instruction(100),
        move |_lua, _debug| {
            if start.elapsed() > timeout {
                Err(mlua::Error::runtime("lua hook timeout"))
            } else {
                Ok(VmState::Continue)
            }
        },
    );
    Ok(())
}

fn map_to_lua_table(lua: &Lua, map: &HashMap<String, String>) -> Result<Table, String> {
    let t = lua.create_table().map_err(|e| e.to_string())?;
    for (k, v) in map {
        t.set(k.as_str(), v.as_str()).map_err(|e| e.to_string())?;
    }
    Ok(t)
}

fn lua_table_to_map(table: &Table) -> Result<HashMap<String, String>, String> {
    let mut map = HashMap::new();
    for pair in table.clone().pairs::<String, String>() {
        let (k, v) = pair.map_err(|e| e.to_string())?;
        map.insert(k, v);
    }
    Ok(map)
}

fn response_from_lua(value: LuaValue) -> Result<Option<Response<Body>>, String> {
    match value {
        LuaValue::Nil => Ok(None),
        LuaValue::Table(t) => {
            let status: u16 = t.get("status").unwrap_or(200u16);
            let body: String = t.get("body").unwrap_or_default();
            let resp = Response::builder()
                .status(status)
                .body(Body::from(body))
                .map_err(|e| e.to_string())?;
            Ok(Some(resp))
        }
        _ => Ok(None),
    }
}

fn internal_error_response() -> Response<Body> {
    Response::builder()
        .status(500)
        .body(Body::from("internal server error (hook fail_closed)"))
        .unwrap()
}