virtiofsd 1.13.3

A virtio-fs vhost-user device daemon
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
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
//! The `xattrmap` module is used to translate extended attribute operations
//! between the server (virtiofsd) and the client (the virtio-fs guest kernel
//! module).
//!
//! Here's a non-exhaustive list of use-cases in which it may be beneficial to
//! install an extended attribute mapping:
//!
//! * The guest VM process is executing at a privilege level where it can't
//!   actually modify the extended attribute on the host. In this case, one
//!   may choose to map those guest's extended attributes to a "user."
//!   namespace on the host.
//!
//! * An extended attribute mapping can partition a host's extended attributes
//!   from a guest's to prevent the guest from clobbering extended attributes
//!   that the host has set and depends on.
//!
//! ## Rules
//!
//! The entity that launches virtiofsd may provide an "extended attributes
//! mapping" (or "xattrmap") that defines how extended attributes should be
//! translated. An xattrmap is really just a series of rules with a specific
//! syntax. When translating an xattr, the xattrmap rules are traversed in the
//! order that the mappings were originally written. The traversal is terminated
//! on the first rule that matches the xattr.
//!
//! The xattrmap _must_ have a terminating rule.
//!
//! ### Reference
//!
//! There are two ways of expressing an xattrmap rule:
//!
//! 1. `:type:scope:key:prepend:`
//! 2. `:map:key:prepend:` - this is just syntactic sugar for expressing a common
//!    rule. It is equivalent to `:prefix:all:key:prepend`.
//!
//! An xattrmap is just a series of these rules separated by whitespace. Each rule
//! can have its own delimiter. The colon (`:`) was just used here as an arbitary
//! example. Use a delimiter that you find readable.
//!
//! Let's dissect the xattrmap rule syntax: `:type:scope:key:prepend:`.
//!
//! | type | description |
//! | - | - |
//! | prefix | The value of `key` is prepended to xattrs originating from the client (i.e., `{get,set,remove}xattr()`). The value of `prepend` is stripped from the server's reply to `listxattr()`. |
//! | ok | If the xattr originating from the client is prefixed with `key`, or if an xattr in a server reply is prefixed with `prepend` it passes through unchanged. |
//! | bad | If the xattr originating from the client is prefixed with `key` it is denied with `EPERM`. If the xattr in a server reply is prefixed with `prepend` it is hidden from the client and not included in the reply. |
//! | unsupported | If a client tries to use a name matching 'key' it's denied using ENOTSUP; when the server passes an attribute name matching 'prepend' it's hidden.  In many ways its use is very like 'ok' as either an explicit terminator or for special handling of certain patterns. |
//!
//! `ok` and `bad` can both be used as simple terminators for an xattrmap to
//! satisfy the expectation that every xattrmap has a terminator. For example,
//! `:ok:all:::`, will vacuously terminate all mappings. Placing a rule like
//! this at the end of the xattrmap rules is a common way of providing a
//! terminator.
//!
//! | scope | description |
//! | - | - |
//! | server | Match on xattrnames in the server reply that are prefixed with `prepend`. |
//! | client | Match on xattrnames from the client that are prefixed with `key`. |
//! | all | Matches on both server replies and client requests as described for `server` and `client` scopes. |
//!
//! ### Examples
//!
//! These have been taken almost verbatim from the original virtiofsd
//! documentation in the QEMU source code.
//!
//! #### Example 1
//!
//! ```text
//! :prefix:all::user.virtiofs.:
//! :bad:all:::
//! ```
//!
//! There are two rules in this xattrmap. The first rule prefixes and strips
//! `user.virtiofs.` from client requests and server replies respectively.
//!
//! The second rule hides any non-prefixed extended attributes that the host
//! set.
//!
//! #### Example 2
//!
//! ```text
//! /prefix/all/trusted./user.virtiofs./
//! /bad/server//trusted./
//! /bad/client/user.virtiofs.//
//! /ok/all///
//! ```
//!
//! The first rule prefixes client xattrnames with `trusted.` and strips
//! `user.virtiofs.` from xattrnames included in the server reply.
//!
//! The second rule hides unprefixed `trusted.` attributes on the host.
//!
//! The third rule prevents the guest from manipulating the `user.virtiofs.`
//! namespace directly.
//!
//! The final rule is the terminator and allows all remaining attributes
//! through unchanged.

#![deny(missing_docs)]

use std::borrow::Cow;
use std::convert::TryFrom;
use std::ffi::{CStr, CString};
use std::fmt;
use std::iter::Peekable;

/// Expected error conditions with respect to parsing an XattrMap or
/// attempting to match on a rule.
#[derive(Debug, Eq, PartialEq)]
pub enum ErrorKind {
    /// Scope is not one of: "all", "server", "client".
    InvalidScope {
        /// The unexpected value parsed from the input stream.
        got: String,

        /// A list of the expected values.
        expected: String,
    },

    /// Type is not one of "prefix", "ok", "bad", or "map".
    InvalidType {
        /// The unexpected value parsed from the input stream.
        got: String,

        /// A list of the expected values.
        expected: String,
    },

    /// A delimiter has been found that does not match the delimiter
    /// the rule started with.
    InvalidDelimiter,

    /// The rule is missing fields.
    IncompleteRule,

    /// There may only be one `map` rule and it must be the final
    /// rule; if this error is returned, then multiple map rules
    /// exist or one exists and it is not the final rule.
    MapRuleViolation,

    /// The input stream doesn't contain any rules.
    NoRulesProvided,

    /// None of the rules matched on the input.
    UnterminatedMapping,
}

impl std::error::Error for ErrorKind {}

impl fmt::Display for ErrorKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{self:?}")
    }
}

/// Errors specific to XattrMap operations.
#[derive(Debug, Eq, PartialEq)]
pub struct Error {
    /// The specific error condition that was detected.
    pub cause: ErrorKind,

    /// The culpable rule, if any.
    pub rule: Option<usize>,
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        Some(&self.cause)
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{self:?}")
    }
}

impl From<ErrorKind> for Error {
    fn from(ek: ErrorKind) -> Self {
        Self {
            cause: ek,
            rule: None,
        }
    }
}

bitflags::bitflags! {
    struct Scope: u8 {
        const CLIENT = 0b01;
        const SERVER = 0b10;
    }
}

impl Scope {
    fn from_bytes<B: AsRef<[u8]>>(bytes: B) -> Result<Self, ErrorKind> {
        let bytes = bytes.as_ref();

        Ok(match bytes {
            b"all" => Scope::CLIENT | Scope::SERVER,
            b"client" => Scope::CLIENT,
            b"server" => Scope::SERVER,
            _ => {
                return Err(ErrorKind::InvalidScope {
                    got: String::from_utf8_lossy(bytes).into(),
                    expected: ["all", "client", "server"].join(", "),
                })
            }
        })
    }
}

#[derive(Copy, Clone, Debug, Eq, PartialEq)]
enum Type {
    Prefix,
    Okay,
    Bad,
    Unsupported,
    Map,
}

impl Type {
    fn from_bytes<B: AsRef<[u8]>>(bytes: B) -> Result<Self, ErrorKind> {
        let bytes = bytes.as_ref();

        Ok(match bytes {
            b"prefix" => Type::Prefix,
            b"ok" => Type::Okay,
            b"bad" => Type::Bad,
            b"unsupported" => Type::Unsupported,
            b"map" => Type::Map,
            _ => {
                return Err(ErrorKind::InvalidType {
                    got: String::from_utf8_lossy(bytes).into(),
                    expected: ["prefix", "ok", "bad", "map"].join(", "),
                })
            }
        })
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
struct Rule {
    scope: Scope,
    type_: Type,
    key: CString,
    prepend: CString,
}

impl Rule {
    fn matches(&self, scope: Scope, xattr_name: &[u8]) -> bool {
        if !self.scope.contains(scope) {
            return false;
        }

        match scope {
            Scope::CLIENT => xattr_name.starts_with(self.key.to_bytes()),
            Scope::SERVER => xattr_name.starts_with(self.prepend.to_bytes()),
            _ => panic!("ambiguous scope"),
        }
    }

    fn from_tokens<I>(tokens: &mut Peekable<I>) -> Result<Self, ErrorKind>
    where
        I: Iterator<Item = char>,
    {
        // The caller has already trimmed the whitespace leading up to here,
        // so the next element should be a rule delimiter.
        let delim = tokens.next().ok_or(ErrorKind::InvalidDelimiter)?;

        // This exists instead of using take_while() because take_while() will
        // consume the delimiter (if it exists) and it won't complain if it doesn't
        // exist. That means that we wouldn't be able to check for an unterminated
        // rule error like this:
        //      :prefix:all:trusted.:user.vm.
        //                                   ^ missing ':'
        let mut next_token = || {
            let mut bytes = vec![];
            loop {
                if let Some(ch) = tokens.peek() {
                    if !ch.eq(&delim) {
                        bytes.push(*ch as u8);
                        let _ = tokens.next();
                    } else {
                        // advance past delimiter
                        let _ = tokens.next();
                        break;
                    }
                } else {
                    // Ran out of tokens without finding a terminating delimiter
                    return Err(ErrorKind::IncompleteRule);
                }
            }

            Ok(bytes)
        };

        let type_ = Type::from_bytes(next_token()?)?;

        Ok(match type_ {
            Type::Map => Rule {
                type_,
                scope: Scope::CLIENT | Scope::SERVER,
                key: CString::new(next_token()?).unwrap(),
                prepend: CString::new(next_token()?).unwrap(),
            },
            Type::Prefix | Type::Okay | Type::Bad | Type::Unsupported => {
                let scope = Scope::from_bytes(next_token()?)?;

                Rule {
                    type_,
                    scope,
                    key: CString::new(next_token()?).unwrap(),
                    prepend: CString::new(next_token()?).unwrap(),
                }
            }
        })
    }

    fn expand_map_type(rule: Self) -> Vec<Self> {
        assert_eq!(rule.type_, Type::Map);

        // 1st: Prefix matches/everything
        let mut rules = vec![Rule {
            type_: Type::Prefix,
            scope: Scope::CLIENT | Scope::SERVER,
            key: rule.key.clone(),
            prepend: rule.prepend.clone(),
        }];

        let last_rule_type = if !rule.key.as_bytes().is_empty() {
            // 2nd: Hide non-prefixed but matching entries on the host, and
            // stop the client accessing prefixed attributes directly
            rules.push(Rule {
                type_: Type::Bad,
                scope: Scope::CLIENT | Scope::SERVER,
                key: rule.prepend,
                prepend: rule.key,
            });

            Type::Okay
        } else {
            Type::Bad
        };

        // Last: Everything else
        rules.push(Rule {
            type_: last_rule_type,
            scope: Scope::CLIENT | Scope::SERVER,
            key: CString::new("").unwrap(),
            prepend: CString::new("").unwrap(),
        });

        rules
    }
}

/// A return value that indicates the xattr name input has passed through
/// the XattrMap where a rule was successfully matched and applied to the
/// xattrname.
#[derive(Debug, Eq, PartialEq)]
pub enum AppliedRule<'a> {
    /// Server should the interior value onward through to the requested operation.
    Pass(Cow<'a, CStr>),

    /// Server should return EPERM (i.e., this matched on a `bad` rule).
    Deny,

    /// Server should return ENOTSUP (i.e., this matched on a `unsupported` rule).
    Unsupported,
}

/// A collection of well-formed xattr translation rules.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct XattrMap {
    rules: Vec<Rule>,
}

impl XattrMap {
    /// Applies xattrmap rules to a single extended attribute name.
    ///
    /// This should be called *before* any other extended attribute
    /// operation is performed on the host file system.
    ///
    /// Client request -> this method -> {get,set,remove}xattr() -> server response
    ///
    /// See also: getxattr(2), setxattr(2), removexattr(2)
    pub fn map_client_xattr<'a>(&self, xattr_name: &'a CStr) -> Result<AppliedRule<'a>, Error> {
        let rule = self.find_rule(Scope::CLIENT, xattr_name.to_bytes())?;

        Ok(match rule.type_ {
            Type::Okay => AppliedRule::Pass(Cow::Borrowed(xattr_name)),
            Type::Bad => AppliedRule::Deny,
            Type::Unsupported => AppliedRule::Unsupported,
            Type::Prefix => {
                let mut concat = rule.prepend.as_bytes().to_vec();
                concat.extend_from_slice(xattr_name.to_bytes());
                AppliedRule::Pass(Cow::Owned(CString::new(concat).unwrap()))
            }
            Type::Map => panic!("Unexpanded MAP rule was found."),
        })
    }

    /// Applies xattrmap rules to a list of extended attribute names.
    ///
    /// This should be called *before* replying to the client with the list
    /// of extended attribute names.
    ///
    /// Client request -> listxattr() -> this method -> server response
    ///
    /// See also: listxattr(2)
    pub fn map_server_xattrlist(&self, xattr_names: Vec<u8>) -> Result<Vec<u8>, Error> {
        let mut filtered = Vec::with_capacity(xattr_names.len());
        let unprocessed = xattr_names.split(|b| *b == 0).filter(|bs| !bs.is_empty());

        for xattr_name in unprocessed {
            let rule = self.find_rule(Scope::SERVER, xattr_name)?;

            let processed = match rule.type_ {
                Type::Bad | Type::Unsupported => continue, // hide this from the client
                Type::Okay => xattr_name,
                Type::Prefix => &xattr_name[rule.prepend.as_bytes().len()..], // strip prefix
                Type::Map => panic!("Unexpanded MAP rule was found."),
            };

            filtered.extend_from_slice(processed);
            filtered.push(0);
        }

        if filtered.is_empty() {
            filtered.push(0);
        }

        filtered.shrink_to_fit();

        Ok(filtered)
    }

    fn find_rule(&self, scope: Scope, xattr_name: &[u8]) -> Result<&Rule, Error> {
        let rule = self
            .rules
            .iter()
            .find(|r| r.matches(scope, xattr_name))
            .ok_or(ErrorKind::UnterminatedMapping)
            .map_err(|e| Error {
                cause: e,
                rule: None,
            })?;

        Ok(rule)
    }
}

impl TryFrom<&str> for XattrMap {
    type Error = Error;

    fn try_from(input: &str) -> Result<Self, Error> {
        let trimmed = input.trim();
        let mut unparsed = trimmed.chars().peekable();
        let mut rules: Vec<Rule> = vec![];

        while unparsed.peek().is_some() {
            // Skip any whitespace between rules
            if let Some(ch) = unparsed.peek() {
                if ch.is_ascii_whitespace() {
                    let _ = unparsed.next();
                    continue;
                }
            }

            let rule = Rule::from_tokens(&mut unparsed).map_err(|e| Error {
                cause: e,
                rule: Some(rules.len() + 1),
            })?;

            if rule.type_ == Type::Map {
                // There may only be one 'map' rule and it must be the final rule
                if unparsed.peek().is_some() {
                    return Err(Error {
                        rule: Some(rules.len() + 1),
                        cause: ErrorKind::MapRuleViolation,
                    });
                }
                rules.append(&mut Rule::expand_map_type(rule));
            } else {
                rules.push(rule);
            };
        }

        if rules.is_empty() {
            return Err(ErrorKind::NoRulesProvided.into());
        }

        Ok(Self { rules })
    }
}

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

    #[test]
    fn test_parser_can_parse_single_rule() {
        let input = ":prefix:client:trusted.:user.virtiofs.:";
        let actual = XattrMap::try_from(input).unwrap();
        let expected = XattrMap {
            rules: vec![Rule {
                type_: Type::Prefix,
                scope: Scope::CLIENT,
                key: CString::new("trusted.").unwrap(),
                prepend: CString::new("user.virtiofs.").unwrap(),
            }],
        };

        assert_eq!(actual, expected);
    }

    #[test]
    fn test_parser_can_parse_multiple_valid_rules() {
        let input = ":prefix:all::user.virtiofs.::bad:all:::";
        let actual = XattrMap::try_from(input).unwrap();
        let expected = XattrMap {
            rules: vec![
                Rule {
                    type_: Type::Prefix,
                    scope: Scope::CLIENT | Scope::SERVER,
                    key: CString::new("").unwrap(),
                    prepend: CString::new("user.virtiofs.").unwrap(),
                },
                Rule {
                    type_: Type::Bad,
                    scope: Scope::CLIENT | Scope::SERVER,
                    key: CString::new("").unwrap(),
                    prepend: CString::new("").unwrap(),
                },
            ],
        };

        assert_eq!(actual, expected);
    }

    #[test]
    fn test_parser_can_parse_rules_separated_by_whitespace() {
        let input = r#"
        /prefix/all/trusted./user.virtiofs./
        /bad/server//trusted./
        /bad/client/user.virtiofs.//
        /ok/all///
        "#;

        let actual = XattrMap::try_from(input).unwrap();
        let expected = XattrMap {
            rules: vec![
                Rule {
                    type_: Type::Prefix,
                    scope: Scope::CLIENT | Scope::SERVER,
                    key: CString::new("trusted.").unwrap(),
                    prepend: CString::new("user.virtiofs.").unwrap(),
                },
                Rule {
                    type_: Type::Bad,
                    scope: Scope::SERVER,
                    key: CString::new("").unwrap(),
                    prepend: CString::new("trusted.").unwrap(),
                },
                Rule {
                    type_: Type::Bad,
                    scope: Scope::CLIENT,
                    key: CString::new("user.virtiofs.").unwrap(),
                    prepend: CString::new("").unwrap(),
                },
                Rule {
                    type_: Type::Okay,
                    scope: Scope::CLIENT | Scope::SERVER,
                    key: CString::new("").unwrap(),
                    prepend: CString::new("").unwrap(),
                },
            ],
        };

        assert_eq!(actual, expected);
    }

    #[test]
    fn test_parser_emits_incomplete_rule_error() {
        let input = ":prefix:client:hi";
        let actual = XattrMap::try_from(input).unwrap_err();
        let expected = Error {
            rule: Some(1),
            cause: ErrorKind::IncompleteRule,
        };
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_parser_emits_error_when_multiple_map_rules_exist() {
        let input = ":map:trusted.:virtiofs.user.::map:trusted.:virtiofs.user.:";
        let actual = XattrMap::try_from(input).unwrap_err();
        let expected = Error {
            rule: Some(1),
            cause: ErrorKind::MapRuleViolation,
        };
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_parser_expands_map_rule_with_empty_key() {
        let input = ":map::user.virtiofs.:";
        let actual = XattrMap::try_from(input).unwrap();
        let expected = XattrMap {
            rules: vec![
                Rule {
                    type_: Type::Prefix,
                    scope: Scope::CLIENT | Scope::SERVER,
                    key: CString::new("").unwrap(),
                    prepend: CString::new("user.virtiofs.").unwrap(),
                },
                Rule {
                    type_: Type::Bad,
                    scope: Scope::CLIENT | Scope::SERVER,
                    key: CString::new("").unwrap(),
                    prepend: CString::new("").unwrap(),
                },
            ],
        };
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_parser_expands_map_rule_with_key_and_prepend() {
        let input = ":map:trusted.:user.virtiofs.:";
        let actual = XattrMap::try_from(input).unwrap();
        let expected = XattrMap {
            rules: vec![
                Rule {
                    type_: Type::Prefix,
                    scope: Scope::CLIENT | Scope::SERVER,
                    key: CString::new("trusted.").unwrap(),
                    prepend: CString::new("user.virtiofs.").unwrap(),
                },
                Rule {
                    type_: Type::Bad,
                    scope: Scope::CLIENT | Scope::SERVER,
                    key: CString::new("user.virtiofs.").unwrap(),
                    prepend: CString::new("trusted.").unwrap(),
                },
                Rule {
                    type_: Type::Okay,
                    scope: Scope::CLIENT | Scope::SERVER,
                    key: CString::new("").unwrap(),
                    prepend: CString::new("").unwrap(),
                },
            ],
        };
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_parser_emits_error_when_invalid_type_is_used() {
        let input = ":TOMATOPIRATE:trusted.:virtiofs.user.:";
        assert!(XattrMap::try_from(input).is_err());
    }

    #[test]
    fn test_parser_emits_error_when_invalid_scope_is_used() {
        let input = "/prefix/helloworld///";
        assert!(XattrMap::try_from(input).is_err());
    }

    #[test]
    fn test_parser_emits_error_when_no_rules_are_provided() {
        let input = " ";
        let actual = XattrMap::try_from(input).unwrap_err();
        let expected = Error {
            rule: None,
            cause: ErrorKind::NoRulesProvided,
        };
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_parser_can_parse_rules_with_different_delimiters() {
        let input = ":prefix:all:trusted.:user.virtiofs.: /prefix/all/trusted./user.virtiofs./";
        let expected_rule = Rule {
            type_: Type::Prefix,
            scope: Scope::CLIENT | Scope::SERVER,
            key: CString::new("trusted.").unwrap(),
            prepend: CString::new("user.virtiofs.").unwrap(),
        };
        let expected = XattrMap {
            rules: vec![expected_rule.clone(), expected_rule],
        };

        let actual = XattrMap::try_from(input).unwrap();
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_rule_ok_all() {
        let map = XattrMap {
            rules: vec![Rule {
                type_: Type::Okay,
                scope: Scope::CLIENT | Scope::SERVER,
                key: CString::new("").unwrap(),
                prepend: CString::new("").unwrap(),
            }],
        };
        let input = CString::new("user.virtiofs.potato").unwrap();
        let actual = map.map_client_xattr(&input).unwrap();
        let expected = AppliedRule::Pass(CString::new("user.virtiofs.potato").unwrap().into());
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_rule_bad_hides_xattr_names_from_client() {
        let input = b"security.secret\x00boring_attr".to_vec();
        let map = XattrMap {
            rules: vec![
                Rule {
                    type_: Type::Bad,
                    scope: Scope::SERVER,
                    key: CString::new("").unwrap(),
                    prepend: CString::new("security.").unwrap(),
                },
                Rule {
                    type_: Type::Okay,
                    scope: Scope::CLIENT | Scope::SERVER,
                    key: CString::new("").unwrap(),
                    prepend: CString::new("").unwrap(),
                },
            ],
        };

        let actual = map.map_server_xattrlist(input).unwrap();
        let expected = b"boring_attr\x00";
        assert_eq!(actual.as_slice(), expected);
    }

    #[test]
    fn test_rule_unsupported_hides_xattr_names_from_client() {
        let input = b"security.secret\x00boring_attr".to_vec();
        let map = XattrMap {
            rules: vec![
                Rule {
                    type_: Type::Unsupported,
                    scope: Scope::SERVER,
                    key: CString::new("").unwrap(),
                    prepend: CString::new("security.").unwrap(),
                },
                Rule {
                    type_: Type::Okay,
                    scope: Scope::CLIENT | Scope::SERVER,
                    key: CString::new("").unwrap(),
                    prepend: CString::new("").unwrap(),
                },
            ],
        };

        let actual = map.map_server_xattrlist(input).unwrap();
        let expected = b"boring_attr\x00";
        assert_eq!(actual.as_slice(), expected);
    }

    #[test]
    fn test_rule_bad_denies_the_client_request() {
        let map = XattrMap {
            rules: vec![Rule {
                type_: Type::Bad,
                scope: Scope::CLIENT,
                key: CString::new("").unwrap(),
                prepend: CString::new("").unwrap(),
            }],
        };

        let input = CString::new("virtiofs.").unwrap();
        let actual = map.map_client_xattr(&input).unwrap();
        let expected = AppliedRule::Deny;
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_rule_unsupported_not_support_the_client_request() {
        let map = XattrMap {
            rules: vec![Rule {
                type_: Type::Unsupported,
                scope: Scope::CLIENT,
                key: CString::new("").unwrap(),
                prepend: CString::new("").unwrap(),
            }],
        };

        let input = CString::new("virtiofs.").unwrap();
        let actual = map.map_client_xattr(&input).unwrap();
        let expected = AppliedRule::Unsupported;
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_rule_prefix_prepends_xattr_names_from_client() {
        let map = XattrMap {
            rules: vec![Rule {
                type_: Type::Prefix,
                scope: Scope::CLIENT | Scope::SERVER,
                key: CString::new("trusted.").unwrap(),
                prepend: CString::new("virtiofs.user.").unwrap(),
            }],
        };

        let input = CString::new("trusted.secret_thing").unwrap();
        let actual = map.map_client_xattr(&input).unwrap();
        let expected = AppliedRule::Pass(Cow::Owned(
            CString::new("virtiofs.user.trusted.secret_thing").unwrap(),
        ));
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_rule_prefix_strips_prefixes_from_server() {
        let map = XattrMap {
            rules: vec![Rule {
                type_: Type::Prefix,
                scope: Scope::SERVER,
                key: CString::new("").unwrap(),
                prepend: CString::new("virtiofs.user.").unwrap(),
            }],
        };

        let list = b"virtiofs.user.x".to_vec();
        let actual = map.map_server_xattrlist(list).unwrap();
        let expected = b"x\x00".to_vec();
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_rule_ok_allows_xattr_names_to_pass_through_unchanged() {
        let map = XattrMap {
            rules: vec![Rule {
                type_: Type::Okay,
                scope: Scope::CLIENT | Scope::SERVER,
                key: CString::new("allow.").unwrap(),
                prepend: CString::new("allow.").unwrap(),
            }],
        };

        let input = CString::new("allow.y").unwrap();
        let actual = map.map_client_xattr(&input).unwrap();
        let expected = AppliedRule::Pass(Cow::Owned(CString::new("allow.y").unwrap()));
        assert_eq!(actual, expected);

        let list = b"allow.y\x00".to_vec();
        let expected = list.clone();
        let actual = map.map_server_xattrlist(list).unwrap();
        assert_eq!(actual, expected);
    }
}