apparmor-policy 0.1.0

Typed, lossless parser and serializer for the AppArmor policy language.
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
//! The AppArmor policy AST (abstract syntax tree).
//!
//! The AST is deliberately *lossless with respect to information*: variables
//! are kept as `@{...}` references (never expanded), unknown rules degrade to
//! [`RawRule`] nodes carrying their original text, and every rule keeps its
//! qualifiers (`deny`, `audit`, `priority`, `owner`, …). Everything the
//! parser sees is either understood *and typed*, or preserved verbatim for
//! the caller to re-emit or repair.

pub use crate::glob::FileRulePattern;

use std::collections::BTreeMap;

/// A complete AppArmor policy file.
///
/// A policy file is a sequence of preamble items (variables, aliases,
/// includes, abi) and one or more [`Profile`]s. See
/// [`crate::parse_str`] / [`crate::parse_policy`] for how to obtain one.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Policy {
    /// Top-level items in source order: preamble items and profiles.
    pub items: Vec<PolicyItem>,
}

/// One top-level item of a policy file.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum PolicyItem {
    /// A `@{VAR} = value` / `@{VAR} += value` assignment.
    Variable(VariableAssignment),
    /// An `alias A -> B` declaration.
    Alias(AliasRule),
    /// A `#include` / `include` directive.
    Include(IncludeRule),
    /// An `abi <...>` declaration.
    Abi(AbiRule),
    /// A profile (or sub-profile).
    Profile(Profile),
    /// A top-level item that was not recognized.
    Raw(RawItem),
}

/// An `@{VAR} = ...` or `@{VAR} += ...` variable assignment.
///
/// Variable *references* inside rules are kept as [`FileRulePattern::Variable`]
/// nodes; only the *definitions* are collected here.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VariableAssignment {
    /// The variable name without `@{}` (e.g. `"HOME"` for `@{HOME}`).
    pub name: String,
    /// `true` when this was an append (`+=`) rather than a replace (`=`).
    pub append: bool,
    /// The assigned values, in source order.
    pub values: Vec<String>,
}

/// An `alias OLD -> NEW` declaration.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AliasRule {
    /// The aliased path.
    pub oldname: String,
    /// The path it rewrites to.
    pub newname: String,
}

/// A `#include <path>` / `include if exists <path>` directive.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IncludeRule {
    /// Whether the `if exists` modifier was present (silently skip a missing
    /// file instead of erroring).
    pub if_exists: bool,
    /// `true` for the magic `<path>` form, `false` for a plain absolute path.
    pub magic: bool,
    /// The include target (magic path without `< >`, or an absolute path).
    pub path: String,
}

/// An `abi <path>` declaration (kernel ABI the profile targets).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AbiRule {
    /// `true` for the magic `<path>` form.
    pub magic: bool,
    /// The abi target.
    pub path: String,
}

/// A profile (top-level) or sub-profile (nested).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Profile {
    /// The profile name (e.g. `"foo"` or `"/usr/bin/foo"`).
    pub name: String,
    /// The attachment: a file-glob the profile applies to. Present when the
    /// profile header carried a path (e.g. `profile foo /usr/bin/foo` or
    /// `profile /usr/bin/foo`).
    pub attachment: Option<FileRulePattern>,
    /// Profile flags (e.g. `complain`, `attach_disconnected`).
    pub flags: Vec<Flag>,
    /// Variable assignments in the profile body (and the immediately
    /// preceding preamble).
    pub variables: Vec<VariableAssignment>,
    /// Includes in the profile body (and the immediately preceding preamble).
    pub includes: Vec<IncludeRule>,
    /// Alias declarations in the profile body.
    pub aliases: Vec<AliasRule>,
    /// Rules in the profile body.
    pub rules: Vec<Rule>,
    /// Hats and sub-profiles.
    pub hats: Vec<Hat>,
}

/// A hat (`hat foo { ... }` or `^foo { ... }`) or sub-profile.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Hat {
    /// `true` if this is a sub-profile (`profile child { ... }`), `false`
    /// for a hat.
    pub is_subprofile: bool,
    /// The hat/sub-profile name.
    pub name: String,
    /// The attachment for sub-profiles (`profile child /usr/bin/x`); always
    /// `None` for hats.
    pub attachment: Option<FileRulePattern>,
    /// Flags (e.g. `complain`).
    pub flags: Vec<Flag>,
    /// Variable assignments inside the hat.
    pub variables: Vec<VariableAssignment>,
    /// Includes inside the hat.
    pub includes: Vec<IncludeRule>,
    /// Alias declarations inside the hat.
    pub aliases: Vec<AliasRule>,
    /// Rules inside the hat.
    pub rules: Vec<Rule>,
    /// Nested hats / sub-profiles.
    pub hats: Vec<Hat>,
}

/// A named flag value used in profile/hat headers, e.g. `complain` or
/// `attach_disconnected.path=/foo`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Flag {
    /// The flag name (e.g. `"complain"`).
    pub name: String,
    /// The value for flags of the form `name=value` (e.g. `"path=/foo"` is
    /// split into name `"path"` … no: `name="path=/foo"`, value is the part
    /// after the first `=`).
    pub value: Option<String>,
}

impl Flag {
    /// Build a flag without a value.
    pub fn new(name: impl Into<String>) -> Self {
        Flag {
            name: name.into(),
            value: None,
        }
    }
    /// Build a `name=value` flag.
    pub fn with_value(name: impl Into<String>, value: impl Into<String>) -> Self {
        Flag {
            name: name.into(),
            value: Some(value.into()),
        }
    }
}

/// A single rule inside a profile or hat body.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Rule {
    /// A file rule (the most common rule type).
    File(FileRule),
    /// A `capability` rule.
    Capability(CapabilityRule),
    /// A `network` rule.
    Network(NetworkRule),
    /// A `mount` / `remount` / `umount` rule.
    Mount(MountRule),
    /// A `pivot_root` rule.
    PivotRoot(PivotRootRule),
    /// A `link` rule.
    Link(LinkRule),
    /// A `change_profile` rule.
    ChangeProfile(ChangeProfileRule),
    /// A `set rlimit` rule.
    Rlimit(RlimitRule),
    /// A `dbus` rule.
    Dbus(DbusRule),
    /// A `unix` rule.
    Unix(UnixRule),
    /// A `mqueue` rule.
    Mqueue(MqueueRule),
    /// A `userns` rule.
    Userns(UsernsRule),
    /// An `io_uring` rule.
    IoUring(IoUringRule),
    /// A `signal` rule.
    Signal(SignalRule),
    /// A `ptrace` rule.
    Ptrace(PtraceRule),
    /// An `all` rule (grants everything).
    All(AllRule),
    /// A rule that was not recognized or failed to parse; the original text
    /// is preserved so nothing is lost.
    Raw(RawRule),
}

/// Qualifiers that may prefix a rule: `[priority=N] [audit] [deny|allow]`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Qualifiers {
    /// The `priority=INT` qualifier (newer AppArmor versions).
    pub priority: Option<u64>,
    /// The `audit` qualifier.
    pub audit: bool,
    /// The `deny` qualifier.
    pub deny: bool,
    /// The `allow` qualifier (usually implicit; present when written).
    pub allow: bool,
}

/// A file rule: `[qualifiers] [owner|group …] PATH ACCESS [-> TARGET]`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FileRule {
    /// The qualifier block.
    pub qualifiers: Qualifiers,
    /// The `owner` qualifier.
    pub owner: bool,
    /// The `group` qualifier value (`group=NAME`).
    pub group: Option<String>,
    /// The file path / glob. `None` for a bare `file` rule (grants access
    /// to all files).
    pub path: Option<FileRulePattern>,
    /// The access modes.
    pub access: Vec<FileAccess>,
    /// The exec transition target (`-> path`), if any.
    pub exec_target: Option<FileRulePattern>,
}

/// One access mode in a file rule.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum FileAccess {
    /// `r` — read.
    Read,
    /// `w` — write.
    Write,
    /// `a` — append.
    Append,
    /// `l` — link.
    Link,
    /// `k` — lock.
    Lock,
    /// `m` — memory map executable.
    MemoryMap,
    /// An exec transition (`ix`, `px`, `cx`, …).
    Exec(ExecTransition),
}

/// An exec transition mode in a file rule.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ExecTransition {
    /// `ix` — inherit the current profile.
    Inherit,
    /// `ux` — unconstrained.
    Unconstrained,
    /// `Ux` — unconstrained (safe).
    UnconstrainedSafe,
    /// `px` — profile transition.
    Profile,
    /// `Px` — profile transition (safe).
    ProfileSafe,
    /// `cx` — child profile transition.
    Child,
    /// `Cx` — child profile transition (safe).
    ChildSafe,
    /// `pix` — profile + inherit.
    ProfileInherit,
    /// `Pix` — profile + inherit (safe).
    ProfileInheritSafe,
    /// `cix` — child + inherit.
    ChildInherit,
    /// `Cix` — child + inherit (safe).
    ChildInheritSafe,
    /// `pux` — profile + unconstrained.
    ProfileUnconstrained,
    /// `PUx` — profile + unconstrained (safe).
    ProfileUnconstrainedSafe,
    /// `cux` — child + unconstrained.
    ChildUnconstrained,
    /// `CUx` — child + unconstrained (safe).
    ChildUnconstrainedSafe,
    /// A bare `x` (only valid inside `deny` rules).
    BareX,
}

/// A `capability NAME[, NAME …]` rule.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CapabilityRule {
    /// The qualifier block.
    pub qualifiers: Qualifiers,
    /// The capability names (e.g. `"setuid"`, `"net_bind_service"`).
    pub capabilities: Vec<String>,
}

/// Access types for network rules.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum NetworkAccess {
    /// `create`
    Create,
    /// `bind`
    Bind,
    /// `listen`
    Listen,
    /// `accept`
    Accept,
    /// `connect`
    Connect,
    /// `shutdown`
    Shutdown,
    /// `getattr`
    GetAttr,
    /// `setattr`
    SetAttr,
    /// `getopt`
    GetOpt,
    /// `setopt`
    SetOpt,
    /// `send`
    Send,
    /// `receive`
    Receive,
    /// `r` / `read`
    Read,
    /// `w` / `write`
    Write,
    /// `rw` / `read write`
    ReadWrite,
    /// An access keyword this parser does not know (kept verbatim).
    Other(String),
}

/// A `network` rule.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NetworkRule {
    /// The qualifier block.
    pub qualifiers: Qualifiers,
    /// Access list (e.g. `create`, `bind`), if present.
    pub access: Vec<NetworkAccess>,
    /// The address family / domain (e.g. `inet`, `inet6`, `unix`, `mctp`).
    pub domain: Option<String>,
    /// The socket type (e.g. `stream`, `dgram`, `raw`, `packet`).
    pub network_type: Option<String>,
    /// The protocol (e.g. `tcp`, `udp`, `icmp`).
    pub protocol: Option<String>,
    /// Extra conditions (`ip=…`, `port=…`).
    pub conditions: Vec<(String, String)>,
}

/// A `mount` / `remount` / `umount` rule.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MountRule {
    /// The qualifier block.
    pub qualifiers: Qualifiers,
    /// The mount operation keyword.
    pub operation: MountOp,
    /// `fstype` / `vfstype` condition (`= value` or `in (a, b)`).
    pub fstype: Option<ValueCondition>,
    /// `options` condition.
    pub options: Option<ValueCondition>,
    /// The source device / path.
    pub source: Option<FileRulePattern>,
    /// The mount point.
    pub mount_point: Option<FileRulePattern>,
    /// The `-> profile` transition target.
    pub target: Option<ProfileTarget>,
}

/// The operation keyword of a mount rule.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum MountOp {
    /// `mount`
    Mount,
    /// `remount`
    Remount,
    /// `umount`
    Umount,
}

/// A `fstype=…` / `options in (…)` style value condition.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ValueCondition {
    /// The condition name as written (`fstype`, `vfstype` or `options`).
    pub name: String,
    /// `true` for `in (a, b, c)`, `false` for `= value`.
    pub in_list: bool,
    /// The value(s).
    pub values: Vec<String>,
}

/// A `pivot_root` rule.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PivotRootRule {
    /// The qualifier block.
    pub qualifiers: Qualifiers,
    /// The `oldroot=` value.
    pub old_root: Option<FileRulePattern>,
    /// The new root.
    pub new_root: Option<FileRulePattern>,
    /// The `-> profile` transition target.
    pub target: Option<ProfileTarget>,
}

/// A `link` rule: `[qualifiers] [owner] link [subset] OLD -> NEW`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LinkRule {
    /// The qualifier block.
    pub qualifiers: Qualifiers,
    /// The `owner` qualifier.
    pub owner: bool,
    /// The `subset` modifier.
    pub subset: bool,
    /// The source path.
    pub oldname: FileRulePattern,
    /// The destination path.
    pub newname: FileRulePattern,
}

/// A `change_profile` rule.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChangeProfileRule {
    /// The qualifier block.
    pub qualifiers: Qualifiers,
    /// `Some(true)` for `safe`, `Some(false)` for `unsafe`, `None` for bare.
    pub safe: Option<bool>,
    /// The executable path.
    pub executable: FileRulePattern,
    /// The `-> profile` transition target.
    pub target: Option<ProfileTarget>,
}

/// A `set rlimit` rule.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RlimitRule {
    /// The qualifier block.
    pub qualifiers: Qualifiers,
    /// The resource name (e.g. `cpu`, `nice`, `nofile`).
    pub rlimit: String,
    /// The comparison operator.
    pub op: Option<RelOp>,
    /// The limit value.
    pub value: Option<LimitValue>,
}

/// The comparison operator in a `set rlimit` rule.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum RelOp {
    /// `<=`
    LessEqual,
    /// `<`
    Less,
}

/// A limit value with an optional unit.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LimitValue {
    /// The numeric value (signed, so `nice -20..19` works).
    pub number: i64,
    /// The unit suffix, if any (`K`, `M`, `G`, `us`, `ms`, `s`, …).
    pub unit: Option<String>,
}

/// A `dbus` rule.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DbusRule {
    /// The qualifier block.
    pub qualifiers: Qualifiers,
    /// Access keywords (`send`, `receive`, `bind`, `eavesdrop`, `r`, `w`, …).
    pub access: Vec<String>,
    /// The `bus=` value (`system` or `session`).
    pub bus: Option<String>,
    /// The `path=` value.
    pub path: Option<FileRulePattern>,
    /// The `interface=` value.
    pub interface: Option<String>,
    /// The `member=` value.
    pub member: Option<String>,
    /// The `peer=(name=…, label=…)` condition.
    pub peer: Option<PeerCondition>,
    /// The `label=` value.
    pub label: Option<FileRulePattern>,
    /// The `name=` value (for `bind` rules).
    pub name: Option<String>,
}

/// A `unix` rule.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnixRule {
    /// The qualifier block.
    pub qualifiers: Qualifiers,
    /// Access keywords.
    pub access: Vec<String>,
    /// The `type=` value.
    pub type_cond: Option<String>,
    /// The `protocol=` value.
    pub protocol: Option<String>,
    /// The `addr=` value.
    pub addr: Option<FileRulePattern>,
    /// The `label=` value.
    pub label: Option<FileRulePattern>,
    /// The `attr=` value.
    pub attr: Option<FileRulePattern>,
    /// The `opt=` value.
    pub opt: Option<FileRulePattern>,
    /// The `peer=(addr=…, label=…)` condition.
    pub peer: Option<PeerCondition>,
}

/// A `mqueue` rule.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MqueueRule {
    /// The qualifier block.
    pub qualifiers: Qualifiers,
    /// Access keywords.
    pub access: Vec<String>,
    /// The `type=` value (`posix` or `sysv`).
    pub mq_type: Option<String>,
    /// The `label=` value.
    pub label: Option<FileRulePattern>,
    /// The `name=` value.
    pub name: Option<FileRulePattern>,
}

/// A `userns` rule.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UsernsRule {
    /// The qualifier block.
    pub qualifiers: Qualifiers,
    /// Access keywords (currently just `create`).
    pub access: Vec<String>,
}

/// An `io_uring` rule.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IoUringRule {
    /// The qualifier block.
    pub qualifiers: Qualifiers,
    /// Access keywords (`sqpoll`, `override_creds`).
    pub access: Vec<String>,
    /// The `label=` value.
    pub label: Option<FileRulePattern>,
}

/// A `signal` rule.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SignalRule {
    /// The qualifier block.
    pub qualifiers: Qualifiers,
    /// Access keywords (`r`, `w`, `rw`, `read`, `write`, `send`, `receive`).
    pub access: Vec<String>,
    /// The `set=(…)` signal set, if present.
    pub set: Option<Vec<String>>,
    /// The `peer=` value.
    pub peer: Option<FileRulePattern>,
}

/// A `ptrace` rule.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PtraceRule {
    /// The qualifier block.
    pub qualifiers: Qualifiers,
    /// Access keywords (`r`, `w`, `rw`, `read`, `readby`, `trace`, `tracedby`).
    pub access: Vec<String>,
    /// The `peer=` value.
    pub peer: Option<FileRulePattern>,
}

/// An `all` rule.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AllRule {
    /// The qualifier block.
    pub qualifiers: Qualifiers,
}

/// A `peer=(…, …)` condition shared by dbus / unix rules.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct PeerCondition {
    /// The `name=` value (dbus).
    pub name: Option<String>,
    /// The `label=` value.
    pub label: Option<String>,
    /// The `addr=` value (unix).
    pub addr: Option<FileRulePattern>,
}

/// A `-> profile` transition target.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProfileTarget {
    /// The target profile name.
    pub name: String,
}

/// A rule that could not be recognized or parsed; the original text is kept.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RawRule {
    /// The verbatim rule text (without the trailing comma).
    pub text: String,
    /// 1-based line of the rule start.
    pub line: usize,
    /// 1-based column of the rule start.
    pub col: usize,
    /// Why the rule was not parsed as a known type (for tooling).
    pub note: Option<String>,
}

/// A top-level item that could not be recognized; the original text is kept.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RawItem {
    /// The verbatim text.
    pub text: String,
    /// 1-based line of the item start.
    pub line: usize,
    /// 1-based column of the item start.
    pub col: usize,
}

impl Profile {
    /// All variable definitions inside the profile body, keyed by name in
    /// insertion order. Append assignments (`+=`) extend the previous value
    /// list; plain assignments (`=`) replace it.
    ///
    /// Preamble-level assignments are separate items in [`Policy`] and are
    /// *not* folded into profiles by the parser.
    ///
    /// # Examples
    ///
    /// ```
    /// use apparmor_policy::parse_str;
    ///
    /// let profiles = parse_str("profile foo {\n  @{LOCAL} += x,\n  @{LOCAL} += y,\n}\n").unwrap();
    /// let vars = profiles[0].variables_map();
    /// assert_eq!(vars["LOCAL"], vec!["x", "y"]);
    /// ```
    pub fn variables_map(&self) -> BTreeMap<&str, Vec<&str>> {
        let mut map: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
        for v in &self.variables {
            let entry = map.entry(v.name.as_str()).or_default();
            if v.append {
                entry.extend(v.values.iter().map(String::as_str));
            } else {
                *entry = v.values.iter().map(String::as_str).collect();
            }
        }
        map
    }
}

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

    #[test]
    fn variables_map_respects_append() {
        let p = Profile {
            name: "foo".into(),
            attachment: None,
            flags: vec![],
            variables: vec![
                VariableAssignment {
                    name: "A".into(),
                    append: false,
                    values: vec!["1".into(), "2".into()],
                },
                VariableAssignment {
                    name: "A".into(),
                    append: true,
                    values: vec!["3".into()],
                },
                VariableAssignment {
                    name: "B".into(),
                    append: true,
                    values: vec!["x".into()],
                },
            ],
            includes: vec![],
            aliases: vec![],
            rules: vec![],
            hats: vec![],
        };
        let map = p.variables_map();
        assert_eq!(map["A"], vec!["1", "2", "3"]);
        assert_eq!(map["B"], vec!["x"]);
    }

    #[test]
    fn flag_accessors() {
        let f = Flag::with_value("kill.signal", "HUP");
        assert_eq!(f.name, "kill.signal");
        assert_eq!(f.value.as_deref(), Some("HUP"));
        let g = Flag::new("complain");
        assert_eq!(g.value, None);
    }
}