guth-cli 0.1.0

Headless plugin discovery and dispatch for the Guth file manager.
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
//! Shared external-plugin discovery and dispatch for Guth.

use serde::{Deserialize, Serialize};
use std::collections::BTreeSet;
use std::ffi::OsString;
use std::fs;
use std::io::{self, Read, Write};
use std::os::fd::AsRawFd;
use std::path::{Path, PathBuf};
use std::process::{Command, ExitStatus, Stdio};
use uuid::{Uuid, Version};

pub const MANIFEST_SCHEMA: u32 = 1;
pub const MANIFEST_BYTES_LIMIT: u64 = 64 * 1024;
pub const PLUGIN_LIMIT: usize = 64;
const PLUGIN_DIRECTORY_ENTRY_LIMIT: usize = 4096;

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct PluginManifest {
    pub schema: u32,
    pub id: Uuid,
    pub name: String,
    pub version: String,
    pub executable: PathBuf,
    pub description: String,
    pub capabilities: Vec<String>,
}

impl PluginManifest {
    pub fn validate(&self) -> io::Result<()> {
        if self.schema != MANIFEST_SCHEMA {
            return Err(invalid_data("unsupported plugin manifest schema"));
        }
        if self.id.get_version() != Some(Version::SortRand) {
            return Err(invalid_data("plugin ID must be a UUIDv7"));
        }
        validate_text(&self.name, "plugin name", 80)?;
        validate_text(&self.version, "plugin version", 32)?;
        validate_text(&self.description, "plugin description", 280)?;
        if !self.executable.is_absolute() {
            return Err(invalid_data("plugin executable must be an absolute path"));
        }
        if self.capabilities.is_empty() || self.capabilities.len() > 16 {
            return Err(invalid_data("plugin must declare 1 to 16 capabilities"));
        }
        let mut seen = BTreeSet::new();
        for capability in &self.capabilities {
            validate_token(capability, "plugin capability")?;
            if !seen.insert(capability) {
                return Err(invalid_data("plugin capabilities must be unique"));
            }
        }
        Ok(())
    }

    pub fn supports(&self, capability: &str) -> bool {
        self.capabilities
            .iter()
            .any(|candidate| candidate == capability)
    }
}

pub fn plugin_data_dir() -> PathBuf {
    std::env::var_os("XDG_DATA_HOME")
        .map(PathBuf::from)
        .unwrap_or_else(|| home_dir().join(".local/share"))
        .join("guth/plugins")
}

pub fn discover_plugins() -> io::Result<Vec<PluginManifest>> {
    discover_plugins_in(&plugin_data_dir())
}

pub fn discover_plugins_in(directory: &Path) -> io::Result<Vec<PluginManifest>> {
    let mut manifests = Vec::new();
    let entries = match fs::read_dir(directory) {
        Ok(entries) => entries,
        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(manifests),
        Err(error) => return Err(error),
    };
    let mut paths = Vec::new();
    for (index, entry) in entries.enumerate() {
        if index >= PLUGIN_DIRECTORY_ENTRY_LIMIT {
            return Err(invalid_data("plugin directory entry limit exceeded"));
        }
        let Ok(entry) = entry else {
            continue;
        };
        let path = entry.path();
        let Some(stem) = path.file_stem().and_then(|stem| stem.to_str()) else {
            continue;
        };
        let Ok(id) = Uuid::parse_str(stem) else {
            continue;
        };
        if id.get_version() == Some(Version::SortRand)
            && id.to_string() == stem
            && path
                .extension()
                .is_some_and(|extension| extension == "json")
        {
            paths.push((id, path));
        }
    }
    paths.sort();
    for (expected_id, path) in paths.into_iter().take(PLUGIN_LIMIT) {
        let Ok(file) = open_verified_file(&path, false, true) else {
            continue;
        };
        let Ok(metadata) = file.metadata() else {
            continue;
        };
        if metadata.len() > MANIFEST_BYTES_LIMIT {
            continue;
        }
        let mut bytes = Vec::with_capacity(metadata.len() as usize);
        if file
            .take(MANIFEST_BYTES_LIMIT + 1)
            .read_to_end(&mut bytes)
            .is_err()
        {
            continue;
        }
        let Ok(manifest) = serde_json::from_slice::<PluginManifest>(&bytes) else {
            continue;
        };
        if manifest.id != expected_id
            || manifest.validate().is_err()
            || open_verified_file(&manifest.executable, true, false).is_err()
        {
            continue;
        }
        manifests.push(manifest);
    }
    manifests.sort_by(|left, right| left.name.cmp(&right.name).then(left.id.cmp(&right.id)));
    manifests.dedup_by_key(|manifest| manifest.id);
    Ok(manifests)
}

pub fn install_manifest(manifest: &PluginManifest) -> io::Result<PathBuf> {
    install_manifest_in(manifest, &plugin_data_dir())
}

pub fn install_manifest_in(manifest: &PluginManifest, directory: &Path) -> io::Result<PathBuf> {
    manifest.validate()?;
    open_verified_file(&manifest.executable, true, false)?;
    if let Some(parent) = directory.parent() {
        create_private_dir(parent)?;
    }
    let directory_file = create_private_dir(directory)?;
    rustix::fs::flock(&directory_file, rustix::fs::FlockOperation::LockExclusive)
        .map_err(errno_error)?;
    let destination = directory.join(format!("{}.json", manifest.id));
    let destination_name = format!("{}.json", manifest.id);
    let temporary_name = format!(".{}.{}.tmp", manifest.id, Uuid::now_v7());
    if !destination.exists() && manifest_count(directory)? >= PLUGIN_LIMIT {
        return Err(invalid_data("plugin limit reached"));
    }
    let bytes = serde_json::to_vec_pretty(manifest).map_err(invalid_json)?;
    let result = (|| {
        let owned_fd = rustix::fs::openat(
            &directory_file,
            temporary_name.as_str(),
            rustix::fs::OFlags::WRONLY
                | rustix::fs::OFlags::CREATE
                | rustix::fs::OFlags::EXCL
                | rustix::fs::OFlags::NOFOLLOW
                | rustix::fs::OFlags::CLOEXEC,
            rustix::fs::Mode::RUSR | rustix::fs::Mode::WUSR,
        )
        .map_err(errno_error)?;
        let mut file = fs::File::from(owned_fd);
        file.write_all(&bytes)?;
        file.write_all(b"\n")?;
        file.sync_all()?;
        drop(file);
        rustix::fs::renameat(
            &directory_file,
            temporary_name.as_str(),
            &directory_file,
            destination_name.as_str(),
        )
        .map_err(errno_error)?;
        directory_file.sync_all()?;
        Ok(destination.clone())
    })();
    if result.is_err() {
        let _ = rustix::fs::unlinkat(
            &directory_file,
            temporary_name.as_str(),
            rustix::fs::AtFlags::empty(),
        );
    }
    result
}

pub fn run_plugin(
    manifest: &PluginManifest,
    arguments: impl IntoIterator<Item = OsString>,
) -> io::Result<ExitStatus> {
    manifest.validate()?;
    let executable = open_verified_file(&manifest.executable, true, false)?;
    rustix::io::fcntl_setfd(&executable, rustix::io::FdFlags::empty()).map_err(errno_error)?;
    let executable_path = format!("/proc/self/fd/{}", executable.as_raw_fd());
    Command::new(executable_path)
        .args(arguments)
        .stdin(Stdio::inherit())
        .stdout(Stdio::inherit())
        .stderr(Stdio::inherit())
        .status()
}

fn validate_text(value: &str, label: &str, max_len: usize) -> io::Result<()> {
    if value.is_empty()
        || value.len() > max_len
        || value.chars().any(|character| character.is_control())
    {
        return Err(invalid_data(format!("invalid {label}")));
    }
    Ok(())
}

fn validate_token(value: &str, label: &str) -> io::Result<()> {
    if value.is_empty()
        || value.len() > 40
        || !value
            .bytes()
            .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')
    {
        return Err(invalid_data(format!("invalid {label}")));
    }
    Ok(())
}

fn open_verified_file(path: &Path, executable: bool, private: bool) -> io::Result<fs::File> {
    let owned_fd = rustix::fs::open(
        path,
        rustix::fs::OFlags::RDONLY
            | rustix::fs::OFlags::CLOEXEC
            | rustix::fs::OFlags::NOFOLLOW
            | rustix::fs::OFlags::NONBLOCK,
        rustix::fs::Mode::empty(),
    )
    .map_err(errno_error)?;
    let file = fs::File::from(owned_fd);
    let metadata = file.metadata()?;
    if !metadata.is_file() {
        return Err(invalid_data("plugin path must be a regular file"));
    }
    #[cfg(unix)]
    {
        use std::os::unix::fs::MetadataExt;
        let current_uid = rustix::process::geteuid().as_raw();
        if metadata.uid() != current_uid && metadata.uid() != 0 {
            return Err(io::Error::new(
                io::ErrorKind::PermissionDenied,
                "plugin file has an untrusted owner",
            ));
        }
        let unsafe_permissions = if private { 0o077 } else { 0o022 };
        if metadata.mode() & unsafe_permissions != 0 {
            return Err(io::Error::new(
                io::ErrorKind::PermissionDenied,
                "plugin file has unsafe permissions",
            ));
        }
        if executable && metadata.mode() & 0o111 == 0 {
            return Err(io::Error::new(
                io::ErrorKind::PermissionDenied,
                "plugin executable is not executable",
            ));
        }
    }
    Ok(file)
}

fn create_private_dir(path: &Path) -> io::Result<fs::File> {
    if !path.is_absolute() {
        return Err(invalid_data("plugin directory must be absolute"));
    }
    fs::create_dir_all(path)?;
    let owned_fd = rustix::fs::open(
        path,
        rustix::fs::OFlags::RDONLY
            | rustix::fs::OFlags::DIRECTORY
            | rustix::fs::OFlags::NOFOLLOW
            | rustix::fs::OFlags::CLOEXEC,
        rustix::fs::Mode::empty(),
    )
    .map_err(errno_error)?;
    let directory = fs::File::from(owned_fd);
    #[cfg(unix)]
    {
        use std::os::unix::fs::MetadataExt;
        let metadata = directory.metadata()?;
        if !metadata.is_dir() {
            return Err(io::Error::new(
                io::ErrorKind::PermissionDenied,
                "plugin directory must be a real directory",
            ));
        }
        if metadata.uid() != rustix::process::geteuid().as_raw() {
            return Err(io::Error::new(
                io::ErrorKind::PermissionDenied,
                "plugin directory has an unexpected owner",
            ));
        }
        rustix::fs::fchmod(&directory, rustix::fs::Mode::RWXU).map_err(errno_error)?;
    }
    Ok(directory)
}

fn manifest_count(directory: &Path) -> io::Result<usize> {
    let mut count = 0;
    for entry in fs::read_dir(directory)?.take(PLUGIN_DIRECTORY_ENTRY_LIMIT) {
        let Ok(entry) = entry else {
            continue;
        };
        let path = entry.path();
        let Some(stem) = path.file_stem().and_then(|stem| stem.to_str()) else {
            continue;
        };
        if path
            .extension()
            .is_some_and(|extension| extension == "json")
            && Uuid::parse_str(stem).is_ok_and(|id| {
                id.get_version() == Some(Version::SortRand) && id.to_string() == stem
            })
        {
            count += 1;
        }
    }
    Ok(count)
}

fn home_dir() -> PathBuf {
    std::env::var_os("HOME")
        .map(PathBuf::from)
        .unwrap_or_else(|| PathBuf::from("/"))
}

fn invalid_data(message: impl Into<String>) -> io::Error {
    io::Error::new(io::ErrorKind::InvalidData, message.into())
}

fn invalid_json(error: impl std::fmt::Display) -> io::Error {
    invalid_data(format!("invalid plugin manifest: {error}"))
}

fn errno_error(error: rustix::io::Errno) -> io::Error {
    io::Error::from_raw_os_error(error.raw_os_error())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::{SystemTime, UNIX_EPOCH};

    struct TestDir(PathBuf);

    impl TestDir {
        fn new(label: &str) -> Self {
            let nonce = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_nanos();
            let path = std::env::temp_dir()
                .join(format!("guth-cli-{label}-{}-{nonce}", std::process::id()));
            fs::create_dir(&path).unwrap();
            Self(path)
        }
    }

    impl Drop for TestDir {
        fn drop(&mut self) {
            let _ = fs::remove_dir_all(&self.0);
        }
    }

    fn test_manifest(executable: PathBuf) -> PluginManifest {
        PluginManifest {
            schema: MANIFEST_SCHEMA,
            id: Uuid::now_v7(),
            name: "Test Sync".to_string(),
            version: "0.1.0".to_string(),
            executable,
            description: "A test plugin".to_string(),
            capabilities: vec!["sync".to_string()],
        }
    }

    #[test]
    fn manifests_require_uuid_v7_and_absolute_executables() {
        let mut manifest = test_manifest(PathBuf::from("relative"));
        assert!(manifest.validate().is_err());
        manifest.executable = PathBuf::from("/bin/true");
        manifest.id = Uuid::nil();
        assert!(manifest.validate().is_err());
    }

    #[cfg(unix)]
    #[test]
    fn installed_manifests_are_private_and_discoverable() {
        use std::os::unix::fs::{MetadataExt, PermissionsExt};

        let root = TestDir::new("discovery");
        let executable = root.0.join("plugin");
        fs::write(&executable, b"#!/bin/sh\nexit 0\n").unwrap();
        fs::set_permissions(&executable, fs::Permissions::from_mode(0o700)).unwrap();
        let manifest = test_manifest(executable);
        let directory = root.0.join("manifests");

        let installed = install_manifest_in(&manifest, &directory).unwrap();
        assert_eq!(fs::metadata(&directory).unwrap().mode() & 0o777, 0o700);
        assert_eq!(fs::metadata(&installed).unwrap().mode() & 0o777, 0o600);
        assert_eq!(discover_plugins_in(&directory).unwrap(), vec![manifest]);
    }

    #[cfg(unix)]
    #[test]
    fn writable_executables_are_rejected() {
        use std::os::unix::fs::PermissionsExt;

        let root = TestDir::new("permissions");
        let executable = root.0.join("plugin");
        fs::write(&executable, b"plugin").unwrap();
        fs::set_permissions(&executable, fs::Permissions::from_mode(0o722)).unwrap();
        let error = open_verified_file(&executable, true, false).unwrap_err();
        assert_eq!(error.kind(), io::ErrorKind::PermissionDenied);
    }

    #[cfg(unix)]
    #[test]
    fn malformed_neighbors_do_not_hide_valid_plugins() {
        use std::os::unix::fs::PermissionsExt;

        let root = TestDir::new("malformed-neighbor");
        let executable = root.0.join("plugin");
        fs::write(&executable, b"plugin").unwrap();
        fs::set_permissions(&executable, fs::Permissions::from_mode(0o700)).unwrap();
        let manifest = test_manifest(executable);
        let directory = root.0.join("manifests");
        install_manifest_in(&manifest, &directory).unwrap();
        let malformed = directory.join(format!("{}.json", Uuid::now_v7()));
        fs::write(&malformed, b"not json").unwrap();
        fs::set_permissions(&malformed, fs::Permissions::from_mode(0o600)).unwrap();

        assert_eq!(discover_plugins_in(&directory).unwrap(), vec![manifest]);
    }

    #[cfg(unix)]
    #[test]
    fn special_file_candidates_do_not_block_discovery() {
        let root = TestDir::new("special-file");
        let fifo = root.0.join(format!("{}.json", Uuid::now_v7()));
        rustix::fs::mkfifoat(
            rustix::fs::CWD,
            &fifo,
            rustix::fs::Mode::RUSR | rustix::fs::Mode::WUSR,
        )
        .unwrap();

        assert!(discover_plugins_in(&root.0).unwrap().is_empty());
    }
}