guth-sync 0.1.0

Private-by-default rsync plugin for Guth and guth-cli.
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
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine as _;
use serde::{Deserialize, Serialize};
use std::fs;
use std::io::{self, Read, Write};
use std::path::{Component, Path, PathBuf};
use uuid::{Uuid, Version};
use zeroize::Zeroizing;

const PROFILE_SCHEMA: u32 = 1;
const PROFILE_BYTES_LIMIT: u64 = 16 * 1024;
const PROFILE_LIMIT: usize = 128;
const KEY_BYTES: usize = 32;

#[derive(Clone)]
pub struct Profile {
    id: Uuid,
    root: PathBuf,
    key: Zeroizing<Vec<u8>>,
}

#[derive(Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
struct StoredProfile {
    schema: u32,
    id: Uuid,
    root: String,
    key: Zeroizing<String>,
}

impl Profile {
    pub fn id(&self) -> Uuid {
        self.id
    }

    pub fn root(&self) -> &Path {
        &self.root
    }

    pub fn create(root: &Path) -> io::Result<Self> {
        let mut key = Zeroizing::new(vec![0_u8; KEY_BYTES]);
        getrandom::fill(&mut key).map_err(|error| io::Error::other(error.to_string()))?;
        let profile = Self {
            id: Uuid::now_v7(),
            root: validate_root(root)?,
            key,
        };
        profile.persist_new()?;
        Ok(profile)
    }

    pub fn join(root: &Path, pairing_code: &str) -> io::Result<Self> {
        let (id, encoded_key) = pairing_code
            .trim()
            .split_once('.')
            .ok_or_else(|| invalid_input("pairing code has an invalid format"))?;
        let id = parse_profile_id(id)?;
        let key = Zeroizing::new(
            URL_SAFE_NO_PAD
                .decode(encoded_key)
                .map_err(|_| invalid_input("pairing code has an invalid key"))?,
        );
        if key.len() != KEY_BYTES || URL_SAFE_NO_PAD.encode(key.as_slice()) != encoded_key {
            return Err(invalid_input("pairing code has an invalid key"));
        }
        let profile = Self {
            id,
            root: validate_root(root)?,
            key,
        };
        profile.persist_new()?;
        Ok(profile)
    }

    pub fn load(id: Uuid) -> io::Result<Self> {
        validate_profile_id(id)?;
        let path = profile_path(id);
        let owned_fd = rustix::fs::open(
            &path,
            rustix::fs::OFlags::RDONLY | rustix::fs::OFlags::CLOEXEC | rustix::fs::OFlags::NOFOLLOW,
            rustix::fs::Mode::empty(),
        )
        .map_err(errno_error)?;
        let file = fs::File::from(owned_fd);
        let metadata = file.metadata()?;
        validate_profile_metadata(&metadata)?;
        if metadata.len() > PROFILE_BYTES_LIMIT {
            return Err(invalid_data("profile file is too large"));
        }
        let mut bytes = Zeroizing::new(Vec::with_capacity(metadata.len() as usize));
        file.take(PROFILE_BYTES_LIMIT + 1).read_to_end(&mut bytes)?;
        let stored: StoredProfile = serde_json::from_slice(&bytes)
            .map_err(|error| invalid_data(format!("invalid profile: {error}")))?;
        if stored.schema != PROFILE_SCHEMA || stored.id != id {
            return Err(invalid_data("profile identity does not match its file"));
        }
        validate_profile_id(stored.id)?;
        let key = Zeroizing::new(
            URL_SAFE_NO_PAD
                .decode(stored.key.as_bytes())
                .map_err(|_| invalid_data("profile key is invalid"))?,
        );
        if key.len() != KEY_BYTES || URL_SAFE_NO_PAD.encode(key.as_slice()) != *stored.key {
            return Err(invalid_data("profile key is invalid"));
        }
        let root = validate_root(Path::new(&stored.root))?;
        Ok(Self { id, root, key })
    }

    pub fn list() -> io::Result<Vec<(Uuid, PathBuf)>> {
        let directory = profiles_dir();
        let entries = match fs::read_dir(directory) {
            Ok(entries) => entries,
            Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
            Err(error) => return Err(error),
        };
        let mut profiles = Vec::new();
        for entry in entries.filter_map(Result::ok).take(PROFILE_LIMIT) {
            let Some(stem) = entry
                .path()
                .file_stem()
                .and_then(|stem| stem.to_str())
                .map(str::to_owned)
            else {
                continue;
            };
            let Ok(id) = parse_profile_id(&stem) else {
                continue;
            };
            if let Ok(profile) = Self::load(id) {
                profiles.push((profile.id, profile.root));
            }
        }
        profiles.sort_by_key(|(id, _)| *id);
        Ok(profiles)
    }

    pub fn pairing_code(&self) -> Zeroizing<String> {
        Zeroizing::new(format!(
            "{}.{}",
            self.id,
            URL_SAFE_NO_PAD.encode(self.key.as_slice())
        ))
    }

    pub(crate) fn key_text(&self) -> Zeroizing<String> {
        Zeroizing::new(URL_SAFE_NO_PAD.encode(self.key.as_slice()))
    }

    fn persist_new(&self) -> io::Result<()> {
        create_private_dir(&config_dir())?;
        let directory = profiles_dir();
        create_private_dir(&directory)?;
        let stored = StoredProfile {
            schema: PROFILE_SCHEMA,
            id: self.id,
            root: path_text(&self.root)?,
            key: Zeroizing::new(URL_SAFE_NO_PAD.encode(self.key.as_slice())),
        };
        let content = Zeroizing::new(
            serde_json::to_vec_pretty(&stored)
                .map_err(|error| invalid_data(format!("could not encode profile: {error}")))?,
        );
        let path = profile_path(self.id);
        let temporary = directory.join(format!(".{}.{}.tmp", self.id, Uuid::now_v7()));
        let mut guard = TemporaryFile::create(temporary)?;
        let result = (|| {
            guard.file.write_all(&content)?;
            guard.file.write_all(b"\n")?;
            guard.file.sync_all()?;
            rustix::fs::renameat_with(
                rustix::fs::CWD,
                guard.path(),
                rustix::fs::CWD,
                &path,
                rustix::fs::RenameFlags::NOREPLACE,
            )
            .map_err(errno_error)
        })();
        if result.is_ok() {
            guard.disarm();
            fs::File::open(&directory)?.sync_all()?;
        }
        result
    }
}

pub fn parse_profile_id(value: &str) -> io::Result<Uuid> {
    let id = Uuid::parse_str(value).map_err(|_| invalid_input("invalid profile UUID"))?;
    if id.to_string() != value {
        return Err(invalid_input(
            "profile UUID must use canonical lowercase text",
        ));
    }
    validate_profile_id(id)?;
    Ok(id)
}

pub fn validate_relative_path(path: &Path) -> io::Result<()> {
    if path.as_os_str().is_empty() || path.is_absolute() {
        return Err(invalid_input("transfer paths must be relative"));
    }
    if path.components().any(|component| {
        matches!(
            component,
            Component::ParentDir | Component::RootDir | Component::Prefix(_)
        )
    }) {
        return Err(invalid_input(
            "transfer paths cannot leave the profile root",
        ));
    }
    Ok(())
}

pub fn runtime_dir() -> io::Result<PathBuf> {
    let base = std::env::var_os("XDG_RUNTIME_DIR")
        .map(PathBuf::from)
        .unwrap_or_else(|| home_dir().join(".cache"));
    let directory = base.join("guth-sync");
    create_private_dir(&directory)?;
    Ok(directory)
}

pub fn private_new_file(path: &Path) -> io::Result<fs::File> {
    let mut options = fs::OpenOptions::new();
    options.write(true).create_new(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        options.mode(0o600);
    }
    options.open(path)
}

fn config_dir() -> PathBuf {
    std::env::var_os("XDG_CONFIG_HOME")
        .map(PathBuf::from)
        .unwrap_or_else(|| home_dir().join(".config"))
        .join("guth-sync")
}

fn profiles_dir() -> PathBuf {
    config_dir().join("profiles")
}

fn profile_path(id: Uuid) -> PathBuf {
    profiles_dir().join(format!("{id}.json"))
}

fn validate_profile_id(id: Uuid) -> io::Result<()> {
    if id.get_version() != Some(Version::SortRand) {
        return Err(invalid_input("profile ID must be a UUIDv7"));
    }
    Ok(())
}

fn validate_root(root: &Path) -> io::Result<PathBuf> {
    let canonical = fs::canonicalize(root)?;
    if !canonical.is_dir() {
        return Err(invalid_input("profile root must be a folder"));
    }
    let text = path_text(&canonical)?;
    if text.chars().any(char::is_control)
        || text.contains(['%', '\\'])
        || text.trim_end().len() != text.len()
    {
        return Err(invalid_input(
            "profile root contains characters unsupported by rsync configuration",
        ));
    }
    Ok(canonical)
}

fn path_text(path: &Path) -> io::Result<String> {
    path.to_str()
        .map(str::to_owned)
        .ok_or_else(|| invalid_input("profile roots must be valid UTF-8"))
}

fn create_private_dir(path: &Path) -> io::Result<()> {
    if !path.is_absolute() {
        return Err(invalid_input("configuration paths must be absolute"));
    }
    let text = path
        .to_str()
        .ok_or_else(|| invalid_input("configuration paths must be valid UTF-8"))?;
    if text.chars().any(char::is_control)
        || text.contains(['%', '\\'])
        || text.trim_end().len() != text.len()
    {
        return Err(invalid_input(
            "configuration path contains characters unsupported by rsync",
        ));
    }
    fs::create_dir_all(path)?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::{MetadataExt, PermissionsExt};
        let metadata = fs::symlink_metadata(path)?;
        if metadata.file_type().is_symlink() || !metadata.is_dir() {
            return Err(io::Error::new(
                io::ErrorKind::PermissionDenied,
                "private path must be a real directory",
            ));
        }
        if metadata.uid() != rustix::process::geteuid().as_raw() {
            return Err(io::Error::new(
                io::ErrorKind::PermissionDenied,
                "private directory has an unexpected owner",
            ));
        }
        fs::set_permissions(path, fs::Permissions::from_mode(0o700))?;
    }
    Ok(())
}

fn validate_profile_metadata(metadata: &fs::Metadata) -> io::Result<()> {
    if metadata.file_type().is_symlink() || !metadata.is_file() {
        return Err(invalid_data("profile must be a regular file"));
    }
    #[cfg(unix)]
    {
        use std::os::unix::fs::MetadataExt;
        if metadata.uid() != rustix::process::geteuid().as_raw() {
            return Err(io::Error::new(
                io::ErrorKind::PermissionDenied,
                "profile has an unexpected owner",
            ));
        }
        if metadata.mode() & 0o077 != 0 {
            return Err(io::Error::new(
                io::ErrorKind::PermissionDenied,
                "profile permissions must be 0600",
            ));
        }
        if metadata.nlink() != 1 {
            return Err(io::Error::new(
                io::ErrorKind::PermissionDenied,
                "profile cannot have hard links",
            ));
        }
    }
    Ok(())
}

struct TemporaryFile {
    path: PathBuf,
    file: fs::File,
}

impl TemporaryFile {
    fn create(path: PathBuf) -> io::Result<Self> {
        let file = private_new_file(&path)?;
        Ok(Self { path, file })
    }

    fn path(&self) -> &Path {
        &self.path
    }

    fn disarm(mut self) {
        self.path.clear();
    }
}

impl Drop for TemporaryFile {
    fn drop(&mut self) {
        if !self.path.as_os_str().is_empty() {
            let _ = fs::remove_file(&self.path);
        }
    }
}

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

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

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

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

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

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

    #[test]
    fn transfer_paths_cannot_escape_the_profile() {
        assert!(validate_relative_path(Path::new("Documents/report.txt")).is_ok());
        assert!(validate_relative_path(Path::new("../secret")).is_err());
        assert!(validate_relative_path(Path::new("/etc/passwd")).is_err());
    }

    #[test]
    fn profile_ids_must_be_canonical_uuid_v7() {
        let id = Uuid::now_v7();
        assert_eq!(parse_profile_id(&id.to_string()).unwrap(), id);
        assert!(parse_profile_id(&id.to_string().to_uppercase()).is_err());
        assert!(parse_profile_id(&Uuid::nil().to_string()).is_err());
    }

    #[test]
    fn rsync_configuration_metacharacters_are_rejected() {
        let root = test_dir("percent%root");
        assert!(validate_root(&root).is_err());
        fs::remove_dir(root).unwrap();
    }
}