chadtmiller.com/hud
A remote MCP server that shows atproto records as interactive UI inside MCP Apps hosts
place.hud.hudkit 0.6.0 Latest 5 packages
0
0
Logs mask percent-encoded secrets, and read off the async workers
crates/hud-core/src/logs.rs+31−27
| @@ -109,10 +109,12 @@ impl Logs { | ||
/// duration beside it, to find it by. A line that isn't JSON is kept as | ||
/// a message of its own. Lines a write fails to keep, as when another | ||
/// server holds the file past the busy timeout, are held again, ahead | ||
/// of those logged since, for the next. | ||
/// of those logged since, for the next. The file is held before the | ||
/// lines are taken, so two flushes write them in the order logged. | ||
pub fn flush(&self) -> rusqlite::Result<()> { | ||
let mut db = self.db(); | ||
let batch = std::mem::take(&mut *self.held()); | ||
let written = self.write(&batch); | ||
let written = write(&mut db, &batch); | ||
if written.is_err() { | ||
let mut pending = self.held(); | ||
let since = std::mem::replace(&mut *pending, batch); | ||
| @@ -123,27 +125,6 @@ impl Logs { | ||
written | ||
} | ||
| ||
/// Writes `pending` in one transaction: all of it or none. | ||
fn write(&self, pending: &VecDeque<Vec<u8>>) -> rusqlite::Result<()> { | ||
let at = now(); | ||
let mut db = self.db(); | ||
let tx = db.transaction()?; | ||
let mut stmt = | ||
tx.prepare_cached("INSERT INTO line VALUES (NULL, ?1, ?2, ?3, ?4, ?5, ?6)")?; | ||
for line in pending { | ||
let text = String::from_utf8_lossy(line); | ||
let v: Value = serde_json::from_str(text.trim()) | ||
.unwrap_or_else(|_| json!({ "message": text.trim() })); | ||
let level = rank(v["level"].as_str().unwrap_or("INFO")); | ||
let message = v["message"].as_str().unwrap_or_default(); | ||
let ms = v["duration_ms"].as_i64(); | ||
let trace = v["trace_id"].as_str(); | ||
stmt.execute(params![at, level, message, trace, ms, v.to_string()])?; | ||
} | ||
drop(stmt); | ||
tx.commit() | ||
} | ||
| ||
/// Lets go of what is past keeping: lines at info and below past the | ||
/// last `keep` of them, and any line older than [`DAYS`]. | ||
pub fn prune(&self) -> rusqlite::Result<()> { | ||
| @@ -211,6 +192,25 @@ impl Logs { | ||
} | ||
} | ||
| ||
/// Writes `pending` to `db` in one transaction: all of it or none. | ||
fn write(db: &mut Connection, pending: &VecDeque<Vec<u8>>) -> rusqlite::Result<()> { | ||
let at = now(); | ||
let tx = db.transaction()?; | ||
let mut stmt = tx.prepare_cached("INSERT INTO line VALUES (NULL, ?1, ?2, ?3, ?4, ?5, ?6)")?; | ||
for line in pending { | ||
let text = String::from_utf8_lossy(line); | ||
let v: Value = | ||
serde_json::from_str(text.trim()).unwrap_or_else(|_| json!({ "message": text.trim() })); | ||
let level = rank(v["level"].as_str().unwrap_or("INFO")); | ||
let message = v["message"].as_str().unwrap_or_default(); | ||
let ms = v["duration_ms"].as_i64(); | ||
let trace = v["trace_id"].as_str(); | ||
stmt.execute(params![at, level, message, trace, ms, v.to_string()])?; | ||
} | ||
drop(stmt); | ||
tx.commit() | ||
} | ||
| ||
/// A level, as a number to compare: `ERROR` the highest. | ||
fn rank(level: &str) -> i64 { | ||
match level.to_ascii_uppercase().as_str() { | ||
| @@ -371,7 +371,7 @@ impl Hud { | ||
/// operator's alone, and logged, `logs read`, with who asked and for | ||
/// what. What was logged up to now is written first, this read's own | ||
/// line with it. | ||
pub fn read_logs( | ||
pub async fn read_logs( | ||
&self, | ||
account: &Account, | ||
given: &Map<String, Value>, | ||
| @@ -379,7 +379,7 @@ impl Hud { | ||
if !self.operator(Some(account)) { | ||
return Err(Unread::Forbidden); | ||
} | ||
let logs = self.logs.as_deref().ok_or(Unread::NotKept)?; | ||
let logs = self.logs.clone().ok_or(Unread::NotKept)?; | ||
let asked = Asked::of(given).map_err(Unread::Invalid)?; | ||
let f = Fields { | ||
did: Some(&account.did), | ||
| @@ -387,7 +387,10 @@ impl Hud { | ||
..Fields::default() | ||
}; | ||
telemetry::note(Level::INFO, "logs read", &f); | ||
let read = logs.flush().and_then(|()| logs.read(&asked)); | ||
// SQLite's work, off the async workers. | ||
let read = | ||
tokio::task::spawn_blocking(move || logs.flush().and_then(|()| logs.read(&asked))); | ||
let read = read.await.expect("a read of the logs does not panic"); | ||
read.map_err(|e| Unread::Failed(e.to_string())) | ||
} | ||
| ||
| @@ -402,6 +405,7 @@ impl Hud { | ||
let given = Args::of(arguments, &ASKED_BY)?; | ||
let lines = self | ||
.read_logs(account, given.0) | ||
.await | ||
.map_err(|e| Refusal::Error(e.message()))?; | ||
Ok(Output { | ||
text: format!("Lines logged: {}.", lines.len()), | ||
| @@ -662,7 +666,7 @@ mod tests { | ||
assert_eq!(out.meta["viewer"]["did"], crate::tests::ALICE); | ||
let none = server(false); | ||
let given = json!({ "level": "info" }); | ||
let read = none.read_logs(&alice, given.as_object().unwrap()); | ||
let read = none.read_logs(&alice, given.as_object().unwrap()).await; | ||
assert_eq!(read, Err(Unread::NotKept)); | ||
} | ||
| ||
crates/hud-core/src/telemetry.rs+12−6
| @@ -337,15 +337,16 @@ const SECRETS: [&str; 9] = [ | ||
]; | ||
| ||
/// The query of a request to `path`, as its line gives it: each value a | ||
/// secret could be in ([`SECRETS`]) replaced by `_`, cut to 200 | ||
/// characters; none for sign-in's (`/oauth`), whose query is all codes and | ||
/// state. | ||
/// secret could be in ([`SECRETS`]) replaced by `_`, its name read as a | ||
/// query is (`%63ode` is `code`), cut to 200 characters; none for | ||
/// sign-in's (`/oauth`), whose query is all codes and state. | ||
pub fn query(path: &str, query: Option<&str>) -> Option<String> { | ||
let query = query.filter(|_| !path.starts_with("/oauth"))?; | ||
let pairs = query.split('&').map(|pair| { | ||
let name = pair.split('=').next().unwrap_or_default(); | ||
match SECRETS.iter().any(|s| name.eq_ignore_ascii_case(s)) { | ||
true => format!("{name}=_"), | ||
let raw = pair.split('=').next().unwrap_or_default(); | ||
let name = url::form_urlencoded::parse(pair.as_bytes()).next(); | ||
match name.is_some_and(|(n, _)| SECRETS.iter().any(|s| n.eq_ignore_ascii_case(s))) { | ||
true => format!("{raw}=_"), | ||
false => pair.to_string(), | ||
} | ||
}); | ||
| @@ -937,6 +938,11 @@ pub(crate) mod tests { | ||
let logged = |q: &str| query("/xrpc/place.hud.getLogs", Some(q)).unwrap(); | ||
assert_eq!(logged("trace=abc&level=warn"), "trace=abc&level=warn"); | ||
assert_eq!(logged("code=abc&ISS=https://pds&x"), "code=_&ISS=_&x"); | ||
// Its name read as a query is, however it is written. | ||
assert_eq!( | ||
logged("%63ode=abc&acc%65ss_token=t&refresh+token=r&&x"), | ||
"%63ode=_&acc%65ss_token=_&refresh+token=r&&x" | ||
); | ||
assert_eq!(logged(&"a".repeat(300)).len(), 200); | ||
assert_eq!(query("/oauth/callback", Some("code=abc")), None); | ||
assert_eq!(query("/xrpc/place.hud.getLogs", None), None); | ||
crates/hud-server/src/xrpc.rs+1−1
| @@ -629,7 +629,7 @@ async fn call( | ||
json!({ "problems": hud_core::theme::problems(&palette) }) | ||
} | ||
"getLogs" => { | ||
let lines = hud.read_logs(&caller.account, input)?; | ||
let lines = hud.read_logs(&caller.account, input).await?; | ||
let lines: Vec<Json> = lines | ||
.into_iter() | ||
.map(|line| json!({ "line": line })) | ||