Skip to content

Building 70 Projects ranging from beginner to advanced so anyone can — learn from, build upon, use as a reference, or even copy directly. Owned by my cybersecurity company 👇

5.3 KB
Raw Blame
// ©AngelaMos | 2026
// wire.rs

use std::time::Duration;

use crate::Ask;

pub const PROMPT_TIMEOUT_SECS: u64 = 180;
pub const PROBE_TIMEOUT_SECS: u64 = 5;
pub const CONTENT_TYPE: &str = "content-type";
pub const APPLICATION_JSON: &str = "application/json";
pub const AUTHORIZATION: &str = "authorization";

pub const PROMPT_TEMPLATE: &str = "\
You are answering ONE question about a C library's public header.

Question: {subject}

Evidence, which is the library's own header text:
{evidence}

Answer with exactly one of these options, copied verbatim:
{options}

Reply with a JSON object of the form {\"choice\": \"<one option>\"} and nothing else. \
If the evidence does not settle the question, pick the option that is safest for a caller \
who must not read or write out of bounds.";

#[derive(Debug, thiserror::Error)]
pub enum WireError {
    #[error("{url} did not answer: {source}")]
    Unreachable {
        url: String,
        source: Box<ureq::Error>,
    },
    #[error("{url} answered with a body this client could not read as JSON: {source}")]
    Unreadable {
        url: String,
        source: Box<ureq::Error>,
    },
    #[error("{url} answered JSON with no {field} field")]
    MissingField { url: String, field: String },
}

#[must_use]
pub fn agent(timeout: Duration) -> ureq::Agent {
    ureq::Agent::config_builder()
        .timeout_global(Some(timeout))
        .build()
        .into()
}

#[must_use]
pub fn prompt(ask: &Ask) -> String {
    let options = ask
        .ballot()
        .iter()
        .map(|option| format!("- {option}"))
        .collect::<Vec<_>>()
        .join("\n");
    PROMPT_TEMPLATE
        .replace("{subject}", ask.subject())
        .replace("{evidence}", ask.evidence())
        .replace("{options}", &options)
}

// The ballot travels to the server as a JSON-schema enum as well as in the prompt. A server that
// honours the schema cannot answer off the ballot at all, which turns the local adjudication from
// the only guard into the second one.
#[must_use]
pub fn schema(ballot: &[String]) -> serde_json::Value {
    serde_json::json!({
        "type": "object",
        "properties": {
            crate::ballot::CHOICE_FIELD: {
                "type": "string",
                "enum": ballot,
            }
        },
        "required": [crate::ballot::CHOICE_FIELD],
    })
}

pub fn post(
    agent: &ureq::Agent,
    url: &str,
    body: &serde_json::Value,
    bearer: Option<&str>,
) -> Result<serde_json::Value, WireError> {
    let mut request = agent.post(url).header(CONTENT_TYPE, APPLICATION_JSON);
    if let Some(token) = bearer {
        request = request.header(AUTHORIZATION, &format!("Bearer {token}"));
    }
    let mut response = request.send_json(body).map_err(|source| {
        let url = url.to_owned();
        WireError::Unreachable {
            url,
            source: Box::new(source),
        }
    })?;
    response
        .body_mut()
        .read_json::<serde_json::Value>()
        .map_err(|source| WireError::Unreadable {
            url: url.to_owned(),
            source: Box::new(source),
        })
}

pub fn get(agent: &ureq::Agent, url: &str) -> Result<serde_json::Value, WireError> {
    let mut response = agent
        .get(url)
        .call()
        .map_err(|source| WireError::Unreachable {
            url: url.to_owned(),
            source: Box::new(source),
        })?;
    response
        .body_mut()
        .read_json::<serde_json::Value>()
        .map_err(|source| WireError::Unreadable {
            url: url.to_owned(),
            source: Box::new(source),
        })
}

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

    fn ask() -> Ask {
        Ask::new(
            "is src a byte buffer or a string",
            "int LZ4_decompress_safe(const char *src, char *dst, int n, int max);",
            vec!["byte_buffer".to_owned(), "nul_terminated_string".to_owned()],
        )
        .expect("valid ask")
    }

    #[test]
    fn the_prompt_carries_the_subject_the_evidence_and_every_option() {
        let text = prompt(&ask());
        assert!(text.contains("is src a byte buffer or a string"));
        assert!(text.contains("LZ4_decompress_safe"));
        assert!(text.contains("- byte_buffer"));
        assert!(text.contains("- nul_terminated_string"));
    }

    #[test]
    fn no_placeholder_survives_into_the_rendered_prompt() {
        let text = prompt(&ask());
        for placeholder in ["{subject}", "{evidence}", "{options}"] {
            assert!(
                !text.contains(placeholder),
                "{placeholder} was never substituted"
            );
        }
    }

    #[test]
    fn the_schema_pins_the_enum_to_exactly_the_ballot() {
        let ballot = vec!["one".to_owned(), "two".to_owned()];
        let built = schema(&ballot);
        let listed = built["properties"][crate::ballot::CHOICE_FIELD]["enum"]
            .as_array()
            .expect("enum is an array");
        assert_eq!(listed.len(), ballot.len());
        for option in &ballot {
            assert!(
                listed.iter().any(|value| value == option),
                "{option} missing from the schema enum"
            );
        }
    }

    #[test]
    fn the_required_field_is_the_one_the_adjudicator_reads() {
        let built = schema(&["one".to_owned()]);
        assert_eq!(built["required"][0], crate::ballot::CHOICE_FIELD);
    }
}