1use std::collections::BTreeMap;
2use std::fmt;
3use std::path::{Path, PathBuf};
4
5use serde::de::{self, SeqAccess, Visitor};
6use serde::{Deserialize, Deserializer, Serialize};
7
8use crate::Error;
9
10#[derive(Debug, Clone, Default, Deserialize)]
12#[serde(default)]
13pub struct Config {
14 pub project: ProjectConfig,
15 pub run: RunConfig,
16 pub custom: CustomConfig,
18 pub rules: BTreeMap<String, String>,
20 pub rule: RuleOptions,
22 pub semantics: SemanticsConfig,
24}
25
26#[derive(Debug, Clone, Default, Deserialize)]
28#[serde(default)]
29pub struct SemanticsConfig {
30 pub luneblox: RuntimeSemantics,
31 pub lute: RuntimeSemantics,
32}
33
34#[derive(Debug, Clone, Default, Deserialize)]
37#[serde(default)]
38pub struct RuntimeSemantics {
39 pub sources: Vec<String>,
41 pub source_calls: Vec<String>,
43 pub command_sinks: Vec<String>,
45 pub path_sinks: Vec<String>,
47 pub url_sinks: Vec<String>,
49 pub log_sinks: Vec<String>,
51 pub sanitizers: Vec<String>,
53}
54
55#[derive(Debug, Clone, Default, Deserialize)]
57#[serde(default)]
58pub struct RuleOptions {
59 #[serde(rename = "GB117", alias = "gb117")]
60 pub gb117: Gb117Options,
61}
62
63#[derive(Debug, Clone, Deserialize)]
65#[serde(default)]
66pub struct Gb117Options {
67 pub remotes: Vec<String>,
69 pub sanitizers: Vec<String>,
71}
72
73impl Default for Gb117Options {
74 fn default() -> Self {
75 Self {
76 remotes: ["SmeersLightsHandler", "Horn", "Smoke_FE"]
77 .into_iter()
78 .map(str::to_owned)
79 .collect(),
80 sanitizers: ["owner", "vehicletokens", "isdescendantof"]
81 .into_iter()
82 .map(str::to_owned)
83 .collect(),
84 }
85 }
86}
87
88#[derive(Debug, Clone, Deserialize)]
90#[serde(default)]
91pub struct CustomConfig {
92 pub dir: String,
94 pub runtime: String,
96 pub timeout: u64,
98}
99
100impl Default for CustomConfig {
101 fn default() -> Self {
102 Self {
103 dir: ".plut/rules".to_owned(),
104 runtime: "luneblox".to_owned(),
105 timeout: 60,
106 }
107 }
108}
109
110#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
112#[serde(rename_all = "lowercase")]
113pub enum Model {
114 #[default]
115 Auto,
116 Rojo,
117 Plain,
118}
119
120impl Model {
121 #[must_use]
123 pub const fn as_str(self) -> &'static str {
124 match self {
125 Self::Auto => "auto",
126 Self::Rojo => "rojo",
127 Self::Plain => "plain",
128 }
129 }
130}
131
132#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
134#[serde(rename_all = "lowercase")]
135pub enum Target {
136 Roblox,
137 Lute,
138 Luneblox,
139 Bare,
140}
141
142impl Target {
143 #[must_use]
145 pub const fn as_str(self) -> &'static str {
146 match self {
147 Self::Roblox => "roblox",
148 Self::Lute => "lute",
149 Self::Luneblox => "luneblox",
150 Self::Bare => "bare",
151 }
152 }
153}
154
155#[derive(Debug, Clone, Copy, PartialEq, Eq)]
157pub struct TargetMask(u8);
158
159impl TargetMask {
160 pub const ROBLOX: Self = Self(0b0001);
161 pub const LUTE: Self = Self(0b0010);
162 pub const LUNEBLOX: Self = Self(0b0100);
163 pub const BARE: Self = Self(0b1000);
164 pub const ANY: Self = Self(0b1111);
165
166 #[must_use]
168 pub fn from_targets(targets: &[Target]) -> Self {
169 targets.iter().fold(Self(0), |mask, target| {
170 mask.union(match target {
171 Target::Roblox => Self::ROBLOX,
172 Target::Lute => Self::LUTE,
173 Target::Luneblox => Self::LUNEBLOX,
174 Target::Bare => Self::BARE,
175 })
176 })
177 }
178
179 #[must_use]
181 pub fn targets(self) -> Vec<Target> {
182 [
183 (Self::ROBLOX, Target::Roblox),
184 (Self::LUTE, Target::Lute),
185 (Self::LUNEBLOX, Target::Luneblox),
186 (Self::BARE, Target::Bare),
187 ]
188 .into_iter()
189 .filter_map(|(bit, target)| self.intersects(bit).then_some(target))
190 .collect()
191 }
192
193 #[must_use]
195 pub const fn union(self, other: Self) -> Self {
196 Self(self.0 | other.0)
197 }
198
199 #[must_use]
201 pub const fn intersects(self, other: Self) -> bool {
202 self.0 & other.0 != 0
203 }
204
205 #[must_use]
207 pub const fn is_empty(self) -> bool {
208 self.0 == 0
209 }
210
211 #[must_use]
213 pub const fn label(self) -> &'static str {
214 match self.0 {
215 0b1111 => "any",
216 0b0001 => "roblox",
217 0b0010 => "lute",
218 0b0100 => "luneblox",
219 0b1000 => "bare",
220 _ => "mixed",
221 }
222 }
223}
224
225#[derive(Debug, Clone, PartialEq, Eq, Default)]
227pub enum TargetsConfig {
228 #[default]
229 Auto,
230 List(Vec<Target>),
231}
232
233impl<'de> Deserialize<'de> for TargetsConfig {
234 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
235 where
236 D: Deserializer<'de>,
237 {
238 struct TargetsVisitor;
239
240 impl<'de> Visitor<'de> for TargetsVisitor {
241 type Value = TargetsConfig;
242
243 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
244 formatter.write_str("targets = \"auto\" or a list of roblox, lute, luneblox, bare")
245 }
246
247 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
248 where
249 E: de::Error,
250 {
251 if value.eq_ignore_ascii_case("auto") {
252 Ok(TargetsConfig::Auto)
253 } else {
254 Err(E::custom(format!(
255 "targets must be \"auto\" or a list, got \"{value}\""
256 )))
257 }
258 }
259
260 fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
261 where
262 A: SeqAccess<'de>,
263 {
264 let mut targets = Vec::new();
265 while let Some(target) = sequence.next_element::<Target>()? {
266 targets.push(target);
267 }
268 Ok(TargetsConfig::List(targets))
269 }
270 }
271
272 deserializer.deserialize_any(TargetsVisitor)
273 }
274}
275
276impl TargetsConfig {
277 #[must_use]
280 pub fn resolve(&self, model_plain: bool) -> Vec<Target> {
281 match self {
282 Self::Auto if model_plain => vec![Target::Bare],
283 Self::Auto => vec![Target::Roblox],
284 Self::List(targets) => targets.clone(),
285 }
286 }
287}
288
289#[derive(Debug, Clone, Deserialize)]
291#[serde(default)]
292pub struct ProjectConfig {
293 pub sourcemap: String,
296 pub model: Model,
298 pub targets: TargetsConfig,
300}
301
302impl Default for ProjectConfig {
303 fn default() -> Self {
304 Self {
305 sourcemap: "auto".to_owned(),
306 model: Model::Auto,
307 targets: TargetsConfig::Auto,
308 }
309 }
310}
311
312#[derive(Debug, Clone, Deserialize)]
314#[serde(default)]
315pub struct RunConfig {
316 pub exclude: Vec<String>,
318}
319
320impl Default for RunConfig {
321 fn default() -> Self {
322 Self {
323 exclude: vec![
324 "**/roblox_packages/**".to_owned(),
327 "**/roblox_server_packages/**".to_owned(),
328 "**/Packages/**".to_owned(),
329 "**/node_modules/**".to_owned(),
330 "**/vendor/**".to_owned(),
331 "**/test/**".to_owned(),
335 "**/tests/**".to_owned(),
336 "**/spec/**".to_owned(),
337 "**/*.spec.luau".to_owned(),
338 "**/*.test.luau".to_owned(),
339 "**/benchmark/**".to_owned(),
341 "**/benchmarks/**".to_owned(),
342 "**/example/**".to_owned(),
343 "**/examples/**".to_owned(),
344 "**/*.d.luau".to_owned(),
346 ],
347 }
348 }
349}
350
351impl Config {
352 pub fn load(explicit: Option<&Path>, root: &Path) -> Result<Self, Error> {
356 let path: PathBuf = explicit.map_or_else(|| root.join("plut.toml"), Path::to_path_buf);
357
358 if !path.is_file() {
359 return Ok(Self::default());
360 }
361
362 let text = std::fs::read_to_string(&path).map_err(|source| Error::Read {
363 path: path.clone(),
364 source,
365 })?;
366
367 toml::from_str(&text).map_err(|source| Error::ParseToml { path, source })
368 }
369}
370
371#[cfg(test)]
372mod tests {
373 use super::Config;
374
375 #[test]
376 fn model_and_targets_default_to_auto() {
377 let config: Config = toml::from_str("").expect("empty config");
378 assert_eq!(config.project.model, super::Model::Auto);
379 assert_eq!(config.project.targets, super::TargetsConfig::Auto);
380 assert_eq!(
381 config.project.targets.resolve(false),
382 vec![super::Target::Roblox]
383 );
384 assert_eq!(
385 config.project.targets.resolve(true),
386 vec![super::Target::Bare]
387 );
388 }
389
390 #[test]
391 fn followers_read_model_and_targets() {
392 let config: Config =
393 toml::from_str("[project]\nmodel = \"plain\"\ntargets = [\"luneblox\", \"bare\"]\n")
394 .expect("config");
395 assert_eq!(config.project.model, super::Model::Plain);
396 assert_eq!(
397 config.project.targets,
398 super::TargetsConfig::List(vec![super::Target::Luneblox, super::Target::Bare])
399 );
400 }
401
402 #[test]
403 fn semantics_overrides_are_read() {
404 let config: Config = toml::from_str(
405 "[semantics.lute]\n\
406 sources = [\"request.query\"]\n\
407 path_sinks = [\"myfs.read\"]\n\
408 sanitizers = [\"safePath\"]\n",
409 )
410 .expect("config");
411 assert_eq!(
412 config.semantics.lute.sources,
413 vec!["request.query".to_owned()]
414 );
415 assert_eq!(
416 config.semantics.lute.path_sinks,
417 vec!["myfs.read".to_owned()]
418 );
419 assert_eq!(
420 config.semantics.lute.sanitizers,
421 vec!["safePath".to_owned()]
422 );
423 assert_eq!(config.semantics.luneblox.sources, Vec::<String>::new());
424 }
425
426 #[test]
427 fn custom_rules_have_defaults() {
428 let config: Config = toml::from_str("").expect("empty config");
429 assert_eq!(config.custom.dir, ".plut/rules");
430 assert_eq!(config.custom.runtime, "luneblox");
431 assert_eq!(config.custom.timeout, 60);
432 }
433
434 #[test]
435 fn gb117_has_default_remotes_and_sanitizers() {
436 let config: Config = toml::from_str("").expect("empty config");
437 assert_eq!(
438 config.rule.gb117.remotes,
439 ["SmeersLightsHandler", "Horn", "Smoke_FE"]
440 );
441 assert!(config.rule.gb117.sanitizers.contains(&"owner".to_owned()));
442 }
443
444 #[test]
445 fn gb117_reads_its_section() {
446 let config: Config = toml::from_str(
447 "[rule.GB117]\n\
448 remotes = [\"MyChassisRemote\"]\n\
449 sanitizers = [\"driver\"]\n",
450 )
451 .expect("config");
452 assert_eq!(config.rule.gb117.remotes, ["MyChassisRemote"]);
453 assert_eq!(config.rule.gb117.sanitizers, ["driver"]);
454 }
455
456 #[test]
457 fn custom_rules_read_their_section() {
458 let config: Config =
459 toml::from_str("[custom]\ndir = \"rules\"\nruntime = \"luneblox\"\ntimeout = 5\n")
460 .expect("config");
461 assert_eq!(config.custom.dir, "rules");
462 assert_eq!(config.custom.runtime, "luneblox");
463 assert_eq!(config.custom.timeout, 5);
464 }
465}