byssus 0.1.0

Live, read-only filesystem attachments between isolated workspaces
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
//! `byssus` — the Byssus command-line tool.

#![allow(clippy::print_stdout, clippy::print_stderr)]

use std::collections::{BTreeMap, BTreeSet};
use std::process::ExitCode;

use anyhow::Context as _;
use byssus::app::{self, ConfigSource};
use byssus::cli::byssus::{Cli, Command, Format, PrivilegeArgs};
use byssus::config::{self, Config, OwnershipPolicy, Severity};
use byssus::logging::{self, LogLevel};
use byssus::mountinfo::MountTable;
use byssus::name::GroupId;
use byssus::privileges::plan::Goal;
use byssus::probe::{self, Feature, PropagationCheck};
use byssus::reconcile::{self, Trigger, observe, plan};
use byssus::report::{self, Check, DryRunReport, Level, StatusReport};
use byssus::runtime::{Runtime, Subject};
use byssus::state::{LoadError, LoadOutcome, State, StateStore};
use clap::Parser as _;
use tracing::Level as TracingLevel;

fn main() -> ExitCode {
    let cli = Cli::parse();
    let default_level = match cli.command {
        Command::Reconcile { .. } => TracingLevel::INFO,
        _ => TracingLevel::WARN,
    };
    logging::init(cli.log_level.unwrap_or(LogLevel(default_level)));

    let result = match cli.command {
        Command::Version => {
            println!("byssus {}", byssus::VERSION);
            Ok(ExitCode::SUCCESS)
        }
        Command::Status { format } => status(&cli.config.source(), format),
        Command::Check {
            add,
            remove,
            allow_slave_namespace,
            format,
        } => check(
            &cli.config.source(),
            config::FragmentChanges { add, remove },
            allow_slave_namespace,
            format,
        ),
        Command::DryRun { format } => dry_run(&cli.config.source(), format),
        Command::Reconcile { privileges } => reconcile_once(&cli.config.source(), &privileges),
    };
    match result {
        Ok(code) => code,
        Err(e) => {
            eprintln!("byssus: {e:#}");
            ExitCode::FAILURE
        }
    }
}

/// Shown when checks run as root because no service user is configured.
const ROOT_WITHOUT_USER_WARNING: &str = "checks ran as root because daemon.user is not set, so access \
    problems for the daemon's service user (for example an unreadable membership or source \
    directory) are not detected; set daemon.user = \"byssus\" in the main configuration";

/// Degraded groups and sets from open failures.
fn degraded_from(errors: &[byssus::runtime::OpenGroupError]) -> reconcile::Degraded {
    let mut degraded = reconcile::Degraded::default();
    for e in errors {
        match &e.subject {
            Subject::Group(group) => {
                degraded.groups.insert(group.clone());
            }
            Subject::Set(set) => {
                degraded.sets.insert(set.clone());
            }
        }
    }
    degraded
}

fn exit_for(level: Level) -> ExitCode {
    if level == Level::Error {
        ExitCode::FAILURE
    } else {
        ExitCode::SUCCESS
    }
}

fn print_report<T: serde::Serialize>(
    format: Format,
    text: impl FnOnce() -> String,
    value: &T,
) -> anyhow::Result<()> {
    match format {
        Format::Text => print!("{}", text()),
        Format::Json => println!("{}", serde_json::to_string_pretty(value)?),
    }
    Ok(())
}

/// Loads state without writing, explaining failures. Returns the state, whether
/// ownership is known, and notes.
fn load_state_read_only(config: &Config) -> (State, bool, Vec<String>, String) {
    let dir = config.daemon.state_dir.as_path();
    let path = dir
        .join(byssus::state::STATE_FILE_NAME)
        .display()
        .to_string();
    let store = match StateStore::open(dir) {
        Ok(store) => store,
        Err(e) => {
            let hint = if e.kind() == std::io::ErrorKind::PermissionDenied {
                " (join the byssus group or run as root to read state)"
            } else {
                ""
            };
            return (
                State::default(),
                false,
                vec![format!(
                    "cannot open state directory {}: {e}{hint}",
                    dir.display()
                )],
                path,
            );
        }
    };
    match store.load_read_only() {
        Ok(LoadOutcome::Loaded(state)) => (state, true, vec![], path),
        Ok(LoadOutcome::Missing) => (
            State::default(),
            true,
            vec!["no state file yet".into()],
            path,
        ),
        Ok(LoadOutcome::Corrupt { reason, .. }) => (
            State::default(),
            false,
            vec![format!("state file is corrupt: {reason}")],
            path,
        ),
        Err(LoadError::Io { source, .. })
            if source.kind() == std::io::ErrorKind::PermissionDenied =>
        {
            (
                State::default(),
                false,
                vec![format!(
                    "cannot read state file: {source} (join the byssus group or run as root)"
                )],
                path,
            )
        }
        Err(e) => (State::default(), false, vec![e.to_string()], path),
    }
}

fn status(source: &ConfigSource, format: Format) -> anyhow::Result<ExitCode> {
    let loaded = app::load_config(source, OwnershipPolicy::Warn)?;
    let config = loaded.config;

    // Look as the daemon would: as the service user when run as root, so
    // directories the daemon cannot read show as unavailable rather than as
    // members about to be mounted.
    let mut notes = Vec::new();
    let checked_as_uid = match app::drop_to_service_user(config.daemon.user.as_deref()) {
        Ok(plan) => {
            if plan.final_uid == 0 {
                notes.push(ROOT_WITHOUT_USER_WARNING.to_owned());
            }
            Some(plan.final_uid)
        }
        Err(e) => {
            notes.push(format!("{e:#}; showing access as the current user"));
            app::drop_to_service_user(None).context("cannot drop capabilities")?;
            None
        }
    };

    let (state, ownership_known, state_notes, state_file) = load_state_read_only(&config);
    notes.extend(state_notes);

    let (mut runtime, open_errors) = Runtime::open_lenient(&config);
    let degraded = degraded_from(&open_errors);
    let mut unavailable: BTreeMap<String, String> = open_errors
        .iter()
        .map(|e| {
            let label = match &e.subject {
                Subject::Group(group) => group.to_string(),
                Subject::Set(set) => reconcile::set_label(set),
            };
            (
                label,
                format!("cannot open {} {}: {}", e.field, e.path, e.source),
            )
        })
        .collect();

    let unique = probe::probe_kernel().unique_mount_ids();
    let observed =
        reconcile::discover_and_observe(&mut runtime, &state, &degraded, unique, &mut |_| {});
    unavailable.extend(observed.notes.iter().filter_map(|n| match n {
        observe::Note::SetRootDeleted { set } => Some((
            reconcile::set_label(set),
            "membership root has been deleted".to_owned(),
        )),
        observe::Note::SetRootUnreadable { set, error } => Some((
            reconcile::set_label(set),
            format!("membership root unreadable: {error}"),
        )),
        observe::Note::MembershipDeleted { group } => Some((
            group.to_string(),
            "membership directory has been deleted".to_owned(),
        )),
        observe::Note::MembershipUnreadable { group, error } => Some((
            group.to_string(),
            format!("membership directory unreadable: {error}"),
        )),
        _ => None,
    }));
    let plan = plan::plan(plan::PlanInput {
        desired: &observed.desired,
        state: &state,
        frozen_groups: &observed.frozen,
        observations: &observed.observations,
    });
    let report = StatusReport {
        state_file,
        ownership_known,
        checked_as_uid,
        notes,
        unavailable,
        ignored: observed
            .ignored
            .iter()
            .map(|(group, names)| (group.to_string(), names.len()))
            .collect(),
        members: report::member_statuses(&observed, &plan, &state, ownership_known),
    };
    print_report(format, || report.to_text(), &report)?;
    Ok(exit_for(report.level()))
}

fn feature_check(name: &str, feature: Feature, required: bool) -> Check {
    match (feature, required) {
        (Feature::Available, _) => Check::new(format!("kernel.{name}"), Level::Ok, ""),
        (Feature::Missing, true) => Check::new(
            format!("kernel.{name}"),
            Level::Error,
            format!(
                "unavailable: {}",
                probe::missing_features_hint(probe::seccomp_filter_active())
            ),
        ),
        (Feature::Missing, false) => Check::new(
            format!("kernel.{name}"),
            Level::Ok,
            "not supported; reusable mount IDs plus device and inode are used",
        ),
    }
}

fn level_of(severity: Severity) -> Level {
    match severity {
        Severity::Error => Level::Error,
        Severity::Warning => Level::Warn,
    }
}

#[allow(clippy::too_many_lines)]
fn dry_run(source: &ConfigSource, format: Format) -> anyhow::Result<ExitCode> {
    let mut checks = Vec::new();

    let loaded = match config::load(&source.options(OwnershipPolicy::Warn)) {
        Ok(loaded) => loaded,
        Err(e) => {
            for issue in &e.issues {
                checks.push(Check::new(
                    "config",
                    level_of(issue.severity),
                    issue.to_string(),
                ));
            }
            let report = DryRunReport {
                checks,
                groups: vec![],
                members: vec![],
            };
            print_report(format, || report.to_text(), &report)?;
            return Ok(ExitCode::FAILURE);
        }
    };
    let config = loaded.config;
    if loaded.warnings.is_empty() {
        checks.push(Check::new(
            "config",
            Level::Ok,
            format!(
                "{} file(s), {} group(s), {} group set(s)",
                config.files.len(),
                config.groups.len(),
                config.group_sets.len()
            ),
        ));
    }
    for issue in &loaded.warnings {
        checks.push(Check::new("config", Level::Warn, issue.to_string()));
    }

    match app::drop_to_service_user(config.daemon.user.as_deref()) {
        Ok(plan) if plan.final_uid == 0 => checks.push(Check::new(
            "privileges",
            Level::Warn,
            ROOT_WITHOUT_USER_WARNING,
        )),
        Ok(plan) => checks.push(Check::new(
            "privileges",
            Level::Ok,
            format!("checks run as uid {} with no capabilities", plan.final_uid),
        )),
        Err(e) => {
            checks.push(Check::new("privileges", Level::Error, format!("{e:#}")));
            // Still drop every capability before inspecting anything.
            app::drop_to_service_user(None).context("cannot drop capabilities")?;
        }
    }

    let features = probe::probe_kernel();
    for (name, feature) in features.required() {
        checks.push(feature_check(name, feature, true));
    }
    checks.push(feature_check(
        "statx_mnt_id_unique",
        features.statx_mnt_id_unique,
        false,
    ));

    checks.push(match probe::verify_procfs(std::path::Path::new("/proc")) {
        Ok(_) => Check::new("procfs", Level::Ok, "/proc"),
        Err(e) => Check::new("procfs", Level::Error, e.to_string()),
    });

    let path_issues = config::check_paths(&config);
    if path_issues.is_empty() {
        checks.push(Check::new("config.paths", Level::Ok, ""));
    }
    for issue in path_issues {
        checks.push(Check::new(
            "config.paths",
            level_of(issue.severity),
            issue.to_string(),
        ));
    }

    let (state, ownership_known, state_notes, state_file) = load_state_read_only(&config);
    checks.push(Check::new(
        "state",
        if ownership_known {
            Level::Ok
        } else {
            Level::Warn
        },
        if state_notes.is_empty() {
            format!("{state_file} ({} record(s))", state.len())
        } else {
            format!("{state_file}: {}", state_notes.join("; "))
        },
    ));

    let (mut runtime, open_errors) = Runtime::open_lenient(&config);
    let mut extra: BTreeMap<GroupId, (String, Level, Vec<String>)> = BTreeMap::new();
    for e in &open_errors {
        match &e.subject {
            Subject::Group(group) => {
                extra.insert(
                    group.clone(),
                    ("unknown".into(), Level::Error, vec![e.to_string()]),
                );
            }
            Subject::Set(set) => checks.push(Check::new(
                format!("group_set.{set}"),
                Level::Error,
                e.to_string(),
            )),
        }
    }
    let table = MountTable::read_self().context("cannot read /proc/self/mountinfo")?;
    let mut propagation_by_label: BTreeMap<String, (String, Level)> = BTreeMap::new();
    for (label, target_root) in app::propagation_targets(&runtime) {
        let check = match runtime.roots.get(&target_root) {
            Ok(fd) => probe::check_propagation(fd, &table),
            Err(e) => PropagationCheck::Unknown(e),
        };
        let level = match check {
            PropagationCheck::Shared => Level::Ok,
            PropagationCheck::Private
            | PropagationCheck::Unbindable
            | PropagationCheck::Unknown(_) => Level::Warn,
            PropagationCheck::SlaveOnly | PropagationCheck::SharedAndSlave => Level::Error,
        };
        propagation_by_label.insert(label, (check.describe(), level));
    }

    let degraded = degraded_from(&open_errors);
    let observed = reconcile::discover_and_observe(
        &mut runtime,
        &state,
        &degraded,
        features.unique_mount_ids(),
        &mut |_| {},
    );
    for set in runtime.sets.values() {
        let label = reconcile::set_label(&set.config.name);
        let (description, level) = propagation_by_label
            .get(&label)
            .cloned()
            .unwrap_or_else(|| ("unknown".into(), Level::Warn));
        let set_level = if observed.scanned_sets.contains(&set.config.name) {
            level.max(Level::Ok)
        } else {
            Level::Error
        };
        checks.push(Check::new(
            format!("group_set.{}", set.config.name),
            set_level,
            format!(
                "membership_root {}; {} group(s); propagation {description}",
                set.config.membership_root,
                runtime
                    .groups
                    .keys()
                    .filter(|id| id.set() == Some(&set.config.name))
                    .count()
            ),
        ));
    }
    for id in runtime.groups.keys() {
        let label = id
            .set()
            .map_or_else(|| id.to_string(), reconcile::set_label);
        if let Some((description, level)) = propagation_by_label.get(&label) {
            extra
                .entry(id.clone())
                .or_insert_with(|| (description.clone(), *level, vec![]));
        }
    }
    reconcile::NoteLog::default().report(&observed, Trigger::Cli);
    let plan = plan::plan(plan::PlanInput {
        desired: &observed.desired,
        state: &state,
        frozen_groups: &observed.frozen,
        observations: &observed.observations,
    });
    let members = report::member_statuses(&observed, &plan, &state, ownership_known);
    let mut groups: Vec<(GroupId, String)> = config
        .groups
        .values()
        .map(|g| (g.name.clone(), g.membership.to_string()))
        .collect();
    groups.extend(
        runtime
            .groups
            .values()
            .filter(|g| g.config.name.set().is_some())
            .map(|g| (g.config.name.clone(), g.config.membership.to_string())),
    );
    let report = DryRunReport {
        checks,
        groups: report::group_reports(&groups, &observed, &plan, &members, &extra),
        members,
    };
    print_report(format, || report.to_text(), &report)?;
    Ok(exit_for(report.level()))
}

fn reconcile_once(source: &ConfigSource, args: &PrivilegeArgs) -> anyhow::Result<ExitCode> {
    let loaded = app::load_config(source, OwnershipPolicy::Enforce)?;
    let config = loaded.config;
    app::set_umask();
    let user = args.user.as_deref().or(config.daemon.user.as_deref());
    app::normalize_privileges(Goal::KeepSysAdmin, user, args.allow_root)?;
    let environment = app::check_environment()?;
    app::verify_config_paths(&config)?;
    let mut writer = app::open_state_for_write(&config)?;
    let mut runtime = Runtime::open(&config)?;
    app::check_propagation(&mut runtime, args.allow_slave_namespace)?;

    let pass = reconcile::run_pass(
        &mut runtime,
        &mut writer.state,
        &writer.store,
        reconcile::PassOptions {
            degraded: &reconcile::Degraded::default(),
            unique_supported: environment.features.unique_mount_ids(),
            trigger: Trigger::Cli,
        },
        &mut reconcile::NoteLog::default(),
        &mut |_| {},
    );
    // Persist even when nothing changed, as on daemon shutdown.
    writer
        .store
        .save(&writer.state)
        .context("cannot write state file")?;
    let failures = pass.execution.failures();
    tracing::info!(
        msg = "reconcile complete",
        steps = pass.plan.steps.len(),
        completed = pass.execution.completed(),
        failed = failures,
        findings = pass.plan.findings.len(),
    );
    drop(environment);
    Ok(if failures == 0 {
        ExitCode::SUCCESS
    } else {
        ExitCode::FAILURE
    })
}

/// Result of `byssus check`.
#[derive(Debug, serde::Serialize)]
struct CheckReport {
    valid: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    checked_as_uid: Option<u32>,
    files: Vec<String>,
    groups: Vec<String>,
    errors: Vec<String>,
    warnings: Vec<String>,
}

impl CheckReport {
    fn to_text(&self) -> String {
        use std::fmt::Write as _;
        let mut out = String::new();
        for file in &self.files {
            let _ = writeln!(out, "file: {file}");
        }
        for group in &self.groups {
            let _ = writeln!(out, "group: {group}");
        }
        for warning in &self.warnings {
            let _ = writeln!(out, "warning: {warning}");
        }
        for error in &self.errors {
            let _ = writeln!(out, "error: {error}");
        }
        let _ = writeln!(
            out,
            "result: {}",
            if self.valid {
                "valid (a reload would accept this configuration)"
            } else {
                "invalid (a reload would keep the previous configuration)"
            }
        );
        out
    }
}

/// Adds group set discovery problems to a `check` report: unreadable or
/// deleted membership roots are errors; problems with individual groups or
/// entries are warnings, as the daemon keeps running.
fn report_discovery(report: &mut CheckReport, notes: &[observe::Note]) {
    for note in notes {
        match note {
            observe::Note::SetRootDeleted { set } => report.errors.push(format!(
                "group set '{set}': membership root has been deleted"
            )),
            observe::Note::SetRootUnreadable { set, error } => report.errors.push(format!(
                "group set '{set}': cannot read membership root: {error}"
            )),
            observe::Note::MembershipUnreadable { group, error } => report.warnings.push(format!(
                "group '{group}': cannot open membership directory: {error}"
            )),
            observe::Note::SetEntryRejected { set, rejection } => report.warnings.push(format!(
                "group set '{set}': entry '{}' rejected: {}",
                rejection.display_name, rejection.reason
            )),
            _ => {}
        }
    }
}

fn check(
    source: &ConfigSource,
    changes: config::FragmentChanges,
    allow_slave_namespace: bool,
    format: Format,
) -> anyhow::Result<ExitCode> {
    let mut report = CheckReport {
        valid: false,
        checked_as_uid: None,
        files: vec![],
        groups: vec![],
        errors: vec![],
        warnings: vec![],
    };
    let finish = |mut report: CheckReport| -> anyhow::Result<ExitCode> {
        report.valid = report.errors.is_empty();
        print_report(format, || report.to_text(), &report)?;
        Ok(if report.valid {
            ExitCode::SUCCESS
        } else {
            ExitCode::FAILURE
        })
    };

    let options = config::LoadOptions {
        fragment_changes: changes,
        ..source.options(OwnershipPolicy::Enforce)
    };
    let loaded = match config::load(&options) {
        Ok(loaded) => loaded,
        Err(e) => {
            for issue in &e.issues {
                match issue.severity {
                    Severity::Error => report.errors.push(issue.to_string()),
                    Severity::Warning => report.warnings.push(issue.to_string()),
                }
            }
            return finish(report);
        }
    };
    report
        .warnings
        .extend(loaded.warnings.iter().map(ToString::to_string));
    let config = loaded.config;
    report.files = config
        .files
        .iter()
        .map(|p| p.display().to_string())
        .collect();
    report.groups = config.groups.keys().map(ToString::to_string).collect();
    report
        .groups
        .extend(config.group_sets.keys().map(reconcile::set_label));

    // Check access as the daemon would: as the service user when run as root.
    let plan = app::drop_to_service_user(config.daemon.user.as_deref())
        .context("cannot drop privileges for checking")?;
    report.checked_as_uid = Some(plan.final_uid);
    if plan.final_uid == 0 {
        report.warnings.push(ROOT_WITHOUT_USER_WARNING.to_owned());
    }

    for issue in config::check_paths(&config) {
        match issue.severity {
            Severity::Error => report.errors.push(issue.to_string()),
            Severity::Warning => report.warnings.push(issue.to_string()),
        }
    }
    if !report.errors.is_empty() {
        return finish(report);
    }

    let mut runtime = match Runtime::open(&config) {
        Ok(runtime) => runtime,
        Err(e) => {
            report.errors.push(e.to_string());
            return finish(report);
        }
    };
    if let Err(e) = byssus::watcher::Watcher::new(&runtime) {
        report.errors.push(e.to_string());
    }
    // Group sets' membership roots must be readable; individual groups that
    // cannot be read are only warnings, as the daemon keeps running.
    let discovery = runtime.discover(&BTreeSet::new());
    report_discovery(&mut report, &discovery.notes);
    let table = MountTable::read_self().context("cannot read /proc/self/mountinfo")?;
    for (name, target_root) in app::propagation_targets(&runtime) {
        let propagation = match runtime.roots.get(&target_root) {
            Ok(fd) => probe::check_propagation(fd, &table),
            Err(e) => PropagationCheck::Unknown(e),
        };
        let message = format!(
            "group '{name}': target root {target_root} is {}",
            propagation.describe()
        );
        match propagation {
            PropagationCheck::Shared => {}
            ref check if check.is_slave() && !allow_slave_namespace => report.errors.push(message),
            _ => report.warnings.push(message),
        }
    }
    finish(report)
}