rho-coding-agent 3.12.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
use super::{script_value, uploads, Shown, Uploads};
use pretty_assertions::assert_eq;
use rho_browser::cdp::runtime::Evaluated;
use serde_json::json;
use std::path::PathBuf;

/// What `uploads` did with one call.
#[derive(Debug, PartialEq)]
enum Outcome {
    Accepted(Vec<PathBuf>),
    Refused,
}

// Covers: file_upload takes only files inside the upload directory, named
// absolute or relative to it, after following links and `..`: a path that
// climbs out, a link inside that points out, a directory, a missing file,
// no file at all and a missing upload directory are refused. Otherwise a
// page that steers the model could have it upload any file rho can read.
// Owner: browser file_upload paths
#[cfg(unix)]
#[test]
fn uploads_come_only_from_the_upload_directory() {
    let outside = tempfile::tempdir().unwrap();
    let secret = outside.path().join("secret.txt");
    std::fs::write(&secret, "key").unwrap();
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path().canonicalize().unwrap();
    std::fs::write(root.join("a.txt"), "a").unwrap();
    std::fs::create_dir(root.join("docs")).unwrap();
    std::fs::write(root.join("docs/b.txt"), "b").unwrap();
    std::os::unix::fs::symlink(&secret, root.join("leak.txt")).unwrap();
    std::os::unix::fs::symlink(root.join("a.txt"), root.join("alias.txt")).unwrap();
    let paths = |paths: &[&str]| paths.iter().map(PathBuf::from).collect::<Vec<_>>();
    // Both temporary directories share a parent, so this reaches the secret.
    let outside_name = outside.path().canonicalize().unwrap();
    assert_eq!(outside_name.parent(), root.parent());
    let climbing = PathBuf::from("docs/../..")
        .join(outside_name.file_name().unwrap())
        .join("secret.txt");
    let cases = [
        (
            "relative and nested",
            paths(&["a.txt", "docs/b.txt"]),
            Outcome::Accepted(vec![root.join("a.txt"), root.join("docs/b.txt")]),
        ),
        (
            "absolute inside",
            vec![root.join("a.txt")],
            Outcome::Accepted(vec![root.join("a.txt")]),
        ),
        (
            "a link to a file inside",
            paths(&["alias.txt"]),
            Outcome::Accepted(vec![root.join("a.txt")]),
        ),
        ("climbing out", vec![climbing], Outcome::Refused),
        ("absolute outside", vec![secret.clone()], Outcome::Refused),
        (
            "a link pointing out",
            paths(&["leak.txt"]),
            Outcome::Refused,
        ),
        ("a directory", paths(&["docs"]), Outcome::Refused),
        ("a missing file", paths(&["nope.txt"]), Outcome::Refused),
        ("no file", paths(&[]), Outcome::Refused),
    ];
    let mut outcomes: Vec<_> = cases
        .iter()
        .map(|(case, paths, _)| (*case, outcome(uploads(dir.path(), paths))))
        .collect();
    outcomes.push((
        "a missing upload directory",
        outcome(uploads(&root.join("gone"), &paths(&["a.txt"]))),
    ));

    let mut expected: Vec<_> = cases
        .into_iter()
        .map(|(case, _, expected)| (case, expected))
        .collect();
    expected.push(("a missing upload directory", Outcome::Refused));
    assert_eq!(outcomes, expected);
}

fn outcome(uploads: Result<Uploads, String>) -> Outcome {
    match uploads {
        Ok(Uploads(files)) => Outcome::Accepted(files),
        Err(_) => Outcome::Refused,
    }
}

// Covers: javascript_exec says what a script returned the way JavaScript
// writes it: a string as itself, other primitives as their literals,
// `undefined`, `null` and values JSON cannot hold such as `NaN` and
// bigints, objects left for the page to describe, and what a script threw
// with its message. The cases are chrome-headless-shell 158's answers to
// `Runtime.evaluate`. Otherwise the model reads `{}` or nothing for a
// value it asked for, or a failure as success.
// Owner: browser javascript_exec values
#[test]
fn a_script_value_reads_as_javascript_writes_it() {
    let object = json!({"type": "object", "className": "Object", "objectId": "1.1.1"});
    let cases = [
        (
            "a number",
            json!({"result": {"type": "number", "value": 2, "description": "2"}}),
            Ok(Shown::Text("2".into())),
        ),
        (
            "a string",
            json!({"result": {"type": "string", "value": "start"}}),
            Ok(Shown::Text("start".into())),
        ),
        (
            "a boolean",
            json!({"result": {"type": "boolean", "value": true}}),
            Ok(Shown::Text("true".into())),
        ),
        (
            "undefined",
            json!({"result": {"type": "undefined"}}),
            Ok(Shown::Text("undefined".into())),
        ),
        (
            "null",
            json!({"result": {"type": "object", "subtype": "null", "value": null}}),
            Ok(Shown::Text("null".into())),
        ),
        (
            "NaN",
            json!({"result": {"type": "number", "unserializableValue": "NaN", "description": "NaN"}}),
            Ok(Shown::Text("NaN".into())),
        ),
        (
            "a bigint",
            json!({"result": {"type": "bigint", "unserializableValue": "1n", "description": "1n"}}),
            Ok(Shown::Text("1n".into())),
        ),
        (
            "an object",
            json!({"result": object}),
            Ok(Shown::Object(
                serde_json::from_value(object.clone()).unwrap(),
            )),
        ),
        (
            "a thrown error",
            json!({
                "result": {"type": "object", "subtype": "error", "objectId": "1.1.2"},
                "exceptionDetails": {
                    "text": "Uncaught",
                    "exception": {"type": "object", "subtype": "error", "className": "Error", "description": "Error: boom\n    at <anonymous>:1:7", "objectId": "1.1.2"}
                }
            }),
            Err("Error: boom\n    at <anonymous>:1:7".to_owned()),
        ),
        (
            "a thrown string",
            json!({
                "result": {"type": "string", "value": "nope"},
                "exceptionDetails": {"text": "Uncaught", "exception": {"type": "string", "value": "nope"}}
            }),
            Err("nope".to_owned()),
        ),
    ];
    let (shown, expected): (Vec<_>, Vec<_>) = cases
        .into_iter()
        .map(|(case, answer, expected)| {
            let evaluated: Evaluated = serde_json::from_value(answer).unwrap();
            ((case, script_value(&evaluated)), (case, expected))
        })
        .unzip();
    assert_eq!(shown, expected);
}