aion-server 0.10.0

Aion workflow server library: HTTP, gRPC, WebSocket, and worker endpoints. Run it with the `aion` binary from the aion-cli crate.
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
//! Descriptor-relative, no-follow filesystem operations for sensitive server roots.
//!
//! Every path component is opened from a held directory capability. Symlinks and
//! Windows reparse points are refused at component boundaries, and final files are
//! opened with no-follow semantics. A concurrent local actor may replace a name
//! after validation, but the operation remains relative to an already-open parent
//! descriptor: it can redirect a name within that held directory, never expand the
//! operation's authority beyond the configured root.

use std::ffi::{OsStr, OsString};
use std::io::{self, Read, Write};
use std::path::{Component, Path, PathBuf};

#[cfg(target_os = "macos")]
mod darwin_acl;

use cap_fs_ext::{DirExt, FollowSymlinks, OpenOptionsFollowExt};
use cap_std::ambient_authority;
use cap_std::fs::{Dir, DirBuilder, OpenOptions};
#[cfg(unix)]
use cap_std::fs::{DirBuilderExt, OpenOptionsExt, PermissionsExt};
#[cfg(all(unix, not(target_os = "macos")))]
use std::os::fd::AsRawFd as _;
#[cfg(target_os = "macos")]
use std::os::unix::ffi::OsStringExt as _;

const PRIVATE_DIR_MODE: u32 = 0o700;
const PRIVATE_FILE_MODE: u32 = 0o600;

/// A held directory descriptor confining all subsequent operations beneath it.
pub(crate) struct ConfinedDir {
    dir: Dir,
}

impl ConfinedDir {
    /// Open an existing real directory without following any path component.
    pub(crate) fn open(path: &Path) -> io::Result<Self> {
        let root = Self {
            dir: open_absolute(path, false)?,
        };
        root.require_private_mode(path)?;
        Ok(root)
    }

    /// Open or create a real directory, creating every missing component privately.
    pub(crate) fn open_or_create(path: &Path) -> io::Result<Self> {
        let root = Self {
            dir: open_absolute(path, true)?,
        };
        root.require_private_mode(path)?;
        Ok(root)
    }

    /// Read a UTF-8 file without following any component or final symlink.
    pub(crate) fn read_to_string(&self, relative: &Path) -> io::Result<String> {
        let mut file = self.open_file(relative, false)?;
        let mut value = String::new();
        file.read_to_string(&mut value)?;
        Ok(value)
    }

    /// Read a file without following any component or final symlink.
    pub(crate) fn read(&self, relative: &Path) -> io::Result<Vec<u8>> {
        let mut file = self.open_file(relative, false)?;
        let mut value = Vec::new();
        file.read_to_end(&mut value)?;
        Ok(value)
    }

    /// Create a new private file, refusing an existing file or link.
    pub(crate) fn create_new(&self, relative: &Path, bytes: &[u8]) -> io::Result<()> {
        let (parent, name) = self.open_parent(relative, true)?;
        let mut options = private_file_options();
        options.write(true).create_new(true);
        let mut file = parent.open_with(name, &options)?;
        if let Err(error) = write_and_sync(&mut file, bytes) {
            drop(file);
            let _ = parent.remove_file(name);
            return Err(error);
        }
        Ok(())
    }

    /// Atomically replace a private file using an unpredictable `create_new`
    /// temporary in the same held parent directory.
    pub(crate) fn atomic_write(&self, relative: &Path, bytes: &[u8]) -> io::Result<()> {
        let (parent, name) = self.open_parent(relative, true)?;
        match parent.symlink_metadata(name) {
            Ok(metadata) if metadata.file_type().is_symlink() => {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidInput,
                    "refusing to replace a symbolic link",
                ));
            }
            Ok(_) => {}
            Err(error) if error.kind() == io::ErrorKind::NotFound => {}
            Err(error) => return Err(error),
        }

        let temp_name = OsString::from(format!(".aion-{}.tmp", uuid::Uuid::new_v4()));
        let mut options = private_file_options();
        options.write(true).create_new(true);
        let mut temp = parent.open_with(&temp_name, &options)?;
        if let Err(error) = write_and_sync(&mut temp, bytes) {
            drop(temp);
            let _ = parent.remove_file(&temp_name);
            return Err(error);
        }
        drop(temp);
        if let Err(error) = parent.rename(&temp_name, &parent, name) {
            let _ = parent.remove_file(&temp_name);
            return Err(error);
        }
        Ok(())
    }

    /// Remove a file relative to this capability, without traversing parents.
    pub(crate) fn remove_file(&self, relative: &Path) -> io::Result<()> {
        let (parent, name) = self.open_parent(relative, false)?;
        parent.remove_file(name)
    }

    /// Recursively list `.awl` files while refusing directory links.
    pub(crate) fn list_awl(&self) -> io::Result<Vec<PathBuf>> {
        let mut paths = Vec::new();
        visit_awl(&self.dir, Path::new(""), &mut paths)?;
        Ok(paths)
    }

    /// Eagerly create a descendant directory through this capability.
    pub(crate) fn create_dir_all(&self, relative: &Path) -> io::Result<()> {
        drop(self.open_dir(relative, true)?);
        Ok(())
    }

    /// Return the narrowest path bridge the platform offers from this held
    /// descriptor to a backend that accepts only `PathBuf`.
    ///
    /// Linux/Android can traverse descendants through `/proc/self/fd`, so the
    /// returned path remains descriptor-authoritative. macOS and other Unix
    /// targets expose a directory descriptor in `/dev/fd` but do not permit
    /// descendant traversal through that name; there we resolve the descriptor's
    /// current real path immediately before backend startup. Normal backend reads
    /// and commits remain ambient pathname operations after startup on those
    /// platforms, so callers must reject renameable ancestor chains until
    /// Haematite exposes descriptor-relative I/O.
    #[cfg(unix)]
    pub(crate) fn backend_path(&self) -> io::Result<PathBuf> {
        #[cfg(any(target_os = "linux", target_os = "android"))]
        {
            Ok(Path::new("/proc/self/fd").join(self.dir.as_raw_fd().to_string()))
        }
        #[cfg(target_os = "macos")]
        {
            let path = rustix::fs::getpath(&self.dir)?;
            Ok(PathBuf::from(OsString::from_vec(path.into_bytes())))
        }
        #[cfg(not(any(target_os = "linux", target_os = "android", target_os = "macos")))]
        {
            std::fs::canonicalize(Path::new("/dev/fd").join(self.dir.as_raw_fd().to_string()))
        }
    }

    /// Return metadata for this held root directory.
    pub(crate) fn metadata(&self) -> io::Result<cap_std::fs::Metadata> {
        self.dir.dir_metadata()
    }

    /// Apply private modes to every existing descendant without following links.
    /// On non-Unix targets this performs no ACL mutation. Startup permits that
    /// limitation only for roots the operator explicitly configured and emits a
    /// warning that ACL privacy was not verified.
    pub(crate) fn harden_tree(&self) -> io::Result<()> {
        #[cfg(unix)]
        harden_dir(&self.dir)?;
        Ok(())
    }

    fn require_private_mode(&self, path: &Path) -> io::Result<()> {
        #[cfg(unix)]
        {
            let mode = self.metadata()?.permissions().mode() & 0o777;
            if mode & 0o077 != 0 {
                return Err(io::Error::new(
                    io::ErrorKind::PermissionDenied,
                    format!(
                        "sensitive root `{}` has mode {mode:04o}; run `chmod 700 {}`",
                        path.display(),
                        path.display()
                    ),
                ));
            }
        }
        #[cfg(not(unix))]
        let _ = path;
        Ok(())
    }

    fn open_file(&self, relative: &Path, create_parents: bool) -> io::Result<cap_std::fs::File> {
        let (parent, name) = self.open_parent(relative, create_parents)?;
        let mut options = OpenOptions::new();
        options.read(true).follow(FollowSymlinks::No);
        parent.open_with(name, &options)
    }

    fn open_parent<'a>(&self, relative: &'a Path, create: bool) -> io::Result<(Dir, &'a OsStr)> {
        validate_relative(relative)?;
        let name = relative.file_name().ok_or_else(invalid_relative)?;
        let parent = relative.parent().unwrap_or_else(|| Path::new(""));
        self.open_dir(parent, create).map(|dir| (dir, name))
    }

    fn open_dir(&self, relative: &Path, create: bool) -> io::Result<Dir> {
        validate_relative_or_empty(relative)?;
        let mut current = self.dir.try_clone()?;
        for component in relative.components() {
            let Component::Normal(name) = component else {
                return Err(invalid_relative());
            };
            current = open_child_dir(&current, name, create)?;
        }
        Ok(current)
    }
}

fn open_absolute(path: &Path, create: bool) -> io::Result<Dir> {
    let absolute = std::path::absolute(path)?;
    let (anchor, names) = split_absolute(&absolute)?;
    let mut current = Dir::open_ambient_dir(&anchor, ambient_authority())?;
    for (index, name) in names.into_iter().enumerate() {
        match open_child_dir(&current, &name, create) {
            Ok(child) => current = child,
            Err(error) if index == 0 => {
                // macOS exposes root-owned compatibility aliases such as
                // `/var -> /private/var`. Following only a filesystem-root
                // entry preserves those platform paths; every user-controlled
                // component below it remains descriptor-relative and no-follow.
                let alias = anchor.join(&name);
                let metadata = std::fs::symlink_metadata(&alias)?;
                if !metadata.file_type().is_symlink() {
                    return Err(component_error(&name, &error));
                }
                let canonical = std::fs::canonicalize(alias)?;
                current = Dir::open_ambient_dir(canonical, ambient_authority())?;
            }
            Err(error) => return Err(component_error(&name, &error)),
        }
    }
    Ok(current)
}

fn split_absolute(path: &Path) -> io::Result<(PathBuf, Vec<OsString>)> {
    let mut anchor = PathBuf::new();
    let mut names = Vec::new();
    for component in path.components() {
        match component {
            Component::Prefix(_) | Component::RootDir => anchor.push(component.as_os_str()),
            Component::CurDir => {}
            Component::ParentDir => {
                if names.pop().is_none() {
                    return Err(invalid_relative());
                }
            }
            Component::Normal(name) => names.push(name.to_owned()),
        }
    }
    if anchor.as_os_str().is_empty() {
        return Err(invalid_relative());
    }
    Ok((anchor, names))
}

fn component_error(name: &OsStr, error: &io::Error) -> io::Error {
    io::Error::new(
        error.kind(),
        format!(
            "failed to open real directory component `{}`: {error}",
            name.to_string_lossy()
        ),
    )
}

fn open_child_dir(parent: &Dir, name: &OsStr, create: bool) -> io::Result<Dir> {
    match parent.open_dir_nofollow(name) {
        Ok(dir) => Ok(dir),
        Err(error) if create && error.kind() == io::ErrorKind::NotFound => {
            let mut builder = DirBuilder::new();
            #[cfg(unix)]
            builder.mode(PRIVATE_DIR_MODE);
            match parent.create_dir_with(name, &builder) {
                Ok(()) => {}
                Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {}
                Err(error) => return Err(error),
            }
            parent.open_dir_nofollow(name)
        }
        Err(error) => Err(error),
    }
}

fn private_file_options() -> OpenOptions {
    let mut options = OpenOptions::new();
    options.follow(FollowSymlinks::No);
    #[cfg(unix)]
    options.mode(PRIVATE_FILE_MODE);
    options
}

fn write_and_sync(file: &mut cap_std::fs::File, bytes: &[u8]) -> io::Result<()> {
    file.write_all(bytes)?;
    file.sync_all()
}

fn visit_awl(dir: &Dir, relative: &Path, paths: &mut Vec<PathBuf>) -> io::Result<()> {
    for entry in dir.entries()? {
        let entry = entry?;
        let name = entry.file_name();
        let file_type = entry.file_type()?;
        if file_type.is_symlink() {
            continue;
        }
        let child_relative = relative.join(&name);
        if file_type.is_dir() {
            let child = dir.open_dir_nofollow(&name)?;
            visit_awl(&child, &child_relative, paths)?;
        } else if file_type.is_file() && child_relative.extension() == Some(OsStr::new("awl")) {
            paths.push(child_relative);
        }
    }
    Ok(())
}

#[cfg(unix)]
fn harden_dir(dir: &Dir) -> io::Result<()> {
    dir.set_permissions(
        Path::new("."),
        cap_std::fs::Permissions::from_mode(PRIVATE_DIR_MODE),
    )?;
    for entry in dir.entries()? {
        let entry = entry?;
        let name = entry.file_name();
        let file_type = entry.file_type()?;
        if file_type.is_symlink() {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!(
                    "sensitive state contains symbolic link `{}`",
                    name.to_string_lossy()
                ),
            ));
        }
        if file_type.is_dir() {
            let child = dir.open_dir_nofollow(&name)?;
            harden_dir(&child)?;
        } else if file_type.is_file() {
            let mut options = OpenOptions::new();
            options.read(true).follow(FollowSymlinks::No);
            let file = dir.open_with(&name, &options)?;
            file.set_permissions(cap_std::fs::Permissions::from_mode(PRIVATE_FILE_MODE))?;
        }
    }
    Ok(())
}

fn validate_relative(path: &Path) -> io::Result<()> {
    if path.as_os_str().is_empty() {
        return Err(invalid_relative());
    }
    validate_relative_or_empty(path)
}

fn validate_relative_or_empty(path: &Path) -> io::Result<()> {
    if path
        .components()
        .any(|component| !matches!(component, Component::Normal(_)))
    {
        return Err(invalid_relative());
    }
    Ok(())
}

fn invalid_relative() -> io::Error {
    io::Error::new(
        io::ErrorKind::InvalidInput,
        "path must be relative and contain only normal components",
    )
}

/// An unsafe component in a path-ambient backend's resolved ancestor chain.
#[cfg(all(unix, not(any(target_os = "linux", target_os = "android"))))]
#[derive(Debug)]
pub(crate) struct DataRootAncestorError {
    component: PathBuf,
    reason: String,
}

#[cfg(all(unix, not(any(target_os = "linux", target_os = "android"))))]
impl DataRootAncestorError {
    fn new(component: PathBuf, reason: impl Into<String>) -> Self {
        Self {
            component,
            reason: reason.into(),
        }
    }

    pub(crate) fn into_parts(self) -> (PathBuf, String) {
        (self.component, self.reason)
    }
}

#[cfg(all(unix, not(any(target_os = "linux", target_os = "android"))))]
impl std::fmt::Display for DataRootAncestorError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            formatter,
            "ancestor `{}` is not owner-controlled: {}",
            self.component.display(),
            self.reason
        )
    }
}

#[cfg(all(unix, not(any(target_os = "linux", target_os = "android"))))]
impl std::error::Error for DataRootAncestorError {}

/// Require every component of a path-ambient Haematite root to be controlled by
/// the server's effective user (or by root for the immutable system prefix) and
/// to deny group/world writes. On macOS, each component's extended ACL is read
/// without following its final name. An allow ACE for any principal other than
/// the effective user is refused when it grants directory traversal, entry
/// creation/removal, child deletion, or ACL/owner mutation. Deny ACEs remain
/// acceptable because they cannot confer the rename authority this gate removes;
/// in particular, this admits the stock macOS home `everyone deny delete` ACE.
///
/// This forecloses another principal renaming a parent after startup, replacing
/// the old name with a symlink, and redirecting Haematite's ambient `DiskStore`
/// reads and commits. Linux and Android are exempt because their
/// `/proc/self/fd/N/...` backend path stays descriptor-authoritative while the
/// retained directory fd lives. Descriptor-relative backend I/O is the long-term
/// Haematite-side fix; until then, Unix platforms without traversable procfs fd
/// paths must fail closed on a renameable ancestor. Sticky directories such as
/// `/tmp` are intentionally refused because the sticky bit does not make an
/// ambient child pathname descriptor-authoritative. A macOS ACL that cannot be
/// read or interpreted is likewise refused rather than treated as absent.
#[cfg(all(unix, not(any(target_os = "linux", target_os = "android"))))]
pub(crate) fn validate_ambient_backend_ancestors(
    data_root: &Path,
) -> Result<(), DataRootAncestorError> {
    use std::os::unix::fs::MetadataExt as _;

    if !data_root.is_absolute() {
        return Err(DataRootAncestorError::new(
            data_root.to_path_buf(),
            "descriptor-resolved backend path is not absolute",
        ));
    }

    let effective_uid = rustix::process::geteuid().as_raw();
    let mut component_path = PathBuf::new();
    for component in data_root.components() {
        component_path.push(component.as_os_str());
        let metadata = std::fs::symlink_metadata(&component_path).map_err(|error| {
            DataRootAncestorError::new(
                component_path.clone(),
                format!("could not inspect ownership and mode: {error}"),
            )
        })?;
        if !metadata.is_dir() || metadata.file_type().is_symlink() {
            return Err(DataRootAncestorError::new(
                component_path,
                "component is not a real directory",
            ));
        }

        let mode = metadata.mode() & 0o7777;
        if mode & 0o022 != 0 {
            return Err(DataRootAncestorError::new(
                component_path,
                format!(
                    "mode {mode:04o} grants group/world write access (sticky bit is not accepted)"
                ),
            ));
        }

        let owner_uid = metadata.uid();
        if owner_uid != effective_uid && owner_uid != 0 {
            return Err(DataRootAncestorError::new(
                component_path,
                format!("owner uid {owner_uid} is neither server euid {effective_uid} nor root"),
            ));
        }

        #[cfg(target_os = "macos")]
        darwin_acl::validate_extended_acl(&component_path, effective_uid)?;
    }
    Ok(())
}

#[cfg(all(test, target_os = "macos"))]
pub(crate) fn darwin_user_uuid_for_test(uid: u32) -> io::Result<uuid::Uuid> {
    darwin_acl::user_uuid_for_test(uid)
}

/// Refuse an existing sensitive root that grants any Unix group/world access.
///
/// On non-Unix targets this function verifies only that an existing root is a
/// real directory. The configuration-resolution boundary separately refuses
/// default roots and warns for explicitly configured roots because ACL privacy
/// is not implemented or claimed here.
pub(crate) fn validate_private_root(path: &Path, label: &str) -> io::Result<()> {
    let metadata = match std::fs::symlink_metadata(path) {
        Ok(metadata) => metadata,
        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),
        Err(error) => return Err(error),
    };
    if metadata.file_type().is_symlink() || !metadata.is_dir() {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            format!("{label} `{}` is not a real directory", path.display()),
        ));
    }
    #[cfg(unix)]
    {
        let mode = std::os::unix::fs::PermissionsExt::mode(&metadata.permissions()) & 0o777;
        if mode & 0o077 != 0 {
            return Err(io::Error::new(
                io::ErrorKind::PermissionDenied,
                format!(
                    "{label} `{}` has mode {mode:04o}; run `chmod 700 {}` before starting Aion",
                    path.display(),
                    path.display()
                ),
            ));
        }
    }
    Ok(())
}

#[cfg(all(test, unix))]
mod tests {
    use std::os::unix::fs::PermissionsExt as _;

    use super::*;

    #[test]
    fn nested_sensitive_roots_and_files_ignore_a_permissive_umask()
    -> Result<(), Box<dyn std::error::Error>> {
        const PROBE: &str = "AION_PRIVATE_MODE_UMASK_PROBE";
        if let Some(path) = std::env::var_os(PROBE) {
            return assert_private_creation(Path::new(&path));
        }

        let sandbox = crate::test_support::private_tempdir()?;
        let executable = std::env::current_exe()?;
        let status = std::process::Command::new("sh")
            .arg("-c")
            .arg(
                "umask 000; exec \"$1\" --exact \
                 filesystem::tests::nested_sensitive_roots_and_files_ignore_a_permissive_umask \
                 --nocapture",
            )
            .arg("aion-private-mode-probe")
            .arg(executable)
            .env(PROBE, sandbox.path())
            .status()?;
        assert!(status.success(), "private-mode umask probe failed");
        Ok(())
    }

    fn assert_private_creation(sandbox: &Path) -> Result<(), Box<dyn std::error::Error>> {
        let home = sandbox.join("aion-home");
        let authoring = home.join("authoring");
        let root = ConfinedDir::open_or_create(&authoring)?;
        root.create_new(Path::new("private.txt"), b"secret")?;
        assert_eq!(
            std::fs::metadata(&home)?.permissions().mode() & 0o777,
            0o700
        );
        assert_eq!(
            std::fs::metadata(&authoring)?.permissions().mode() & 0o777,
            0o700
        );
        assert_eq!(
            std::fs::metadata(authoring.join("private.txt"))?
                .permissions()
                .mode()
                & 0o777,
            0o600
        );
        Ok(())
    }

    #[test]
    fn permissive_existing_root_fails_with_precise_remediation()
    -> Result<(), Box<dyn std::error::Error>> {
        let sandbox = crate::test_support::private_tempdir()?;
        let home = sandbox.path().join("aion-home");
        std::fs::create_dir(&home)?;
        std::fs::set_permissions(&home, std::fs::Permissions::from_mode(0o755))?;

        let error = validate_private_root(&home, "Aion home")
            .err()
            .ok_or("expected permissive home refusal")?;
        let message = error.to_string();
        assert!(message.contains("mode 0755"));
        assert!(message.contains("chmod 700"));
        assert!(ConfinedDir::open(&home).is_err());
        Ok(())
    }
}