plut-core 2.10.0

Project model, run context and diagnostics for Plut
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
use std::collections::BTreeMap;
use std::fmt;
use std::path::{Path, PathBuf};

use serde::de::{self, SeqAccess, Visitor};
use serde::{Deserialize, Deserializer, Serialize};

use crate::Error;

/// Project-level configuration, read from `plut.toml` at the project root.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct Config {
    pub project: ProjectConfig,
    pub run: RunConfig,
    /// Custom Luau rules and the runtime that executes them.
    pub custom: CustomConfig,
    /// Per-rule switches: `[rules] GB204 = "off"`. A rule not listed uses its default.
    pub rules: BTreeMap<String, String>,
    /// Per-rule options that are more than an on/off switch.
    pub rule: RuleOptions,
    /// Additional sources, sinks and sanitizers for the standalone runtimes.
    pub semantics: SemanticsConfig,
}

/// `[semantics.luneblox]` and `[semantics.lute]` overrides.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct SemanticsConfig {
    pub luneblox: RuntimeSemantics,
    pub lute: RuntimeSemantics,
}

/// Extra source, sink and sanitizer paths for one runtime. Entries are added to the
/// built-in tables; they do not replace them.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct RuntimeSemantics {
    /// Variables that carry external input, such as `process.args`.
    pub sources: Vec<String>,
    /// Calls that return external input.
    pub source_calls: Vec<String>,
    /// Calls that execute a program.
    pub command_sinks: Vec<String>,
    /// Calls whose first argument is a filesystem path.
    pub path_sinks: Vec<String>,
    /// Calls whose first argument is a network URL.
    pub url_sinks: Vec<String>,
    /// Calls that write to the console.
    pub log_sinks: Vec<String>,
    /// Calls whose result is safe even when an argument is tainted.
    pub sanitizers: Vec<String>,
}

/// Options for the rules that need a list rather than a switch.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct RuleOptions {
    #[serde(rename = "GB117", alias = "gb117")]
    pub gb117: Gb117Options,
}

/// `[rule.GB117]`: the vehicle remotes and the checks that guard them.
#[derive(Debug, Clone, Deserialize)]
#[serde(default)]
pub struct Gb117Options {
    /// Remote names that belong to a vehicle chassis.
    pub remotes: Vec<String>,
    /// Substrings that prove an ownership check in the handler body.
    pub sanitizers: Vec<String>,
}

impl Default for Gb117Options {
    fn default() -> Self {
        Self {
            remotes: ["SmeersLightsHandler", "Horn", "Smoke_FE"]
                .into_iter()
                .map(str::to_owned)
                .collect(),
            sanitizers: ["owner", "vehicletokens", "isdescendantof"]
                .into_iter()
                .map(str::to_owned)
                .collect(),
        }
    }
}

/// Custom rules written in Luau, executed by a `LuneBlox` runtime.
#[derive(Debug, Clone, Deserialize)]
#[serde(default)]
pub struct CustomConfig {
    /// Directory of `*.luau` rule files, relative to the project root.
    pub dir: String,
    /// The Luau runtime binary used to execute the rules.
    pub runtime: String,
    /// Seconds a custom-rule run may take before it is stopped.
    pub timeout: u64,
}

impl Default for CustomConfig {
    fn default() -> Self {
        Self {
            dir: ".plut/rules".to_owned(),
            runtime: "luneblox".to_owned(),
            timeout: 60,
        }
    }
}

/// How the project model is obtained.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Model {
    #[default]
    Auto,
    Rojo,
    Plain,
}

impl Model {
    /// The lowercase name used in configuration and output.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Auto => "auto",
            Self::Rojo => "rojo",
            Self::Plain => "plain",
        }
    }
}

/// A runtime whose semantics the analyzed code uses.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Target {
    Roblox,
    Lute,
    Luneblox,
    Bare,
}

impl Target {
    /// The lowercase name used in configuration, manifests and reports.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Roblox => "roblox",
            Self::Lute => "lute",
            Self::Luneblox => "luneblox",
            Self::Bare => "bare",
        }
    }
}

/// The set of runtimes a rule applies to.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TargetMask(u8);

impl TargetMask {
    pub const ROBLOX: Self = Self(0b0001);
    pub const LUTE: Self = Self(0b0010);
    pub const LUNEBLOX: Self = Self(0b0100);
    pub const BARE: Self = Self(0b1000);
    pub const ANY: Self = Self(0b1111);

    /// Build a mask from a list of targets.
    #[must_use]
    pub fn from_targets(targets: &[Target]) -> Self {
        targets.iter().fold(Self(0), |mask, target| {
            mask.union(match target {
                Target::Roblox => Self::ROBLOX,
                Target::Lute => Self::LUTE,
                Target::Luneblox => Self::LUNEBLOX,
                Target::Bare => Self::BARE,
            })
        })
    }

    /// The targets in the mask, in catalog order.
    #[must_use]
    pub fn targets(self) -> Vec<Target> {
        [
            (Self::ROBLOX, Target::Roblox),
            (Self::LUTE, Target::Lute),
            (Self::LUNEBLOX, Target::Luneblox),
            (Self::BARE, Target::Bare),
        ]
        .into_iter()
        .filter_map(|(bit, target)| self.intersects(bit).then_some(target))
        .collect()
    }

    /// The union of two masks.
    #[must_use]
    pub const fn union(self, other: Self) -> Self {
        Self(self.0 | other.0)
    }

    /// Whether the masks share a target.
    #[must_use]
    pub const fn intersects(self, other: Self) -> bool {
        self.0 & other.0 != 0
    }

    /// Whether the mask is empty.
    #[must_use]
    pub const fn is_empty(self) -> bool {
        self.0 == 0
    }

    /// A short label for the rule catalog.
    #[must_use]
    pub const fn label(self) -> &'static str {
        match self.0 {
            0b1111 => "any",
            0b0001 => "roblox",
            0b0010 => "lute",
            0b0100 => "luneblox",
            0b1000 => "bare",
            _ => "mixed",
        }
    }
}

/// `auto` or an explicit list of targets.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum TargetsConfig {
    #[default]
    Auto,
    List(Vec<Target>),
}

impl<'de> Deserialize<'de> for TargetsConfig {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct TargetsVisitor;

        impl<'de> Visitor<'de> for TargetsVisitor {
            type Value = TargetsConfig;

            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
                formatter.write_str("targets = \"auto\" or a list of roblox, lute, luneblox, bare")
            }

            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                if value.eq_ignore_ascii_case("auto") {
                    Ok(TargetsConfig::Auto)
                } else {
                    Err(E::custom(format!(
                        "targets must be \"auto\" or a list, got \"{value}\""
                    )))
                }
            }

            fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
            where
                A: SeqAccess<'de>,
            {
                let mut targets = Vec::new();
                while let Some(target) = sequence.next_element::<Target>()? {
                    targets.push(target);
                }
                Ok(TargetsConfig::List(targets))
            }
        }

        deserializer.deserialize_any(TargetsVisitor)
    }
}

impl TargetsConfig {
    /// Resolve the automatic mode against the project model. Plain projects get `bare`
    /// (generic rules only); Rojo and place models get `roblox`.
    #[must_use]
    pub fn resolve(&self, model_plain: bool) -> Vec<Target> {
        match self {
            Self::Auto if model_plain => vec![Target::Bare],
            Self::Auto => vec![Target::Roblox],
            Self::List(targets) => targets.clone(),
        }
    }
}

/// How the project model is obtained.
#[derive(Debug, Clone, Deserialize)]
#[serde(default)]
pub struct ProjectConfig {
    /// `auto` generates a sourcemap with Rojo when one is missing (ADR-004).
    /// Any other value is treated as a path relative to the project root.
    pub sourcemap: String,
    /// `auto`, `rojo` or `plain`.
    pub model: Model,
    /// `auto` or a list of `roblox`, `lute`, `luneblox`, `bare`.
    pub targets: TargetsConfig,
}

impl Default for ProjectConfig {
    fn default() -> Self {
        Self {
            sourcemap: "auto".to_owned(),
            model: Model::Auto,
            targets: TargetsConfig::Auto,
        }
    }
}

/// What to analyze.
#[derive(Debug, Clone, Deserialize)]
#[serde(default)]
pub struct RunConfig {
    /// Glob patterns, relative to the project root, that are never analyzed.
    pub exclude: Vec<String>,
}

impl Default for RunConfig {
    fn default() -> Self {
        Self {
            exclude: vec![
                // Third-party code installed by a package manager. A finding in a
                // dependency is not the project's to fix.
                "**/roblox_packages/**".to_owned(),
                "**/roblox_server_packages/**".to_owned(),
                "**/Packages/**".to_owned(),
                "**/node_modules/**".to_owned(),
                "**/vendor/**".to_owned(),
                // Test code is not shipped with the game. Environment tricks and test
                // vectors live here by design, and flagging them is noise on real
                // projects.
                "**/test/**".to_owned(),
                "**/tests/**".to_owned(),
                "**/spec/**".to_owned(),
                "**/*.spec.luau".to_owned(),
                "**/*.test.luau".to_owned(),
                // Benchmarks and examples are not shipped either.
                "**/benchmark/**".to_owned(),
                "**/benchmarks/**".to_owned(),
                "**/example/**".to_owned(),
                "**/examples/**".to_owned(),
                // Typedefs for the editor, not code that runs.
                "**/*.d.luau".to_owned(),
            ],
        }
    }
}

impl Config {
    /// Load configuration, falling back to defaults when no file exists.
    ///
    /// `explicit` is the `--config` path; otherwise `plut.toml` under `root` is used.
    pub fn load(explicit: Option<&Path>, root: &Path) -> Result<Self, Error> {
        let path: PathBuf = explicit.map_or_else(|| root.join("plut.toml"), Path::to_path_buf);

        if !path.is_file() {
            return Ok(Self::default());
        }

        let text = std::fs::read_to_string(&path).map_err(|source| Error::Read {
            path: path.clone(),
            source,
        })?;

        toml::from_str(&text).map_err(|source| Error::ParseToml { path, source })
    }
}

#[cfg(test)]
mod tests {
    use super::Config;

    #[test]
    fn model_and_targets_default_to_auto() {
        let config: Config = toml::from_str("").expect("empty config");
        assert_eq!(config.project.model, super::Model::Auto);
        assert_eq!(config.project.targets, super::TargetsConfig::Auto);
        assert_eq!(
            config.project.targets.resolve(false),
            vec![super::Target::Roblox]
        );
        assert_eq!(
            config.project.targets.resolve(true),
            vec![super::Target::Bare]
        );
    }

    #[test]
    fn followers_read_model_and_targets() {
        let config: Config =
            toml::from_str("[project]\nmodel = \"plain\"\ntargets = [\"luneblox\", \"bare\"]\n")
                .expect("config");
        assert_eq!(config.project.model, super::Model::Plain);
        assert_eq!(
            config.project.targets,
            super::TargetsConfig::List(vec![super::Target::Luneblox, super::Target::Bare])
        );
    }

    #[test]
    fn semantics_overrides_are_read() {
        let config: Config = toml::from_str(
            "[semantics.lute]\n\
             sources = [\"request.query\"]\n\
             path_sinks = [\"myfs.read\"]\n\
             sanitizers = [\"safePath\"]\n",
        )
        .expect("config");
        assert_eq!(
            config.semantics.lute.sources,
            vec!["request.query".to_owned()]
        );
        assert_eq!(
            config.semantics.lute.path_sinks,
            vec!["myfs.read".to_owned()]
        );
        assert_eq!(
            config.semantics.lute.sanitizers,
            vec!["safePath".to_owned()]
        );
        assert_eq!(config.semantics.luneblox.sources, Vec::<String>::new());
    }

    #[test]
    fn custom_rules_have_defaults() {
        let config: Config = toml::from_str("").expect("empty config");
        assert_eq!(config.custom.dir, ".plut/rules");
        assert_eq!(config.custom.runtime, "luneblox");
        assert_eq!(config.custom.timeout, 60);
    }

    #[test]
    fn gb117_has_default_remotes_and_sanitizers() {
        let config: Config = toml::from_str("").expect("empty config");
        assert_eq!(
            config.rule.gb117.remotes,
            ["SmeersLightsHandler", "Horn", "Smoke_FE"]
        );
        assert!(config.rule.gb117.sanitizers.contains(&"owner".to_owned()));
    }

    #[test]
    fn gb117_reads_its_section() {
        let config: Config = toml::from_str(
            "[rule.GB117]\n\
             remotes = [\"MyChassisRemote\"]\n\
             sanitizers = [\"driver\"]\n",
        )
        .expect("config");
        assert_eq!(config.rule.gb117.remotes, ["MyChassisRemote"]);
        assert_eq!(config.rule.gb117.sanitizers, ["driver"]);
    }

    #[test]
    fn custom_rules_read_their_section() {
        let config: Config =
            toml::from_str("[custom]\ndir = \"rules\"\nruntime = \"luneblox\"\ntimeout = 5\n")
                .expect("config");
        assert_eq!(config.custom.dir, "rules");
        assert_eq!(config.custom.runtime, "luneblox");
        assert_eq!(config.custom.timeout, 5);
    }
}