use mlua::{ExternalResult as _, Function, Lua, ObjectLike as _, Table, Value};
use sha2::Sha256;
mod cookies;
pub use cookies::{
CookieDefaults, RequestCookies, ResponseCookies, SetCookie, parse_set_cookie, sign, verify,
};
pub(crate) use cookies::{attach_cookie, build_cookie, merge_cookie_opts};
pub fn response_table(lua: &Lua, status: u16) -> mlua::Result<Table> {
let table = lua.create_table()?;
table.set("status", status)?;
table.set("headers", lua.create_table()?)?;
table.set("cookies", ResponseCookies::default())?;
Ok(table)
}
fn set_content_type(table: &Table, value: &str) -> mlua::Result<()> {
table.get::<Table>("headers")?.set("Content-Type", value)
}
pub(crate) fn register(lua: &Lua, nitr: &Table) -> mlua::Result<()> {
nitr.set(
"text",
lua.create_function(|lua, (body, status): (mlua::LuaString, Option<u16>)| {
let table = response_table(lua, status.unwrap_or(200))?;
set_content_type(&table, "text/plain; charset=utf-8")?;
table.set("body", body)?;
Ok(table)
})?,
)?;
nitr.set(
"html",
lua.create_function(|lua, (body, status): (mlua::LuaString, Option<u16>)| {
let table = response_table(lua, status.unwrap_or(200))?;
set_content_type(&table, "text/html; charset=utf-8")?;
table.set("body", body)?;
Ok(table)
})?,
)?;
nitr.set(
"redirect",
lua.create_function(|lua, (location, status): (String, Option<u16>)| {
let table = response_table(lua, status.unwrap_or(302))?;
table.get::<Table>("headers")?.set("Location", location)?;
Ok(table)
})?,
)?;
nitr.set(
"status",
lua.create_function(|lua, code: u16| response_table(lua, code))?,
)?;
nitr.set(
"sse",
lua.create_function(|lua, handler: Function| {
let table = response_table(lua, 200)?;
let headers = table.get::<Table>("headers")?;
headers.set("Content-Type", "text/event-stream")?;
headers.set("Cache-Control", "no-cache")?;
let body = lua.create_async_function(move |lua, writer: mlua::AnyUserData| {
let handler = handler.clone();
async move {
let send =
lua.create_async_function(move |_, (event, data): (String, Value)| {
let writer = writer.clone();
async move {
writer
.call_async_method::<()>("write", format_event(&event, data)?)
.await
}
})?;
handler.call_async::<()>(send).await
}
})?;
table.set("body", body)?;
Ok(table)
})?,
)?;
nitr.set(
"negotiate",
lua.create_async_function(|lua, (req, offers): (Value, Table)| async move {
negotiate(&lua, req, offers).await
})?,
)?;
nitr.set(
"error",
lua.create_function(|lua, (code, body): (u16, Option<Value>)| {
let table = response_table(lua, code)?;
match body {
None => {}
Some(Value::String(s)) => {
set_content_type(&table, "text/plain; charset=utf-8")?;
table.set("body", s)?;
}
Some(Value::Table(t)) => {
let t = Value::Table(t);
let body = crate::bounded::to_json_string(&t).into_lua_err()?;
set_content_type(&table, "application/json")?;
table.set("body", body)?;
}
Some(other) => {
return Err(mlua::Error::RuntimeError(format!(
"nitr.error body must be a string or a table, got {}",
other.type_name()
)));
}
}
Ok(table)
})?,
)?;
nitr.set(
"etag",
lua.create_function(|lua, (value, weak): (Value, Option<bool>)| {
let bytes = match &value {
Value::String(s) => s.as_bytes().to_vec(),
Value::Integer(n) => n.to_string().into_bytes(),
Value::Number(n) => n.to_string().into_bytes(),
other => crate::bounded::to_json_vec(other).into_lua_err()?,
};
let digest = <Sha256 as sha2::Digest>::digest(&bytes);
let tag = digest[..8].iter().fold(String::new(), |mut acc, byte| {
use std::fmt::Write as _;
let _ = write!(acc, "{byte:02x}");
acc
});
let prefix = if weak.unwrap_or(false) { "W/" } else { "" };
lua.create_string(format!("{prefix}\"{tag}\""))
})?,
)?;
let cookie = lua.create_table()?;
cookie.set(
"sign",
lua.create_function(|_, (name, value, secret): (String, String, String)| {
Ok(sign(&name, &value, &secret))
})?,
)?;
cookie.set(
"verify",
lua.create_function(
|lua, (name, signed, secret): (String, String, String)| match verify(
&name, &signed, &secret,
) {
Some(value) => Ok(Value::String(lua.create_string(value)?)),
None => Ok(Value::Nil),
},
)?,
)?;
nitr.set("cookie", cookie)?;
Ok(())
}
fn format_event(event: &str, data: Value) -> mlua::Result<String> {
if event.contains(['\r', '\n']) {
return Err(mlua::Error::RuntimeError(
"an SSE event name cannot contain a line break".into(),
));
}
let data = match data {
Value::String(s) => s.to_string_lossy().to_string(),
other => crate::bounded::to_json_string(&other).into_lua_err()?,
};
let mut out = format!("event: {event}\n");
for line in data.replace("\r\n", "\n").split(['\r', '\n']) {
out.push_str("data: ");
out.push_str(line);
out.push('\n');
}
out.push('\n');
Ok(out)
}
async fn negotiate(lua: &Lua, req: Value, offers: Table) -> mlua::Result<Value> {
let headers: Option<Table> = match &req {
Value::UserData(ud) => ud.get("headers").ok(),
Value::Table(t) => t.get("headers").ok(),
_ => None,
};
let accept = headers
.and_then(|h| h.get::<Option<String>>("accept").ok().flatten())
.unwrap_or_else(|| "*/*".to_string());
let (offered, mut values) = offer_list(&offers)?;
let offered_refs: Vec<&str> = offered.iter().map(String::as_str).collect();
match best_match(&accept, &offered_refs) {
Some(i) => match values.swap_remove(i) {
Value::Function(f) => f.call_async(req).await,
value => Ok(value),
},
None => {
let table = response_table(lua, 406)?;
set_content_type(&table, "text/plain; charset=utf-8")?;
table.set("body", "Not Acceptable")?;
Ok(Value::Table(table))
}
}
}
fn offer_list(offers: &Table) -> mlua::Result<(Vec<String>, Vec<Value>)> {
let mut pairs = Vec::new();
if offers.raw_len() > 0 {
for offer in offers.sequence_values::<Table>() {
let offer = offer?;
pairs.push((offer.raw_get::<String>(1)?, offer.raw_get::<Value>(2)?));
}
} else {
for pair in offers.pairs::<String, Value>() {
pairs.push(pair?);
}
pairs.sort_by(|a, b| a.0.cmp(&b.0));
}
Ok(pairs.into_iter().unzip())
}
pub fn best_match(accept: &str, offered: &[&str]) -> Option<usize> {
let mut best: Option<(usize, f32, u8)> = None;
for item in accept.split(',') {
let mut parts = item.trim().split(';');
let range = match parts.next() {
Some(r) if !r.trim().is_empty() => r.trim(),
_ => continue,
};
let mut q = 1.0_f32;
for param in parts {
if let Some(v) = param.trim().strip_prefix("q=") {
q = v.trim().parse().unwrap_or(0.0);
}
}
if q <= 0.0 {
continue;
}
for (i, offer) in offered.iter().enumerate() {
let specificity = if range.eq_ignore_ascii_case(offer) {
2
} else if range == "*/*" {
0
} else if let Some(main) = range.strip_suffix("/*") {
match offer.split('/').next() {
Some(offer_main) if offer_main.eq_ignore_ascii_case(main) => 1,
_ => continue,
}
} else {
continue;
};
let better = match best {
None => true,
Some((bi, bq, bs)) => {
q > bq || (q == bq && (specificity > bs || (specificity == bs && i < bi)))
}
};
if better {
best = Some((i, q, specificity));
}
}
}
best.map(|(i, _, _)| i)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sse_framing_cannot_be_broken_out_of() {
let lua = Lua::new();
let data = |s: &str| Value::String(lua.create_string(s).expect("string"));
assert_eq!(
format_event("msg", data("hi\rretry: 1\revent: admin")).expect("event"),
"event: msg\ndata: hi\ndata: retry: 1\ndata: event: admin\n\n"
);
assert_eq!(
format_event("msg", data("a\r\nb\nc")).expect("event"),
"event: msg\ndata: a\ndata: b\ndata: c\n\n"
);
assert!(format_event("x\nretry: 1", data("d")).is_err());
assert!(format_event("x\r", data("d")).is_err());
}
#[tokio::test]
async fn negotiation_ties_are_the_same_in_every_state() {
for _ in 0..32 {
let lua = Lua::new();
let req: Value = lua
.load("{ headers = { accept = '*/*' } }")
.eval()
.expect("req");
let map: Table = lua
.load("{ ['text/html'] = 'html', ['application/json'] = 'json', ['text/plain'] = 'text' }")
.eval()
.expect("offers");
let picked = negotiate(&lua, req.clone(), map).await.expect("negotiate");
assert_eq!(picked.as_string().expect("string"), "json");
let list: Table = lua
.load("{ { 'text/html', 'html' }, { 'application/json', 'json' } }")
.eval()
.expect("offers");
let picked = negotiate(&lua, req, list).await.expect("negotiate");
assert_eq!(picked.as_string().expect("string"), "html");
}
}
#[test]
fn accept_header_negotiation_honors_quality_and_wildcards() {
let offers = &["application/json", "text/html"];
assert_eq!(best_match("text/html, */*;q=0.5", offers), Some(1));
assert_eq!(
best_match("application/json;q=0.2, text/html;q=0.9", offers),
Some(1)
);
assert_eq!(best_match("text/*", offers), Some(1));
assert_eq!(best_match("*/*", offers), Some(0));
assert_eq!(best_match("text/html;q=0", offers), None);
assert_eq!(best_match("image/png", offers), None);
}
}