subc-os 0.1.51

Operating-system primitives for the subc daemon that need unsafe code, behind a safe API: per-process identity, signalling, memory and CPU usage, and the launch-nonce descriptor handoff.
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
use super::*;
use cortexkit_test_support::ScratchDir;
use std::{fs, io::Write};

fn leaf(name: &str) -> &OsStr {
    OsStr::new(name)
}

#[cfg(unix)]
fn open_parent(path: &Path) -> File {
    File::open(path).unwrap()
}

#[cfg(windows)]
fn open_parent(path: &Path) -> File {
    // The fixture is inside a freshly created scratch directory. This opens
    // that directory, not protected Windows ancestors outside the fixture.
    use std::os::windows::fs::OpenOptionsExt;
    use windows_sys::Win32::Storage::FileSystem::{
        FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT,
    };
    fs::OpenOptions::new()
        .read(true)
        .custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT)
        .open(path)
        .unwrap()
}

fn stage(parent: &File, publish: bool) -> RetainedTempFile<'_> {
    let mut temp = if publish {
        RetainedTempFile::create_for_publish(parent)
    } else {
        RetainedTempFile::create(parent)
    }
    .unwrap();
    temp.file_mut().write_all(b"replacement").unwrap();
    temp
}

#[test]
fn retained_read_distinguishes_absent_directory_hardlink_and_file() {
    use std::io::Read;
    let scratch = ScratchDir::new("retained-read");
    let parent = open_parent(&scratch);
    assert!(open_directory_nofollow_at(&parent, leaf("config"))
        .unwrap()
        .is_none());
    fs::create_dir(scratch.join("config")).unwrap();
    assert!(matches!(
        open_single_link_file_nofollow_at(&parent, leaf("config")),
        Err(OpenRetainedError::NotRegular)
    ));
    let config = open_directory_nofollow_at(&parent, leaf("config"))
        .unwrap()
        .unwrap();
    assert!(open_single_link_file_nofollow_at(&config, leaf("layer"))
        .unwrap()
        .is_none());
    fs::write(scratch.join("config/layer"), b"retained contents").unwrap();
    let mut opened = open_single_link_file_nofollow_at(&config, leaf("layer"))
        .unwrap()
        .unwrap();
    let mut bytes = Vec::new();
    opened.read_to_end(&mut bytes).unwrap();
    assert_eq!(bytes, b"retained contents");
    fs::hard_link(scratch.join("config/layer"), scratch.join("other")).unwrap();
    assert!(matches!(
        open_single_link_file_nofollow_at(&config, leaf("layer")),
        Err(OpenRetainedError::Hardlinked)
    ));
    assert!(open_single_link_file_nofollow_at(&config, leaf("../other")).is_err());
}

#[cfg(unix)]
#[test]
fn retained_read_stays_anchored_after_rename_and_rejects_link() {
    use std::{io::Read, os::unix::fs::symlink};
    let scratch = ScratchDir::new("retained-read-rename");
    fs::create_dir(scratch.join("config")).unwrap();
    fs::write(scratch.join("config/layer"), b"old").unwrap();
    let config = open_parent(&scratch.join("config"));
    fs::rename(scratch.join("config"), scratch.join("original")).unwrap();
    fs::create_dir(scratch.join("config")).unwrap();
    fs::write(scratch.join("config/layer"), b"new").unwrap();
    let mut file = open_single_link_file_nofollow_at(&config, leaf("layer"))
        .unwrap()
        .unwrap();
    let mut bytes = Vec::new();
    file.read_to_end(&mut bytes).unwrap();
    assert_eq!(bytes, b"old");
    symlink(scratch.join("config"), scratch.join("original/link")).unwrap();
    assert!(matches!(
        open_directory_nofollow_at(&config, leaf("link")),
        Err(OpenRetainedError::Symlink)
    ));
}

#[test]
fn no_replace_refuses_existing_file_and_directory() {
    let scratch = ScratchDir::new("retained-no-replace");
    let parent = open_parent(&scratch);
    let stage = stage(&parent, true);
    fs::write(scratch.join("layer"), b"other writer").unwrap();
    let error = stage.publish(leaf("layer")).unwrap_err();
    assert!(!error.renamed());
    assert_eq!(io::Error::from(error).kind(), io::ErrorKind::AlreadyExists);
    assert_eq!(fs::read(scratch.join("layer")).unwrap(), b"other writer");

    fs::create_dir(scratch.join(".cortexkit")).unwrap();
    let error = create_directory_nofollow_at(&parent, leaf(".cortexkit")).unwrap_err();
    assert!(!error.renamed());
    assert_eq!(io::Error::from(error).kind(), io::ErrorKind::AlreadyExists);
    assert_eq!(fs::read_dir(&*scratch).unwrap().count(), 2);
}

#[test]
fn checked_replace_refuses_changed_contents_without_publishing() {
    let scratch = ScratchDir::new("retained-checked-replace");
    let parent = open_parent(&scratch);
    let path = scratch.join("layer");
    fs::write(&path, b"old").unwrap();
    let expected = open_single_link_file_nofollow_at(&parent, leaf("layer"))
        .unwrap()
        .unwrap();
    let temp = stage(&parent, false);
    fs::write(&path, b"other writer").unwrap();

    let mut checks = 0;
    let error = temp
        .replace_checked(leaf("layer"), &expected, || {
            checks += 1;
            if fs::read(&path)? == b"old" {
                Ok(())
            } else {
                Err(io::Error::other("target contents changed"))
            }
        })
        .unwrap_err();
    assert!(!error.renamed());
    assert_eq!(
        io::Error::from(error).to_string(),
        "target contents changed"
    );
    assert_eq!(checks, 1);
    assert_eq!(fs::read(&path).unwrap(), b"other writer");
    assert_eq!(fs::read_dir(&*scratch).unwrap().count(), 1);
}

#[test]
fn error_after_rename_reports_publication() {
    let scratch = ScratchDir::new("retained-published-error");
    let parent = open_parent(&scratch);
    let error = stage(&parent, true)
        .publish_impl(leaf("layer"), || {
            Err(io::Error::other("injected flush error"))
        })
        .unwrap_err();
    assert!(error.renamed());
    assert_eq!(fs::read(scratch.join("layer")).unwrap(), b"replacement");
}

#[cfg(unix)]
mod unix {
    use super::*;
    use std::os::unix::fs::{symlink, MetadataExt, PermissionsExt};

    #[test]
    fn refuses_symlinked_leaf_without_touching_referent() {
        let scratch = ScratchDir::new("retained-leaf-symlink");
        let parent = File::open(&*scratch).unwrap();
        let original = scratch.join("original");
        fs::write(&original, b"original").unwrap();
        symlink(&original, scratch.join("layer")).unwrap();
        let error = stage(&parent, false)
            .replace(leaf("layer"), &File::open(&original).unwrap())
            .unwrap_err();
        assert!(!error.renamed());
        assert_eq!(io::Error::from(error).raw_os_error(), Some(libc::ELOOP));
        assert!(fs::symlink_metadata(scratch.join("layer"))
            .unwrap()
            .is_symlink());
        assert_eq!(fs::read(original).unwrap(), b"original");
    }

    #[test]
    fn refuses_directory_symlink_and_stays_anchored_after_parent_rename() {
        let scratch = ScratchDir::new("retained-directory-symlink");
        let root = scratch.canonicalize().unwrap();
        let original = root.join("directory");
        let moved = root.join("moved");
        let outside = root.join("outside");
        fs::create_dir(&original).unwrap();
        fs::create_dir(&outside).unwrap();
        let parent = File::open(&original).unwrap();
        fs::rename(&original, &moved).unwrap();
        symlink(&outside, &original).unwrap();
        let root = File::open(root).unwrap();
        let error = create_directory_nofollow_at(&root, leaf("directory")).unwrap_err();
        assert!(!error.renamed());
        assert_eq!(io::Error::from(error).kind(), io::ErrorKind::AlreadyExists);
        let error = stage(&root, true)
            .publish(leaf("directory/layer"))
            .unwrap_err();
        assert!(!error.renamed());
        assert_eq!(io::Error::from(error).kind(), io::ErrorKind::InvalidInput);
        // Stage creation and publication must both use the handle, not the
        // original path which now redirects into outside.
        let config = create_directory_nofollow_at(&parent, leaf(".cortexkit")).unwrap();
        stage(&config, true).publish(leaf("layer")).unwrap();
        assert_eq!(
            fs::read(moved.join(".cortexkit/layer")).unwrap(),
            b"replacement"
        );
        assert_eq!(fs::read_dir(outside).unwrap().count(), 0);
    }

    #[test]
    fn replaces_atomically_and_preserves_mode_owner_and_group() {
        let scratch = ScratchDir::new("retained-replace-mode");
        let parent = File::open(&*scratch).unwrap();
        let target = scratch.join("layer");
        fs::write(&target, b"original").unwrap();
        fs::set_permissions(&target, fs::Permissions::from_mode(0o640)).unwrap();
        let expected = File::open(&target).unwrap();
        let old = expected.metadata().unwrap();
        let mut staging = stage(&parent, false);
        assert_eq!(staging.file_mut().metadata().unwrap().mode() & 0o077, 0);
        staging.replace(leaf("layer"), &expected).unwrap();
        let replacement = fs::metadata(&target).unwrap();
        assert_eq!(replacement.mode() & 0o7777, 0o640);
        assert_eq!(
            (replacement.uid(), replacement.gid()),
            (old.uid(), old.gid())
        );
        assert_ne!(replacement.ino(), old.ino());
        assert_eq!(fs::read(target).unwrap(), b"replacement");
        let mut original = Vec::new();
        std::io::Read::read_to_end(&mut &expected, &mut original).unwrap();
        assert_eq!(original, b"original");
    }

    #[test]
    fn refuses_a_different_regular_file_even_at_the_same_leaf() {
        let scratch = ScratchDir::new("retained-stale-target");
        let parent = File::open(&*scratch).unwrap();
        let target = scratch.join("layer");
        fs::write(&target, b"same bytes").unwrap();
        let expected = File::open(&target).unwrap();
        fs::rename(&target, scratch.join("old")).unwrap();
        fs::write(&target, b"same bytes").unwrap();
        let error = stage(&parent, false)
            .replace(leaf("layer"), &expected)
            .unwrap_err();
        assert!(!error.renamed());
        assert_eq!(fs::read(target).unwrap(), b"same bytes");
    }

    #[test]
    fn new_file_and_directory_have_ordinary_creation_modes() {
        let scratch = ScratchDir::new("retained-publish-mode");
        let parent = File::open(&*scratch).unwrap();
        let ordinary_dir = scratch.join("ordinary-dir");
        let ordinary_file = scratch.join("ordinary-file");
        fs::create_dir(&ordinary_dir).unwrap();
        File::create(&ordinary_file).unwrap();
        let published_dir = create_directory_nofollow_at(&parent, leaf(".cortexkit")).unwrap();
        stage(&parent, true).publish(leaf("layer")).unwrap();
        assert_eq!(
            published_dir.metadata().unwrap().mode(),
            fs::metadata(ordinary_dir).unwrap().mode()
        );
        assert_eq!(
            fs::metadata(scratch.join("layer")).unwrap().mode(),
            fs::metadata(ordinary_file).unwrap().mode()
        );
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn preserves_posix_acl_and_inherits_it_on_publish() {
        use rustix::fs::{fgetxattr, fsetxattr, XattrFlags};

        let scratch = ScratchDir::new("retained-posix-acl");
        let parent = File::open(&*scratch).unwrap();
        let acl_name = "system.posix_acl_access";
        // Linux xattr ACL v2: grant one named user access in addition to the
        // ordinary user/group/other entries. The mask matches mode 0640.
        let mut acl = 2u32.to_le_bytes().to_vec();
        for (tag, permission, id) in [
            (1u16, 6u16, u32::MAX),
            (2, 4, 65534),
            (4, 0, u32::MAX),
            (16, 4, u32::MAX),
            (32, 0, u32::MAX),
        ] {
            acl.extend(tag.to_le_bytes());
            acl.extend(permission.to_le_bytes());
            acl.extend(id.to_le_bytes());
        }
        let target = scratch.join("layer");
        fs::write(&target, b"original").unwrap();
        let expected = File::open(&target).unwrap();
        fsetxattr(&expected, acl_name, &acl, XattrFlags::empty()).unwrap();
        stage(&parent, false)
            .replace(leaf("layer"), &expected)
            .unwrap();
        let mut default = acl.clone();
        default[6] |= 1; // The owner also needs search permission on new directories.
        fsetxattr(
            &parent,
            "system.posix_acl_default",
            &default,
            XattrFlags::empty(),
        )
        .unwrap();
        let config = create_directory_nofollow_at(&parent, leaf(".cortexkit")).unwrap();
        stage(&config, true).publish(leaf("new-layer")).unwrap();
        for file in [target, scratch.join(".cortexkit/new-layer")] {
            let mut buffer = [0; 64];
            let count = fgetxattr(File::open(file).unwrap(), acl_name, &mut buffer[..]).unwrap();
            assert_eq!(&buffer[..count], acl);
        }
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn preserves_extended_acl() {
        use std::process::Command;

        let scratch = ScratchDir::new("retained-mac-acl");
        let parent = File::open(&*scratch).unwrap();
        let target = scratch.join("layer");
        fs::write(&target, b"original").unwrap();
        assert!(Command::new("/bin/chmod")
            .args(["+a", "everyone allow read"])
            .arg(&target)
            .status()
            .unwrap()
            .success());
        let acl = || {
            let listing = Command::new("/bin/ls")
                .arg("-le")
                .arg(&target)
                .output()
                .unwrap();
            assert!(listing.status.success());
            String::from_utf8(listing.stdout)
                .unwrap()
                .lines()
                .skip(1)
                .collect::<Vec<_>>()
                .join("\n")
        };
        let original = acl();
        assert!(original.contains("everyone allow read"));
        stage(&parent, false)
            .replace(leaf("layer"), &File::open(&target).unwrap())
            .unwrap();
        assert_eq!(acl(), original);
    }

    #[cfg(target_os = "macos")]
    #[test]
    fn keeps_new_file_acl_inheritance_out_of_private_staging() {
        use std::process::Command;

        let scratch = ScratchDir::new("retained-mac-inherited-acl");
        let parent = File::open(&*scratch).unwrap();
        let target = scratch.join("without-acl");
        fs::write(&target, b"original").unwrap();
        assert!(Command::new("/bin/chmod")
            .args(["+a", "everyone allow read,file_inherit,directory_inherit"])
            .arg(&*scratch)
            .status()
            .unwrap()
            .success());
        let get_acl = |path: &Path| {
            let listing = Command::new("/bin/ls")
                .arg("-led")
                .arg(path)
                .output()
                .unwrap();
            assert!(listing.status.success());
            let listing = String::from_utf8(listing.stdout).unwrap();
            listing
                .lines()
                .any(|line| line.contains("everyone") && line.contains("allow read"))
        };
        let stage_file = stage(&parent, false);
        assert!(!get_acl(&scratch.join(&stage_file.stage.name)));
        stage_file
            .replace(leaf("without-acl"), &File::open(&target).unwrap())
            .unwrap();
        assert!(!get_acl(&target));
        let config = create_directory_nofollow_at(&parent, leaf(".cortexkit")).unwrap();
        stage(&config, true).publish(leaf("new-layer")).unwrap();
        assert!(get_acl(&scratch.join(".cortexkit/new-layer")));
    }
}

#[cfg(windows)]
#[test]
fn publishes_into_a_new_retained_directory_on_windows() {
    let scratch = ScratchDir::new("retained-windows-publish");
    let parent = open_parent(&scratch);
    let config = create_directory_nofollow_at(&parent, leaf(".cortexkit")).unwrap();
    stage(&config, true).publish(leaf("layer")).unwrap();
    let layer = scratch.join(".cortexkit/layer");
    assert_eq!(fs::read(&layer).unwrap(), b"replacement");
    let expected = File::open(&layer).unwrap();
    let mut replacement = RetainedTempFile::create(&config).unwrap();
    replacement.file_mut().write_all(b"new contents").unwrap();
    replacement.replace(leaf("layer"), &expected).unwrap();
    assert_eq!(fs::read(layer).unwrap(), b"new contents");
}

#[cfg(windows)]
#[test]
fn retained_read_and_replace_refuse_reparse_parent_and_leaf() {
    use std::{fs::OpenOptions, os::windows::fs::OpenOptionsExt, process::Command};
    use windows_sys::Win32::Storage::FileSystem::{
        FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT,
    };

    let scratch = ScratchDir::new("retained-reparse");
    let target = scratch.join("target");
    let junction = scratch.join("junction");
    fs::create_dir(&target).unwrap();
    assert!(Command::new("cmd")
        .args(["/d", "/c", "mklink", "/j"])
        .arg(&junction)
        .arg(&target)
        .status()
        .unwrap()
        .success());
    let reparse_handle = OpenOptions::new()
        .read(true)
        .custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT)
        .open(&junction)
        .unwrap();
    assert_eq!(
        RetainedTempFile::create(&reparse_handle)
            .unwrap_err()
            .kind(),
        io::ErrorKind::InvalidData
    );

    let parent = open_parent(&scratch);
    assert!(matches!(
        open_directory_nofollow_at(&parent, leaf("junction")),
        Err(OpenRetainedError::Symlink)
    ));
    assert!(matches!(
        open_single_link_file_nofollow_at(&parent, leaf("junction")),
        Err(OpenRetainedError::Symlink)
    ));
    fs::write(scratch.join("expected"), b"original").unwrap();
    let expected = File::open(scratch.join("expected")).unwrap();
    let error = stage(&parent, false)
        .replace(leaf("junction"), &expected)
        .unwrap_err();
    assert!(!error.renamed());
    assert_eq!(io::Error::from(error).kind(), io::ErrorKind::InvalidData);
    assert_eq!(fs::read_dir(target).unwrap().count(), 0);
}