aion-server 0.21.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
//! Dynamic Aion-home defaults, legacy-directory migration guards, and startup provenance.

use std::{
    fmt, io,
    path::{Path, PathBuf},
};
use tracing::{info, warn};

use crate::error::ServerError;

use super::{
    DEFAULT_AUTHORING_WORKSPACE_DIR, DEFAULT_HAEMATITE_DATA_DIR, HomeSource,
    LEGACY_AUTHORING_WORKSPACE_DIR, LEGACY_HAEMATITE_DATA_DIR, ServerConfig,
};

/// The winning file layer in server configuration discovery.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) enum ConfigSource {
    /// An explicit `--config PATH`.
    Explicit(PathBuf),
    /// Project-local `./aion.toml`.
    ProjectLocal(PathBuf),
    /// User-level `<AION_HOME>/config.toml`.
    AionHome(PathBuf),
    /// No file was discovered.
    BuiltInDefaults,
}

impl fmt::Display for ConfigSource {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Explicit(path) => write!(formatter, "explicit file `{}`", path.display()),
            Self::ProjectLocal(path) => {
                write!(formatter, "project-local file `{}`", path.display())
            }
            Self::AionHome(path) => write!(formatter, "Aion home file `{}`", path.display()),
            Self::BuiltInDefaults => formatter.write_str("built-in defaults"),
        }
    }
}

/// What became of a legacy working-directory path that exists on disk.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum LegacyDisposition {
    /// The home was derived, so the legacy directory keeps being used and the
    /// operator is told to migrate. This is the case the guard exists for:
    /// an operator who has moved nothing and whose durable state genuinely
    /// lives in the working directory must never have it stranded.
    Adopted,
    /// The operator named a home with `AION_HOME`, so the legacy directory did
    /// not compete for the default and was left untouched.
    IgnoredForExplicitHome,
}

/// One legacy working-directory path found during default resolution, and what
/// was decided about it.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct LegacyNotice {
    kind: &'static str,
    legacy: PathBuf,
    home_default: PathBuf,
    disposition: LegacyDisposition,
}

impl LegacyNotice {
    /// The startup log message that fits this notice's disposition.
    fn headline(&self) -> &'static str {
        match self.disposition {
            LegacyDisposition::Adopted => "Aion home legacy-directory migration guard active",
            LegacyDisposition::IgnoredForExplicitHome => {
                "Aion home legacy directory ignored because AION_HOME is set"
            }
        }
    }
}

impl fmt::Display for LegacyNotice {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.disposition {
            LegacyDisposition::Adopted => write!(
                formatter,
                "AION HOME MIGRATION REQUIRED: using legacy {} directory `{}` instead of new Aion-home default `{}`; stop the server, move `{}` to `{}`, then remove the legacy directory to complete migration",
                self.kind,
                self.legacy.display(),
                self.home_default.display(),
                self.legacy.display(),
                self.home_default.display(),
            ),
            // The operator asked for isolation and got it. What they still need
            // told is that the other directory is sitting there and that this
            // server is not the thing reading or writing it.
            LegacyDisposition::IgnoredForExplicitHome => write!(
                formatter,
                "AION HOME IS SET, SO THE LEGACY DIRECTORY WAS IGNORED: legacy {} directory `{}` exists but this server uses `{}`; the legacy directory is untouched and no state is being read from or written to it",
                self.kind,
                self.legacy.display(),
                self.home_default.display(),
            ),
        }
    }
}

/// Startup-visible provenance and resolved roots accompanying a loaded config.
#[derive(Clone, Debug)]
pub(crate) struct ConfigResolution {
    pub(crate) home: PathBuf,
    pub(crate) source: ConfigSource,
    pub(crate) data_dir: Option<String>,
    pub(crate) authoring_workspace: Option<PathBuf>,
    pub(crate) legacy_notices: Vec<LegacyNotice>,
    #[cfg(not(unix))]
    pub(crate) home_explicit: bool,
    #[cfg(not(unix))]
    pub(crate) data_dir_explicit: bool,
    #[cfg(not(unix))]
    pub(crate) data_root_required: bool,
    #[cfg(not(unix))]
    pub(crate) authoring_workspace_explicit: bool,
}

impl ConfigResolution {
    /// Provision the resolved Aion home as an owner-only directory, refusing
    /// only what the server cannot make safe on the operator's behalf.
    pub(crate) fn ensure_private_home(&self) -> Result<(), ServerError> {
        #[cfg(unix)]
        {
            // The Aion home is Aion's own directory, so Aion provisions it:
            // created owner-only when absent, tightened when a permissive umask
            // (or an earlier tool) left it group- or world-readable. Telling the
            // operator to go and run `chmod 700 ~/.aion` before his own server
            // would start was the defect this replaces — it is a step the server
            // could always have taken itself.
            //
            // Doing it here, rather than leaving it to whichever surface writes
            // first, means the home is correct even on a boot whose store and
            // authoring surfaces never touch the disk. The capability is dropped
            // immediately; only its construction side effects are wanted.
            crate::filesystem::ConfinedDir::open_or_create(&self.home)
                .map(drop)
                .map_err(|error| ServerError::Config {
                    message: format!("unsafe Aion home `{}`: {error}", self.home.display()),
                })?;
        }
        #[cfg(not(unix))]
        {
            require_explicit_non_unix_root(
                self.home_explicit,
                "Aion home",
                "AION_HOME",
                &self.home,
            )?;
            if self.data_root_required {
                let data_dir = self
                    .data_dir
                    .as_deref()
                    .ok_or_else(|| ServerError::Config {
                        message: "store.data_dir is required for the haematite backend".to_owned(),
                    })?;
                require_explicit_non_unix_root(
                    self.data_dir_explicit,
                    "data root",
                    "store.data_dir or AION_STORE_DATA_DIR",
                    Path::new(data_dir),
                )?;
            }
            if let Some(authoring) = &self.authoring_workspace {
                require_explicit_non_unix_root(
                    self.authoring_workspace_explicit,
                    "authoring and authoring-state root",
                    "authoring.workspace_dir or AION_AUTHORING_WORKSPACE_DIR",
                    authoring,
                )?;
            }
        }
        Ok(())
    }

    pub(crate) fn log_startup(&self) {
        for notice in &self.legacy_notices {
            warn!(notice = %notice, "{}", notice.headline());
        }
        #[cfg(not(unix))]
        {
            warn_unverified_acl("Aion home", &self.home);
            if self.data_root_required {
                if let Some(data_dir) = &self.data_dir {
                    warn_unverified_acl("data root", Path::new(data_dir));
                }
            }
            if let Some(authoring) = &self.authoring_workspace {
                warn_unverified_acl("authoring and authoring-state root", authoring);
            }
        }
        info!(
            config_source = %self.source,
            aion_home = %self.home.display(),
            "aion-server configuration resolved"
        );
        info!(
            data_root = self.data_dir.as_deref().unwrap_or("disabled"),
            "aion-server data root resolved"
        );
        if let Some(path) = &self.authoring_workspace {
            info!(authoring_root = %path.display(), "aion-server authoring root resolved");
        } else {
            info!(
                authoring_root = "disabled",
                "aion-server authoring root resolved"
            );
        }
    }
}

#[cfg(not(unix))]
fn require_explicit_non_unix_root(
    explicit: bool,
    label: &str,
    configuration: &str,
    path: &Path,
) -> Result<(), ServerError> {
    require_explicit_root_selection(explicit, label, configuration, path)?;
    crate::filesystem::validate_real_directory_root(path, label).map_err(|error| {
        ServerError::Config {
            message: format!("unsafe explicitly configured {label}: {error}"),
        }
    })
}

#[cfg(any(not(unix), test))]
fn require_explicit_root_selection(
    explicit: bool,
    label: &str,
    configuration: &str,
    path: &Path,
) -> Result<(), ServerError> {
    if !explicit {
        return Err(ServerError::Config {
            message: format!(
                "refusing default-sensitive {label} `{}` on this non-Unix platform because Aion cannot verify or install a private ACL; pre-provision a private directory and explicitly configure it with {configuration}",
                path.display()
            ),
        });
    }
    Ok(())
}

#[cfg(not(unix))]
fn warn_unverified_acl(label: &str, path: &Path) {
    warn!(
        sensitive_root = label,
        path = %path.display(),
        "ACL PRIVACY NOT VERIFIED: using explicitly configured sensitive root on a non-Unix platform; Aion does not install or validate an owner-only ACL"
    );
}

/// Apply dynamic home-rooted defaults and the two legacy-directory guards.
///
/// A path is eligible for migration only while its config field is absent. File
/// and environment values are therefore final before this function runs, and an
/// explicitly configured value can never activate a legacy fallback.
///
/// **Setting `AION_HOME` counts as such an explicit configuration.** Relocating
/// the home is how an operator isolates a server's state, so a legacy directory
/// that happens to sit in the working directory must not be able to drag that
/// state back to the shared location the operator was steering away from. When
/// `home_source` is [`HomeSource::Explicit`] the legacy path is not eligible at
/// all; it is still reported, so the operator learns it is there and is being
/// left alone.
pub(super) fn fill_home_defaults(
    config: &mut ServerConfig,
    home: &Path,
    home_source: HomeSource,
    working_dir: &Path,
) -> Result<Vec<LegacyNotice>, ServerError> {
    let mut notices = Vec::new();
    if config.store.data_dir.is_none() {
        let home_default = home.join(DEFAULT_HAEMATITE_DATA_DIR);
        let legacy = working_dir.join(LEGACY_HAEMATITE_DATA_DIR);
        let selected = select_default(
            "store data",
            legacy,
            home_default,
            home_source,
            &mut notices,
        )?;
        config.store.data_dir = Some(path_to_string(&selected, "store.data_dir")?);
    }
    if config.authoring.workspace_dir.is_none() {
        let home_default = home.join(DEFAULT_AUTHORING_WORKSPACE_DIR);
        let legacy = working_dir.join(LEGACY_AUTHORING_WORKSPACE_DIR);
        config.authoring.workspace_dir = Some(select_default(
            "authoring workspace",
            legacy,
            home_default,
            home_source,
            &mut notices,
        )?);
    }
    Ok(notices)
}

fn select_default(
    kind: &'static str,
    legacy: PathBuf,
    home_default: PathBuf,
    home_source: HomeSource,
    notices: &mut Vec<LegacyNotice>,
) -> Result<PathBuf, ServerError> {
    let is_real_directory = match std::fs::symlink_metadata(&legacy) {
        Ok(metadata) => metadata.is_dir() && !metadata.file_type().is_symlink(),
        Err(error) if error.kind() == io::ErrorKind::NotFound => false,
        Err(error) => {
            return Err(ServerError::Config {
                message: format!(
                    "failed to inspect legacy {kind} path `{}`: {error}",
                    legacy.display()
                ),
            });
        }
    };
    if !is_real_directory {
        return Ok(home_default);
    }
    let disposition = match home_source {
        HomeSource::Derived => LegacyDisposition::Adopted,
        HomeSource::Explicit => LegacyDisposition::IgnoredForExplicitHome,
    };
    notices.push(LegacyNotice {
        kind,
        legacy: legacy.clone(),
        home_default: home_default.clone(),
        disposition,
    });
    match disposition {
        LegacyDisposition::Adopted => Ok(legacy),
        LegacyDisposition::IgnoredForExplicitHome => Ok(home_default),
    }
}

fn path_to_string(path: &Path, field: &str) -> Result<String, ServerError> {
    path.to_str()
        .map(str::to_owned)
        .ok_or_else(|| ServerError::Config {
            message: format!(
                "resolved {field} path `{}` is not valid UTF-8; configure {field} explicitly with a UTF-8 path",
                path.display()
            ),
        })
}

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

    #[cfg(unix)]
    fn resolution_for(home: PathBuf) -> ConfigResolution {
        ConfigResolution {
            home,
            source: ConfigSource::BuiltInDefaults,
            data_dir: None,
            authoring_workspace: None,
            legacy_notices: Vec::new(),
        }
    }

    /// Startup provisions its own home. A first run on a clean machine must not
    /// require the operator to `mkdir` anything.
    #[cfg(unix)]
    #[test]
    fn a_missing_home_is_created_owner_only() -> Result<(), Box<dyn std::error::Error>> {
        use std::os::unix::fs::PermissionsExt as _;

        let scratch = crate::test_support::private_tempdir()?;
        let home = scratch.path().join("nested").join(".aion");

        resolution_for(home.clone()).ensure_private_home()?;

        assert_eq!(
            std::fs::metadata(&home)?.permissions().mode() & 0o777,
            0o700
        );
        Ok(())
    }

    /// The exact complaint: `~/.aion` sitting at 0755 under a conventional
    /// umask used to stop a stock server and hand back a `chmod` command.
    #[cfg(unix)]
    #[test]
    fn a_permissive_home_is_tightened_instead_of_refused() -> Result<(), Box<dyn std::error::Error>>
    {
        use std::os::unix::fs::PermissionsExt as _;

        let scratch = crate::test_support::private_tempdir()?;
        let home = scratch.path().join(".aion");
        std::fs::create_dir(&home)?;
        std::fs::set_permissions(&home, std::fs::Permissions::from_mode(0o755))?;

        let resolution = resolution_for(home.clone());
        let (captured, outcome) =
            crate::test_support::CapturedLogs::capture(|| resolution.ensure_private_home());
        outcome?;

        assert_eq!(
            std::fs::metadata(&home)?.permissions().mode() & 0o777,
            0o700
        );
        assert!(
            captured
                .text()?
                .contains("tightened a sensitive root to owner-only")
        );
        Ok(())
    }

    /// A home Aion cannot make safe still refuses, and the refusal names the
    /// home, not just the inner filesystem error.
    #[cfg(unix)]
    #[test]
    fn a_symlinked_home_refuses_naming_the_path() -> Result<(), Box<dyn std::error::Error>> {
        let scratch = crate::test_support::private_tempdir()?;
        let target = scratch.path().join("elsewhere");
        let home = scratch.path().join(".aion");
        std::fs::create_dir(&target)?;
        std::os::unix::fs::symlink(&target, &home)?;

        let error = resolution_for(home.clone())
            .ensure_private_home()
            .err()
            .ok_or("a symlinked Aion home was accepted")?;
        let message = error.to_string();
        assert!(message.contains("unsafe Aion home"));
        assert!(message.contains(&home.display().to_string()));
        Ok(())
    }

    #[test]
    fn non_unix_default_sensitive_roots_fail_with_explicit_acl_remediation()
    -> Result<(), Box<dyn std::error::Error>> {
        let path = Path::new(r"C:\ProgramData\Aion");
        let error = require_explicit_root_selection(false, "Aion home", "AION_HOME", path)
            .err()
            .ok_or("a non-Unix default root did not fail closed")?;
        let message = error.to_string();
        assert!(message.contains("default-sensitive Aion home"));
        assert!(message.contains("cannot verify or install a private ACL"));
        assert!(message.contains("pre-provision a private directory"));
        assert!(message.contains("AION_HOME"));
        Ok(())
    }

    #[test]
    fn non_unix_explicit_sensitive_root_selection_is_accepted_for_shape_validation()
    -> Result<(), Box<dyn std::error::Error>> {
        require_explicit_root_selection(
            true,
            "data root",
            "store.data_dir or AION_STORE_DATA_DIR",
            Path::new(r"C:\Aion\data"),
        )?;
        Ok(())
    }
}