llm-bench

"""Task rust_cli: a cctv-tools-shape Rust CLI (tokio + reqwest/rustls + quick-xml) that fetches an
XML device list behind HTTP Digest auth and prints `id|name|ip` per device.

Gates: build (`cargo build`); test (`cargo test` exits 0 with >= 1 passed test, summed over every
`test result:` line); fetches (the binary prints both expected lines AND the harness's mock served
the XML to an authorized request). The mock verifies Digest: username/realm/nonce must match the
challenge and the response is recomputed from admin/secret (MD5 default, also MD5-sess and
SHA-256[-sess]; qop=auth with nc+cnonce, or RFC 2069 without qop); HA2 uses the uri the client
sent, which must name the requested resource (the request-target, or an absolute URL with that
path). Basic admin:secret is accepted too, because the PLAN tells the model the mock accepts
Basic; gate_detail.auth_scheme records which scheme worked. ENV unsets CARGO_TARGET_DIR so the
gate finds target/debug/device-list.
"""
import base64
import hashlib
import os
import re
import socket
import threading
import urllib.parse

from bench.core import tools

CATEGORY = "rust"
GATES = ("build", "test", "fetches")
PORT_TOKEN = None
TOOLSET = tools.RUST_TOOLSET
ENV = {"CARGO_TARGET_DIR": None}

TASK_NAME = "rust_cli"

PLAN = """\
# Task — Build a Rust CLI that fetches + parses XML over HTTP with Digest auth

## Goal
`cargo build` and `cargo test` run green, and the resulting binary fetches an
XML device list from a URL (with HTTP Digest auth), parses it with serde +
quick-xml, and prints one device per line as `id|name|ip`. Mirrors the
cctv-tools shape: Rust + reqwest (rustls) + quick-XML + async (tokio) + a
native binary that talks to an HTTP endpoint.

## Prerequisites
Starter scaffold in the work dir:
  - `Cargo.toml` (package `device-list`, edition 2021, no deps)
  - `src/main.rs` (empty stub: `fn main() {}`)

## Spec — the app to build
A Rust CLI that takes `--url <URL> --user <user> --pass <pass>`, fetches the
URL with HTTP Digest auth, parses the XML response as a list of `<Device>`
elements (each with `<ID>`, `<Name>`, `<IP>`), and prints each as
`id|name|ip` on its own line. Async via tokio; HTTP via reqwest (rustls, no
default features); XML via quick-xml + serde.

### XML format the server returns (Content-Type: application/xml)
  <?xml version="1.0" encoding="UTF-8"?>
  <DeviceList>
    <Device>
      <ID>1</ID>
      <Name>Camera-Front</Name>
      <IP>10.0.0.50</IP>
    </Device>
    <Device>
      <ID>2</ID>
      <Name>Camera-Back</Name>
      <IP>10.0.0.51</IP>
    </Device>
  </DeviceList>

### Files to produce
  Cargo.toml              [package] name="device-list", edition="2021"; [dependencies] tokio (rt-multi-thread + macros), reqwest (rustls, no default features, charset), quick-xml (serde), serde (derive), serde_json (optional, for debug). Binary at src/main.rs.
  src/main.rs             arg parsing (manual or std::env::args -- no clap needed), the async fetch (reqwest with Digest auth), XML parse (quick-xml de::from_str into a Vec<Device>), print `id|name|ip` per line. Use `reqwest::Client` with `.digest()` (the `digest_auth` or reqwest's digest support — use the `digest-auth` feature or handle the 401→retry manually). The simplest path: reqwest doesn't have built-in digest, so use the `digest_auth` crate OR handle the two-step (GET → 401 with WWW-Authenticate → compute response → GET with Authorization) manually. For this bench, either is fine — the mock server's Digest challenge is standard RFC 7616.
  src/parser.rs           the XML types: `#[derive(Debug, Deserialize)] struct DeviceList { #[serde(rename = "Device")] devices: Vec<Device> }` and `#[derive(Debug, Deserialize)] struct Device { #[serde(rename = "ID")] id: String, #[serde(rename = "Name")] name: String, #[serde(rename = "IP")] ip: String }`, plus a `parse_devices(xml: &str) -> Result<DeviceList, quick_xml::DeError>` function.
  src/parser.rs           (same file) a #[test] that parses a sample XML string and asserts 2 devices with the right fields.
  src/main.rs             (same file, in a #[cfg(test)] mod) an integration-ish test that spins up an in-process mock HTTP server (use `std::net::TcpListener` + a tiny thread that writes a raw HTTP response — no extra dep needed), fetches from it, and asserts the parsed output. Keep it simple: the mock can return 200 + the XML directly (skip Digest in the test if it complicates things — the bench's scoring gate handles the Digest path against the harness's mock).

### Constraints
  - Use `reqwest` with `default-features = false, features = ["rustls", "charset"]`. No OpenSSL.
  - Use `quick-xml` with `serde` for parsing (the `serde` feature on quick-xml).
  - Use `tokio` with `features = ["rt-multi-thread", "macros"]` for the async runtime.
  - For Digest auth: the simplest approach is to use the `digest_auth` crate (add it as a dep) to compute the response from the 401's WWW-Authenticate header, then retry with the Authorization header. OR if that's too much, just do Basic auth for the fetch and note Digest as a TODO — the scoring harness's mock accepts Basic too for this bench. **BUT** the plan's intent is Digest; try it.
  - Arg parsing: manual (std::env::args) is fine — no need for clap.
  - The binary must exit 0 on success, non-zero on error.

## Steps
1. Write Cargo.toml with the deps.
2. Write src/parser.rs (the XML types + parse function + a unit test).
3. Write src/main.rs (arg parsing, async fetch, parse, print).
4. `cargo build` — fix compile errors (expect some Rust borrow-checker friction; that's normal).
5. `cargo test` — the parser unit test + the integration test must pass.
6. Optionally test the binary against a real URL (the harness will test it against a mock).

## Acceptance (harness-verified)
1. `cargo build` exits 0.
2. `cargo test` exits 0.
3. The binary, pointed at the harness's mock HTTP server (serves the XML above behind Digest auth at a URL the harness provides), fetches it and prints `1|Camera-Front|10.0.0.50` and `2|Camera-Back|10.0.0.51` on separate lines.

## Out of scope
Tauri (no GUI), keyring (no OS keychain), ONVIF, ISAPI-specific endpoints, batch operations, config files. This is the smallest real cctv-tools-shape — a working fetch+parse CLI.

## Commit
You do not commit; the harness owns the work dir.
"""

STARTER = {
    "Cargo.toml": '''[package]
name = "device-list"
version = "0.1.0"
edition = "2021"

[dependencies]
''',
    "src/main.rs": "fn main() {}\n",
}

REFERENCE = {
    "Cargo.toml": '''[package]
name = "device-list"
version = "0.1.0"
edition = "2021"

[dependencies]
tokio = { version = "1", features = ["rt-multi-thread", "macros"] }
reqwest = { version = "0.13", default-features = false, features = ["rustls", "charset"] }
quick-xml = { version = "0.36", features = ["serialize"] }
serde = { version = "1", features = ["derive"] }
digest_auth = "0.3"
''',
    "src/parser.rs": '''use serde::Deserialize;
use quick_xml::de::from_str;

#[derive(Debug, Deserialize)]
pub struct DeviceList {
    #[serde(rename = "Device")]
    pub devices: Vec<Device>,
}

#[derive(Debug, Deserialize)]
pub struct Device {
    #[serde(rename = "ID")]
    pub id: String,
    #[serde(rename = "Name")]
    pub name: String,
    #[serde(rename = "IP")]
    pub ip: String,
}

pub fn parse_devices(xml: &str) -> Result<DeviceList, quick_xml::de::DeError> {
    from_str(xml)
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn parse_two_devices() {
        let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<DeviceList>
  <Device><ID>1</ID><Name>Camera-Front</Name><IP>10.0.0.50</IP></Device>
  <Device><ID>2</ID><Name>Camera-Back</Name><IP>10.0.0.51</IP></Device>
</DeviceList>"#;
        let list = parse_devices(xml).unwrap();
        assert_eq!(list.devices.len(), 2);
        assert_eq!(list.devices[0].id, "1");
        assert_eq!(list.devices[0].name, "Camera-Front");
        assert_eq!(list.devices[0].ip, "10.0.0.50");
        assert_eq!(list.devices[1].name, "Camera-Back");
    }
}
''',
    "src/main.rs": '''mod parser;

use std::env;
use std::process;

fn parse_args() -> (String, String, String) {
    let mut url = String::new();
    let mut user = String::new();
    let mut pass = String::new();
    let mut args = env::args().skip(1);
    while let Some(arg) = args.next() {
        match arg.as_str() {
            "--url" => { url = args.next().unwrap_or_default(); }
            "--user" => { user = args.next().unwrap_or_default(); }
            "--pass" => { pass = args.next().unwrap_or_default(); }
            _ => {}
        }
    }
    (url, user, pass)
}

async fn fetch_with_digest(url: &str, user: &str, pass: &str) -> Result<String, Box<dyn std::error::Error>> {
    let client = reqwest::Client::builder()
        .build()?;
    // First request — get the 401 + WWW-Authenticate.
    let resp = client.get(url).send().await?;
    if resp.status() == 401 {
        let www_auth = resp.headers().get("www-authenticate")
            .and_then(|v| v.to_str().ok())
            .ok_or("no WWW-Authenticate header")?;
        // Parse the challenge + compute the digest response.
        let mut prompt = digest_auth::parse(www_auth)?;
        let ctx = digest_auth::AuthContext::new(user, pass, url);
        let auth_header = prompt.respond(&ctx)?;
        let resp2 = client.get(url)
            .header("Authorization", auth_header.to_header_string())
            .send().await?;
        let body = resp2.text().await?;
        Ok(body)
    } else {
        let body = resp.text().await?;
        Ok(body)
    }
}

#[tokio::main]
async fn main() {
    let (url, user, pass) = parse_args();
    if url.is_empty() {
        eprintln!("usage: device-list --url <URL> --user <user> --pass <pass>");
        process::exit(1);
    }
    let xml = match fetch_with_digest(&url, &user, &pass).await {
        Ok(x) => x,
        Err(e) => { eprintln!("fetch error: {e}"); process::exit(1); }
    };
    let list = match parser::parse_devices(&xml) {
        Ok(l) => l,
        Err(e) => { eprintln!("parse error: {e}"); process::exit(1); }
    };
    for d in list.devices {
        println!("{}|{}|{}", d.id, d.name, d.ip);
    }
}
''',
}

def _has_real_app(work_dir):
    main_rs = os.path.join(work_dir, "src", "main.rs")
    if not os.path.isfile(main_rs): return False
    with open(main_rs) as f:
        src = f.read()
    return "tokio" in src and "reqwest" in src and "parse_devices" in src


_DIGEST_PARAM = re.compile(r'([A-Za-z0-9_-]+)\s*=\s*(?:"((?:[^"\\]|\\.)*)"|([^\s,]*))')
_HASHES = {"MD5": hashlib.md5, "SHA-256": hashlib.sha256}


def parse_digest(header_value):
    """Parse `Digest k=v, k="v", ...` into a lower-cased-key dict (None if not Digest)."""
    if not header_value or not header_value.strip().lower().startswith("digest "):
        return None
    rest = header_value.strip()[len("digest "):]
    out = {}
    for m in _DIGEST_PARAM.finditer(rest):
        v = m.group(2) if m.group(2) is not None else m.group(3)
        out[m.group(1).lower()] = v.replace('\\"', '"') if v is not None else ""
    return out


def check_authorization(method, target, header, *, user, password, realm, nonce):
    """(ok, scheme, why) for one request's Authorization header."""
    if not header:
        return False, None, "no Authorization header"
    h = header.strip()
    if h.lower().startswith("basic "):
        try:
            cred = base64.b64decode(h[6:].strip()).decode("utf-8", "replace")
        except Exception:
            return False, "basic", "undecodable Basic credentials"
        if cred == f"{user}:{password}":
            return True, "basic", "basic credentials ok"
        return False, "basic", "wrong Basic credentials"
    p = parse_digest(h)
    if p is None:
        return False, "other", "unsupported auth scheme"
    missing = [k for k in ("username", "realm", "nonce", "uri", "response") if not p.get(k)]
    if missing:
        return False, "digest", "Digest header missing " + ",".join(missing)
    if p["username"] != user:
        return False, "digest", "wrong username"
    if p["realm"] != realm:
        return False, "digest", "realm mismatch"
    if p["nonce"] != nonce:
        return False, "digest", "nonce mismatch"
    uri = p["uri"]
    up = urllib.parse.urlsplit(uri)
    uri_path = (up.path or "/") + ("?" + up.query if up.query else "") if up.scheme else uri
    if uri_path != target:
        return False, "digest", f"uri {uri!r} does not name {target!r}"
    alg = (p.get("algorithm") or "MD5").upper()
    sess = alg.endswith("-SESS")
    hfn = _HASHES.get(alg[:-5] if sess else alg)
    if hfn is None:
        return False, "digest", f"unsupported algorithm {alg}"
    H = lambda s: hfn(s.encode()).hexdigest()  # noqa: E731
    ha1 = H(f"{user}:{realm}:{password}")
    qop = p.get("qop")
    if sess:
        if not p.get("cnonce"):
            return False, "digest", "-sess without cnonce"
        ha1 = H(f"{ha1}:{nonce}:{p['cnonce']}")
    ha2 = H(f"{method}:{uri}")
    if qop:
        if qop.lower() != "auth":
            return False, "digest", f"unsupported qop {qop}"
        if not p.get("nc") or not p.get("cnonce"):
            return False, "digest", "qop=auth without nc/cnonce"
        expected = H(f"{ha1}:{nonce}:{p['nc']}:{p['cnonce']}:{qop}:{ha2}")
    else:
        expected = H(f"{ha1}:{nonce}:{ha2}")
    if p["response"].lower() != expected:
        return False, "digest", "wrong Digest response hash"
    return True, "digest", "digest response ok"


class _DigestMockServer:
    """A tiny HTTP server that serves the XML behind Digest auth (credentials verified;
    Basic admin:secret also accepted, as the PLAN promises)."""
    XML_BODY = (
        '<?xml version="1.0" encoding="UTF-8"?>\n'
        '<DeviceList>\n'
        '  <Device><ID>1</ID><Name>Camera-Front</Name><IP>10.0.0.50</IP></Device>\n'
        '  <Device><ID>2</ID><Name>Camera-Back</Name><IP>10.0.0.51</IP></Device>\n'
        '</DeviceList>'
    )
    REALM = "test"
    NONCE = "abc123"
    CHALLENGE = 'Digest realm="test", qop="auth", nonce="abc123", opaque=""'

    def __init__(self, user="admin", password="secret"):
        self.user, self.password = user, password
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.bind(("127.0.0.1", 0))
        self.port = self.sock.getsockname()[1]
        self.sock.listen(4)
        self.sock.settimeout(0.2)
        self.thread = threading.Thread(target=self._serve, daemon=True)
        self.running = True
        self.auth_log = []
        self.served_xml = 0

    def start(self): self.thread.start()

    def stop(self):
        self.running = False
        self.thread.join(timeout=5)
        try: self.sock.close()
        except OSError: pass

    @staticmethod
    def _read_head(conn):
        data = b""
        while b"\r\n\r\n" not in data and len(data) < 65536:
            chunk = conn.recv(4096)
            if not chunk:
                break
            data += chunk
        return data.split(b"\r\n\r\n", 1)[0].decode("iso-8859-1")

    def _serve(self):
        while self.running:
            try:
                conn, _ = self.sock.accept()
            except socket.timeout:
                continue
            except OSError:
                break
            try:
                conn.settimeout(5)
                lines = self._read_head(conn).split("\r\n")
                parts = lines[0].split(" ") if lines else []
                method = parts[0] if parts else ""
                target = parts[1] if len(parts) > 1 else ""
                headers = {}
                for ln in lines[1:]:
                    if ":" in ln:
                        k, v = ln.split(":", 1)
                        headers[k.strip().lower()] = v.strip()
                ok, scheme, why = check_authorization(
                    method, target, headers.get("authorization"), user=self.user,
                    password=self.password, realm=self.REALM, nonce=self.NONCE)
                self.auth_log.append({"scheme": scheme, "ok": ok, "why": why})
                if not ok:
                    resp = (
                        "HTTP/1.1 401 Unauthorized\r\n"
                        f"WWW-Authenticate: {self.CHALLENGE}\r\n"
                        "Content-Length: 0\r\n"
                        "Connection: close\r\n"
                        "\r\n"
                    )
                    conn.sendall(resp.encode())
                else:
                    body = self.XML_BODY.encode()
                    resp = (
                        "HTTP/1.1 200 OK\r\n"
                        "Content-Type: application/xml\r\n"
                        f"Content-Length: {len(body)}\r\n"
                        "Connection: close\r\n"
                        "\r\n"
                    )
                    conn.sendall(resp.encode() + body)
                    self.served_xml += 1
            except Exception:
                pass
            finally:
                conn.close()


def gates(ws, port=None):
    """Return ({gate_name: bool}, detail)."""
    g = {k: False for k in GATES}
    if not _has_real_app(ws.dir):
        return g, {"reason": "no real app present (src/main.rs lacks tokio/reqwest/parse_devices)"}
    bt, d = tools.build_test_gates(ws, TOOLSET, "cargo test", tools.cargo_tests_passed)
    g.update(bt)
    # fetches gate: run the binary against the mock server
    binpath = os.path.join(ws.dir, "target", "debug", "device-list")
    if not os.path.isfile(binpath):
        d["fetches"] = "no target/debug/device-list"
        return g, d
    srv = _DigestMockServer(); srv.start()
    try:
        url = f"http://127.0.0.1:{srv.port}/"
        r = ws.run([binpath, "--url", url, "--user", srv.user, "--pass", srv.password], 30)
        out = r.out.strip()
        lines_ok = ("1|Camera-Front|10.0.0.50" in out and
                    "2|Camera-Back|10.0.0.51" in out)
        g["fetches"] = lines_ok and srv.served_xml > 0
        oks = [a for a in srv.auth_log if a["ok"]]
        d["auth_scheme"] = oks[-1]["scheme"] if oks else None
        d["auth_log"] = srv.auth_log[-4:]
        if not g["fetches"]:
            d["fetch_detail"] = (f"exit={r.rc} timeout={r.timed_out} served_xml={srv.served_xml} "
                                 f"stdout={out[:200]} stderr={r.err[:200]}")
    finally:
        srv.stop()
    return g, d