1use std::collections::BTreeMap;
16
17use mlua::Value;
18
19pub(super) const MAX_TEMPLATE_CHARS: usize = 500;
22
23pub(super) const MAX_REASON_CHARS: usize = 200;
26
27#[derive(Debug, Clone, PartialEq)]
30pub(crate) enum Param {
31 Str(String),
32 Num(f64),
33 Bool(bool),
34 Size(u64),
36 List(Vec<Param>),
38}
39
40impl Param {
41 pub(crate) fn render(&self) -> String {
43 match self {
44 Self::Str(s) => s.clone(),
45 Self::Num(n) => fmt_num(*n),
46 Self::Bool(b) => b.to_string(),
47 Self::Size(bytes) => fmt_size(*bytes),
48 Self::List(items) => items
49 .iter()
50 .map(|item| match item {
51 Self::Str(s) => format!("\"{s}\""),
52 other => other.render(),
53 })
54 .collect::<Vec<_>>()
55 .join(", "),
56 }
57 }
58
59 pub(crate) fn to_json(&self) -> serde_json::Value {
61 match self {
62 Self::Str(s) => serde_json::Value::String(s.clone()),
63 Self::Num(n) => serde_json::Number::from_f64(*n)
64 .map(serde_json::Value::Number)
65 .unwrap_or(serde_json::Value::Null),
66 Self::Bool(b) => serde_json::Value::Bool(*b),
67 Self::Size(bytes) => serde_json::Value::from(*bytes),
68 Self::List(items) => {
69 serde_json::Value::Array(items.iter().map(Self::to_json).collect())
70 }
71 }
72 }
73
74 pub(crate) fn to_lua(&self, lua: &mlua::Lua) -> mlua::Result<Value> {
76 Ok(match self {
77 Self::Str(s) => Value::String(lua.create_string(s)?),
78 Self::Num(n) if n.fract() == 0.0 && n.abs() < 9.0e15 => Value::Integer(*n as i64),
79 Self::Num(n) => Value::Number(*n),
80 Self::Bool(b) => Value::Boolean(*b),
81 Self::Size(bytes) => Value::Integer(i64::try_from(*bytes).unwrap_or(i64::MAX)),
82 Self::List(items) => {
83 let t = lua.create_table_with_capacity(items.len(), 0)?;
84 for (i, item) in items.iter().enumerate() {
85 t.raw_set(i + 1, item.to_lua(lua)?)?;
86 }
87 Value::Table(t)
88 }
89 })
90 }
91}
92
93pub(crate) fn fmt_num(n: f64) -> String {
95 if n.fract() == 0.0 && n.abs() < 1.0e15 {
96 format!("{}", n as i64)
97 } else {
98 format!("{n}")
99 }
100}
101
102pub fn fmt_size(bytes: u64) -> String {
105 const UNITS: [(&str, u64); 3] = [("GB", 1 << 30), ("MB", 1 << 20), ("KB", 1 << 10)];
106 for (unit, size) in UNITS {
107 if bytes >= size {
108 let value = bytes as f64 / size as f64;
109 return if value.fract() == 0.0 {
110 format!("{} {unit}", value as u64)
111 } else {
112 format!("{value:.1} {unit}")
113 };
114 }
115 }
116 format!("{bytes} B")
117}
118
119const COMMON_PLACEHOLDERS: &[&str] = &["label", "path"];
121
122pub(crate) fn rule_params(rule: &str) -> &'static [&'static str] {
127 match rule {
128 "type" => &["type"],
129 "min_len" | "min" | "exclusive_min" | "min_items" | "min_keys" | "min_bytes"
130 | "min_width" | "min_height" => &["min"],
131 "max_len" | "max" | "exclusive_max" | "max_items" | "max_keys" | "max_bytes"
132 | "max_total_bytes" | "max_width" | "max_height" | "max_pixels" => &["max"],
133 "len" => &["len"],
134 "multiple_of" => &["step"],
135 "decimals" => &["decimals"],
136 "format" => &["format"],
137 "one_of" | "not_one_of" | "contains_any" | "contains_all" => &["choices"],
138 "equals" => &["expected"],
139 "starts_with" | "ends_with" | "does_not_contain" => &["text"],
140 "contains" => &["text", "item"],
141 "after" | "before" => &["limit"],
142 "types" => &["types"],
143 "extensions" => &["extensions"],
144 "filename" => &["text"],
145 "aspect" => &["aspect"],
146 "at_least_one" | "mutually_exclusive" | "dependent_required" => &["fields"],
147 "equal_fields" | "ordered" => &["field"],
148 _ => &[],
149 }
150}
151
152pub fn rule_codes() -> &'static [&'static str] {
158 RULE_CODES
159}
160
161pub(crate) const RULE_CODES: &[&str] = &[
162 "type",
163 "required",
164 "min_len",
165 "max_len",
166 "len",
167 "min",
168 "max",
169 "exclusive_min",
170 "exclusive_max",
171 "multiple_of",
172 "decimals",
173 "format",
174 "one_of",
175 "not_one_of",
176 "equals",
177 "starts_with",
178 "ends_with",
179 "contains",
180 "does_not_contain",
181 "after",
182 "before",
183 "min_items",
184 "max_items",
185 "unique",
186 "contains_any",
187 "contains_all",
188 "min_keys",
189 "max_keys",
190 "max_bytes",
191 "min_bytes",
192 "max_total_bytes",
193 "types",
194 "extensions",
195 "match_extension",
196 "executable",
197 "filename",
198 "min_width",
199 "max_width",
200 "min_height",
201 "max_height",
202 "max_pixels",
203 "aspect",
204 "dimensions",
205 "utf8",
206 "at_least_one",
207 "mutually_exclusive",
208 "dependent_required",
209 "equal_fields",
210 "ordered",
211 "unknown",
212 "keys",
213 "check",
214 "json",
215 "multipart",
216 "body",
217];
218
219fn characters(count: &str) -> String {
223 match count {
224 "1" => "1 character".into(),
225 n => format!("{n} characters"),
226 }
227}
228
229pub(crate) fn default_message(rule: &str, kind: &str, params: &BTreeMap<&str, Param>) -> String {
230 let p = |name: &str| params.get(name).map(Param::render).unwrap_or_default();
231 match rule {
232 "type" => match kind {
233 "string" => "must be a string".into(),
234 "integer" => "must be an integer".into(),
235 "number" => "must be a number".into(),
236 "boolean" => "must be a boolean".into(),
237 "array" => "must be a list".into(),
238 "table" | "map" => "must be an object".into(),
239 "file" => "must be a file".into(),
240 "any" => "must be a JSON value".into(),
241 _ => format!("must be a {kind}"),
242 },
243 "required" => "is required".into(),
244 "min_len" => format!("must be at least {}", characters(&p("min"))),
245 "max_len" => format!("must be at most {}", characters(&p("max"))),
246 "len" => format!("must be exactly {}", characters(&p("len"))),
247 "min" => format!("must be at least {}", p("min")),
248 "max" => format!("must be at most {}", p("max")),
249 "exclusive_min" => format!("must be greater than {}", p("min")),
250 "exclusive_max" => format!("must be less than {}", p("max")),
251 "multiple_of" => format!("must be a multiple of {}", p("step")),
252 "decimals" => format!("must have at most {} decimal places", p("decimals")),
253 "format" => format!("must be {}", p("format")),
256 "one_of" => format!("must be one of: {}", p("choices")),
257 "not_one_of" => format!("must not be one of: {}", p("choices")),
258 "equals" => format!("must be {}", p("expected")),
259 "starts_with" => format!("must start with {}", p("text")),
260 "ends_with" => format!("must end with {}", p("text")),
261 "contains" if kind == "array" => format!("must include {}", p("item")),
262 "contains" => format!("must contain {}", p("text")),
263 "does_not_contain" => format!("must not contain {}", p("text")),
264 "after" if params.get("limit") == Some(&Param::Str("now".into())) => {
265 "must be in the future".into()
266 }
267 "before" if params.get("limit") == Some(&Param::Str("now".into())) => {
268 "must be in the past".into()
269 }
270 "after" => format!("must be after {}", p("limit")),
271 "before" => format!("must be before {}", p("limit")),
272 "min_items" => format!("must have at least {} items", p("min")),
273 "max_items" => format!("must have at most {} items", p("max")),
274 "unique" => "must not contain duplicates".into(),
275 "contains_any" => format!("must include one of: {}", p("choices")),
276 "contains_all" => format!("must include all of: {}", p("choices")),
277 "min_keys" => format!("must have at least {} entries", p("min")),
278 "max_keys" => format!("must have at most {} entries", p("max")),
279 "max_bytes" if kind == "file" => format!("must be at most {}", p("max")),
280 "max_bytes" => format!("must be at most {} in size", p("max")),
281 "min_bytes" => format!("must be at least {}", p("min")),
282 "max_total_bytes" => format!("must be at most {} in total", p("max")),
283 "types" => format!("must be {}", p("types")),
284 "extensions" => format!("must have one of these extensions: {}", p("extensions")),
285 "match_extension" => "must have an extension that matches its content".into(),
286 "executable" => "must not be an executable".into(),
287 "min_width" => format!("must be at least {} px wide", p("min")),
288 "max_width" => format!("must be at most {} px wide", p("max")),
289 "min_height" => format!("must be at least {} px tall", p("min")),
290 "max_height" => format!("must be at most {} px tall", p("max")),
291 "max_pixels" => format!("must be at most {} pixels", p("max")),
292 "aspect" => format!("must have a {} aspect ratio", p("aspect")),
293 "dimensions" => "must have readable image dimensions".into(),
294 "utf8" => "must be UTF-8 text".into(),
295 "at_least_one" => format!("at least one of {} is required", p("fields")),
296 "mutually_exclusive" => format!("only one of {} may be given", p("fields")),
297 "dependent_required" => format!("requires {}", p("fields")),
298 "equal_fields" => format!("must equal {}", p("field")),
299 "ordered" => format!("must be after {}", p("field")),
300 "unknown" => "is not a known field".into(),
301 "keys" => "must have string keys".into(),
302 "filename" if params.contains_key("text") => {
303 format!("must have a valid name: {}", p("text"))
304 }
305 "filename" => "must have a name".into(),
306 "check" => "is invalid".into(),
307 "json" => "must be valid JSON".into(),
308 "multipart" => "must be a well-formed multipart body".into(),
309 "body" => "must be an object".into(),
310 other => format!("failed the {other} rule"),
311 }
312}
313
314#[derive(Debug, Clone, PartialEq)]
316enum Seg {
317 Lit(String),
318 Var(String),
319}
320
321#[derive(Debug, Clone, PartialEq)]
323pub(crate) struct Template {
324 segs: Vec<Seg>,
325}
326
327impl Template {
328 pub(crate) fn compile(text: &str, allowed: &[&str], what: &str) -> mlua::Result<Self> {
331 let bad =
332 |msg: String| mlua::Error::RuntimeError(format!("invalid message for {what}: {msg}"));
333 if text.chars().count() > MAX_TEMPLATE_CHARS {
334 return Err(bad(format!("longer than {MAX_TEMPLATE_CHARS} characters")));
335 }
336 if text.chars().any(|c| c.is_control()) {
337 return Err(bad("contains a control character".into()));
338 }
339 let mut segs = Vec::new();
340 let mut lit = String::new();
341 let mut rest = text;
342 while let Some(start) = rest.find('{') {
343 lit.push_str(&rest[..start]);
344 let after = &rest[start + 1..];
345 let Some(end) = after.find('}') else {
346 return Err(bad("unbalanced `{`".into()));
347 };
348 let name = &after[..end];
349 if name.is_empty() || !name.chars().all(|c| c.is_ascii_lowercase() || c == '_') {
350 return Err(bad(format!("bad placeholder `{{{name}}}`")));
351 }
352 if !allowed.contains(&name) && !COMMON_PLACEHOLDERS.contains(&name) {
353 let mut names: Vec<&str> = allowed.to_vec();
354 names.extend(COMMON_PLACEHOLDERS);
355 return Err(bad(format!(
356 "unknown placeholder `{{{name}}}` (allowed: {})",
357 names
358 .iter()
359 .map(|n| format!("{{{n}}}"))
360 .collect::<Vec<_>>()
361 .join(", ")
362 )));
363 }
364 if !lit.is_empty() {
365 segs.push(Seg::Lit(std::mem::take(&mut lit)));
366 }
367 segs.push(Seg::Var(name.to_string()));
368 rest = &after[end + 1..];
369 }
370 if rest.contains('}') {
371 return Err(bad("unbalanced `}`".into()));
372 }
373 lit.push_str(rest);
374 if !lit.is_empty() {
375 segs.push(Seg::Lit(lit));
376 }
377 Ok(Self { segs })
378 }
379
380 pub(crate) fn render(&self, params: &BTreeMap<&str, Param>, label: &str, path: &str) -> String {
383 let mut out = String::new();
384 for seg in &self.segs {
385 match seg {
386 Seg::Lit(s) => out.push_str(s),
387 Seg::Var(name) => match name.as_str() {
388 "label" => out.push_str(label),
389 "path" => out.push_str(path),
390 other => {
391 out.push_str(¶ms.get(other).map(Param::render).unwrap_or_default())
392 }
393 },
394 }
395 }
396 out
397 }
398}
399
400pub(crate) fn sanitize(text: &str) -> String {
403 text.chars()
404 .filter(|c| !c.is_control())
405 .take(MAX_REASON_CHARS)
406 .collect()
407}
408
409pub(crate) fn compile_messages(
412 table: &mlua::Table,
413 what: &str,
414) -> mlua::Result<BTreeMap<String, Template>> {
415 let mut out = BTreeMap::new();
416 for pair in table.pairs::<Value, Value>() {
417 let (key, value) = pair?;
418 let Value::String(key) = key else {
419 return Err(mlua::Error::RuntimeError(format!(
420 "invalid messages for {what}: keys must be rule names"
421 )));
422 };
423 let rule = key.to_string_lossy().to_string();
424 if rule != "summary" && !RULE_CODES.contains(&rule.as_str()) {
425 return Err(mlua::Error::RuntimeError(format!(
426 "invalid messages for {what}: unknown rule `{rule}`"
427 )));
428 }
429 let Value::String(text) = value else {
430 return Err(mlua::Error::RuntimeError(format!(
431 "invalid messages for {what}: the message for `{rule}` must be a string"
432 )));
433 };
434 let template = Template::compile(
435 &text.to_string_lossy(),
436 rule_params(&rule),
437 &format!("{what} (rule `{rule}`)"),
438 )?;
439 out.insert(rule, template);
440 }
441 Ok(out)
442}
443
444#[derive(Debug, Default)]
447pub(crate) struct AppMessages {
448 pub(crate) rules: BTreeMap<String, Template>,
449 pub(crate) summary: Option<String>,
450 pub(crate) frozen: bool,
453}
454
455#[cfg(test)]
456mod tests {
457 use super::*;
458
459 #[test]
460 fn templates_substitute_only_known_placeholders() {
461 let t = Template::compile("{label} must be at least {min}", &["min"], "x").expect("ok");
462 let params = BTreeMap::from([("min", Param::Num(3.0))]);
463 assert_eq!(
464 t.render(¶ms, "Age", "body.age"),
465 "Age must be at least 3"
466 );
467 for bad in ["{value}", "{min", "min}", "{Min}", "{}"] {
468 assert!(Template::compile(bad, &["min"], "x").is_err(), "{bad}");
469 }
470 }
471
472 #[test]
473 fn sizes_and_numbers_render_for_people() {
474 assert_eq!(fmt_size(512), "512 B");
475 assert_eq!(fmt_size(2 * 1024 * 1024), "2 MB");
476 assert_eq!(fmt_size(1536 * 1024), "1.5 MB");
477 assert_eq!(fmt_num(3.0), "3");
478 assert_eq!(fmt_num(0.5), "0.5");
479 assert_eq!(
480 Param::List(vec![Param::Str("a".into()), Param::Num(2.0)]).render(),
481 "\"a\", 2"
482 );
483 }
484
485 #[test]
486 fn sanitize_caps_and_strips_control_characters() {
487 let long = "x".repeat(400);
488 assert_eq!(sanitize(&long).chars().count(), MAX_REASON_CHARS);
489 assert_eq!(sanitize("a\nb\x1bc"), "abc");
490 }
491}