kcode-k1-rust-podman 0.2.3

Synchronous Podman-backed Cargo check and binary build helper.
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
use std::error::Error;
use std::ffi::{OsStr, OsString};
use std::fmt;
use std::fs::{self, DirBuilder};
use std::io;
use std::os::unix::fs::{DirBuilderExt, PermissionsExt};
use std::path::{Path, PathBuf};
use std::process::{Command, ExitStatus};

const FORMAT: &str = "mkdir -p /tmp/home && cargo fmt --all";
const CHECK: &str = "mkdir -p /tmp/home && cargo generate-lockfile && cargo fetch --locked && cargo build --locked && cargo test --locked";
const BUILD: &str = "mkdir -p /tmp/home && cargo build --release --locked --bin \"$K1_BINARY\" && cp -- \"/target/release/$K1_BINARY\" /output/binary";

#[derive(Debug)]
pub struct CommandDiagnostics {
    pub status: ExitStatus,
    pub stdout: Vec<u8>,
    pub stderr: Vec<u8>,
}

#[derive(Debug)]
pub struct FileFailure {
    pub operation: &'static str,
    pub path: PathBuf,
    pub source: io::Error,
}

#[derive(Debug)]
pub enum RustPodmanError {
    InvalidInput {
        field: &'static str,
        reason: String,
    },
    File(FileFailure),
    Spawn(io::Error),
    CommandFailed(CommandDiagnostics),
    AfterCommand {
        diagnostics: CommandDiagnostics,
        failure: FileFailure,
    },
}

impl fmt::Display for RustPodmanError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "{self:?}")
    }
}

impl Error for RustPodmanError {}

#[derive(Clone, Debug)]
pub struct RustPodmanPaths {
    pub workspace: PathBuf,
    pub cargo_home: PathBuf,
    pub target: PathBuf,
    pub local_registry: PathBuf,
    pub cargo_config: PathBuf,
}

impl RustPodmanPaths {
    pub fn new(
        workspace: impl Into<PathBuf>,
        cargo_home: impl Into<PathBuf>,
        target: impl Into<PathBuf>,
        local_registry: impl Into<PathBuf>,
        cargo_config: impl Into<PathBuf>,
    ) -> Self {
        Self {
            workspace: workspace.into(),
            cargo_home: cargo_home.into(),
            target: target.into(),
            local_registry: local_registry.into(),
            cargo_config: cargo_config.into(),
        }
    }
}

#[derive(Clone, Debug)]
pub struct RustPodman {
    program: OsString,
    image: OsString,
}

impl RustPodman {
    pub fn new(
        program: impl Into<OsString>,
        image: impl Into<OsString>,
    ) -> Result<Self, RustPodmanError> {
        let program = program.into();
        let image = image.into();
        require_nonempty(&program, "program")?;
        require_nonempty(&image, "image")?;
        Ok(Self { program, image })
    }

    pub fn format(&self, paths: &RustPodmanPaths) -> Result<CommandDiagnostics, RustPodmanError> {
        let paths = ResolvedPaths::new(paths)?;
        let mut command = self.command(&paths);
        command.arg("--network=none");
        self.run(command, FORMAT)
    }

    pub fn check(&self, paths: &RustPodmanPaths) -> Result<CommandDiagnostics, RustPodmanError> {
        let paths = ResolvedPaths::new(paths)?;
        let diagnostics = self.run(self.command(&paths), CHECK)?;
        if let Err(failure) = ordinary_file(&paths.workspace.join("Cargo.lock")) {
            return Err(after(diagnostics, failure));
        }
        Ok(diagnostics)
    }

    pub fn build_binary(
        &self,
        paths: &RustPodmanPaths,
        binary: &str,
        output: impl AsRef<Path>,
    ) -> Result<CommandDiagnostics, RustPodmanError> {
        valid_binary(binary)?;
        let paths = ResolvedPaths::new(paths)?;
        ordinary_file(&paths.workspace.join("Cargo.lock")).map_err(RustPodmanError::File)?;
        let output = output_location(output.as_ref())?;
        validate_output(&output).map_err(RustPodmanError::File)?;
        let mut stage = StageDir::create(output.parent().unwrap(), output.file_name().unwrap())?;
        let mut command = self.command(&paths);
        command.arg(format!("--env=K1_BINARY={binary}"));
        volume(&mut command, &stage.path, "/output:rw");
        let diagnostics = self.run(command, BUILD)?;
        let staged = stage.path.join("binary");
        if let Err(failure) = ordinary_file(&staged) {
            return Err(after(diagnostics, failure));
        }
        if let Err(failure) = validate_output(&output) {
            return Err(after(diagnostics, failure));
        }
        if let Err(source) = fs::rename(&staged, &output) {
            return Err(after_file(diagnostics, "rename output", &output, source));
        }
        let _ = stage.cleanup();
        Ok(diagnostics)
    }

    fn command(&self, paths: &ResolvedPaths) -> Command {
        let mut command = Command::new(&self.program);
        command.args([
            "run",
            "--rm",
            "--read-only",
            "--userns=keep-id",
            "--cap-drop=ALL",
            "--security-opt=no-new-privileges",
            "--workdir=/workspace",
            "--env=HOME=/tmp/home",
            "--env=CARGO_HOME=/cargo-home",
            "--env=CARGO_TARGET_DIR=/target",
            "--tmpfs=/tmp:rw,nosuid,nodev",
        ]);
        volume(&mut command, &paths.workspace, "/workspace:rw");
        volume(&mut command, &paths.local_registry, "/k1/local-registry:ro");
        volume(&mut command, &paths.cargo_home, "/cargo-home:rw");
        volume(&mut command, &paths.target, "/target:rw");
        volume(
            &mut command,
            &paths.cargo_config,
            "/cargo-home/config.toml:ro",
        );
        command
    }

    fn run(
        &self,
        mut command: Command,
        script: &'static str,
    ) -> Result<CommandDiagnostics, RustPodmanError> {
        let output = command
            .arg("--")
            .arg(&self.image)
            .args(["sh", "-c", script])
            .output()
            .map_err(RustPodmanError::Spawn)?;
        let diagnostics = CommandDiagnostics {
            status: output.status,
            stdout: output.stdout,
            stderr: output.stderr,
        };
        if diagnostics.status.success() {
            Ok(diagnostics)
        } else {
            Err(RustPodmanError::CommandFailed(diagnostics))
        }
    }
}

struct ResolvedPaths {
    workspace: PathBuf,
    cargo_home: PathBuf,
    target: PathBuf,
    local_registry: PathBuf,
    cargo_config: PathBuf,
}

impl ResolvedPaths {
    fn new(paths: &RustPodmanPaths) -> Result<Self, RustPodmanError> {
        let roots = [
            canonical_dir(&paths.workspace, "workspace")?,
            canonical_dir(&paths.cargo_home, "cargo_home")?,
            canonical_dir(&paths.target, "target")?,
            canonical_dir(&paths.local_registry, "local_registry")?,
        ];
        for left in 0..roots.len() {
            for right in left + 1..roots.len() {
                if roots[left].starts_with(&roots[right]) || roots[right].starts_with(&roots[left])
                {
                    return Err(invalid("paths", "directory roots overlap"));
                }
            }
        }
        ordinary_file(&paths.cargo_config).map_err(RustPodmanError::File)?;
        let cargo_config = fs::canonicalize(&paths.cargo_config)
            .map_err(|source| file("canonicalize", &paths.cargo_config, source))?;
        Ok(Self {
            workspace: roots[0].clone(),
            cargo_home: roots[1].clone(),
            target: roots[2].clone(),
            local_registry: roots[3].clone(),
            cargo_config,
        })
    }
}

fn require_nonempty(value: &OsStr, field: &'static str) -> Result<(), RustPodmanError> {
    if value.is_empty() {
        Err(invalid(field, "must not be empty"))
    } else {
        Ok(())
    }
}

fn valid_binary(value: &str) -> Result<(), RustPodmanError> {
    let bytes = value.as_bytes();
    let alphanumeric = |byte: &u8| byte.is_ascii_lowercase() || byte.is_ascii_digit();
    let valid = (1..=250).contains(&bytes.len())
        && alphanumeric(&bytes[0])
        && alphanumeric(&bytes[bytes.len() - 1])
        && bytes.iter().all(|byte| alphanumeric(byte) || *byte == b'-')
        && !bytes.windows(2).any(|pair| pair == b"--");
    if valid {
        Ok(())
    } else {
        Err(invalid(
            "binary",
            "must be lowercase kebab-case of length 1-250",
        ))
    }
}

fn canonical_dir(path: &Path, field: &'static str) -> Result<PathBuf, RustPodmanError> {
    let metadata = fs::symlink_metadata(path).map_err(|source| file("metadata", path, source))?;
    if metadata.file_type().is_symlink() || !metadata.is_dir() {
        return Err(invalid(field, "must be an ordinary nonsymlink directory"));
    }
    fs::canonicalize(path).map_err(|source| file("canonicalize", path, source))
}

fn ordinary_file(path: &Path) -> Result<(), FileFailure> {
    let metadata =
        fs::symlink_metadata(path).map_err(|source| failure("metadata", path, source))?;
    if metadata.file_type().is_symlink() || !metadata.is_file() {
        return Err(failure(
            "validate ordinary file",
            path,
            io::Error::new(
                io::ErrorKind::InvalidInput,
                "not an ordinary nonsymlink file",
            ),
        ));
    }
    Ok(())
}

fn output_location(path: &Path) -> Result<PathBuf, RustPodmanError> {
    let name = path
        .file_name()
        .ok_or_else(|| invalid("output", "must name a file"))?;
    let parent = path
        .parent()
        .filter(|value| !value.as_os_str().is_empty())
        .unwrap_or(Path::new("."));
    Ok(canonical_dir(parent, "output parent")?.join(name))
}

fn validate_output(path: &Path) -> Result<(), FileFailure> {
    match fs::symlink_metadata(path) {
        Ok(metadata) if !metadata.file_type().is_symlink() && metadata.is_file() => Ok(()),
        Ok(_) => Err(failure(
            "validate output",
            path,
            io::Error::new(
                io::ErrorKind::InvalidInput,
                "not absent or an ordinary nonsymlink file",
            ),
        )),
        Err(source) if source.kind() == io::ErrorKind::NotFound => Ok(()),
        Err(source) => Err(failure("metadata", path, source)),
    }
}

fn volume(command: &mut Command, host: &Path, destination: &str) {
    let mut value = host.as_os_str().to_os_string();
    value.push(":");
    value.push(destination);
    command.arg("--volume").arg(value);
}

fn invalid(field: &'static str, reason: impl Into<String>) -> RustPodmanError {
    RustPodmanError::InvalidInput {
        field,
        reason: reason.into(),
    }
}

fn failure(operation: &'static str, path: &Path, source: io::Error) -> FileFailure {
    FileFailure {
        operation,
        path: path.to_path_buf(),
        source,
    }
}

fn file(operation: &'static str, path: &Path, source: io::Error) -> RustPodmanError {
    RustPodmanError::File(failure(operation, path, source))
}

fn after(diagnostics: CommandDiagnostics, failure: FileFailure) -> RustPodmanError {
    RustPodmanError::AfterCommand {
        diagnostics,
        failure,
    }
}

fn after_file(
    diagnostics: CommandDiagnostics,
    operation: &'static str,
    path: &Path,
    source: io::Error,
) -> RustPodmanError {
    after(diagnostics, failure(operation, path, source))
}

struct StageDir {
    path: PathBuf,
    armed: bool,
}

impl StageDir {
    fn create(parent: &Path, output_name: &OsStr) -> Result<Self, RustPodmanError> {
        let mut name = OsString::from(".");
        name.push(output_name);
        name.push(format!(".k1-stage-{}", std::process::id()));
        let path = parent.join(name);
        match fs::symlink_metadata(&path) {
            Ok(metadata) if !metadata.file_type().is_symlink() && metadata.is_dir() => {
                fs::remove_dir_all(&path)
                    .map_err(|source| file("remove stale stage directory", &path, source))?;
            }
            Ok(_) => {
                return Err(file(
                    "validate stage directory",
                    &path,
                    io::Error::new(
                        io::ErrorKind::InvalidInput,
                        "not an ordinary nonsymlink directory",
                    ),
                ));
            }
            Err(source) if source.kind() == io::ErrorKind::NotFound => {}
            Err(source) => return Err(file("metadata", &path, source)),
        }
        DirBuilder::new()
            .mode(0o700)
            .create(&path)
            .map_err(|source| file("create stage directory", &path, source))?;
        if let Err(source) = fs::set_permissions(&path, fs::Permissions::from_mode(0o700)) {
            let _ = fs::remove_dir(&path);
            return Err(file("set stage permissions", &path, source));
        }
        Ok(Self { path, armed: true })
    }

    fn cleanup(&mut self) -> io::Result<()> {
        match fs::remove_dir_all(&self.path) {
            Ok(()) => {
                self.armed = false;
                Ok(())
            }
            Err(source) if source.kind() == io::ErrorKind::NotFound => {
                self.armed = false;
                Ok(())
            }
            Err(source) => Err(source),
        }
    }
}

impl Drop for StageDir {
    fn drop(&mut self) {
        if self.armed {
            let _ = self.cleanup();
            if self.armed {
                let _ = self.cleanup();
            }
        }
    }
}

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

    #[test]
    fn binary_names_use_the_shared_250_character_boundary() {
        for valid in [
            "a".to_owned(),
            "1".to_owned(),
            "a1".to_owned(),
            "one-binary".to_owned(),
            "a".repeat(250),
        ] {
            assert!(valid_binary(&valid).is_ok(), "{valid}");
        }
        for invalid_name in [
            String::new(),
            "A".to_owned(),
            "-a".to_owned(),
            "a-".to_owned(),
            "a--b".to_owned(),
            "a_b".to_owned(),
            "a".repeat(251),
        ] {
            assert!(valid_binary(&invalid_name).is_err(), "{invalid_name}");
        }
    }

    #[test]
    fn ordinary_check_uses_default_cargo_scope() {
        assert_eq!(
            CHECK,
            "mkdir -p /tmp/home && cargo generate-lockfile && cargo fetch --locked && cargo build --locked && cargo test --locked"
        );
        for restriction in [
            "fmt",
            "clippy",
            "--all-targets",
            "--all-features",
            "-D warnings",
            "test --doc",
        ] {
            assert!(
                !CHECK.contains(restriction),
                "unexpected check restriction: {restriction}"
            );
        }
    }
}