rustsy-process 0.2.0-alpha.1

Declared process graphs with verified local artifact caching
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
use crate::fs_safety::{self, invalid, node_md};
use rayon::prelude::*;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::{
    fs,
    io::{self, Read, Write},
    path::Path,
};

pub(crate) type Hash = [u8; 32];
#[cfg(feature = "lab")]
pub(crate) mod profiling;

#[derive(Clone, Copy, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Kind {
    File,
    Directory,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct Artifact {
    pub path: String,
    pub kind: Kind,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub(crate) struct Entry {
    pub name: String,
    pub file: Option<Hash>,
    pub permissions: u32,
}

#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub(crate) struct Tree {
    pub path: String,
    pub entries: Vec<Entry>,
}

pub(crate) fn sha(bytes: &[u8]) -> Hash {
    Sha256::digest(bytes).into()
}

pub(crate) fn text(hash: &Hash) -> String {
    use std::fmt::Write as _;
    let mut result = String::with_capacity(64);
    for byte in hash {
        write!(&mut result, "{byte:02x}").unwrap();
    }
    result
}

pub(crate) fn copy_hash(src: &Path, mut out: impl Write) -> io::Result<Hash> {
    copy_hash_buffered(src, &mut out, &mut vec![0; 128 * 1024])
}

pub(crate) fn copy_hash_buffered(
    src: &Path,
    mut out: impl Write,
    buf: &mut [u8],
) -> io::Result<Hash> {
    let mut input = open_file(src, true)?;
    let metadata = fs_safety::checked(src, input.metadata()?)?;
    if !metadata.is_file() {
        return Err(invalid("expected a regular file"));
    }
    let mut remaining = metadata.len();
    let mut hash = Sha256::new();
    while remaining != 0 {
        let size = remaining.min(buf.len() as u64) as usize;
        let block = &mut buf[..size];
        input.read_exact(block)?;
        out.write_all(block)?;
        hash.update(block);
        remaining -= size as u64;
    }
    #[cfg(unix)]
    {
        if input.read(&mut [0])? != 0 {
            return Err(invalid("file size changed during fingerprinting"));
        }
        finish_read(src, &metadata, &input)?;
    }
    Ok(hash.finalize().into())
}

#[cfg(unix)]
fn finish_read(src: &Path, before: &fs::Metadata, input: &fs::File) -> io::Result<()> {
    use std::os::unix::fs::MetadataExt;

    let fingerprint = |md: &fs::Metadata| {
        (
            md.dev(),
            md.ino(),
            md.len(),
            md.mtime(),
            md.mtime_nsec(),
            md.ctime(),
            md.ctime_nsec(),
        )
    };
    // Compare both the open handle and its path to detect edits and replacement
    // during the read. These timestamps never authorize reusing a cached digest.
    if fingerprint(before) != fingerprint(&input.metadata()?)
        || fingerprint(before) != fingerprint(&node_md(src)?)
    {
        return Err(invalid("file changed during fingerprinting"));
    }
    Ok(())
}

pub(crate) fn open_file(src: &Path, strict: bool) -> io::Result<fs::File> {
    let mut settings = fs::OpenOptions::new();
    settings.read(true);
    #[cfg(windows)]
    {
        use std::os::windows::fs::OpenOptionsExt;
        settings.custom_flags(0x0020_0000); // FILE_FLAG_OPEN_REPARSE_POINT
        if strict {
            // Deny opens for writes and deletes throughout the content read.
            settings.share_mode(1); // FILE_SHARE_READ
        }
    }
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        settings.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK);
        let _ = strict;
    }
    settings.open(src)
}

/// Independent fixed byte ranges for large declared inputs. Blob names keep
/// their regular SHA-256 because this fingerprint exists only in action keys.
pub(crate) fn fingerprint_file(src: &Path, pool: &rayon::ThreadPool) -> io::Result<Hash> {
    const BLOCK: u64 = 8 * 1024 * 1024;
    let file = open_file(src, true)?;
    let meta = fs_safety::checked(src, file.metadata()?)?;
    if !meta.is_file() {
        return Err(invalid("expected a regular file"));
    }
    let length = meta.len();
    let blocks = length.div_ceil(BLOCK).max(1);
    let hash_part = |buffer: &mut Vec<u8>, part: u64| -> io::Result<Hash> {
        let offset = part * BLOCK;
        let mut remaining = length.saturating_sub(offset).min(BLOCK);
        #[cfg(unix)]
        let mut offset = offset;
        let mut hash = Sha256::new();
        #[cfg(not(unix))]
        let mut source = {
            use std::io::{Seek, SeekFrom};
            let mut handle = open_file(src, true)?;
            handle.seek(SeekFrom::Start(offset))?;
            handle
        };
        while remaining > 0 {
            let count = remaining.min(buffer.len() as u64) as usize;
            #[cfg(unix)]
            {
                use std::os::unix::fs::FileExt;
                file.read_exact_at(&mut buffer[..count], offset)?;
                offset += count as u64;
            }
            #[cfg(not(unix))]
            source.read_exact(&mut buffer[..count])?;
            hash.update(&buffer[..count]);
            remaining -= count as u64;
        }
        Ok(hash.finalize().into())
    };
    let count = usize::try_from(blocks).map_err(invalid)?;
    let mut result = Sha256::new();
    result.update(b"rustsy-input-sha256-segments-v1\0");
    result.update(length.to_le_bytes());
    result.update(BLOCK.to_le_bytes());
    result.update(blocks.to_le_bytes());
    if count == 1 {
        if length > 0 {
            result.update(hash_part(&mut vec![0; 128 * 1024], 0)?);
        } else {
            result.update(sha(b""));
        }
    } else {
        let digests = pool.install(|| {
            (0..count)
                .into_par_iter()
                .map_init(
                    || vec![0; 128 * 1024],
                    |buffer, part| hash_part(buffer, part as u64),
                )
                .collect::<io::Result<Vec<_>>>()
        })?;
        for digest in digests {
            result.update(digest);
        }
    }
    #[cfg(unix)]
    finish_read(src, &meta, &file)?;
    Ok(result.finalize().into())
}

pub(crate) fn hash_input(
    root: &Path,
    input: &Artifact,
    pool: Option<&rayon::ThreadPool>,
    parallel_large: bool,
) -> io::Result<Tree> {
    if parallel_large && input.kind == Kind::File {
        let pool = pool.ok_or_else(|| invalid("missing segment worker pool"))?;
        return describe(root, input, |path| fingerprint_file(path, pool));
    }
    hash_tree(root, input, pool)
}

pub(crate) fn hash_tree(
    root: &Path,
    declaration: &Artifact,
    pool: Option<&rayon::ThreadPool>,
) -> io::Result<Tree> {
    process_tree(root, declaration, pool, |buffer, path| {
        copy_hash_buffered(path, io::sink(), buffer)
    })
}

pub(crate) fn process_tree(
    root: &Path,
    declaration: &Artifact,
    pool: Option<&rayon::ThreadPool>,
    hash: impl Fn(&mut [u8], &Path) -> io::Result<Hash> + Sync,
) -> io::Result<Tree> {
    let mut paths = Vec::new();
    let mut tree = describe(root, declaration, |path| {
        paths.push(path.to_owned());
        Ok([0; 32])
    })?;
    let work = |buf: &mut Vec<u8>, path: &std::path::PathBuf| hash(buf, path);
    let hashes = if let Some(pool) = pool.filter(|_| paths.len() >= 64) {
        pool.install(|| {
            paths
                .par_iter()
                .with_min_len(16)
                .map_init(|| vec![0; 128 * 1024], work)
                .collect::<io::Result<Vec<_>>>()
        })?
    } else {
        let mut buffer = vec![0; 128 * 1024];
        paths
            .iter()
            .map(|path| work(&mut buffer, path))
            .collect::<io::Result<Vec<_>>>()?
    };
    for (entry, digest) in tree
        .entries
        .iter_mut()
        .filter(|entry| entry.file.is_some())
        .zip(hashes)
    {
        entry.file = Some(digest);
    }
    Ok(tree)
}

pub(crate) fn describe(
    root: &Path,
    declaration: &Artifact,
    mut file: impl FnMut(&Path) -> io::Result<Hash>,
) -> io::Result<Tree> {
    let target = fs_safety::path(root, &declaration.path, false)?;
    let metadata = node_md(&target)?;
    if metadata.is_file() != (declaration.kind == Kind::File) {
        return Err(invalid(format!(
            "artifact type changed for {}",
            declaration.path
        )));
    }
    let mut entries = Vec::new();
    visit(&target, metadata, String::new(), &mut entries, &mut file)?;
    Ok(Tree {
        path: declaration.path.clone(),
        entries,
    })
}

fn visit(
    path: &Path,
    metadata: fs::Metadata,
    name: String,
    found: &mut Vec<Entry>,
    file: &mut impl FnMut(&Path) -> io::Result<Hash>,
) -> io::Result<()> {
    #[cfg(unix)]
    let permissions = {
        use std::os::unix::fs::PermissionsExt;
        metadata.permissions().mode() & 0o777
    };
    #[cfg(not(unix))]
    let permissions = 0;
    found.push(Entry {
        name: name.clone(),
        file: metadata.is_file().then(|| file(path)).transpose()?,
        permissions,
    });
    if metadata.is_dir() {
        let mut children = fs::read_dir(path)?.collect::<io::Result<Vec<_>>>()?;
        children.sort_unstable_by_key(|x| x.file_name());
        for child in children {
            let filename = child
                .file_name()
                .into_string()
                .map_err(|_| invalid("artifact file name is not Unicode"))?;
            if filename.contains('/') {
                return Err(invalid("unexpected separator"));
            }
            fs_safety::relative(&filename, false)?;
            let context = if name.is_empty() {
                filename
            } else {
                format!("{name}/{filename}")
            };
            let path = child.path();
            let metadata = fs_safety::checked(&path, child.metadata()?)?;
            visit(&path, metadata, context, found, file)?;
        }
    }
    Ok(())
}

pub(crate) fn permissions(path: &Path, mode: u32) -> io::Result<()> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        fs::set_permissions(path, fs::Permissions::from_mode(mode & 0o777))?;
    }
    #[cfg(not(unix))]
    let _ = (path, mode);
    Ok(())
}

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

    struct EditDuringCopy<'a>(&'a Path, bool);

    impl Write for EditDuringCopy<'_> {
        fn write(&mut self, data: &[u8]) -> io::Result<usize> {
            if !self.1 {
                let result = fs::write(self.0, [2; 1024]);
                #[cfg(windows)]
                assert_eq!(result.unwrap_err().raw_os_error(), Some(32));
                #[cfg(unix)]
                {
                    result?;
                    // Make the write detectable even on filesystems with coarse timestamps.
                    fs::File::options().write(true).open(self.0)?.set_modified(
                        std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_000_000),
                    )?;
                }
                self.1 = true;
            }
            Ok(data.len())
        }

        fn flush(&mut self) -> io::Result<()> {
            Ok(())
        }
    }

    #[test]
    #[cfg(any(windows, unix))]
    fn detect_or_exclude_same_size_write_during_read() -> io::Result<()> {
        let root = fs_safety::Scratch::new(&std::env::temp_dir())?;
        let path = root.0.join("data");
        fs::write(&path, [1; 1024])?;
        let digest = copy_hash_buffered(&path, EditDuringCopy(&path, false), &mut [0; 256]);
        #[cfg(windows)]
        assert_eq!(digest?, sha(&[1; 1024]));
        #[cfg(unix)]
        assert_eq!(digest.unwrap_err().kind(), io::ErrorKind::InvalidData);
        Ok(())
    }

    #[test]
    fn segmented_fingerprints_preserve_order_and_the_final_byte() -> io::Result<()> {
        let root = fs_safety::Scratch::new(&std::env::temp_dir())?;
        let path = root.0.join("file");
        let mut data = vec![5; 8 * 1024 * 1024 + 1];
        let one = rayon::ThreadPoolBuilder::new()
            .num_threads(1)
            .build()
            .unwrap();
        let many = rayon::ThreadPoolBuilder::new()
            .num_threads(4)
            .build()
            .unwrap();
        fs::write(&path, &data)?;
        let digest = fingerprint_file(&path, &one)?;
        assert_eq!(digest, fingerprint_file(&path, &many)?);
        *data.last_mut().unwrap() = 9;
        fs::write(&path, &data)?;
        assert_ne!(digest, fingerprint_file(&path, &many)?);
        data.rotate_right(1);
        fs::write(&path, &data)?;
        assert_ne!(digest, fingerprint_file(&path, &many)?);
        Ok(())
    }
}