solidb 1.0.2

A lightweight, high-performance structured database server written in Rust.
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
//! Enhanced Lua HTTP Helper Methods
//!
//! This module provides HTTP utilities like redirects, cookies, caching,
//! and response helpers for Lua scripts in SoliDB.

use cookie::{Cookie as HttpCookie, SameSite};
use lru::LruCache;
use mlua::{Function, Lua, Result as LuaResult, Value as LuaValue};
use serde_json::Value as JsonValue;
use std::sync::{Arc, Mutex};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use time::{format_description, OffsetDateTime};

use crate::scripting::lua_to_json_value;

/// Global cache for HTTP caching
pub struct HttpCache {
    cache: Arc<Mutex<LruCache<String, CacheEntry>>>,
}

#[derive(Clone)]
struct CacheEntry {
    value: JsonValue,
    expires_at: SystemTime,
}

impl HttpCache {
    pub fn new(capacity: usize) -> Self {
        Self {
            cache: Arc::new(Mutex::new(LruCache::new(
                std::num::NonZeroUsize::new(capacity).unwrap(),
            ))),
        }
    }

    pub fn get(&self, key: &str) -> Option<JsonValue> {
        let mut cache = self.cache.lock().unwrap();
        if let Some(entry) = cache.get(key) {
            if entry.expires_at > SystemTime::now() {
                return Some(entry.value.clone());
            } else {
                cache.pop(key);
            }
        }
        None
    }

    pub fn set(&self, key: String, value: JsonValue, ttl_seconds: Option<u64>) {
        let mut cache = self.cache.lock().unwrap();
        let expires_at = if let Some(ttl) = ttl_seconds {
            SystemTime::now() + Duration::from_secs(ttl)
        } else {
            SystemTime::now() + Duration::from_secs(3600) // Default 1 hour
        };

        cache.put(key, CacheEntry { value, expires_at });
    }
}

/// Parse an origin entry from `SOLIDB_ALLOWED_REDIRECT_ORIGINS` into
/// (scheme, host, port). Accepts forms `host`, `scheme://host`, `scheme://host:port`.
/// `host`-only entries match either http or https.
fn parse_allowed_origin(entry: &str) -> Option<(Option<String>, String, Option<u16>)> {
    let entry = entry.trim();
    if entry.is_empty() {
        return None;
    }
    if entry.contains("://") {
        let parsed = url::Url::parse(entry).ok()?;
        let host = parsed.host_str()?.to_lowercase();
        Some((Some(parsed.scheme().to_string()), host, parsed.port()))
    } else {
        // Bare host (and optional :port)
        let (host, port) = match entry.rsplit_once(':') {
            Some((h, p)) if p.chars().all(|c| c.is_ascii_digit()) => {
                (h.to_lowercase(), p.parse::<u16>().ok())
            }
            _ => (entry.to_lowercase(), None),
        };
        Some((None, host, port))
    }
}

/// Returns true iff `url` matches one of the configured allowed origins.
/// Match is by exact (scheme, host, port) — never substring.
fn redirect_url_allowed(url_str: &str, allowed: &[&str]) -> bool {
    let parsed = match url::Url::parse(url_str) {
        Ok(u) => u,
        Err(_) => return false,
    };
    let url_host = match parsed.host_str() {
        Some(h) => h.to_lowercase(),
        None => return false,
    };
    let url_scheme = parsed.scheme();
    let url_port = parsed.port_or_known_default();

    allowed.iter().any(|raw| {
        let (allowed_scheme, allowed_host, allowed_port) = match parse_allowed_origin(raw) {
            Some(t) => t,
            None => return false,
        };
        if allowed_host != url_host {
            return false;
        }
        if let Some(scheme) = &allowed_scheme {
            if scheme != url_scheme {
                return false;
            }
        }
        if let Some(port) = allowed_port {
            if Some(port) != url_port {
                return false;
            }
        }
        true
    })
}

/// Create solidb.redirect(url) -> error with redirect status function
pub fn create_redirect_function(lua: &Lua) -> LuaResult<Function> {
    lua.create_function(|_, url: String| {
        let allowed_origins = std::env::var("SOLIDB_ALLOWED_REDIRECT_ORIGINS").unwrap_or_default();
        let allowed_list: Vec<&str> = allowed_origins
            .split(',')
            .map(str::trim)
            .filter(|o| !o.is_empty())
            .collect();

        // Absolute URLs are checked against the allowlist when one is configured.
        // Relative paths and (when no allowlist is set) absolute URLs are passed through —
        // SEC-095 made the allowlist opt-in.
        let is_absolute = url.starts_with("http://") || url.starts_with("https://");
        if is_absolute && !allowed_list.is_empty() && !redirect_url_allowed(&url, &allowed_list) {
            return Err(mlua::Error::RuntimeError(
                "REDIRECT: Forbidden - redirect to untrusted domain".to_string(),
            ));
        }

        Err::<LuaValue, mlua::Error>(mlua::Error::RuntimeError(format!("REDIRECT:{}", url)))
    })
}

/// Create solidb.set_cookie(name, value, options) function
pub fn create_set_cookie_function(lua: &Lua) -> LuaResult<Function> {
    lua.create_function(
        move |_lua, (name, value, options): (String, String, Option<LuaValue>)| {
            let mut cookie = HttpCookie::new(name, value);

            if let Some(LuaValue::Table(t)) = options {
                // Parse expires timestamp or ISO string
                if let Ok(expires) = t.get::<String>("expires") {
                    if let Ok(timestamp) = expires.parse::<i64>() {
                        if let Ok(datetime) = OffsetDateTime::from_unix_timestamp(timestamp) {
                            cookie.set_expires(datetime);
                        }
                    } else if let Ok(datetime) =
                        OffsetDateTime::parse(&expires, &format_description::well_known::Rfc3339)
                    {
                        cookie.set_expires(datetime);
                    }
                }

                // Path
                if let Ok(path) = t.get::<String>("path") {
                    cookie.set_path(path);
                }

                // Domain
                if let Ok(domain) = t.get::<String>("domain") {
                    cookie.set_domain(domain);
                }

                // Secure flag
                if let Ok(secure) = t.get::<bool>("secure") {
                    cookie.set_secure(secure);
                }

                // HttpOnly flag
                if let Ok(http_only) = t.get::<bool>("httpOnly") {
                    cookie.set_http_only(http_only);
                }

                // SameSite
                if let Ok(same_site) = t.get::<String>("sameSite") {
                    match same_site.as_str() {
                        "Strict" => cookie.set_same_site(SameSite::Strict),
                        "Lax" => cookie.set_same_site(SameSite::Lax),
                        "None" => cookie.set_same_site(SameSite::None),
                        _ => {}
                    }
                }
            }

            // Set the cookie as a special header that will be processed by the response handler
            let cookie_str = cookie.to_string();

            // This should be captured by the response system
            tracing::debug!("Setting cookie: {}", cookie_str);

            Ok(true)
        },
    )
}

/// Global HTTP cache singleton
fn get_http_cache() -> &'static HttpCache {
    use std::sync::OnceLock;
    static HTTP_CACHE: OnceLock<HttpCache> = OnceLock::new();
    HTTP_CACHE.get_or_init(|| HttpCache::new(1000))
}

/// Create solidb.cache(key, value, ttl_seconds) -> boolean function
pub fn create_cache_function(lua: &Lua) -> LuaResult<Function> {
    lua.create_function(
        move |lua, (key, value, ttl): (String, LuaValue, Option<u64>)| {
            let json_value = lua_to_json_value(lua, value)?;
            get_http_cache().set(key, json_value, ttl);
            Ok(true)
        },
    )
}

/// Create solidb.cache_get(key) -> value function
pub fn create_cache_get_function(lua: &Lua) -> LuaResult<Function> {
    lua.create_function(move |lua, key: String| {
        if let Some(value) = get_http_cache().get(&key) {
            json_to_lua(lua, &value)
        } else {
            Ok(LuaValue::Nil)
        }
    })
}

/// Create response.html(content) function
pub fn create_response_html_function(_lua: &Lua) -> LuaResult<Function> {
    let lua_ref = _lua;
    lua_ref.create_function(move |lua, content: String| {
        // Return a special marker that response system will understand
        Ok(LuaValue::String(
            lua.create_string(format!("HTML_RESPONSE:{}", content))
                .unwrap(),
        ))
    })
}

/// Create response.file(path) function
pub fn create_response_file_function(_lua: &Lua) -> LuaResult<Function> {
    let lua_ref = _lua;
    lua_ref.create_function(move |lua, path: String| {
        // Security: reject absolute paths and any ParentDir component.
        // Component-based check avoids false positives on legit names like `v1.2..md`
        // and false negatives on tricks substring-matching would miss.
        let p = std::path::Path::new(&path);
        let has_parent_dir = p
            .components()
            .any(|c| matches!(c, std::path::Component::ParentDir));
        if p.is_absolute() || has_parent_dir {
            let file_info = lua.create_table()?;
            file_info.set(
                "error",
                "Invalid path: absolute paths and parent-dir traversal are not allowed",
            )?;
            file_info.set("exists", false)?;
            return Ok(LuaValue::Table(file_info));
        }

        // Check if file exists and get its metadata
        match std::fs::metadata(&path) {
            Ok(metadata) => {
                let file_info = lua.create_table()?;
                file_info.set("path", path.clone())?;
                file_info.set("size", metadata.len())?;
                file_info.set("exists", true)?;

                if let Ok(modified) = metadata.modified() {
                    if let Ok(duration) = modified.duration_since(UNIX_EPOCH) {
                        file_info.set("modified", duration.as_secs())?;
                    }
                }

                Ok(LuaValue::Table(file_info))
            }
            Err(_) => {
                let file_info = lua.create_table()?;
                file_info.set("path", path)?;
                file_info.set("exists", false)?;
                Ok(LuaValue::Table(file_info))
            }
        }
    })
}

/// Create response.stream(data) function
pub fn create_response_stream_function(lua: &Lua) -> LuaResult<Function> {
    lua.create_function(|lua, data: LuaValue| {
        // Return a marker indicating streaming response
        let stream_info = lua.create_table()?;
        stream_info.set("type", "stream")?;
        stream_info.set("data", data)?;
        Ok(LuaValue::Table(stream_info))
    })
}

/// Create response.cors(options) function
pub fn create_response_cors_function(lua: &Lua) -> LuaResult<Function> {
    lua.create_function(|lua, options: Option<LuaValue>| {
        let cors_info = lua.create_table()?;

        if let Some(opts) = options {
            if let LuaValue::Table(t) = opts {
                // Origins
                if let Ok(origins) = t.get::<LuaValue>("origins") {
                    cors_info.set("origins", origins)?;
                }

                // Methods
                if let Ok(methods) = t.get::<LuaValue>("methods") {
                    cors_info.set("methods", methods)?;
                }

                // Headers
                if let Ok(headers) = t.get::<LuaValue>("headers") {
                    cors_info.set("headers", headers)?;
                }

                // Credentials
                if let Ok(credentials) = t.get::<bool>("credentials") {
                    cors_info.set("credentials", credentials)?;
                }

                // Max age
                if let Ok(max_age) = t.get::<u64>("max_age") {
                    cors_info.set("max_age", max_age)?;
                }
            }
        } else {
            // Default CORS settings
            cors_info.set("origins", "*")?;
            cors_info.set("methods", "GET, POST, PUT, DELETE, OPTIONS")?;
            cors_info.set("headers", "Content-Type, Authorization")?;
        }

        // Return CORS configuration that will be processed by response system
        Ok(LuaValue::Table(cors_info))
    })
}

/// Helper to convert JSON to Lua value
fn json_to_lua(lua: &Lua, json: &JsonValue) -> LuaResult<LuaValue> {
    match json {
        JsonValue::Null => Ok(LuaValue::Nil),
        JsonValue::Bool(b) => Ok(LuaValue::Boolean(*b)),
        JsonValue::Number(n) => {
            if let Some(i) = n.as_i64() {
                Ok(LuaValue::Integer(i))
            } else if let Some(f) = n.as_f64() {
                Ok(LuaValue::Number(f))
            } else {
                Ok(LuaValue::Nil)
            }
        }
        JsonValue::String(s) => Ok(LuaValue::String(lua.create_string(s)?)),
        JsonValue::Array(arr) => {
            let table = lua.create_table()?;
            for (i, v) in arr.iter().enumerate() {
                table.set(i + 1, json_to_lua(lua, v)?)?;
            }
            Ok(LuaValue::Table(table))
        }
        JsonValue::Object(obj) => {
            let table = lua.create_table()?;
            for (k, v) in obj {
                table.set(k.clone(), json_to_lua(lua, v)?)?;
            }
            Ok(LuaValue::Table(table))
        }
    }
}

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

    #[test]
    fn test_redirect_function() {
        let lua = Lua::new();
        let redirect_fn = create_redirect_function(&lua).unwrap();

        let result: Result<LuaValue, _> = redirect_fn.call("https://example.com");
        match result {
            Ok(_) => panic!("Expected error"),
            Err(e) => assert!(e.to_string().contains("REDIRECT:https://example.com")),
        }
    }

    #[test]
    fn test_cache_function() {
        let lua = Lua::new();
        let cache_fn = create_cache_function(&lua).unwrap();

        let data = lua.create_table().unwrap();
        data.set("test", "value").unwrap();

        let result: Result<bool, _> =
            cache_fn.call(("test_key".to_string(), LuaValue::Table(data), Some(60)));
        assert!(result.unwrap());
    }

    #[test]
    fn test_response_html() {
        let lua = Lua::new();
        let html_fn = create_response_html_function(&lua).unwrap();

        let result: Result<LuaValue, _> = html_fn.call("<h1>Test</h1>");
        match result {
            Ok(LuaValue::String(s)) => {
                assert!(s.to_str().unwrap().starts_with("HTML_RESPONSE:"));
            }
            _ => panic!("Expected string result"),
        }
    }
}