//! Pilot feedback: private records on a persistent volume, explicit public consent //! and a separate maintainer decision. No exercise completion is inferred. use crate::Reply; use serde::{Deserialize, Serialize}; use serde_json::json; use sha2::{Digest, Sha256}; use std::{ fs::{self, File, OpenOptions}, io::{Read, Write}, path::{Path, PathBuf}, sync::atomic::{AtomicU64, Ordering}, time::{SystemTime, UNIX_EPOCH}, }; pub const MAX_FEEDBACK_BYTES: usize = 8192; const MAX_RECORDS: usize = 5000; static SEQUENCE: AtomicU64 = AtomicU64::new(0); #[derive(Deserialize, Serialize, Clone, Debug)] #[serde(deny_unknown_fields)] pub struct Submission { completion: String, duration: String, reflection: String, #[serde(default)] share_public: bool, #[serde(default)] display_name: String, #[serde(default)] github_url: String, } #[derive(Deserialize, Serialize, Debug)] #[serde(deny_unknown_fields)] struct Record { id: String, submitted_at: u64, response: Submission, } pub struct FeedbackStore { dir: PathBuf, token_hash: Option<[u8; 32]>, } fn storage_error() -> Reply { Reply::error( 503, "feedback_unavailable", "Feedback could not be saved or loaded. Please try again later.", ) } fn invalid(message: &str) -> Reply { Reply::error(422, "invalid_input", message) } fn valid_id(id: &str) -> bool { id.len() == 32 && id .bytes() .all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase()) } impl Submission { fn validate(&mut self) -> Result<(), Reply> { self.reflection = self.reflection.trim().to_owned(); self.display_name = self.display_name.trim().to_owned(); self.github_url = self.github_url.trim().trim_end_matches('/').to_owned(); if !["without_help", "with_help", "not_finished"].contains(&self.completion.as_str()) || !["under_5", "5_to_10", "10_to_20", "over_20"].contains(&self.duration.as_str()) { return Err(invalid("Choose completion and time spent.")); } if self.reflection.is_empty() || self.reflection.chars().count() > 2000 || self.display_name.chars().count() > 80 || self .reflection .chars() .chain(self.display_name.chars()) .any(|c| c.is_control() && c != '\n' && c != '\t') { return Err(invalid( "Use 1–2000 characters for feedback and at most 80 for a name.", )); } if !self.github_url.is_empty() { let handle = self .github_url .strip_prefix("https://github.com/") .unwrap_or(""); if handle.is_empty() || handle.len() > 39 || handle.starts_with('-') || handle.ends_with('-') || handle.contains("--") || !handle .bytes() .all(|b| b.is_ascii_alphanumeric() || b == b'-') { return Err(invalid( "Use a GitHub profile URL such as https://github.com/octocat, or leave it blank.", )); } } if !self.share_public && (!self.display_name.is_empty() || !self.github_url.is_empty()) { return Err(invalid( "Optional public identity requires sharing consent.", )); } Ok(()) } } impl FeedbackStore { pub fn open(dir: impl AsRef, token: Option<&str>) -> Result { if token.is_some_and(|t| t.len() < 32) { return Err("MAINTAINER_TOKEN must be at least 32 characters".into()); } fs::create_dir_all(&dir).map_err(|e| format!("feedback directory: {e}"))?; #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; fs::set_permissions(&dir, fs::Permissions::from_mode(0o700)) .map_err(|e| e.to_string())?; } let store = Self { dir: dir.as_ref().to_path_buf(), token_hash: token.map(|t| Sha256::digest(t.as_bytes()).into()), }; // Fail startup on unreadable/corrupt records instead of exposing partial data. store .records() .map_err(|_| "feedback store is unreadable or corrupt".to_string())?; Ok(store) } fn sync_dir(&self) -> Result<(), Reply> { #[cfg(unix)] File::open(&self.dir) .and_then(|f| f.sync_all()) .map_err(|_| storage_error())?; Ok(()) } fn records(&self) -> Result, Reply> { let mut records = Vec::new(); for entry in fs::read_dir(&self.dir).map_err(|_| storage_error())? { let entry = entry.map_err(|_| storage_error())?; if entry.path().extension().is_none_or(|e| e != "json") { continue; } let mut bytes = Vec::new(); File::open(entry.path()) .and_then(|f| { f.take((MAX_FEEDBACK_BYTES + 1) as u64) .read_to_end(&mut bytes) }) .map_err(|_| storage_error())?; if bytes.len() > MAX_FEEDBACK_BYTES { return Err(storage_error()); } let mut record: Record = serde_json::from_slice(&bytes).map_err(|_| storage_error())?; if !valid_id(&record.id) || entry.path().file_stem().and_then(|s| s.to_str()) != Some(&record.id) || record.response.validate().is_err() { return Err(storage_error()); } records.push(record); if records.len() > MAX_RECORDS { return Err(storage_error()); } } records.sort_by(|a, b| b.submitted_at.cmp(&a.submitted_at).then(b.id.cmp(&a.id))); Ok(records) } fn marker(&self, id: &str, suffix: &str) -> PathBuf { self.dir.join(format!("{id}.{suffix}")) } fn review(&self, id: &str) -> &'static str { if self.marker(id, "rejected").exists() { "rejected" } else if self.marker(id, "approved").exists() { "approved" } else { "pending" } } pub fn authorized(&self, authorization: Option<&str>) -> bool { let Some(expected) = self.token_hash else { return false; }; let Some(token) = authorization.and_then(|s| s.strip_prefix("Bearer ")) else { return false; }; if token.len() > 256 { return false; } let actual = Sha256::digest(token.as_bytes()); expected .iter() .zip(actual) .fold(0u8, |difference, (a, b)| difference | (a ^ b)) == 0 } pub fn submit(&self, body: &[u8]) -> Reply { let result = (|| { if body.len() > MAX_FEEDBACK_BYTES { return Err(Reply::error( 413, "invalid_input", "The feedback is too large.", )); } let mut response: Submission = serde_json::from_slice(body).map_err(|_| { Reply::error(400, "invalid_input", "Send the feedback form as JSON.") })?; response.validate()?; if self.records()?.len() >= MAX_RECORDS { return Err(storage_error()); } let now = SystemTime::now() .duration_since(UNIX_EPOCH) .map_err(|_| storage_error())?; let id = format!( "{:032x}", now.as_nanos() ^ ((std::process::id() as u128) << 64) ^ SEQUENCE.fetch_add(1, Ordering::Relaxed) as u128 ); let record = Record { id: id.clone(), submitted_at: now.as_secs(), response, }; let bytes = serde_json::to_vec(&record).map_err(|_| storage_error())?; let path = self.dir.join(format!("{id}.json")); let mut file = OpenOptions::new() .write(true) .create_new(true) .open(&path) .map_err(|_| storage_error())?; if file .write_all(&bytes) .and_then(|()| file.sync_all()) .is_err() { let _ = fs::remove_file(path); return Err(storage_error()); } self.sync_dir()?; Ok(Reply::json(201, json!({"status":"saved","public":false}))) })(); result.unwrap_or_else(|r| r) } pub fn public(&self) -> Reply { match self.records() { Ok(records) => Reply::json( 200, json!({"entries":records.into_iter().filter(|r|r.response.share_public && self.review(&r.id)=="approved").take(100).map(|r| json!({"completion":r.response.completion,"duration":r.response.duration,"reflection":r.response.reflection,"display_name":r.response.display_name,"github_url":r.response.github_url})).collect::>()}), ), Err(reply) => reply, } } /// Called only after bearer authorization at the HTTP boundary. pub fn list(&self) -> Reply { match self.records() { Ok(records) => Reply::json( 200, json!({"entries":records.iter().map(|r|json!({"id":r.id,"submitted_at":r.submitted_at,"response":r.response,"review":self.review(&r.id)})).collect::>()}), ), Err(r) => r, } } pub fn moderate(&self, body: &[u8]) -> Reply { #[derive(Deserialize)] #[serde(deny_unknown_fields)] struct Decision { id: String, action: String, } let result = (|| { let decision: Decision = serde_json::from_slice(body) .map_err(|_| invalid("Choose a response and a review action."))?; if !valid_id(&decision.id) || !["approve", "reject", "delete"].contains(&decision.action.as_str()) { return Err(invalid("Invalid review action or response ID.")); } let records = self.records()?; let record = records .iter() .find(|r| r.id == decision.id) .ok_or_else(|| Reply::error(404, "not_found", "Response not found."))?; if decision.action == "approve" && !record.response.share_public { return Err(Reply::error( 409, "consent_required", "Private feedback cannot be published.", )); } let approved = self.marker(&decision.id, "approved"); let rejected = self.marker(&decision.id, "rejected"); let remove = |p: &Path| -> Result<(), Reply> { match fs::remove_file(p) { Ok(()) => Ok(()), Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()), Err(_) => Err(storage_error()), } }; match decision.action.as_str() { "approve" => { File::create(&approved) .and_then(|f| f.sync_all()) .map_err(|_| storage_error())?; remove(&rejected)?; } "reject" => { File::create(&rejected) .and_then(|f| f.sync_all()) .map_err(|_| storage_error())?; remove(&approved)?; } _ => { remove(&approved)?; self.sync_dir()?; remove(&self.dir.join(format!("{}.json", decision.id)))?; remove(&rejected)?; } } self.sync_dir()?; Ok(Reply::json(200, json!({"status":"saved"}))) })(); result.unwrap_or_else(|r| r) } } #[cfg(test)] mod tests { use super::*; fn values(r: Reply) -> serde_json::Value { serde_json::from_slice(&r.body).unwrap() } fn setup() -> (PathBuf, FeedbackStore) { let p = std::env::temp_dir().join(format!( "halo-feedback-{}-{}", std::process::id(), SEQUENCE.fetch_add(1, Ordering::Relaxed) )); let s = FeedbackStore::open(&p, Some("test-maintainer-secret-32-characters")).unwrap(); (p, s) } fn submission(consent: bool) -> Vec { json!({"completion":"not_finished","duration":"5_to_10","reflection":"TEST fixture; not a learner result","share_public":consent}).to_string().into_bytes() } #[test] fn private_pending_consent_and_restart_boundaries() { let (p, s) = setup(); assert_eq!(s.submit(&submission(false)).status, 201); let private = values(s.list())["entries"][0]["id"] .as_str() .unwrap() .to_owned(); assert_eq!( s.moderate( json!({"id":private,"action":"approve"}) .to_string() .as_bytes() ) .status, 409 ); assert_eq!(s.submit(&submission(true)).status, 201); assert_eq!(values(s.public())["entries"].as_array().unwrap().len(), 0); let list = values(s.list()); let public = list["entries"] .as_array() .unwrap() .iter() .find(|e| e["response"]["share_public"] == true) .unwrap()["id"] .as_str() .unwrap(); assert_eq!( s.moderate( json!({"id":public,"action":"approve"}) .to_string() .as_bytes() ) .status, 200 ); drop(s); let s = FeedbackStore::open(&p, None).unwrap(); assert_eq!(values(s.public())["entries"].as_array().unwrap().len(), 1); assert_eq!( s.moderate( json!({"id":public,"action":"reject"}) .to_string() .as_bytes() ) .status, 200 ); assert_eq!(values(s.public())["entries"].as_array().unwrap().len(), 0); for id in [public, &private] { assert_eq!( s.moderate(json!({"id":id,"action":"delete"}).to_string().as_bytes()) .status, 200 ); } assert!(values(s.list())["entries"].as_array().unwrap().is_empty()); fs::remove_dir_all(p).unwrap(); } #[test] fn invalid_schemas_identity_urls_and_auth_fail_closed() { let (p, s) = setup(); assert!(!s.authorized(None)); assert!(!s.authorized(Some("Bearer wrong"))); assert!(s.authorized(Some("Bearer test-maintainer-secret-32-characters"))); for extra in [ json!({"review":"approved"}), json!({"share_public":"true"}), json!({"display_name":"name"}), json!({"share_public":true,"github_url":"https://github.com/user/repo"}), json!({"share_public":true,"github_url":"javascript:alert(1)"}), json!({"completion":"verified_by_server"}), json!({"reflection":" "}), ] { let mut r: serde_json::Value = serde_json::from_slice(&submission(false)).unwrap(); for (k, v) in extra.as_object().unwrap() { r[k] = v.clone(); } assert_ne!(s.submit(r.to_string().as_bytes()).status, 201); } assert_eq!( s.submit(br#"{"completion":"not_finished","completion":"without_help"}"#) .status, 400 ); assert_eq!(s.submit(&vec![0; MAX_FEEDBACK_BYTES + 1]).status, 413); assert_eq!( s.moderate(br#"{"id":"../../secret","action":"approve"}"#) .status, 422 ); fs::write(p.join("broken.json"), b"{").unwrap(); assert_eq!(s.public().status, 503); assert!(FeedbackStore::open(&p, None).is_err()); fs::remove_dir_all(p).unwrap(); } }