Skip to main content

plut_core/
config.rs

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/// Project-level configuration, read from `plut.toml` at the project root.
11#[derive(Debug, Clone, Default, Deserialize)]
12#[serde(default)]
13pub struct Config {
14    pub project: ProjectConfig,
15    pub run: RunConfig,
16    /// Custom Luau rules and the runtime that executes them.
17    pub custom: CustomConfig,
18    /// Per-rule switches: `[rules] GB204 = "off"`. A rule not listed uses its default.
19    pub rules: BTreeMap<String, String>,
20    /// Per-rule options that are more than an on/off switch.
21    pub rule: RuleOptions,
22    /// Additional sources, sinks and sanitizers for the standalone runtimes.
23    pub semantics: SemanticsConfig,
24}
25
26/// `[semantics.luneblox]` and `[semantics.lute]` overrides.
27#[derive(Debug, Clone, Default, Deserialize)]
28#[serde(default)]
29pub struct SemanticsConfig {
30    pub luneblox: RuntimeSemantics,
31    pub lute: RuntimeSemantics,
32}
33
34/// Extra source, sink and sanitizer paths for one runtime. Entries are added to the
35/// built-in tables; they do not replace them.
36#[derive(Debug, Clone, Default, Deserialize)]
37#[serde(default)]
38pub struct RuntimeSemantics {
39    /// Variables that carry external input, such as `process.args`.
40    pub sources: Vec<String>,
41    /// Calls that return external input.
42    pub source_calls: Vec<String>,
43    /// Calls that execute a program.
44    pub command_sinks: Vec<String>,
45    /// Calls whose first argument is a filesystem path.
46    pub path_sinks: Vec<String>,
47    /// Calls whose first argument is a network URL.
48    pub url_sinks: Vec<String>,
49    /// Calls that write to the console.
50    pub log_sinks: Vec<String>,
51    /// Calls whose result is safe even when an argument is tainted.
52    pub sanitizers: Vec<String>,
53}
54
55/// Options for the rules that need a list rather than a switch.
56#[derive(Debug, Clone, Default, Deserialize)]
57#[serde(default)]
58pub struct RuleOptions {
59    #[serde(rename = "GB117", alias = "gb117")]
60    pub gb117: Gb117Options,
61}
62
63/// `[rule.GB117]`: the vehicle remotes and the checks that guard them.
64#[derive(Debug, Clone, Deserialize)]
65#[serde(default)]
66pub struct Gb117Options {
67    /// Remote names that belong to a vehicle chassis.
68    pub remotes: Vec<String>,
69    /// Substrings that prove an ownership check in the handler body.
70    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/// Custom rules written in Luau, executed by a `LuneBlox` runtime.
89#[derive(Debug, Clone, Deserialize)]
90#[serde(default)]
91pub struct CustomConfig {
92    /// Directory of `*.luau` rule files, relative to the project root.
93    pub dir: String,
94    /// The Luau runtime binary used to execute the rules.
95    pub runtime: String,
96    /// Seconds a custom-rule run may take before it is stopped.
97    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/// How the project model is obtained.
111#[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    /// The lowercase name used in configuration and output.
122    #[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/// A runtime whose semantics the analyzed code uses.
133#[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    /// The lowercase name used in configuration, manifests and reports.
144    #[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/// The set of runtimes a rule applies to.
156#[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    /// Build a mask from a list of targets.
167    #[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    /// The targets in the mask, in catalog order.
180    #[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    /// The union of two masks.
194    #[must_use]
195    pub const fn union(self, other: Self) -> Self {
196        Self(self.0 | other.0)
197    }
198
199    /// Whether the masks share a target.
200    #[must_use]
201    pub const fn intersects(self, other: Self) -> bool {
202        self.0 & other.0 != 0
203    }
204
205    /// Whether the mask is empty.
206    #[must_use]
207    pub const fn is_empty(self) -> bool {
208        self.0 == 0
209    }
210
211    /// A short label for the rule catalog.
212    #[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/// `auto` or an explicit list of targets.
226#[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    /// Resolve the automatic mode against the project model. Plain projects get `bare`
278    /// (generic rules only); Rojo and place models get `roblox`.
279    #[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/// How the project model is obtained.
290#[derive(Debug, Clone, Deserialize)]
291#[serde(default)]
292pub struct ProjectConfig {
293    /// `auto` generates a sourcemap with Rojo when one is missing (ADR-004).
294    /// Any other value is treated as a path relative to the project root.
295    pub sourcemap: String,
296    /// `auto`, `rojo` or `plain`.
297    pub model: Model,
298    /// `auto` or a list of `roblox`, `lute`, `luneblox`, `bare`.
299    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/// What to analyze.
313#[derive(Debug, Clone, Deserialize)]
314#[serde(default)]
315pub struct RunConfig {
316    /// Glob patterns, relative to the project root, that are never analyzed.
317    pub exclude: Vec<String>,
318}
319
320impl Default for RunConfig {
321    fn default() -> Self {
322        Self {
323            exclude: vec![
324                // Third-party code installed by a package manager. A finding in a
325                // dependency is not the project's to fix.
326                "**/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 code is not shipped with the game. Environment tricks and test
332                // vectors live here by design, and flagging them is noise on real
333                // projects.
334                "**/test/**".to_owned(),
335                "**/tests/**".to_owned(),
336                "**/spec/**".to_owned(),
337                "**/*.spec.luau".to_owned(),
338                "**/*.test.luau".to_owned(),
339                // Benchmarks and examples are not shipped either.
340                "**/benchmark/**".to_owned(),
341                "**/benchmarks/**".to_owned(),
342                "**/example/**".to_owned(),
343                "**/examples/**".to_owned(),
344                // Typedefs for the editor, not code that runs.
345                "**/*.d.luau".to_owned(),
346            ],
347        }
348    }
349}
350
351impl Config {
352    /// Load configuration, falling back to defaults when no file exists.
353    ///
354    /// `explicit` is the `--config` path; otherwise `plut.toml` under `root` is used.
355    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}