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
10mod contexts;
11
12pub use contexts::Contexts;
13
14/// Project-level configuration, read from `plut.toml` at the project root.
15#[derive(Debug, Clone, Default, Deserialize)]
16#[serde(default)]
17pub struct Config {
18    pub project: ProjectConfig,
19    pub run: RunConfig,
20    /// Custom Luau rules and the runtime that executes them.
21    pub custom: CustomConfig,
22    /// Per-rule switches: `[rules] GB204 = "off"`. A rule not listed uses its default.
23    pub rules: BTreeMap<String, String>,
24    /// Per-rule options that are more than an on/off switch.
25    pub rule: RuleOptions,
26    /// Additional sources, sinks and sanitizers for the standalone runtimes.
27    pub semantics: SemanticsConfig,
28}
29
30/// `[semantics.luneblox]` and `[semantics.lute]` overrides.
31#[derive(Debug, Clone, Default, Deserialize)]
32#[serde(default)]
33pub struct SemanticsConfig {
34    pub luneblox: RuntimeSemantics,
35    pub lute: RuntimeSemantics,
36}
37
38/// Extra source, sink and sanitizer paths for one runtime. Entries are added to the
39/// built-in tables; they do not replace them.
40#[derive(Debug, Clone, Default, Deserialize)]
41#[serde(default)]
42pub struct RuntimeSemantics {
43    /// Variables that carry external input, such as `process.args`.
44    pub sources: Vec<String>,
45    /// Calls that return external input.
46    pub source_calls: Vec<String>,
47    /// Calls that execute a program.
48    pub command_sinks: Vec<String>,
49    /// Calls whose first argument is a filesystem path.
50    pub path_sinks: Vec<String>,
51    /// Calls whose first argument is a network URL.
52    pub url_sinks: Vec<String>,
53    /// Calls that write to the console.
54    pub log_sinks: Vec<String>,
55    /// Calls whose result is safe even when an argument is tainted.
56    pub sanitizers: Vec<String>,
57}
58
59/// Options for the rules that need a list rather than a switch.
60#[derive(Debug, Clone, Default, Deserialize)]
61#[serde(default)]
62pub struct RuleOptions {
63    #[serde(rename = "GB117", alias = "gb117")]
64    pub gb117: Gb117Options,
65}
66
67/// `[rule.GB117]`: the vehicle remotes and the checks that guard them.
68#[derive(Debug, Clone, Deserialize)]
69#[serde(default)]
70pub struct Gb117Options {
71    /// Remote names that belong to a vehicle chassis.
72    pub remotes: Vec<String>,
73    /// Substrings that prove an ownership check in the handler body.
74    pub sanitizers: Vec<String>,
75}
76
77impl Default for Gb117Options {
78    fn default() -> Self {
79        Self {
80            remotes: ["SmeersLightsHandler", "Horn", "Smoke_FE"]
81                .into_iter()
82                .map(str::to_owned)
83                .collect(),
84            sanitizers: ["owner", "vehicletokens", "isdescendantof"]
85                .into_iter()
86                .map(str::to_owned)
87                .collect(),
88        }
89    }
90}
91
92/// Custom rules written in Luau, executed by a `LuneBlox` runtime.
93#[derive(Debug, Clone, Deserialize)]
94#[serde(default)]
95pub struct CustomConfig {
96    /// Directory of `*.luau` rule files, relative to the project root.
97    pub dir: String,
98    /// The Luau runtime binary used to execute the rules.
99    pub runtime: String,
100    /// Seconds a custom-rule run may take before it is stopped.
101    pub timeout: u64,
102}
103
104impl Default for CustomConfig {
105    fn default() -> Self {
106        Self {
107            dir: ".plut/rules".to_owned(),
108            runtime: "luneblox".to_owned(),
109            timeout: 60,
110        }
111    }
112}
113
114/// How the project model is obtained.
115#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
116#[serde(rename_all = "lowercase")]
117pub enum Model {
118    #[default]
119    Auto,
120    Rojo,
121    Plain,
122}
123
124impl Model {
125    /// The lowercase name used in configuration and output.
126    #[must_use]
127    pub const fn as_str(self) -> &'static str {
128        match self {
129            Self::Auto => "auto",
130            Self::Rojo => "rojo",
131            Self::Plain => "plain",
132        }
133    }
134}
135
136/// A runtime whose semantics the analyzed code uses.
137#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
138#[serde(rename_all = "lowercase")]
139pub enum Target {
140    Roblox,
141    Lute,
142    Luneblox,
143    Bare,
144}
145
146impl Target {
147    /// The lowercase name used in configuration, manifests and reports.
148    #[must_use]
149    pub const fn as_str(self) -> &'static str {
150        match self {
151            Self::Roblox => "roblox",
152            Self::Lute => "lute",
153            Self::Luneblox => "luneblox",
154            Self::Bare => "bare",
155        }
156    }
157}
158
159/// The set of runtimes a rule applies to.
160#[derive(Debug, Clone, Copy, PartialEq, Eq)]
161pub struct TargetMask(u8);
162
163impl TargetMask {
164    pub const ROBLOX: Self = Self(0b0001);
165    pub const LUTE: Self = Self(0b0010);
166    pub const LUNEBLOX: Self = Self(0b0100);
167    pub const BARE: Self = Self(0b1000);
168    pub const ANY: Self = Self(0b1111);
169
170    /// Build a mask from a list of targets.
171    #[must_use]
172    pub fn from_targets(targets: &[Target]) -> Self {
173        targets.iter().fold(Self(0), |mask, target| {
174            mask.union(match target {
175                Target::Roblox => Self::ROBLOX,
176                Target::Lute => Self::LUTE,
177                Target::Luneblox => Self::LUNEBLOX,
178                Target::Bare => Self::BARE,
179            })
180        })
181    }
182
183    /// The targets in the mask, in catalog order.
184    #[must_use]
185    pub fn targets(self) -> Vec<Target> {
186        [
187            (Self::ROBLOX, Target::Roblox),
188            (Self::LUTE, Target::Lute),
189            (Self::LUNEBLOX, Target::Luneblox),
190            (Self::BARE, Target::Bare),
191        ]
192        .into_iter()
193        .filter_map(|(bit, target)| self.intersects(bit).then_some(target))
194        .collect()
195    }
196
197    /// The union of two masks.
198    #[must_use]
199    pub const fn union(self, other: Self) -> Self {
200        Self(self.0 | other.0)
201    }
202
203    /// Whether the masks share a target.
204    #[must_use]
205    pub const fn intersects(self, other: Self) -> bool {
206        self.0 & other.0 != 0
207    }
208
209    /// Whether the mask is empty.
210    #[must_use]
211    pub const fn is_empty(self) -> bool {
212        self.0 == 0
213    }
214
215    /// A short label for the rule catalog.
216    #[must_use]
217    pub const fn label(self) -> &'static str {
218        match self.0 {
219            0b1111 => "any",
220            0b0001 => "roblox",
221            0b0010 => "lute",
222            0b0100 => "luneblox",
223            0b1000 => "bare",
224            _ => "mixed",
225        }
226    }
227}
228
229/// `auto` or an explicit list of targets.
230#[derive(Debug, Clone, PartialEq, Eq, Default)]
231pub enum TargetsConfig {
232    #[default]
233    Auto,
234    List(Vec<Target>),
235}
236
237impl<'de> Deserialize<'de> for TargetsConfig {
238    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
239    where
240        D: Deserializer<'de>,
241    {
242        struct TargetsVisitor;
243
244        impl<'de> Visitor<'de> for TargetsVisitor {
245            type Value = TargetsConfig;
246
247            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
248                formatter.write_str("targets = \"auto\" or a list of roblox, lute, luneblox, bare")
249            }
250
251            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
252            where
253                E: de::Error,
254            {
255                if value.eq_ignore_ascii_case("auto") {
256                    Ok(TargetsConfig::Auto)
257                } else {
258                    Err(E::custom(format!(
259                        "targets must be \"auto\" or a list, got \"{value}\""
260                    )))
261                }
262            }
263
264            fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
265            where
266                A: SeqAccess<'de>,
267            {
268                let mut targets = Vec::new();
269                while let Some(target) = sequence.next_element::<Target>()? {
270                    targets.push(target);
271                }
272                Ok(TargetsConfig::List(targets))
273            }
274        }
275
276        deserializer.deserialize_any(TargetsVisitor)
277    }
278}
279
280impl TargetsConfig {
281    /// Resolve the automatic mode against the project model. Plain projects get `bare`
282    /// (generic rules only); Rojo and place models get `roblox`.
283    #[must_use]
284    pub fn resolve(&self, model_plain: bool) -> Vec<Target> {
285        match self {
286            Self::Auto if model_plain => vec![Target::Bare],
287            Self::Auto => vec![Target::Roblox],
288            Self::List(targets) => targets.clone(),
289        }
290    }
291}
292
293/// How the project model is obtained.
294#[derive(Debug, Clone, Deserialize)]
295#[serde(default)]
296pub struct ProjectConfig {
297    /// `auto` generates a sourcemap with Rojo when one is missing (ADR-004).
298    /// Any other value is treated as a path relative to the project root.
299    pub sourcemap: String,
300    /// `auto`, `rojo` or `plain`.
301    pub model: Model,
302    /// `auto` or a list of `roblox`, `lute`, `luneblox`, `bare`.
303    pub targets: TargetsConfig,
304    /// How a plain tree assigns a run context: `suffixes` (default) or `paths`.
305    pub contexts: Contexts,
306}
307
308impl Default for ProjectConfig {
309    fn default() -> Self {
310        Self {
311            sourcemap: "auto".to_owned(),
312            model: Model::Auto,
313            targets: TargetsConfig::Auto,
314            contexts: Contexts::Suffixes,
315        }
316    }
317}
318
319/// What to analyze.
320#[derive(Debug, Clone, Deserialize)]
321#[serde(default)]
322pub struct RunConfig {
323    /// Glob patterns, relative to the project root, that are never analyzed.
324    pub exclude: Vec<String>,
325}
326
327impl Default for RunConfig {
328    fn default() -> Self {
329        Self {
330            exclude: vec![
331                // Third-party code installed by a package manager. A finding in a
332                // dependency is not the project's to fix.
333                "**/roblox_packages/**".to_owned(),
334                "**/roblox_server_packages/**".to_owned(),
335                "**/Packages/**".to_owned(),
336                "**/node_modules/**".to_owned(),
337                "**/vendor/**".to_owned(),
338                // Test code is not shipped with the game. Environment tricks and test
339                // vectors live here by design, and flagging them is noise on real
340                // projects.
341                "**/test/**".to_owned(),
342                "**/tests/**".to_owned(),
343                "**/spec/**".to_owned(),
344                "**/*.spec.luau".to_owned(),
345                "**/*.test.luau".to_owned(),
346                // Benchmarks and examples are not shipped either.
347                "**/benchmark/**".to_owned(),
348                "**/benchmarks/**".to_owned(),
349                "**/example/**".to_owned(),
350                "**/examples/**".to_owned(),
351                // Typedefs for the editor, not code that runs.
352                "**/*.d.luau".to_owned(),
353            ],
354        }
355    }
356}
357
358impl Config {
359    /// Load configuration, falling back to defaults when no file exists.
360    ///
361    /// `explicit` is the `--config` path; otherwise `plut.toml` under `root` is used.
362    pub fn load(explicit: Option<&Path>, root: &Path) -> Result<Self, Error> {
363        let path: PathBuf = explicit.map_or_else(|| root.join("plut.toml"), Path::to_path_buf);
364
365        if !path.is_file() {
366            return Ok(Self::default());
367        }
368
369        let text = std::fs::read_to_string(&path).map_err(|source| Error::Read {
370            path: path.clone(),
371            source,
372        })?;
373
374        toml::from_str(&text).map_err(|source| Error::ParseToml { path, source })
375    }
376}
377
378#[cfg(test)]
379mod tests {
380    use super::Config;
381
382    #[test]
383    fn model_and_targets_default_to_auto() {
384        let config: Config = toml::from_str("").expect("empty config");
385        assert_eq!(config.project.model, super::Model::Auto);
386        assert_eq!(config.project.targets, super::TargetsConfig::Auto);
387        assert_eq!(
388            config.project.targets.resolve(false),
389            vec![super::Target::Roblox]
390        );
391        assert_eq!(
392            config.project.targets.resolve(true),
393            vec![super::Target::Bare]
394        );
395    }
396
397    #[test]
398    fn contexts_default_to_suffixes_and_accept_paths() {
399        let config: Config = toml::from_str("").expect("empty config");
400        assert_eq!(config.project.contexts, super::Contexts::Suffixes);
401
402        let config: Config =
403            toml::from_str("[project]\ncontexts = \"paths\"\n").expect("contexts config");
404        assert_eq!(config.project.contexts, super::Contexts::Paths);
405    }
406
407    #[test]
408    fn followers_read_model_and_targets() {
409        let config: Config =
410            toml::from_str("[project]\nmodel = \"plain\"\ntargets = [\"luneblox\", \"bare\"]\n")
411                .expect("config");
412        assert_eq!(config.project.model, super::Model::Plain);
413        assert_eq!(
414            config.project.targets,
415            super::TargetsConfig::List(vec![super::Target::Luneblox, super::Target::Bare])
416        );
417    }
418
419    #[test]
420    fn semantics_overrides_are_read() {
421        let config: Config = toml::from_str(
422            "[semantics.lute]\n\
423             sources = [\"request.query\"]\n\
424             path_sinks = [\"myfs.read\"]\n\
425             sanitizers = [\"safePath\"]\n",
426        )
427        .expect("config");
428        assert_eq!(
429            config.semantics.lute.sources,
430            vec!["request.query".to_owned()]
431        );
432        assert_eq!(
433            config.semantics.lute.path_sinks,
434            vec!["myfs.read".to_owned()]
435        );
436        assert_eq!(
437            config.semantics.lute.sanitizers,
438            vec!["safePath".to_owned()]
439        );
440        assert_eq!(config.semantics.luneblox.sources, Vec::<String>::new());
441    }
442
443    #[test]
444    fn custom_rules_have_defaults() {
445        let config: Config = toml::from_str("").expect("empty config");
446        assert_eq!(config.custom.dir, ".plut/rules");
447        assert_eq!(config.custom.runtime, "luneblox");
448        assert_eq!(config.custom.timeout, 60);
449    }
450
451    #[test]
452    fn gb117_has_default_remotes_and_sanitizers() {
453        let config: Config = toml::from_str("").expect("empty config");
454        assert_eq!(
455            config.rule.gb117.remotes,
456            ["SmeersLightsHandler", "Horn", "Smoke_FE"]
457        );
458        assert!(config.rule.gb117.sanitizers.contains(&"owner".to_owned()));
459    }
460
461    #[test]
462    fn gb117_reads_its_section() {
463        let config: Config = toml::from_str(
464            "[rule.GB117]\n\
465             remotes = [\"MyChassisRemote\"]\n\
466             sanitizers = [\"driver\"]\n",
467        )
468        .expect("config");
469        assert_eq!(config.rule.gb117.remotes, ["MyChassisRemote"]);
470        assert_eq!(config.rule.gb117.sanitizers, ["driver"]);
471    }
472
473    #[test]
474    fn custom_rules_read_their_section() {
475        let config: Config =
476            toml::from_str("[custom]\ndir = \"rules\"\nruntime = \"luneblox\"\ntimeout = 5\n")
477                .expect("config");
478        assert_eq!(config.custom.dir, "rules");
479        assert_eq!(config.custom.runtime, "luneblox");
480        assert_eq!(config.custom.timeout, 5);
481    }
482}