Skip to main content

kcode_k1_web_podman/
lib.rs

1use kcode_k1_web_checker_protocol::{
2    Outcome, Report, Request, SCHEMA_VERSION, SelectionInput, WebIdInput, decode_report,
3    encode_report, encode_request,
4};
5use nix::sys::signal::{Signal, killpg};
6use nix::unistd::Pid;
7use sha2::{Digest, Sha256};
8use std::error::Error;
9use std::ffi::OsString;
10use std::fmt;
11use std::fs;
12use std::io::{self, Write};
13use std::os::unix::ffi::OsStrExt;
14use std::os::unix::fs::PermissionsExt;
15use std::os::unix::process::CommandExt;
16use std::path::{Component, Path, PathBuf};
17use std::process::{Command, ExitStatus, Stdio};
18use std::sync::mpsc::{self, RecvTimeoutError};
19use std::thread;
20use std::time::{Duration, Instant};
21
22const CANDIDATE: &str = "/k1/input/candidate";
23const ADMITTED: &str = "/k1/input/admitted";
24const PROJECTION: &str = "/k1/input/public";
25const CHECKER: &str = "/k1/bin/web-checker";
26const DATA_OPTIONS: &str = "ro,nosuid,nodev,noexec";
27const CHECKER_OPTIONS: &str = "ro,nosuid,nodev";
28
29#[derive(Clone)]
30pub struct WebPodmanConfig {
31    pub podman: PathBuf,
32    pub image: String,
33    pub checker: PathBuf,
34    pub chromium: PathBuf,
35    pub chromium_version: String,
36    pub cpu_millis: u32,
37    pub memory_bytes: u64,
38    pub pids_limit: u32,
39    pub tmpfs_bytes: u64,
40    pub shm_bytes: u64,
41    pub checker_timeout: Duration,
42    pub wall_timeout: Duration,
43}
44
45pub struct CheckInput {
46    pub candidate: WebIdInput,
47    pub candidate_root: PathBuf,
48    pub projection_root: PathBuf,
49    pub entry: String,
50    pub tests: String,
51    pub selections: Vec<SelectionInput>,
52}
53
54#[derive(Debug)]
55pub struct CommandDiagnostics {
56    pub status: ExitStatus,
57    pub stdout: Vec<u8>,
58    pub stderr: Vec<u8>,
59}
60
61pub struct CheckOutput {
62    pub diagnostics: CommandDiagnostics,
63    pub report: Report,
64}
65
66#[derive(Debug)]
67pub enum WebPodmanError {
68    InvalidInput {
69        field: &'static str,
70        reason: String,
71    },
72    Spawn(io::Error),
73    Process(String),
74    Timeout {
75        diagnostics: CommandDiagnostics,
76        kill_failure: Option<String>,
77    },
78    Infrastructure {
79        diagnostics: CommandDiagnostics,
80        report: Option<Box<Report>>,
81        reason: String,
82    },
83}
84
85impl fmt::Display for WebPodmanError {
86    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87        write!(f, "{self:?}")
88    }
89}
90
91impl Error for WebPodmanError {}
92
93pub struct WebPodman {
94    config: WebPodmanConfig,
95    checker_digest: String,
96    image_digest: String,
97    policy_identity: String,
98    frozen_policy_identity: String,
99    args: Vec<OsString>,
100}
101
102impl WebPodman {
103    pub fn new(mut config: WebPodmanConfig) -> Result<Self, WebPodmanError> {
104        config.podman = host_path(&config.podman, "podman", false, true)?;
105        config.checker = host_path(&config.checker, "checker", false, true)?;
106        container_path(&config.chromium, "chromium")?;
107        if config.chromium_version.is_empty()
108            || config.chromium_version.trim() != config.chromium_version
109            || config.chromium_version.chars().any(char::is_control)
110        {
111            return Err(invalid(
112                "chromium_version",
113                "must be nonempty trimmed text without controls",
114            ));
115        }
116        let image_digest = image_identity(&config.image)?;
117        let timeout_ms = milliseconds(config.checker_timeout, "checker_timeout")?;
118        let wall_ms = milliseconds(config.wall_timeout, "wall_timeout")?;
119        if wall_ms < timeout_ms {
120            return Err(invalid("wall_timeout", "must not precede checker_timeout"));
121        }
122        let checker_digest = file_digest(&config.checker, "checker")?;
123        let args = run_args(&config);
124        let policy_identity = make_policy_identity(
125            b"k1-web-podman-policy-v1",
126            &args,
127            &[
128                CANDIDATE,
129                DATA_OPTIONS,
130                PROJECTION,
131                DATA_OPTIONS,
132                CHECKER,
133                CHECKER_OPTIONS,
134            ],
135            &config.chromium,
136            timeout_ms,
137            wall_ms,
138        );
139        let frozen_policy_identity = make_policy_identity(
140            b"k1-web-podman-frozen-policy-v1",
141            &args,
142            &[
143                "candidate",
144                CANDIDATE,
145                DATA_OPTIONS,
146                "admitted",
147                ADMITTED,
148                DATA_OPTIONS,
149                "public",
150                PROJECTION,
151                DATA_OPTIONS,
152                "checker",
153                CHECKER,
154                CHECKER_OPTIONS,
155                "request_projection",
156                ADMITTED,
157            ],
158            &config.chromium,
159            timeout_ms,
160            wall_ms,
161        );
162        Ok(Self {
163            config,
164            checker_digest,
165            image_digest,
166            policy_identity,
167            frozen_policy_identity,
168            args,
169        })
170    }
171
172    pub fn checker_digest(&self) -> &str {
173        &self.checker_digest
174    }
175    pub fn image_identity(&self) -> &str {
176        &self.config.image
177    }
178    pub fn image_digest(&self) -> &str {
179        &self.image_digest
180    }
181    pub fn chromium_version(&self) -> &str {
182        &self.config.chromium_version
183    }
184    pub fn command_policy_identity(&self) -> &str {
185        &self.policy_identity
186    }
187    pub fn frozen_command_policy_identity(&self) -> &str {
188        &self.frozen_policy_identity
189    }
190
191    pub fn check(&self, input: CheckInput) -> Result<CheckOutput, WebPodmanError> {
192        self.check_with_public(input, None)
193    }
194
195    pub fn check_frozen(
196        &self,
197        input: CheckInput,
198        public_projection_root: impl AsRef<Path>,
199    ) -> Result<CheckOutput, WebPodmanError> {
200        self.check_with_public(input, Some(public_projection_root.as_ref()))
201    }
202
203    fn check_with_public(
204        &self,
205        input: CheckInput,
206        public_projection_root: Option<&Path>,
207    ) -> Result<CheckOutput, WebPodmanError> {
208        let candidate = host_path(&input.candidate_root, "candidate_root", true, false)?;
209        let projection = host_path(&input.projection_root, "projection_root", true, false)?;
210        let public = public_projection_root
211            .map(|path| host_path(path, "public_projection_root", true, false))
212            .transpose()?;
213        if public.is_none()
214            && (overlaps(&candidate, &projection)
215                || self.config.checker.starts_with(&candidate)
216                || self.config.checker.starts_with(&projection))
217        {
218            return Err(invalid("paths", "mounted host paths overlap"));
219        }
220        let checker = host_path(&self.config.checker, "checker", false, true)?;
221        if file_digest(&checker, "checker")? != self.checker_digest {
222            return Err(invalid("checker", "bytes changed after construction"));
223        }
224        let request_projection = if let Some(public) = &public {
225            let paths = [
226                candidate.as_path(),
227                projection.as_path(),
228                public.as_path(),
229                checker.as_path(),
230            ];
231            let overlapping = paths
232                .iter()
233                .enumerate()
234                .any(|(index, left)| paths[index + 1..].iter().any(|right| overlaps(left, right)));
235            if overlapping {
236                return Err(invalid("paths", "mounted host paths overlap"));
237            }
238            ADMITTED
239        } else {
240            PROJECTION
241        };
242        let request = Request {
243            schema: SCHEMA_VERSION,
244            candidate: input.candidate,
245            candidate_root: PathBuf::from(CANDIDATE),
246            projection_root: PathBuf::from(request_projection),
247            entry: input.entry,
248            tests: input.tests,
249            selections: input.selections,
250            chromium: self.config.chromium.clone(),
251            timeout_ms: self.config.checker_timeout.as_millis() as u64,
252        };
253        let bytes = encode_request(&request)
254            .map_err(|source| invalid("request", format!("cannot encode: {source}")))?;
255        let mut command = Command::new(&self.config.podman);
256        command.args(&self.args);
257        volume(&mut command, &candidate, CANDIDATE, DATA_OPTIONS);
258        if let Some(public) = &public {
259            volume(&mut command, &projection, ADMITTED, DATA_OPTIONS);
260            volume(&mut command, public, PROJECTION, DATA_OPTIONS);
261        } else {
262            volume(&mut command, &projection, PROJECTION, DATA_OPTIONS);
263        }
264        volume(&mut command, &checker, CHECKER, CHECKER_OPTIONS);
265        command.arg("--").arg(&self.config.image).arg(CHECKER);
266        let diagnostics = self.execute(command, bytes)?;
267        let report = match decode_report(&diagnostics.stdout) {
268            Ok(report) => report,
269            Err(source) => {
270                return Err(infrastructure(
271                    diagnostics,
272                    None,
273                    format!("invalid report: {source}"),
274                ));
275            }
276        };
277        if report.schema != SCHEMA_VERSION {
278            return Err(infrastructure(
279                diagnostics,
280                Some(report),
281                "report schema mismatch",
282            ));
283        }
284        let canonical = match encode_report(&report) {
285            Ok(canonical) => canonical,
286            Err(source) => {
287                return Err(infrastructure(
288                    diagnostics,
289                    None,
290                    format!("cannot re-encode report: {source}"),
291                ));
292            }
293        };
294        if canonical != diagnostics.stdout {
295            return Err(infrastructure(
296                diagnostics,
297                Some(report),
298                "report is not canonical",
299            ));
300        }
301        let matching = matches!(
302            (diagnostics.status.code(), &report.outcome),
303            (Some(0), Outcome::Success) | (Some(1), Outcome::Failure { .. })
304        );
305        if !matching {
306            return Err(infrastructure(
307                diagnostics,
308                Some(report),
309                "status and outcome mismatch",
310            ));
311        }
312        Ok(CheckOutput {
313            diagnostics,
314            report,
315        })
316    }
317
318    fn execute(
319        &self,
320        mut command: Command,
321        bytes: Vec<u8>,
322    ) -> Result<CommandDiagnostics, WebPodmanError> {
323        command
324            .process_group(0)
325            .stdin(Stdio::piped())
326            .stdout(Stdio::piped())
327            .stderr(Stdio::piped());
328        let started = Instant::now();
329        let mut child = command.spawn().map_err(WebPodmanError::Spawn)?;
330        let pid = Pid::from_raw(child.id() as i32);
331        let mut stdin = child.stdin.take().expect("piped stdin");
332        let writer = thread::spawn(move || stdin.write_all(&bytes));
333        let (sender, receiver) = mpsc::sync_channel(1);
334        let waiter = thread::spawn(move || sender.send(child.wait_with_output()));
335        let remaining = self.config.wall_timeout.saturating_sub(started.elapsed());
336        let (result, timed_out, kill_failure) = match receiver.recv_timeout(remaining) {
337            Ok(result) => (result, false, None),
338            Err(RecvTimeoutError::Timeout) => {
339                let failure = killpg(pid, Signal::SIGKILL)
340                    .err()
341                    .map(|source| source.to_string());
342                let result = receiver
343                    .recv()
344                    .map_err(|source| WebPodmanError::Process(source.to_string()))?;
345                (result, true, failure)
346            }
347            Err(source) => return Err(WebPodmanError::Process(source.to_string())),
348        };
349        waiter
350            .join()
351            .map_err(|_| WebPodmanError::Process("wait thread panicked".to_owned()))?
352            .map_err(|source| WebPodmanError::Process(source.to_string()))?;
353        let write_failure = match writer.join() {
354            Ok(Ok(())) => None,
355            Ok(Err(source)) => Some(format!("stdin: {source}")),
356            Err(_) => Some("stdin thread panicked".to_owned()),
357        };
358        let output = result.map_err(|source| WebPodmanError::Process(source.to_string()))?;
359        let diagnostics = CommandDiagnostics {
360            status: output.status,
361            stdout: output.stdout,
362            stderr: output.stderr,
363        };
364        if timed_out {
365            return Err(WebPodmanError::Timeout {
366                diagnostics,
367                kill_failure,
368            });
369        }
370        if let Some(reason) = write_failure {
371            return Err(infrastructure(diagnostics, None, reason));
372        }
373        Ok(diagnostics)
374    }
375}
376
377fn run_args(config: &WebPodmanConfig) -> Vec<OsString> {
378    let mut args = [
379        "--remote=false",
380        "run",
381        "--rm",
382        "--pull=never",
383        "--network=none",
384        "--read-only",
385        "--userns=keep-id",
386        "--cap-drop=ALL",
387        "--security-opt=no-new-privileges",
388        "--http-proxy=false",
389        "--ipc=private",
390        "--workdir=/tmp",
391        "--env=HOME=/tmp/home",
392        "--env=TMPDIR=/tmp",
393    ]
394    .into_iter()
395    .map(OsString::from)
396    .collect::<Vec<_>>();
397    if config.cpu_millis != 0 {
398        args.push(
399            format!(
400                "--cpus={}.{:03}",
401                config.cpu_millis / 1000,
402                config.cpu_millis % 1000
403            )
404            .into(),
405        );
406    }
407    if config.memory_bytes != 0 {
408        args.push(format!("--memory={}", config.memory_bytes).into());
409        args.push(format!("--memory-swap={}", config.memory_bytes).into());
410    }
411    if config.pids_limit != 0 {
412        args.push(format!("--pids-limit={}", config.pids_limit).into());
413    }
414    let tmpfs = if config.tmpfs_bytes == 0 {
415        "--tmpfs=/tmp:rw,nosuid,nodev,noexec".to_owned()
416    } else {
417        format!(
418            "--tmpfs=/tmp:rw,nosuid,nodev,noexec,size={}",
419            config.tmpfs_bytes
420        )
421    };
422    args.push(tmpfs.into());
423    if config.shm_bytes != 0 {
424        args.push(format!("--shm-size={}", config.shm_bytes).into());
425    }
426    args
427}
428
429fn host_path(
430    path: &Path,
431    field: &'static str,
432    directory: bool,
433    executable: bool,
434) -> Result<PathBuf, WebPodmanError> {
435    if !path.is_absolute() || path.as_os_str().as_bytes().contains(&b':') {
436        return Err(invalid(field, "must be an absolute colon-free path"));
437    }
438    let metadata = fs::symlink_metadata(path)
439        .map_err(|source| invalid(field, format!("metadata failed: {source}")))?;
440    let ordinary = if directory {
441        metadata.is_dir()
442    } else {
443        metadata.is_file()
444    };
445    if metadata.file_type().is_symlink() || !ordinary {
446        return Err(invalid(
447            field,
448            "must be an ordinary nonsymlink path of the required kind",
449        ));
450    }
451    if executable && metadata.permissions().mode() & 0o111 == 0 {
452        return Err(invalid(field, "must be executable"));
453    }
454    let canonical = fs::canonicalize(path)
455        .map_err(|source| invalid(field, format!("canonicalization failed: {source}")))?;
456    if canonical != path {
457        return Err(invalid(
458            field,
459            "must be canonical and contain no symlink component",
460        ));
461    }
462    Ok(canonical)
463}
464
465fn container_path(path: &Path, field: &'static str) -> Result<(), WebPodmanError> {
466    let clean = path.is_absolute()
467        && path.to_str().is_some()
468        && path
469            .components()
470            .filter(|part| matches!(part, Component::Normal(_)))
471            .count()
472            > 0
473        && path
474            .components()
475            .all(|part| matches!(part, Component::RootDir | Component::Normal(_)));
476    if clean {
477        Ok(())
478    } else {
479        Err(invalid(field, "must be a normalized absolute UTF-8 path"))
480    }
481}
482
483fn image_identity(value: &str) -> Result<String, WebPodmanError> {
484    if value.is_empty()
485        || value.trim() != value
486        || value.bytes().any(|byte| !byte.is_ascii_graphic())
487    {
488        return Err(invalid(
489            "image",
490            "must be a nonempty trimmed ordinary image reference",
491        ));
492    }
493    if let Some((name, digest)) = value.rsplit_once("@sha256:") {
494        let canonical = !name.is_empty()
495            && !name.contains('@')
496            && digest.len() == 64
497            && digest
498                .bytes()
499                .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte));
500        if canonical {
501            return Ok(format!("sha256:{digest}"));
502        }
503    }
504    let mut hash = Sha256::new();
505    add(&mut hash, b"k1-web-podman-image-reference-v1");
506    add(&mut hash, value.as_bytes());
507    Ok(finish(hash))
508}
509
510fn milliseconds(value: Duration, field: &'static str) -> Result<u64, WebPodmanError> {
511    let millis = value.as_millis();
512    if value.is_zero()
513        || !value.subsec_nanos().is_multiple_of(1_000_000)
514        || millis > u64::MAX as u128
515    {
516        Err(invalid(
517            field,
518            "must be a positive whole number of milliseconds",
519        ))
520    } else {
521        Ok(millis as u64)
522    }
523}
524
525fn file_digest(path: &Path, field: &'static str) -> Result<String, WebPodmanError> {
526    let bytes =
527        fs::read(path).map_err(|source| invalid(field, format!("read failed: {source}")))?;
528    let mut hash = Sha256::new();
529    hash.update(bytes);
530    Ok(finish(hash))
531}
532
533fn overlaps(left: &Path, right: &Path) -> bool {
534    left.starts_with(right) || right.starts_with(left)
535}
536
537fn volume(command: &mut Command, host: &Path, target: &str, options: &str) {
538    let mut value = host.as_os_str().to_os_string();
539    value.push(format!(":{target}:{options}"));
540    command.arg("--volume").arg(value);
541}
542
543fn make_policy_identity(
544    tag: &[u8],
545    args: &[OsString],
546    bindings: &[&str],
547    chromium: &Path,
548    checker_ms: u64,
549    wall_ms: u64,
550) -> String {
551    let mut hash = Sha256::new();
552    add(&mut hash, tag);
553    for arg in args {
554        add(&mut hash, arg.as_bytes());
555    }
556    for value in bindings {
557        add(&mut hash, value.as_bytes());
558    }
559    add(&mut hash, chromium.as_os_str().as_bytes());
560    add(&mut hash, &checker_ms.to_be_bytes());
561    add(&mut hash, &wall_ms.to_be_bytes());
562    finish(hash)
563}
564
565fn add(hash: &mut Sha256, value: &[u8]) {
566    hash.update((value.len() as u64).to_be_bytes());
567    hash.update(value);
568}
569
570fn finish(hash: Sha256) -> String {
571    let mut value = String::from("sha256:");
572    for byte in hash.finalize() {
573        value.push_str(&format!("{byte:02x}"));
574    }
575    value
576}
577
578fn invalid(field: &'static str, reason: impl Into<String>) -> WebPodmanError {
579    WebPodmanError::InvalidInput {
580        field,
581        reason: reason.into(),
582    }
583}
584
585fn infrastructure(
586    diagnostics: CommandDiagnostics,
587    report: Option<Report>,
588    reason: impl Into<String>,
589) -> WebPodmanError {
590    WebPodmanError::Infrastructure {
591        diagnostics,
592        report: report.map(Box::new),
593        reason: reason.into(),
594    }
595}
596
597#[cfg(test)]
598mod tests;