minco-workbench 1.2.1

Optional local dashboard and deterministic exports for bounded Minco project views
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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
use minco_project_view::ProjectView;
use serde::Serialize;
use std::{
    ffi::{OsStr, OsString},
    path::{Component, Path, PathBuf},
};
use thiserror::Error;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ExportFormat {
    Json,
    Mermaid,
    Static,
}

#[derive(Debug, Clone, Copy)]
pub struct ExportRequest<'a> {
    pub root: &'a Path,
    pub destination: &'a Path,
    pub canonical_inputs: &'a [PathBuf],
    pub format: ExportFormat,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ExportReport {
    pub schema_version: u32,
    pub status: &'static str,
    pub format: ExportFormat,
    pub destination: PathBuf,
    pub files: Vec<String>,
    pub source_digest: String,
}

#[derive(Debug, Error)]
pub enum WorkbenchError {
    #[error("workbench export root must be an explicit canonical absolute directory: {0}")]
    InvalidRoot(PathBuf),
    #[error("workbench export destination must be a new normalized project-relative path: {0}")]
    InvalidDestination(PathBuf),
    #[error("workbench export destination overlaps canonical input {input}: {destination}")]
    CanonicalInputOverlap {
        destination: PathBuf,
        input: PathBuf,
    },
    #[error("workbench export destination already exists: {0}")]
    DestinationExists(PathBuf),
    #[error("safe atomic no-clobber directory installation is unsupported on this platform")]
    SafeInstallationUnsupported,
    #[error("workbench export serialization failed: {0}")]
    Serialization(#[from] serde_json::Error),
    #[error("workbench export I/O failed during {operation} at {path}: {source}")]
    Io {
        operation: &'static str,
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },
}

pub fn export_project_view(
    view: &ProjectView,
    request: ExportRequest<'_>,
) -> Result<ExportReport, WorkbenchError> {
    validate_request(&request)?;
    let artifacts = match request.format {
        ExportFormat::Json => vec![(
            PathBuf::from("project-view.json"),
            serde_json::to_vec(view)?,
        )],
        ExportFormat::Mermaid => vec![(
            PathBuf::from("project-view.mmd"),
            crate::render_mermaid(view).into_bytes(),
        )],
        ExportFormat::Static => vec![
            (
                PathBuf::from("index.html"),
                include_bytes!("../assets/index.html").to_vec(),
            ),
            (
                PathBuf::from("project-view.json"),
                serde_json::to_vec(view)?,
            ),
            (
                PathBuf::from("project-view.mmd"),
                crate::render_mermaid(view).into_bytes(),
            ),
            (
                PathBuf::from("workbench.css"),
                include_bytes!("../assets/workbench.css").to_vec(),
            ),
            (
                PathBuf::from("workbench.js"),
                include_bytes!("../assets/workbench.js").to_vec(),
            ),
        ],
    };
    let files = artifacts
        .iter()
        .map(|(path, _)| path.display().to_string())
        .collect::<Vec<_>>();

    secure::publish(request.root, request.destination, &artifacts)?;

    Ok(ExportReport {
        schema_version: 1,
        status: "ok",
        format: request.format,
        destination: request.destination.to_path_buf(),
        files,
        source_digest: view.project.source_digest.clone(),
    })
}

fn validate_request(request: &ExportRequest<'_>) -> Result<(), WorkbenchError> {
    let canonical_root = request
        .root
        .canonicalize()
        .map_err(|source| WorkbenchError::Io {
            operation: "canonicalize root",
            path: request.root.to_path_buf(),
            source,
        })?;
    if !request.root.is_absolute() || canonical_root != request.root || !request.root.is_dir() {
        return Err(WorkbenchError::InvalidRoot(request.root.to_path_buf()));
    }
    if request.destination.as_os_str().is_empty()
        || request.destination.is_absolute()
        || !request
            .destination
            .components()
            .all(|component| matches!(component, Component::Normal(_)))
    {
        return Err(WorkbenchError::InvalidDestination(
            request.destination.to_path_buf(),
        ));
    }
    for input in request.canonical_inputs {
        if request.destination.starts_with(input) || input.starts_with(request.destination) {
            return Err(WorkbenchError::CanonicalInputOverlap {
                destination: request.destination.to_path_buf(),
                input: input.clone(),
            });
        }
    }
    Ok(())
}

#[cfg(any(target_os = "linux", target_vendor = "apple"))]
mod secure {
    use super::{Component, OsStr, OsString, Path, PathBuf, WorkbenchError};
    use rustix::{
        fd::OwnedFd,
        fs::{
            AtFlags, Mode, OFlags, RenameFlags, fstat, fsync, mkdirat, open, openat, renameat_with,
            statat, unlinkat,
        },
        io::Errno,
    };
    use std::{fs::File, io::Write};
    use uuid::Uuid;

    const DIRECTORY_FLAGS: OFlags = OFlags::RDONLY
        .union(OFlags::DIRECTORY)
        .union(OFlags::NOFOLLOW)
        .union(OFlags::CLOEXEC);

    pub(super) fn publish(
        root: &Path,
        destination: &Path,
        artifacts: &[(PathBuf, Vec<u8>)],
    ) -> Result<(), WorkbenchError> {
        let mut staging_names = || {
            Some(OsString::from(format!(
                ".minco-workbench-{}.staging",
                Uuid::new_v4().simple()
            )))
        };
        publish_inner(
            root,
            destination,
            artifacts,
            &mut staging_names,
            || {},
            None,
            None,
        )
    }

    #[cfg(test)]
    pub(super) fn publish_with_before_install<F>(
        root: &Path,
        destination: &Path,
        artifacts: &[(PathBuf, Vec<u8>)],
        before_install: F,
    ) -> Result<(), WorkbenchError>
    where
        F: FnOnce(),
    {
        let mut staging_names = || {
            Some(OsString::from(format!(
                ".minco-workbench-{}.staging",
                Uuid::new_v4().simple()
            )))
        };
        publish_inner(
            root,
            destination,
            artifacts,
            &mut staging_names,
            before_install,
            None,
            None,
        )
    }

    #[cfg(test)]
    pub(super) fn publish_with_staging_names<I>(
        root: &Path,
        destination: &Path,
        artifacts: &[(PathBuf, Vec<u8>)],
        names: I,
    ) -> Result<(), WorkbenchError>
    where
        I: IntoIterator<Item = OsString>,
    {
        let mut names = names.into_iter();
        publish_inner(
            root,
            destination,
            artifacts,
            &mut || names.next(),
            || {},
            None,
            None,
        )
    }

    #[cfg(test)]
    pub(super) fn publish_with_install_error(
        root: &Path,
        destination: &Path,
        artifacts: &[(PathBuf, Vec<u8>)],
        install_error: Errno,
    ) -> Result<(), WorkbenchError> {
        let mut staging_names = || Some(OsString::from(".owned.staging"));
        publish_inner(
            root,
            destination,
            artifacts,
            &mut staging_names,
            || {},
            Some(install_error),
            None,
        )
    }

    #[cfg(test)]
    pub(super) fn publish_with_post_install_error(
        root: &Path,
        destination: &Path,
        artifacts: &[(PathBuf, Vec<u8>)],
        post_install_error: Errno,
    ) -> Result<(), WorkbenchError> {
        let mut staging_names = || Some(OsString::from(".owned.staging"));
        publish_inner(
            root,
            destination,
            artifacts,
            &mut staging_names,
            || {},
            None,
            Some(post_install_error),
        )
    }

    fn publish_inner<F, N>(
        root: &Path,
        destination: &Path,
        artifacts: &[(PathBuf, Vec<u8>)],
        staging_names: &mut N,
        before_install: F,
        forced_install_error: Option<Errno>,
        forced_post_install_error: Option<Errno>,
    ) -> Result<(), WorkbenchError>
    where
        F: FnOnce(),
        N: FnMut() -> Option<OsString>,
    {
        let parent_path = destination.parent().unwrap_or_else(|| Path::new(""));
        let destination_name = destination
            .file_name()
            .ok_or_else(|| WorkbenchError::InvalidDestination(destination.to_path_buf()))?;
        let parent = open_directory_chain(root, parent_path)?;
        let parent_identity = identity(&parent, parent_path)?;
        ensure_absent(&parent, destination_name, destination)?;
        let staging_name = create_private_staging(&parent, destination, staging_names)?;
        let staging = openat(&parent, &staging_name, DIRECTORY_FLAGS, Mode::empty())
            .map_err(|source| io_error("open private staging directory", destination, source))?;
        let staging_identity = identity(&staging, destination)?;
        let mut installed = false;

        let result = (|| {
            for (relative, contents) in artifacts {
                write_artifact(&staging, relative, contents, destination)?;
            }
            fsync(&staging).map_err(|source| {
                io_error("sync private staging directory", destination, source)
            })?;
            before_install();

            let restaged =
                statat(&parent, &staging_name, AtFlags::SYMLINK_NOFOLLOW).map_err(|source| {
                    io_error("verify private staging identity", destination, source)
                })?;
            if (restaged.st_dev, restaged.st_ino) != staging_identity {
                return Err(WorkbenchError::Io {
                    operation: "verify private staging identity",
                    path: destination.to_path_buf(),
                    source: std::io::Error::other("staging directory identity changed"),
                });
            }

            let resolved_parent = open_directory_chain(root, parent_path)?;
            if identity(&resolved_parent, parent_path)? != parent_identity {
                return Err(WorkbenchError::Io {
                    operation: "verify destination parent identity",
                    path: destination.to_path_buf(),
                    source: std::io::Error::other("destination parent identity changed"),
                });
            }
            ensure_absent(&parent, destination_name, destination)?;
            let installation = forced_install_error.map_or_else(
                || {
                    renameat_with(
                        &parent,
                        &staging_name,
                        &parent,
                        destination_name,
                        RenameFlags::NOREPLACE,
                    )
                },
                Err,
            );
            match installation {
                Ok(()) => installed = true,
                Err(Errno::EXIST) => {
                    return Err(WorkbenchError::DestinationExists(destination.to_path_buf()));
                }
                Err(source)
                    if [Errno::NOSYS, Errno::NOTSUP, Errno::OPNOTSUPP].contains(&source) =>
                {
                    return Err(WorkbenchError::SafeInstallationUnsupported);
                }
                Err(source) => {
                    return Err(io_error(
                        "atomically install export without replacement",
                        destination,
                        source,
                    ));
                }
            }
            if let Some(source) = forced_post_install_error {
                return Err(io_error("sync destination parent", destination, source));
            }
            fsync(&parent)
                .map_err(|source| io_error("sync destination parent", destination, source))?;
            Ok(())
        })();

        if result.is_err() {
            for (relative, _) in artifacts.iter().rev() {
                let _ = unlinkat(&staging, relative, AtFlags::empty());
            }
            let owned_name = if installed {
                destination_name
            } else {
                staging_name.as_os_str()
            };
            let published_name_still_owned = statat(&parent, owned_name, AtFlags::SYMLINK_NOFOLLOW)
                .is_ok_and(|stat| (stat.st_dev, stat.st_ino) == staging_identity);
            drop(staging);
            if published_name_still_owned {
                let _ = unlinkat(&parent, owned_name, AtFlags::REMOVEDIR);
            }
        }
        result
    }

    fn open_directory_chain(root: &Path, relative: &Path) -> Result<OwnedFd, WorkbenchError> {
        let mut current = open(root, DIRECTORY_FLAGS, Mode::empty())
            .map_err(|source| io_error("open canonical project root", root, source))?;
        for component in relative.components() {
            let Component::Normal(name) = component else {
                return Err(WorkbenchError::InvalidDestination(relative.to_path_buf()));
            };
            current = openat(&current, name, DIRECTORY_FLAGS, Mode::empty()).map_err(|source| {
                io_error("open destination parent without symlinks", relative, source)
            })?;
        }
        Ok(current)
    }

    fn create_private_staging<N>(
        parent: &OwnedFd,
        destination: &Path,
        staging_names: &mut N,
    ) -> Result<OsString, WorkbenchError>
    where
        N: FnMut() -> Option<OsString>,
    {
        for _ in 0..32 {
            let Some(name) = staging_names() else {
                break;
            };
            match mkdirat(parent, &name, Mode::RUSR | Mode::WUSR | Mode::XUSR) {
                Ok(()) => return Ok(name),
                Err(Errno::EXIST) => {}
                Err(source) => {
                    return Err(io_error(
                        "exclusively create private staging directory",
                        destination,
                        source,
                    ));
                }
            }
        }
        Err(WorkbenchError::Io {
            operation: "exclusively create private staging directory",
            path: destination.to_path_buf(),
            source: std::io::Error::new(
                std::io::ErrorKind::AlreadyExists,
                "staging name collision limit exceeded",
            ),
        })
    }

    fn write_artifact(
        staging: &OwnedFd,
        relative: &Path,
        contents: &[u8],
        destination: &Path,
    ) -> Result<(), WorkbenchError> {
        if relative
            .parent()
            .is_some_and(|parent| !parent.as_os_str().is_empty())
            || relative
                .components()
                .any(|component| !matches!(component, Component::Normal(_)))
        {
            return Err(WorkbenchError::InvalidDestination(relative.to_path_buf()));
        }
        let fd = openat(
            staging,
            relative,
            OFlags::WRONLY | OFlags::CREATE | OFlags::EXCL | OFlags::NOFOLLOW | OFlags::CLOEXEC,
            Mode::RUSR | Mode::WUSR,
        )
        .map_err(|source| io_error("create staged artifact", destination, source))?;
        let mut file = File::from(fd);
        file.write_all(contents)
            .map_err(|source| WorkbenchError::Io {
                operation: "write staged artifact",
                path: destination.join(relative),
                source,
            })?;
        file.sync_all().map_err(|source| WorkbenchError::Io {
            operation: "sync staged artifact",
            path: destination.join(relative),
            source,
        })?;
        Ok(())
    }

    fn ensure_absent(
        parent: &OwnedFd,
        name: &OsStr,
        destination: &Path,
    ) -> Result<(), WorkbenchError> {
        match statat(parent, name, AtFlags::SYMLINK_NOFOLLOW) {
            Ok(_) => Err(WorkbenchError::DestinationExists(destination.to_path_buf())),
            Err(Errno::NOENT) => Ok(()),
            Err(source) => Err(io_error("check export destination", destination, source)),
        }
    }

    fn identity(fd: &OwnedFd, path: &Path) -> Result<(rustix::fs::Dev, u64), WorkbenchError> {
        let stat =
            fstat(fd).map_err(|source| io_error("read filesystem identity", path, source))?;
        Ok((stat.st_dev, stat.st_ino))
    }

    fn io_error(operation: &'static str, path: &Path, source: Errno) -> WorkbenchError {
        WorkbenchError::Io {
            operation,
            path: path.to_path_buf(),
            source: source.into(),
        }
    }
}

#[cfg(all(test, any(target_os = "linux", target_vendor = "apple")))]
mod race_tests {
    use super::*;
    use std::fs;

    #[test]
    fn concurrently_created_destination_is_not_replaced_and_staging_is_removed() {
        let root = tempfile::tempdir().expect("export root");
        let canonical_root = root.path().canonicalize().expect("canonical export root");
        fs::create_dir(canonical_root.join("parent")).expect("destination parent");
        let destination = Path::new("parent/workbench");
        let artifacts = vec![(PathBuf::from("project-view.json"), b"{}".to_vec())];

        let error =
            secure::publish_with_before_install(&canonical_root, destination, &artifacts, || {
                fs::create_dir(canonical_root.join(destination)).expect("concurrent destination");
                fs::write(
                    canonical_root.join(destination).join("sentinel"),
                    "owned elsewhere",
                )
                .expect("concurrent sentinel");
            })
            .expect_err("concurrent destination must fail closed");

        assert!(matches!(error, WorkbenchError::DestinationExists(_)));
        assert_eq!(
            fs::read_to_string(canonical_root.join(destination).join("sentinel"))
                .expect("concurrent sentinel retained"),
            "owned elsewhere"
        );
        let entries = fs::read_dir(canonical_root.join("parent"))
            .expect("destination parent entries")
            .map(|entry| entry.expect("parent entry").file_name())
            .collect::<Vec<_>>();
        assert_eq!(entries, vec![OsString::from("workbench")]);
    }

    #[test]
    fn destination_parent_identity_swap_fails_closed_and_cleans_only_owned_staging() {
        let root = tempfile::tempdir().expect("export root");
        let canonical_root = root.path().canonicalize().expect("canonical export root");
        fs::create_dir(canonical_root.join("parent")).expect("destination parent");
        let destination = Path::new("parent/workbench");
        let artifacts = vec![(PathBuf::from("project-view.json"), b"{}".to_vec())];

        let error =
            secure::publish_with_before_install(&canonical_root, destination, &artifacts, || {
                fs::rename(
                    canonical_root.join("parent"),
                    canonical_root.join("moved-parent"),
                )
                .expect("swap original parent");
                fs::create_dir(canonical_root.join("parent")).expect("replacement parent");
            })
            .expect_err("parent identity swap must fail closed");

        assert!(
            error
                .to_string()
                .contains("destination parent identity changed")
        );
        assert!(!canonical_root.join(destination).exists());
        assert!(!canonical_root.join("moved-parent/workbench").exists());
        assert!(
            fs::read_dir(canonical_root.join("moved-parent"))
                .expect("original parent entries")
                .next()
                .is_none()
        );
    }

    #[test]
    fn preexisting_staging_entry_is_never_adopted_and_name_collision_is_retried() {
        let root = tempfile::tempdir().expect("export root");
        let canonical_root = root.path().canonicalize().expect("canonical export root");
        let parent = canonical_root.join("parent");
        fs::create_dir(&parent).expect("destination parent");
        let occupied = parent.join(".occupied.staging");
        fs::create_dir(&occupied).expect("preexisting staging entry");
        fs::write(occupied.join("sentinel"), "owned elsewhere")
            .expect("preexisting staging sentinel");
        let destination = Path::new("parent/workbench");
        let artifacts = vec![(PathBuf::from("project-view.json"), b"{}".to_vec())];

        secure::publish_with_staging_names(
            &canonical_root,
            destination,
            &artifacts,
            [
                OsString::from(".occupied.staging"),
                OsString::from(".owned.staging"),
            ],
        )
        .expect("collision should retry with an exclusively created staging name");

        assert_eq!(
            fs::read_to_string(occupied.join("sentinel")).expect("sentinel retained"),
            "owned elsewhere"
        );
        assert!(!parent.join(".owned.staging").exists());
        assert_eq!(
            fs::read_to_string(parent.join("workbench/project-view.json"))
                .expect("published artifact"),
            "{}"
        );
    }

    #[test]
    fn unsupported_no_clobber_primitive_fails_closed_and_removes_owned_staging() {
        let root = tempfile::tempdir().expect("export root");
        let canonical_root = root.path().canonicalize().expect("canonical export root");
        let parent = canonical_root.join("parent");
        fs::create_dir(&parent).expect("destination parent");
        let destination = Path::new("parent/workbench");
        let artifacts = vec![(PathBuf::from("project-view.json"), b"{}".to_vec())];

        for source in [
            rustix::io::Errno::NOSYS,
            rustix::io::Errno::NOTSUP,
            rustix::io::Errno::OPNOTSUPP,
        ] {
            let error = secure::publish_with_install_error(
                &canonical_root,
                destination,
                &artifacts,
                source,
            )
            .expect_err("unsupported no-clobber primitive must fail closed");

            assert!(matches!(error, WorkbenchError::SafeInstallationUnsupported));
            assert!(!canonical_root.join(destination).exists());
            assert!(
                fs::read_dir(&parent)
                    .expect("destination parent entries")
                    .next()
                    .is_none()
            );
        }
    }

    #[test]
    fn post_install_failure_removes_the_owned_destination() {
        let root = tempfile::tempdir().expect("export root");
        let canonical_root = root.path().canonicalize().expect("canonical export root");
        let parent = canonical_root.join("parent");
        fs::create_dir(&parent).expect("destination parent");
        let destination = Path::new("parent/workbench");
        let artifacts = vec![(PathBuf::from("project-view.json"), b"{}".to_vec())];

        let error = secure::publish_with_post_install_error(
            &canonical_root,
            destination,
            &artifacts,
            rustix::io::Errno::IO,
        )
        .expect_err("post-install failure must fail closed");

        assert!(error.to_string().contains("sync destination parent"));
        assert!(!canonical_root.join(destination).exists());
        assert!(
            fs::read_dir(parent)
                .expect("destination parent entries")
                .next()
                .is_none()
        );
    }

    #[test]
    fn staging_identity_swap_never_removes_the_unrelated_replacement_entry() {
        let root = tempfile::tempdir().expect("export root");
        let canonical_root = root.path().canonicalize().expect("canonical export root");
        let parent = canonical_root.join("parent");
        fs::create_dir(&parent).expect("destination parent");
        let destination = Path::new("parent/workbench");
        let artifacts = vec![(PathBuf::from("project-view.json"), b"{}".to_vec())];
        let replacement_name = std::cell::RefCell::new(None);

        let error =
            secure::publish_with_before_install(&canonical_root, destination, &artifacts, || {
                let staging_name = fs::read_dir(&parent)
                    .expect("staging entries")
                    .map(|entry| entry.expect("staging entry").file_name())
                    .find(|name| name.to_string_lossy().ends_with(".staging"))
                    .expect("created staging name");
                fs::rename(
                    parent.join(&staging_name),
                    parent.join("moved-owned-staging"),
                )
                .expect("move owned staging");
                fs::create_dir(parent.join(&staging_name)).expect("unrelated replacement staging");
                replacement_name.replace(Some(staging_name));
            })
            .expect_err("staging identity swap must fail closed");

        assert!(
            error
                .to_string()
                .contains("staging directory identity changed")
        );
        let replacement_name = replacement_name
            .into_inner()
            .expect("replacement staging name");
        assert!(
            parent.join(replacement_name).is_dir(),
            "cleanup must not remove the unrelated replacement entry"
        );
        assert!(parent.join("moved-owned-staging").is_dir());
        assert!(
            !parent
                .join("moved-owned-staging/project-view.json")
                .exists()
        );
        assert!(!canonical_root.join(destination).exists());
    }
}

#[cfg(not(any(target_os = "linux", target_vendor = "apple")))]
mod secure {
    use super::{Path, PathBuf, WorkbenchError};

    pub(super) fn publish(
        _root: &Path,
        _destination: &Path,
        _artifacts: &[(PathBuf, Vec<u8>)],
    ) -> Result<(), WorkbenchError> {
        Err(WorkbenchError::SafeInstallationUnsupported)
    }
}