fetter 3.4.0

System-wide Python package discovery, validation, vulnerability scanning, and allow-listing.
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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
use crate::util::ResultDynError;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::Path;
use std::process::Command;

use crate::version_spec::VersionSpec;

//------------------------------------------------------------------------------

#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub(crate) struct EnvMarkerExpr {
    pub(crate) left: String,
    pub(crate) operator: String,
    pub(crate) right: String,
}

impl EnvMarkerExpr {
    /// Used for testing.
    #[cfg(test)]
    pub fn new(left: &str, operator: &str, right: &str) -> Self {
        Self {
            left: left.to_string(),
            operator: operator.to_string(),
            right: right.to_string(),
        }
    }
}

//------------------------------------------------------------------------------

//1 os_name 	                    os.name
//2 sys_platform 	                sys.platform
//3 platform_machine 	            platform.machine()
//4 platform_python_implementation 	platform.python_implementation()
//5 platform_release 	            platform.release()
//6 platform_system 	            platform.system()
//7 python_version 	                '.'.join(platform.python_version_tuple()[:2])
//8 python_full_version 	        platform.python_version()
//9 implementation_name 	        sys.implementation.name

const PY_ENV_MARKERS: &str = "import os;import sys;import platform;print(os.name);print(sys.platform);print(platform.machine());print(platform.python_implementation());print(platform.release());print(platform.system());print('.'.join(platform.python_version_tuple()[:2]));print(platform.python_version());print(sys.implementation.name)";

// NOTE: not implementing "implementation_version", "platform.version", or "extra"
#[derive(Clone, Debug, PartialEq)]
pub struct EnvMarkerState {
    pub os_name: String,
    pub sys_platform: String,
    pub platform_machine: String,
    pub platform_python_implementation: String,
    pub platform_release: String,
    pub platform_system: String,
    pub python_version: String,
    pub python_full_version: String,
    pub implementation_name: String,
}

enum EvalType {
    StringEval,
    VersionEval,
}

impl EnvMarkerState {
    pub(crate) fn from_exe(executable: &Path) -> ResultDynError<Self> {
        match Command::new(executable)
            .arg("-S") // disable site on startup
            .arg("-c")
            .arg(PY_ENV_MARKERS)
            .output()
        {
            Ok(output) => {
                let mut lines = std::str::from_utf8(&output.stdout)
                    .expect("Failed to convert to UTF-8")
                    .trim()
                    .lines()
                    .map(String::from);
                Ok(EnvMarkerState {
                    os_name: lines.next().ok_or("Missing os_name")?,
                    sys_platform: lines.next().ok_or("Missing sys_platform")?,
                    platform_machine: lines.next().ok_or("Missing platform_machine")?,
                    platform_python_implementation: lines
                        .next()
                        .ok_or("Missing platform_python_implementation")?,
                    platform_release: lines.next().ok_or("Missing platform_release")?,
                    platform_system: lines.next().ok_or("Missing platform_system")?,
                    python_version: lines.next().ok_or("Missing python_version")?,
                    python_full_version: lines
                        .next()
                        .ok_or("Missing python_full_version")?,
                    implementation_name: lines
                        .next()
                        .ok_or("Missing implementation_name")?,
                })
            }
            Err(_) => Ok(EnvMarkerState {
                os_name: "Missing os_name".to_string(),
                sys_platform: "Missing sys_platform".to_string(),
                platform_machine: "Missing platform_machine".to_string(),
                platform_python_implementation: "Missing platform_python_implementation"
                    .to_string(),
                platform_release: "Missing platform_release".to_string(),
                platform_system: "Missing platform_system".to_string(),
                python_version: "Missing python_version".to_string(),
                python_full_version: "Missing python_full_version".to_string(),
                implementation_name: "Missing implementation_name".to_string(),
            }),
        }
    }

    // Constructor for testing.
    #[cfg(test)]
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn from_str(
        os_name: &str,
        sys_platform: &str,
        platform_machine: &str,
        platform_python_implementation: &str,
        platform_release: &str,
        platform_system: &str,
        python_version: &str,
        python_full_version: &str,
        implementation_name: &str,
    ) -> Self {
        Self {
            os_name: os_name.to_string(),
            sys_platform: sys_platform.to_string(),
            platform_machine: platform_machine.to_string(),
            platform_python_implementation: platform_python_implementation.to_string(),
            platform_release: platform_release.to_string(),
            platform_system: platform_system.to_string(),
            python_version: python_version.to_string(),
            python_full_version: python_full_version.to_string(),
            implementation_name: implementation_name.to_string(),
        }
    }

    //--------------------------------------------------------------------------

    fn eval_version(
        &self,
        left_value: &str,
        operator: &str,
        right_value: &str,
    ) -> ResultDynError<bool> {
        let lv = VersionSpec::new(left_value);
        let rv = VersionSpec::new(right_value);
        let result = match operator {
            "<" => lv < rv,
            "<=" => lv <= rv,
            "==" => lv == rv,
            "!=" => lv != rv,
            ">" => lv > rv,
            ">=" => lv >= rv,
            "~=" => lv.is_compatible(&rv),
            "===" => lv.is_arbitrary_equal(&rv),
            "^" => lv.is_caret(&rv),
            "~" => lv.is_tilde(&rv),
            "in" => left_value.contains(right_value),
            "not in" => !left_value.contains(right_value),
            _ => return Err(format!("Unsupported operator: {operator}").into()),
        };
        Ok(result)
    }

    fn eval_string(
        &self,
        left_value: &str,
        operator: &str,
        right_value: &str,
    ) -> ResultDynError<bool> {
        let result = match operator {
            "<" => left_value < right_value,
            "<=" => left_value <= right_value,
            "==" => left_value == right_value,
            "!=" => left_value != right_value,
            ">" => left_value > right_value,
            ">=" => left_value >= right_value,
            "in" => right_value.contains(left_value),
            "not in" => !right_value.contains(left_value),
            _ => return Err(format!("Unsupported operator: {operator}").into()),
        };
        Ok(result)
    }

    pub(crate) fn eval(&self, eme: &EnvMarkerExpr) -> ResultDynError<bool> {
        use EvalType::*;

        let (left_value, eval_type) = match eme.left.as_ref() {
            "os_name" => (&self.os_name, StringEval),
            "sys_platform" => (&self.sys_platform, StringEval),
            "platform_machine" => (&self.platform_machine, StringEval),
            "platform_python_implementation" => {
                (&self.platform_python_implementation, StringEval)
            }
            "platform_system" => (&self.platform_system, StringEval),
            "implementation_name" => (&self.implementation_name, StringEval),
            "platform_release" => (&self.platform_release, VersionEval),
            "python_version" => (&self.python_version, VersionEval),
            "python_full_version" => (&self.python_full_version, VersionEval),
            _ => return Err("invalid key".into()),
        };

        match eval_type {
            VersionEval => self.eval_version(left_value, &eme.operator, &eme.right),
            StringEval => self.eval_string(left_value, &eme.operator, &eme.right),
        }
    }
}

//------------------------------------------------------------------------------

#[derive(Debug, PartialEq)]
enum BExpToken {
    And,
    Or,
    ParenOpen,
    ParenClose,
    Phrase(String), // Arbitrary strings
}

fn bexp_tokenize(expr: &str) -> Vec<BExpToken> {
    let mut tokens = Vec::new();
    let mut chars = expr.chars().peekable();
    let mut phrase = String::new();

    while let Some(&ch) = chars.peek() {
        match ch {
            '(' => {
                if !phrase.is_empty() {
                    tokens.push(BExpToken::Phrase(phrase.clone()));
                    phrase.clear();
                }
                tokens.push(BExpToken::ParenOpen);
                chars.next();
            }
            ')' => {
                if !phrase.is_empty() {
                    tokens.push(BExpToken::Phrase(phrase.clone()));
                    phrase.clear();
                }
                tokens.push(BExpToken::ParenClose);
                chars.next();
            }
            _ => {
                while let Some(&c) = chars.peek() {
                    if c == ' ' {
                        // when adding a space, can check if we have a leading or / and
                        if !phrase.is_empty() {
                            if phrase.eq("or") {
                                tokens.push(BExpToken::Or);
                                phrase.clear();
                            } else if phrase.eq("and") {
                                tokens.push(BExpToken::And);
                                phrase.clear();
                            } else {
                                // only accumulate if not leading
                                phrase.push(c);
                            }
                        }
                        chars.next();
                    } else if c != '(' && c != ')' {
                        phrase.push(c);
                        chars.next();

                        if c == 'r' && phrase.ends_with(" or") {
                            let pre_op = phrase[..phrase.len() - 3].trim();
                            if !pre_op.is_empty() {
                                tokens.push(BExpToken::Phrase(pre_op.to_string()));
                            }
                            tokens.push(BExpToken::Or);
                            phrase.clear();
                        } else if c == 'd' && phrase.ends_with(" and") {
                            let pre_op = phrase[..phrase.len() - 4].trim();
                            if !pre_op.is_empty() {
                                tokens.push(BExpToken::Phrase(pre_op.to_string()));
                            }
                            tokens.push(BExpToken::And);
                            phrase.clear();
                        }
                    } else {
                        break; // c is ( or )
                    }
                }
            }
        }
    }
    if !phrase.is_empty() {
        tokens.push(BExpToken::Phrase(phrase.clone()));
    }
    tokens
}

fn bexp_eval(tokens: &[BExpToken], lookup: &HashMap<String, bool>) -> bool {
    let mut index = 0;

    fn eval(
        tokens: &[BExpToken],
        index: &mut usize,
        lookup: &HashMap<String, bool>,
    ) -> bool {
        let mut result = false;
        let mut op = None;

        while *index < tokens.len() {
            match &tokens[*index] {
                BExpToken::Phrase(phrase) => {
                    // println!(
                    //     "lookup phrase: {:?} lookup keys: {:?}",
                    //     phrase,
                    //     lookup.keys()
                    // );
                    result = *lookup.get(phrase).unwrap(); // should never happen
                    *index += 1;
                }
                BExpToken::And => {
                    op = Some(BExpToken::And);
                    *index += 1;
                }
                BExpToken::Or => {
                    op = Some(BExpToken::Or);
                    *index += 1;
                }
                BExpToken::ParenOpen => {
                    *index += 1;
                    let sub_result = eval(tokens, index, lookup);
                    if let Some(BExpToken::ParenClose) = tokens.get(*index) {
                        *index += 1;
                    }
                    result = sub_result;
                }
                _ => break,
            }

            if let Some(BExpToken::And) = op {
                result = result && eval(tokens, index, lookup);
            } else if let Some(BExpToken::Or) = op {
                result = result || eval(tokens, index, lookup);
            }
        }
        result
    }
    eval(tokens, &mut index, lookup)
}

// Given an EMS (which will need to be stored in HashMap<ExePath, EnvMarkerState>), validate the marker string.
pub(crate) fn marker_eval(
    marker: &str,
    marker_expr: &HashMap<String, EnvMarkerExpr>,
    ems: &EnvMarkerState,
) -> ResultDynError<bool> {
    // replace marker_expr with evaluated bools
    let mut marker_values: HashMap<String, bool> = HashMap::new();
    for (exp, eme) in marker_expr {
        marker_values.insert(exp.clone(), ems.eval(eme)?);
    }
    let tokens = bexp_tokenize(marker);
    Ok(bexp_eval(&tokens, &marker_values))
}

//------------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::dep_spec::DepSpec;
    use std::path::PathBuf;

    #[test]
    fn test_bexp_a() {
        let expression = "foo bar or (baz qux and quux corge)";

        let lookup: HashMap<String, bool> = vec![
            ("foo bar".to_string(), true),
            ("baz qux".to_string(), false),
            ("quux corge".to_string(), true),
        ]
        .into_iter()
        .collect();

        let tokens = bexp_tokenize(expression);
        let result = bexp_eval(&tokens, &lookup);
        assert!(!result);
    }

    #[test]
    fn test_bexp_b() {
        let expression = "a or b or c";

        let lookup: HashMap<String, bool> = vec![
            ("a".to_string(), false),
            ("b".to_string(), false),
            ("c".to_string(), true),
        ]
        .into_iter()
        .collect();

        let tokens = bexp_tokenize(expression);
        let result = bexp_eval(&tokens, &lookup);
        assert!(result);
    }

    #[test]
    fn test_bexp_c() {
        let expression = "a a or b b b b or c c c";

        let lookup: HashMap<String, bool> = vec![
            ("a a".to_string(), false),
            ("b b b b".to_string(), false),
            ("c c c".to_string(), false),
        ]
        .into_iter()
        .collect();

        let tokens = bexp_tokenize(expression);
        let result = bexp_eval(&tokens, &lookup);
        assert!(!result);
    }

    #[test]
    fn test_bexp_d() {
        let expression = "'a a' or ('b b b b' and 'c c c')";

        let lookup: HashMap<String, bool> = vec![
            ("'a a'".to_string(), false),
            ("'b b b b'".to_string(), true),
            ("'c c c'".to_string(), true),
        ]
        .into_iter()
        .collect();

        let tokens = bexp_tokenize(expression);
        let result = bexp_eval(&tokens, &lookup);
        assert!(result);
    }

    #[test]
    fn test_bexp_e1() {
        let expression = "foo and bar";

        let lookup: HashMap<String, bool> =
            vec![("foo".to_string(), true), ("bar".to_string(), true)]
                .into_iter()
                .collect();

        let tokens = bexp_tokenize(expression);
        let result = bexp_eval(&tokens, &lookup);
        assert!(result);
    }

    #[test]
    fn test_bexp_e2() {
        let expression = "foo and bar";

        let lookup: HashMap<String, bool> =
            vec![("foo".to_string(), true), ("bar".to_string(), false)]
                .into_iter()
                .collect();

        let tokens = bexp_tokenize(expression);
        let result = bexp_eval(&tokens, &lookup);
        assert!(!result);
    }

    #[test]
    fn test_bexp_f1() {
        let expression = "foo and (bar or (baz or (zab or pax)))";

        let lookup: HashMap<String, bool> = vec![
            ("foo".to_string(), true),
            ("bar".to_string(), false),
            ("baz".to_string(), false),
            ("zab".to_string(), false),
            ("pax".to_string(), true),
        ]
        .into_iter()
        .collect();

        let tokens = bexp_tokenize(expression);
        let result = bexp_eval(&tokens, &lookup);
        assert!(result);
    }

    #[test]
    fn test_bexp_f2() {
        let expression = "foo and (bar or (baz or (zab or pax)))";

        let lookup: HashMap<String, bool> = vec![
            ("foo".to_string(), true),
            ("bar".to_string(), false),
            ("baz".to_string(), false),
            ("zab".to_string(), false),
            ("pax".to_string(), false),
        ]
        .into_iter()
        .collect();

        let tokens = bexp_tokenize(expression);
        let result = bexp_eval(&tokens, &lookup);
        assert!(!result);
    }

    #[test]
    fn test_bexp_g1() {
        let expression = "(python_version > '2.0' and python_version < '2.7.9') or python_version >= '3.0'";

        let lookup: HashMap<String, bool> = vec![
            ("python_version > '2.0'".to_string(), true),
            ("python_version < '2.7.9'".to_string(), false),
            ("python_version >= '3.0'".to_string(), false),
        ]
        .into_iter()
        .collect();

        let tokens = bexp_tokenize(expression);
        let result = bexp_eval(&tokens, &lookup);
        assert!(!result);
    }

    //--------------------------------------------------------------------------

    #[test]
    fn test_emv_a() {
        let emv = EnvMarkerState::from_exe(&PathBuf::from("python3"));
        assert!(emv.is_ok());
    }

    fn get_ems_darwin() -> EnvMarkerState {
        EnvMarkerState::from_str(
            "posix", "darwin", "arm64", "CPython", "23.1.0", "Darwin", "3.13", "3.13.1",
            "cpython",
        )
    }

    #[test]
    fn test_emv_eval_a1() {
        let emv = get_ems_darwin();
        let eme1 = EnvMarkerExpr::new("python_version", "<", "3.9");
        assert!(!emv.eval(&eme1).unwrap());
        let eme2 = EnvMarkerExpr::new("python_version", ">=", "3.13");
        assert!(emv.eval(&eme2).unwrap());
        let eme3 = EnvMarkerExpr::new("python_version", ">", "3.12");
        assert!(emv.eval(&eme3).unwrap());
    }

    #[test]
    fn test_emv_eval_a2() {
        let emv = get_ems_darwin();
        let eme1 = EnvMarkerExpr::new("python_full_version", ">", "3.13.0");
        assert!(emv.eval(&eme1).unwrap());
        let eme2 = EnvMarkerExpr::new("python_full_version", ">=", "3.13.3");
        assert!(!emv.eval(&eme2).unwrap());
        let eme3 = EnvMarkerExpr::new("python_full_version", "==", "3.13.*");
        assert!(emv.eval(&eme3).unwrap());
    }

    #[test]
    fn test_emv_eval_b() {
        let emv = get_ems_darwin();
        let eme1 = EnvMarkerExpr::new("platform_machine", "in", "arm64");
        assert!(emv.eval(&eme1).unwrap());
        let eme2 = EnvMarkerExpr::new("platform_machine", "==", "arm64");
        assert!(emv.eval(&eme2).unwrap());
        let eme3 = EnvMarkerExpr::new("platform_machine", "not in", "unarm64");
        assert!(!emv.eval(&eme3).unwrap());
    }

    #[test]
    fn test_emv_eval_c() {
        let emv = get_ems_darwin();
        let eme1 = EnvMarkerExpr::new("os_name", "in", "posix");
        assert!(emv.eval(&eme1).unwrap());
        let eme2 = EnvMarkerExpr::new("os_name", "==", "posix");
        assert!(emv.eval(&eme2).unwrap());
        let eme3 = EnvMarkerExpr::new("os_name", "!=", "nt");
        assert!(emv.eval(&eme3).unwrap());
    }

    //--------------------------------------------------------------------------
    #[test]
    fn test_marker_eval_a1() {
        let ds = DepSpec::from_string("foo >= 3.4 ;(python_version > '2.0' and python_version < '2.7.9') or python_version >= '3.0'").unwrap();
        let ems = get_ems_darwin();
        assert!(marker_eval(&ds.env_marker, &ds.env_marker_expr.unwrap(), &ems).unwrap(),)
    }

    #[test]
    fn test_marker_eval_a2() {
        let ds = DepSpec::from_string("foo >= 3.4 ;(python_version > '2.0' and python_version < '2.7.9') or python_version >= '3.15'").unwrap();
        let ems = get_ems_darwin();
        assert!(!marker_eval(&ds.env_marker, &ds.env_marker_expr.unwrap(), &ems).unwrap(),)
    }

    #[test]
    fn test_marker_eval_a3() {
        let ds = DepSpec::from_string("foo >= 3.4 ;(python_version > '2.0' and python_version < '2.7.9') or python_version < '3.5' or python_version >= '3.13'").unwrap();
        let ems = get_ems_darwin();
        assert!(marker_eval(&ds.env_marker, &ds.env_marker_expr.unwrap(), &ems).unwrap(),)
    }

    #[test]
    fn test_marker_eval_b1() {
        let ds = DepSpec::from_string(
            "foo >= 3.4 ;sys_platform == 'darwin' and platform_machine == 'arm64'",
        )
        .unwrap();
        let ems = get_ems_darwin();
        assert!(marker_eval(&ds.env_marker, &ds.env_marker_expr.unwrap(), &ems).unwrap(),)
    }

    #[test]
    fn test_marker_eval_b2() {
        let ds = DepSpec::from_string("foo >= 3.4;   sys_platform == 'darwin' and platform_machine == 'arm64' and   platform_system   == 'foo' ").unwrap();
        let ems = get_ems_darwin();
        assert!(!marker_eval(&ds.env_marker, &ds.env_marker_expr.unwrap(), &ems).unwrap(),)
    }

    #[test]
    fn test_marker_eval_b3() {
        let ds = DepSpec::from_string("foo >= 3.4;   sys_platform == 'darwin' and platform_machine == 'arm64' and   platform_system   == 'Darwin' ").unwrap();
        let ems = get_ems_darwin();
        assert!(marker_eval(&ds.env_marker, &ds.env_marker_expr.unwrap(), &ems).unwrap(),)
    }

    #[test]
    fn test_marker_eval_c1() {
        let ds = DepSpec::from_string("foo >= 3.4;   os_name == 'posix' and platform_python_implementation == 'CPython' and   platform_release  == '23.*' ").unwrap();
        let ems = get_ems_darwin();
        assert!(marker_eval(&ds.env_marker, &ds.env_marker_expr.unwrap(), &ems).unwrap(),)
    }

    #[test]
    fn test_marker_eval_c2() {
        let ds = DepSpec::from_string("foo >= 3.4;   os_name == 'posix' and platform_python_implementation == 'foo' and   platform_release  == '23.*' ").unwrap();
        let ems = get_ems_darwin();
        assert!(!marker_eval(&ds.env_marker, &ds.env_marker_expr.unwrap(), &ems).unwrap(),)
    }

    #[test]
    fn test_marker_eval_c3() {
        let ds = DepSpec::from_string("foo >= 3.4;   os_name == 'posix' and platform_python_implementation == 'CPython' and  implementation_name  == 'cpython' ").unwrap();
        let ems = get_ems_darwin();
        assert!(marker_eval(&ds.env_marker, &ds.env_marker_expr.unwrap(), &ems).unwrap(),)
    }
}