//! A small same-origin web lesson. All proof verification is delegated to the //! unchanged Ragu-backed ChainLab; there is no proof generation in this service. use std::{ io::Read, panic::{AssertUnwindSafe, catch_unwind}, time::Instant, }; use pulldown_cmark::{Options, Parser, html}; use recursive_demo::{ChainLab, Statement}; use serde::Deserialize; use serde_json::{Value, json}; use sha2::{Digest, Sha256}; pub mod feedback; pub const MAX_BODY_BYTES: usize = 256; pub const PROOF: &[u8] = include_bytes!("../assets/chain-2.bin"); const PAGE: &str = include_str!("../assets/index.html"); const STYLE: &str = include_str!("../assets/style.css"); const SCRIPT: &str = include_str!("../assets/app.mjs"); const LESSON: &str = include_str!("../../../lessons/ipa/README.md"); #[derive(Debug)] pub struct Reply { pub status: u16, pub content_type: &'static str, pub body: Vec, } impl Reply { fn content(status: u16, content_type: &'static str, body: impl Into>) -> Self { Self { status, content_type, body: body.into(), } } fn json(status: u16, body: Value) -> Self { Self::content(status, "application/json; charset=utf-8", body.to_string()) } pub fn error(status: u16, category: &str, message: &str) -> Self { // Errors deliberately have no `verified` field: they are not a rejection. Self::json(status, json!({"status": category, "message": message})) } } #[derive(Deserialize)] #[serde(deny_unknown_fields)] struct VerifyRequest { claimed_final: String, } fn parse_claim(body: &[u8]) -> Result { if body.len() > MAX_BODY_BYTES { return Err(Reply::error( 413, "invalid_input", "The request is too large.", )); } let request: VerifyRequest = serde_json::from_slice(body).map_err(|_| { Reply::error( 400, "invalid_input", "Send only claimed_final as a JSON string.", ) })?; let value = &request.claimed_final; if value.is_empty() || value.len() > 20 || !value.bytes().all(|b| b.is_ascii_digit()) { return Err(invalid_number()); } value .parse::() .map(|n| n.to_string()) .map_err(|_| invalid_number()) } fn invalid_number() -> Reply { Reply::error( 422, "invalid_input", "Enter a whole number from 0 to 18446744073709551615.", ) } pub fn read_body(reader: impl Read) -> Result, Reply> { read_body_limit(reader, MAX_BODY_BYTES) } pub fn read_body_limit(reader: impl Read, limit: usize) -> Result, Reply> { let mut body = Vec::with_capacity(limit + 1); reader .take((limit + 1) as u64) .read_to_end(&mut body) .map_err(|_| Reply::error(400, "invalid_input", "The request body could not be read."))?; if body.len() > limit { return Err(Reply::error( 413, "invalid_input", "The request is too large.", )); } Ok(body) } /// Initialized once at process startup, then borrowed by every request. pub struct WebLab { verifier: ChainLab, proof_sha256: String, page: String, lesson: String, } impl WebLab { pub fn initialize() -> Result { let verifier = ChainLab::new()?; // Fail startup if the bundled artifact or pinned application is wrong. // This is a real verification, not a rule used to answer HTTP requests. if !verifier.verify(PROOF, &statement("52"))? { return Err("bundled two-step proof failed startup verification".into()); } let proof_sha256 = format!("{:x}", Sha256::digest(PROOF)); let page = PAGE.replace("__PROOF_SHA256__", &proof_sha256); let lesson = markdown_page("The deeper IPA lesson", LESSON); Ok(Self { verifier, proof_sha256, page, lesson, }) } pub fn proof_sha256(&self) -> &str { &self.proof_sha256 } pub fn verify_body(&self, body: &[u8]) -> Reply { let claim = match parse_claim(body) { Ok(claim) => claim, Err(reply) => return reply, }; let expected = statement(&claim); verification_reply(&claim, &self.proof_sha256, || { self.verifier.verify(PROOF, &expected) }) } pub fn get(&self, path: &str) -> Reply { match path { "/" => Reply::content(200, "text/html; charset=utf-8", self.page.as_bytes()), "/style.css" => Reply::content(200, "text/css; charset=utf-8", STYLE), "/app.mjs" => Reply::content(200, "text/javascript; charset=utf-8", SCRIPT), "/feedback.mjs" => Reply::content( 200, "text/javascript; charset=utf-8", include_str!("../assets/feedback.mjs"), ), "/maintainer" => Reply::content( 200, "text/html; charset=utf-8", include_str!("../assets/maintainer.html"), ), "/maintainer.mjs" => Reply::content( 200, "text/javascript; charset=utf-8", include_str!("../assets/maintainer.mjs"), ), "/fonts/chivo-latin.woff2" => Reply::content( 200, "font/woff2", include_bytes!("../assets/fonts/chivo-latin.woff2").as_slice(), ), "/fonts/commit-mono.woff2" => Reply::content( 200, "font/woff2", include_bytes!("../assets/fonts/commit-mono.woff2").as_slice(), ), "/healthz" => Reply::json( 200, json!({"status":"ready", "proof_sha256":self.proof_sha256}), ), "/source" | "/source/" => { Reply::content(200, "text/html; charset=utf-8", source_index()) } "/lessons/ipa/" | "/lessons/ipa/README.md" => { Reply::content(200, "text/html; charset=utf-8", self.lesson.as_bytes()) } "/docs/ipa-construction.md" => Reply::content( 200, "text/html; charset=utf-8", markdown_page( "IPA construction notes", include_str!("../../../docs/ipa-construction.md"), ), ), "/docs/pilot.md" => Reply::content( 200, "text/html; charset=utf-8", markdown_page("Learner pilot kit", include_str!("../../../docs/pilot.md")), ), "/docs/review-checklist.md" => Reply::content( 200, "text/html; charset=utf-8", markdown_page( "Technical review checklist", include_str!("../../../docs/review-checklist.md"), ), ), _ => match source_file(path) { Some(text) => Reply::content(200, "text/plain; charset=utf-8", text), None => Reply::error(404, "not_found", "This page does not exist."), }, } } } fn statement(claim: &str) -> Statement { Statement { initial: "2".into(), final_value: claim.into(), steps: 2, } } fn verification_reply( claim: &str, proof_sha256: &str, verify: impl FnOnce() -> Result, ) -> Reply { let start = Instant::now(); match catch_unwind(AssertUnwindSafe(verify)) { Ok(Ok(verified)) => Reply::json( 200, json!({ "status": if verified { "accepted" } else { "rejected" }, "verified": verified, "statement": {"initial":2, "steps":2, "claimed_final":claim}, "proof_sha256":proof_sha256, "verification_ms":start.elapsed().as_secs_f64() * 1000.0 }), ), Ok(Err(error)) => { eprintln!("verifier error: {error}"); verifier_error() } Err(_) => { eprintln!("verifier panicked; no verification outcome returned"); verifier_error() } } } fn verifier_error() -> Reply { Reply::error( 500, "server_error", "The verifier could not complete this check. Please try again. No proof result was returned.", ) } fn markdown_page(title: &str, markdown: &str) -> String { let mut rendered = String::new(); html::push_html( &mut rendered, Parser::new_ext(markdown, Options::ENABLE_TABLES), ); format!( "{title} · Build Halo Lab
{rendered}
" ) } fn source_index() -> String { let files = [ ( "/source/web-service.rs", "Rust web service and real verification call", ), ("/source/web-main.rs", "HTTP server and startup"), ( "/source/feedback.rs", "Persistent pilot feedback and consent checks", ), ("/source/web-Cargo.toml", "Web dependencies"), ("/source/index.html", "Learner page"), ("/source/app.mjs", "Browser interaction and local grading"), ("/source/style.css", "Styles"), ( "/source/recursive-demo.rs", "Existing recursive application", ), ("/source/edu-ipa.rs", "Original educational IPA"), ("/source/lab-cli.rs", "Existing CLI"), ("/source/Cargo.toml", "Workspace manifest"), ("/source/Cargo.lock", "Pinned dependency graph"), ( "/source/ragu-transport.patch", "Attributed Ragu transport patch", ), ("/source/proof-provenance.json", "Bundled proof provenance"), ("/source/LICENSE", "Lab license"), ( "/source/font-provenance.json", "Self-hosted font sources and checksums", ), ("/source/Chivo-OFL.txt", "Chivo font license"), ("/source/CommitMono-OFL.txt", "Commit Mono font license"), ]; let links = files .iter() .map(|(path, label)| format!("
  • {label}
  • ")) .collect::(); format!( "Source · Build Halo Lab

    Open the lab

    The web service calls the existing ChainLab verifier. Ragu supplies the recursive cryptography; the separate educational IPA is original lab code implementing a published construction.

      {links}

    Pinned upstream Ragu source and licenses

    Read the deeper IPA lesson

    " ) } fn source_file(path: &str) -> Option<&'static str> { Some(match path { "/source/web-service.rs" => include_str!("lib.rs"), "/source/web-main.rs" => include_str!("main.rs"), "/source/feedback.rs" => include_str!("feedback.rs"), "/source/web-Cargo.toml" => include_str!("../Cargo.toml"), "/source/index.html" => PAGE, "/source/app.mjs" => SCRIPT, "/source/style.css" => STYLE, "/source/recursive-demo.rs" => include_str!("../../recursive-demo/src/lib.rs"), "/source/edu-ipa.rs" => include_str!("../../edu-ipa/src/lib.rs"), "/source/lab-cli.rs" => include_str!("../../lab-cli/src/main.rs"), "/source/Cargo.toml" => include_str!("../../../Cargo.toml"), "/source/Cargo.lock" => include_str!("../../../Cargo.lock"), "/source/ragu-transport.patch" => include_str!("../../../evidence/ragu-transport.patch"), "/source/proof-provenance.json" => include_str!("../assets/proof-provenance.json"), "/source/LICENSE" => include_str!("../../../LICENSE"), "/source/font-provenance.json" => include_str!("../assets/fonts/provenance.json"), "/source/Chivo-OFL.txt" => include_str!("../assets/fonts/Chivo-OFL.txt"), "/source/CommitMono-OFL.txt" => include_str!("../assets/fonts/CommitMono-OFL.txt"), "/lessons/ipa/starter.py" => include_str!("../../../lessons/ipa/starter.py"), "/lessons/ipa/solution.py" => include_str!("../../../lessons/ipa/solution.py"), "/lessons/ipa/source-notes.md" => include_str!("../../../lessons/ipa/source-notes.md"), "/tests/assessment.py" => include_str!("../../../tests/assessment.py"), _ => return None, }) } #[cfg(test)] mod tests { use super::*; use std::io::Cursor; fn body(reply: &Reply) -> Value { serde_json::from_slice(&reply.body).unwrap() } #[test] fn request_cannot_override_the_server_statement_or_artifact() { assert_eq!(parse_claim(br#"{"claimed_final":"00052"}"#).unwrap(), "52"); for input in [ br#"{"claimed_final":"52","initial":3}"#.as_slice(), br#"{"claimed_final":"52","steps":1}"#, br#"{"claimed_final":"52","proof":"fake"}"#, br#"{"claimed_final":"52","claimed_final":"53"}"#, br#"{"claimed_final":52}"#, b"not json", b"{}", ] { assert_eq!(parse_claim(input).unwrap_err().status, 400); } } #[test] fn malformed_values_are_input_errors_not_rejected_proofs() { for claim in [ "", "abc", "-1", "+52", "52.0", " 52", "0x34", "18446744073709551616", "52", ] { let reply = parse_claim(json!({"claimed_final":claim}).to_string().as_bytes()).unwrap_err(); assert_eq!(reply.status, 422); assert_eq!(body(&reply)["status"], "invalid_input"); assert!(body(&reply).get("verified").is_none()); } } #[test] fn request_reader_is_bounded() { let mut source = Cursor::new(vec![0; MAX_BODY_BYTES * 4]); assert_eq!(read_body(&mut source).unwrap_err().status, 413); assert_eq!(source.position(), MAX_BODY_BYTES as u64 + 1); } #[test] fn verifier_errors_and_panics_are_never_proof_rejections() { // Error-path fixtures only; real proof verification is exercised below // and through the actual HTTP/browser flow. for reply in [ verification_reply("52", "test", || Err("injected error".into())), verification_reply("52", "test", || panic!("injected verifier panic")), ] { assert_eq!(reply.status, 500); assert_eq!(body(&reply)["status"], "server_error"); assert!(body(&reply).get("verified").is_none()); } } #[test] fn real_fixed_proof_accepts_52_and_rejects_53() { let lab = WebLab::initialize().unwrap(); let accepted = lab.verify_body(br#"{"claimed_final":"52"}"#); let rejected = lab.verify_body(br#"{"claimed_final":"53"}"#); assert_eq!(accepted.status, 200); assert_eq!(rejected.status, 200); assert_eq!(body(&accepted)["verified"], true); assert_eq!(body(&rejected)["verified"], false); assert_eq!( body(&accepted)["proof_sha256"], body(&rejected)["proof_sha256"] ); assert_eq!(body(&accepted)["proof_sha256"], lab.proof_sha256()); assert_eq!(body(&accepted)["statement"]["initial"], 2); assert_eq!(body(&accepted)["statement"]["steps"], 2); } }