shine-cli 1.5.0

Keep development environments portable across machines and remote sessions
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
use anyhow::{Context, Result, bail};
use std::collections::BTreeSet;
use std::path::Path;

use crate::config::Config;

use super::{
    LoadedSysPreset, SysDetection, SysDetectionProbe, SysDriverKind, SysInstall, SysItem,
    SysItemMode, SysItemStatus, SysManifest,
};

pub(super) async fn load_sys_preset(config: &Config, os_id: &str) -> Result<LoadedSysPreset> {
    if os_id.contains('/') || os_id.contains('\\') || os_id.contains("..") {
        bail!("invalid os id: {os_id:?}");
    }
    let prefix = format!("sys/{os_id}");
    if !config.is_external_presets {
        crate::presets::extract_prefix(&prefix, config.presets_dir(), true).await?;
    }

    let root = Path::new("sys").join(os_id);
    let preset_root = config.preset_path(&root);
    let manifest_path = preset_root.join("shine.toml");
    let content = tokio::fs::read_to_string(&manifest_path)
        .await
        .with_context(|| format!("reading {}", manifest_path.display()))?;
    let manifest = parse_and_validate_manifest(&content)
        .with_context(|| format!("parsing {}", manifest_path.display()))?;
    Ok(LoadedSysPreset {
        manifest,
        root: std::fs::canonicalize(&preset_root)
            .with_context(|| format!("resolving sys preset root {}", preset_root.display()))?,
    })
}

pub(super) fn parse_and_validate_manifest(content: &str) -> Result<SysManifest> {
    let manifest: SysManifest = toml::from_str(content)?;
    validate_manifest(&manifest)?;
    Ok(manifest)
}

fn validate_manifest(manifest: &SysManifest) -> Result<()> {
    match manifest.version {
        Some(2) => {}
        None | Some(1) => bail!(
            "sys preset v1 is unsupported; migrate it to version = 2 by removing the monolithic dispatcher, adding detect/install to every init item, and moving software-specific profile code to item integrations. See docs/manual/guides/sys-preset-v2-migration.md"
        ),
        Some(version) => {
            bail!("sys preset version {version} is not supported by this Shine release")
        }
    }
    let mut ids = BTreeSet::new();
    for item in &manifest.items {
        validate_item_id(&item.id)?;
        if item.label.trim().is_empty() {
            bail!("sys bootstrap item `{}` must have a label", item.id);
        }
        if !ids.insert(item.id.clone()) {
            bail!("duplicate sys bootstrap item id `{}`", item.id);
        }
        let mut env_keys = BTreeSet::new();
        for key in &item.required_env {
            let mut chars = key.chars();
            let valid = chars
                .next()
                .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
                && chars.all(|c| c.is_ascii_alphanumeric() || c == '_');
            if !valid {
                bail!(
                    "sys item `{}` has invalid required_env key `{key}`",
                    item.id
                );
            }
            if !env_keys.insert(key) {
                bail!("sys item `{}` repeats required_env key `{key}`", item.id);
            }
        }
        validate_driver_config(item)?;
        validate_bootstrap_config(item)?;
        validate_shell_integrations(item)?;
    }

    if let Some(default_profile) = &manifest.default_profile
        && !manifest.profiles.contains_key(default_profile)
    {
        bail!("default profile `{default_profile}` is not defined");
    }

    for (profile_name, profile) in &manifest.profiles {
        for item_id in &profile.items {
            if !ids.contains(item_id) {
                bail!("profile `{profile_name}` references unknown item `{item_id}`");
            }
            if manifest
                .items
                .iter()
                .find(|item| item.id == *item_id)
                .is_some_and(|item| item.mode == SysItemMode::Managed)
            {
                bail!(
                    "profile `{profile_name}` references managed item `{item_id}`; enable it with `shine sys apply {item_id}`"
                );
            }
        }
    }

    Ok(())
}

fn validate_bootstrap_config(item: &SysItem) -> Result<()> {
    if item.mode == SysItemMode::Managed {
        if item.detect.is_some() || item.install.is_some() || !item.shell.is_empty() {
            bail!(
                "managed sys item `{}` cannot declare bootstrap detect/install/shell fields",
                item.id
            );
        }
        return Ok(());
    }

    let detect = item
        .detect
        .as_ref()
        .with_context(|| format!("sys bootstrap item `{}` must declare `detect`", item.id))?;
    let install = item
        .install
        .as_ref()
        .with_context(|| format!("sys bootstrap item `{}` must declare `install`", item.id))?;
    validate_detection(&item.id, detect)?;
    {
        match install {
            SysInstall::Package {
                package,
                success_status,
                success_hint,
                ..
            } => {
                validate_plain_value(&item.id, "package", package)?;
                if package.starts_with('-')
                    || !package
                        .chars()
                        .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '+' | '-'))
                {
                    bail!(
                        "sys item `{}` has invalid package identifier `{package}`",
                        item.id
                    );
                }
                validate_success_status(&item.id, *success_status)?;
                if !success_hint.is_empty() {
                    validate_plain_value(&item.id, "success hint", success_hint)?;
                }
            }
            SysInstall::Script {
                path,
                success_status,
                success_hint,
            } => {
                validate_relative_preset_path(&item.id, "install script", path)?;
                validate_success_status(&item.id, *success_status)?;
                if !success_hint.is_empty() {
                    validate_plain_value(&item.id, "success hint", success_hint)?;
                }
            }
        }
    }
    Ok(())
}

fn validate_detection(item_id: &str, detect: &SysDetection) -> Result<()> {
    match detect {
        SysDetection::Command {
            command,
            version_args,
        } => {
            validate_command_name(item_id, command)?;
            for arg in version_args {
                validate_plain_value(item_id, "version argument", arg)?;
            }
        }
        SysDetection::Path { path } => validate_plain_value(item_id, "detection path", path)?,
        SysDetection::Any { probes } => {
            if probes.is_empty() {
                bail!("sys item `{item_id}` detection `any` requires at least one probe");
            }
            for probe in probes {
                match probe {
                    SysDetectionProbe::Command { command } => {
                        validate_command_name(item_id, command)?
                    }
                    SysDetectionProbe::Path { path } => {
                        validate_plain_value(item_id, "detection path", path)?
                    }
                }
            }
        }
    }
    Ok(())
}

fn validate_success_status(item_id: &str, status: Option<SysItemStatus>) -> Result<()> {
    if status.is_some_and(|status| {
        !matches!(
            status,
            SysItemStatus::Installed | SysItemStatus::NeedsAction
        )
    }) {
        bail!("sys item `{item_id}` install success_status must be installed or needs-action");
    }
    Ok(())
}

fn validate_shell_integrations(item: &SysItem) -> Result<()> {
    for (index, integration) in item.shell.iter().enumerate() {
        if integration.shells.is_empty() {
            bail!(
                "sys item `{}` shell integration {} requires at least one shell",
                item.id,
                index + 1
            );
        }
        if let Some(command) = &integration.when_command {
            validate_command_name(&item.id, command)?;
        }
        let action_count = usize::from(integration.path.is_some())
            + usize::from(!integration.env.is_empty())
            + usize::from(!integration.eval_argv.is_empty())
            + usize::from(integration.source.is_some())
            + usize::from(!integration.aliases.is_empty())
            + usize::from(integration.fragment.is_some());
        if action_count != 1 {
            bail!(
                "sys item `{}` shell integration {} must declare exactly one of path, env, eval, source, aliases, or fragment",
                item.id,
                index + 1
            );
        }
        if let Some(path) = &integration.path {
            validate_plain_value(&item.id, "profile path", path)?;
        }
        for (key, value) in &integration.env {
            validate_env_key(&item.id, key)?;
            validate_plain_value(&item.id, "profile env value", value)?;
        }
        for arg in &integration.eval_argv {
            validate_plain_value(&item.id, "profile eval argument", arg)?;
        }
        if let Some(source) = &integration.source {
            validate_plain_value(&item.id, "profile source", source)?;
        }
        for (name, value) in &integration.aliases {
            if name.is_empty()
                || !name
                    .chars()
                    .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-'))
            {
                bail!("sys item `{}` has invalid alias name `{name}`", item.id);
            }
            validate_plain_value(&item.id, "profile alias", value)?;
        }
        if let Some(fragment) = &integration.fragment {
            validate_relative_preset_path(&item.id, "profile fragment", fragment)?;
        }
    }
    Ok(())
}

fn validate_command_name(item_id: &str, command: &str) -> Result<()> {
    if command.is_empty()
        || !command
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | '+'))
    {
        bail!("sys item `{item_id}` has invalid command name `{command}`");
    }
    Ok(())
}

fn validate_env_key(item_id: &str, key: &str) -> Result<()> {
    let mut chars = key.chars();
    let valid = chars
        .next()
        .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
        && chars.all(|c| c.is_ascii_alphanumeric() || c == '_');
    if !valid {
        bail!("sys item `{item_id}` has invalid profile env key `{key}`");
    }
    Ok(())
}

fn validate_plain_value(item_id: &str, label: &str, value: &str) -> Result<()> {
    if value.trim().is_empty() || value.chars().any(char::is_control) {
        bail!("sys item `{item_id}` has invalid {label}");
    }
    Ok(())
}

fn validate_relative_preset_path(item_id: &str, label: &str, value: &str) -> Result<()> {
    validate_plain_value(item_id, label, value)?;
    let path = Path::new(value);
    if path.is_absolute()
        || path.components().any(|component| {
            matches!(
                component,
                std::path::Component::ParentDir
                    | std::path::Component::RootDir
                    | std::path::Component::Prefix(_)
            )
        })
    {
        bail!("sys item `{item_id}` {label} must stay inside the preset: `{value}`");
    }
    Ok(())
}

fn validate_driver_config(item: &SysItem) -> Result<()> {
    if item.mode == SysItemMode::Init && item.driver != SysDriverKind::Script {
        bail!(
            "sys bootstrap item `{}` cannot use managed driver `{:?}`",
            item.id,
            item.driver
        );
    }
    let allowed: &[&str] = match item.driver {
        SysDriverKind::Script => &[],
        SysDriverKind::SplitDns => &["domain_env", "servers_env"],
        SysDriverKind::ManagedFile => &["source", "target", "transforms", "restart_hint"],
    };
    for key in item.config.keys() {
        if !allowed.contains(&key.as_str()) {
            bail!(
                "sys item `{}` has unknown {:?} driver config key `{key}`",
                item.id,
                item.driver
            );
        }
    }
    let require_string = |key: &str| -> Result<&str> {
        item.config
            .get(key)
            .and_then(toml::Value::as_str)
            .filter(|value| !value.trim().is_empty())
            .with_context(|| format!("sys item `{}` requires config `{key}`", item.id))
    };
    match item.driver {
        SysDriverKind::Script => {
            if !item.config.is_empty() {
                bail!(
                    "script sys item `{}` does not accept driver config",
                    item.id
                );
            }
        }
        SysDriverKind::SplitDns => {
            for key in ["domain_env", "servers_env"] {
                let env_key = require_string(key)?;
                if !item.required_env.iter().any(|required| required == env_key) {
                    bail!(
                        "sys item `{}` config `{key}` references `{env_key}` but required_env does not include it",
                        item.id
                    );
                }
            }
        }
        SysDriverKind::ManagedFile => {
            require_string("source")?;
            require_string("target")?;
            if let Some(transforms) = item.config.get("transforms") {
                let transforms = transforms.as_array().with_context(|| {
                    format!(
                        "sys item `{}` config `transforms` must be an array",
                        item.id
                    )
                })?;
                if transforms.iter().any(|value| value.as_str().is_none()) {
                    bail!(
                        "sys item `{}` config `transforms` must contain strings",
                        item.id
                    );
                }
            }
        }
    }
    Ok(())
}

fn validate_item_id(item_id: &str) -> Result<()> {
    if item_id.trim().is_empty() {
        bail!("sys bootstrap item ids must not be empty");
    }
    if !item_id
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
    {
        bail!(
            "sys bootstrap item id `{item_id}` contains invalid characters (allowed: a-z A-Z 0-9 - _)"
        );
    }
    Ok(())
}

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

    const ITEM: &str = r#"
[[items]]
id = "tool"
label = "Tool"
detect = { kind = "command", command = "tool" }
install = { kind = "package", provider = "apt", package = "tool" }
"#;

    #[test]
    fn rejects_missing_or_unknown_sys_preset_versions() {
        let missing = parse_and_validate_manifest(ITEM).unwrap_err();
        assert!(missing.to_string().contains("v1 is unsupported"));
        let unknown = parse_and_validate_manifest(&format!("version = 3\n{ITEM}")).unwrap_err();
        assert!(unknown.to_string().contains("version 3 is not supported"));
    }

    #[test]
    fn v2_requires_detection_and_installer_for_init_items() {
        let missing_detect = parse_and_validate_manifest(
            "version = 2\n[[items]]\nid = 'tool'\nlabel = 'Tool'\ninstall = { kind = 'package', provider = 'apt', package = 'tool' }",
        )
        .unwrap_err();
        assert!(missing_detect.to_string().contains("must declare `detect`"));
        let missing_install = parse_and_validate_manifest(
            "version = 2\n[[items]]\nid = 'tool'\nlabel = 'Tool'\ndetect = { kind = 'command', command = 'tool' }",
        )
        .unwrap_err();
        assert!(
            missing_install
                .to_string()
                .contains("must declare `install`")
        );
    }

    #[test]
    fn built_in_sys_presets_are_all_executable_v2_manifests() {
        for manifest in [
            include_str!("../../../presets/sys/macos/shine.toml"),
            include_str!("../../../presets/sys/ubuntu/shine.toml"),
            include_str!("../../../presets/sys/windows/shine.toml"),
        ] {
            parse_and_validate_manifest(manifest).unwrap();
        }
    }
}