From 843ec9bdbc60ea89bf7b37b502ccca7909725d90 Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Sat, 28 Nov 2026 08:39:38 -0500 Subject: [PATCH 1/4] feat: readable approval view (channel label, mentions, embeds) The held-request view page shows the message as text: an optional [passthrough].channel_labels label next to the channel id from the path, mentions marked in place (user/role/channel, @everyone/@here warning, no lookup), embed title/description/fields as inert escaped text, bounded with a truncated marker, raw JSON in Details unchanged. Telegram push, auth, CSP, hold and approval behaviour are unchanged. Verified on macmini (arm64), clone $HOME/work/auth-proxy-view-render (rsync of the worktree, umask 022): - cargo fmt --all -- --check: exit 0 - cargo clippy --workspace --all-targets -- -D warnings: exit 0 - cargo test --workspace: exit 0, no failures (no pre-existing reds seen, so none needed a base comparison) --- crates/ap-core/src/config.rs | 66 +++- crates/ap-proxy/src/approval/mod.rs | 17 +- crates/ap-proxy/src/approval/page.rs | 519 ++++++++++++++++++++++++-- crates/ap-proxy/src/approval/tests.rs | 1 + crates/ap-proxy/src/lib.rs | 1 + docs/runbooks/muse-stage2.md | 3 + 6 files changed, 565 insertions(+), 42 deletions(-) diff --git a/crates/ap-core/src/config.rs b/crates/ap-core/src/config.rs index 698076f..83492d6 100644 --- a/crates/ap-core/src/config.rs +++ b/crates/ap-core/src/config.rs @@ -6,7 +6,7 @@ use crate::canon::canonical_host; use crate::headers::{AUTH_HEADERS, HOP_HEADERS}; use serde::Deserialize; -use std::collections::{HashMap, HashSet}; +use std::collections::{BTreeMap, HashMap, HashSet}; use std::fmt; use std::net::SocketAddr; @@ -138,6 +138,11 @@ pub struct Passthrough { /// Seconds an identity is refused after a human deny, 0..=3600 (0 disables). #[serde(default = "default_cooldown_secs")] pub cooldown_secs: u64, + /// Optional display labels for channel ids, shown next to the id on the approval view page. + /// At most 64 entries; each id is 1..=20 digits and each label 1..=64 printable characters + /// without `<`, `>` or `&`. Display only: never read by routing, grants or approval. + #[serde(default)] + pub channel_labels: BTreeMap, } /// How a held request is answered to its caller. @@ -675,6 +680,26 @@ fn validate_passthrough(p: &Passthrough) -> Result<(), ConfigError> { ))); } } + if p.channel_labels.len() > 64 { + return Err(invalid("passthrough.channel_labels has too many entries")); + } + for (id, label) in &p.channel_labels { + if !(1..=20).contains(&id.len()) || !id.bytes().all(|b| b.is_ascii_digit()) { + return Err(invalid( + "passthrough.channel_labels ids must be 1..=20 digits", + )); + } + if label.is_empty() + || label.chars().count() > 64 + || label + .chars() + .any(|c| c.is_control() || matches!(c, '<' | '>' | '&')) + { + return Err(invalid(format!( + "passthrough.channel_labels label for {id} must be 1..=64 printable characters without <, > or &" + ))); + } + } if !(1..=1024).contains(&p.max_held_total) { return Err(invalid("passthrough.max_held_total must be in 1..=1024")); } @@ -2185,6 +2210,45 @@ paths = ["/api/v10/channels/", "/api/v10/users/@me"] expect_invalid(&text, "paths must not be empty"); } + #[test] + fn channel_labels_load_and_are_validated() { + let with = |extra: &str| { + pt_base().replace( + "public_authority = \"gate.example.test\"", + &format!("public_authority = \"gate.example.test\"\n{extra}"), + ) + }; + assert!(load(&pt_base()) + .unwrap() + .passthrough + .unwrap() + .channel_labels + .is_empty()); + let ok = load(&with("channel_labels = { \"123\" = \"ops-alerts\" }")).unwrap(); + assert_eq!(ok.passthrough.unwrap().channel_labels["123"], "ops-alerts"); + for bad in [ + "channel_labels = { \"12a\" = \"x\" }", + "channel_labels = { \"\" = \"x\" }", + "channel_labels = { \"123456789012345678901\" = \"x\" }", + "channel_labels = { \"1\" = \"\" }", + "channel_labels = { \"1\" = \"x\" }", + "channel_labels = { \"1\" = \"a&b\" }", + "channel_labels = { \"1\" = \"a\\nb\" }", + ] { + expect_invalid(&with(bad), "channel_labels"); + } + let long = "x".repeat(65); + expect_invalid( + &with(&format!("channel_labels = {{ \"1\" = \"{long}\" }}")), + "channel_labels", + ); + let many: Vec = (1..=65).map(|i| format!("\"{i}\" = \"l\"")).collect(); + expect_invalid( + &with(&format!("channel_labels = {{ {} }}", many.join(", "))), + "too many", + ); + } + #[test] fn rejects_hold_limits_out_of_range() { for (k, v) in [ diff --git a/crates/ap-proxy/src/approval/mod.rs b/crates/ap-proxy/src/approval/mod.rs index ef91bf8..6ee51ee 100644 --- a/crates/ap-proxy/src/approval/mod.rs +++ b/crates/ap-proxy/src/approval/mod.rs @@ -17,6 +17,7 @@ pub mod csrf; pub mod page; pub mod telegram; +use std::collections::BTreeMap; use std::sync::Arc; use std::time::Duration; @@ -46,6 +47,8 @@ pub struct ApprovalApp { fail_delay: Duration, /// Serve `GET /view/` without Basic auth. Set only when the Telegram buttons are on. view_links: bool, + /// Display-only labels for channel ids, from `[passthrough].channel_labels`. + channel_labels: BTreeMap, } impl std::fmt::Debug for ApprovalApp { @@ -59,7 +62,7 @@ pub type PolicySource = Arc Option> + impl ApprovalApp { pub fn new(table: Arc, cfg: &Approval, policy: PolicySource) -> Arc { - Self::build(table, cfg, FAIL_DELAY, policy, false) + Self::build(table, cfg, FAIL_DELAY, policy, false, BTreeMap::new()) } /// Like [`ApprovalApp::new`], and with `view_links` also serves the no-login one-time view @@ -69,8 +72,9 @@ impl ApprovalApp { cfg: &Approval, policy: PolicySource, view_links: bool, + channel_labels: BTreeMap, ) -> Arc { - Self::build(table, cfg, FAIL_DELAY, policy, view_links) + Self::build(table, cfg, FAIL_DELAY, policy, view_links, channel_labels) } fn build( @@ -79,6 +83,7 @@ impl ApprovalApp { fail_delay: Duration, policy: PolicySource, view_links: bool, + channel_labels: BTreeMap, ) -> Arc { Arc::new(ApprovalApp { table, @@ -88,6 +93,7 @@ impl ApprovalApp { realm: cfg.realm.clone(), fail_delay, view_links, + channel_labels, }) } @@ -270,14 +276,17 @@ fn show(app: &ApprovalApp, id: &str, json_wanted: bool) -> Response { if json_wanted { json_response(StatusCode::OK, &page::entry_json(&view, token.as_deref())) } else { - html_response(StatusCode::OK, page::entry(&view, token.as_deref())) + html_response( + StatusCode::OK, + page::entry(&view, token.as_deref(), &app.channel_labels), + ) } } /// The read-only page for a `Pending` hold, or the generic 404. fn view_by_token(app: &ApprovalApp, token: &str) -> Response { match app.table.view_by_token(token) { - Some(view) => html_response(StatusCode::OK, page::view_only(&view)), + Some(view) => html_response(StatusCode::OK, page::view_only(&view, &app.channel_labels)), None => result(StatusCode::NOT_FOUND, false, "not_found", None), } } diff --git a/crates/ap-proxy/src/approval/page.rs b/crates/ap-proxy/src/approval/page.rs index bc10908..bd495f7 100644 --- a/crates/ap-proxy/src/approval/page.rs +++ b/crates/ap-proxy/src/approval/page.rs @@ -10,6 +10,7 @@ //! block (method, route, redacted path and the message content), the approve and deny buttons on //! the decision page, and a closed `
` with the secondary facts. +use std::collections::BTreeMap; use std::sync::OnceLock; use base64::engine::general_purpose::STANDARD; @@ -19,6 +20,15 @@ use sha2::{Digest, Sha256}; use crate::hold::{State, View, ViewContent}; +/// Display-only channel labels, keyed by channel id. +pub type Labels = BTreeMap; + +/// Most embeds, fields per embed and characters per text shown; the rest is cut and marked. +const MAX_EMBEDS: usize = 10; +const MAX_FIELDS: usize = 25; +const MAX_TEXT: usize = 4000; +const CUT: &str = "… [truncated]"; + /// The stylesheet inlined in every page. The Content-Security-Policy allows this block by hash. const STYLE: &str = r#" *{box-sizing:border-box} @@ -175,19 +185,200 @@ fn header(v: &View) -> String { h } -/// The text of the `content` field when the body is a JSON object whose `content` is a string. -/// The JSON string is decoded, so escapes such as `\uff5c` become the characters they stand for. -/// `None` for anything else, including malformed JSON; this never panics. -fn message_content(body: &str) -> Option { - match serde_json::from_str::(body).ok()? { - Value::Object(mut fields) => match fields.remove("content")? { - Value::String(text) => Some(text), - _ => None, +/// The readable parts of a JSON object body: the `content` string and the text of each embed. +#[derive(Debug, PartialEq, Eq)] +struct Parsed { + content: Option, + embeds: Vec, + /// Some text, embed or field was cut for display. + truncated: bool, +} + +#[derive(Debug, PartialEq, Eq, Default)] +struct EmbedText { + title: Option, + description: Option, + fields: Vec<(String, String)>, +} + +/// Cut `s` to [`MAX_TEXT`] characters; the second value says whether it was cut. +fn clip(s: &str) -> (String, bool) { + match s.char_indices().nth(MAX_TEXT) { + Some((i, _)) => (format!("{}{CUT}", &s[..i]), true), + None => (s.to_string(), false), + } +} + +fn clip_str(v: Option<&Value>, cut: &mut bool) -> Option { + let (t, c) = clip(v?.as_str()?); + *cut |= c; + Some(t) +} + +/// Parse the held body text. `None` when it is not a JSON object with a string `content` or at +/// least one embed with text; this never panics and never fails, so the caller falls back to the +/// raw text. Values of other types are skipped. +fn parse_body(body: &str) -> Option { + let Value::Object(fields) = serde_json::from_str::(body).ok()? else { + return None; + }; + let mut truncated = false; + let content = clip_str(fields.get("content"), &mut truncated); + let mut embeds = Vec::new(); + if let Some(Value::Array(list)) = fields.get("embeds") { + truncated |= list.len() > MAX_EMBEDS; + for e in list.iter().take(MAX_EMBEDS) { + let Value::Object(e) = e else { continue }; + let mut t = EmbedText { + title: clip_str(e.get("title"), &mut truncated), + description: clip_str(e.get("description"), &mut truncated), + fields: Vec::new(), + }; + if let Some(Value::Array(fl)) = e.get("fields") { + truncated |= fl.len() > MAX_FIELDS; + for f in fl.iter().take(MAX_FIELDS) { + let name = clip_str(f.get("name"), &mut truncated); + let value = clip_str(f.get("value"), &mut truncated); + if name.is_some() || value.is_some() { + t.fields + .push((name.unwrap_or_default(), value.unwrap_or_default())); + } + } + } + if t != EmbedText::default() { + embeds.push(t); + } + } + } + if content.is_none() && embeds.is_empty() { + return None; + } + Some(Parsed { + content, + embeds, + truncated, + }) +} + +/// A mention found in message content. +#[derive(Debug, PartialEq, Eq)] +enum Mention<'a> { + User(&'a str), + Role(&'a str), + Channel(&'a str), + Everyone, + Here, +} + +/// The mention at the start of `s`, with its byte length. Ids are 1..=20 ASCII digits. +fn mention_at(s: &str) -> Option<(Mention<'_>, usize)> { + if s.starts_with("@everyone") { + return Some((Mention::Everyone, 9)); + } + if s.starts_with("@here") { + return Some((Mention::Here, 5)); + } + let rest = s.strip_prefix("<")?; + let prefix = if rest.starts_with("@&") { + "@&" + } else if rest.starts_with("@!") { + "@!" + } else if rest.starts_with('@') { + "@" + } else if rest.starts_with('#') { + "#" + } else { + return None; + }; + let after = &rest[prefix.len()..]; + let n = after.bytes().take_while(u8::is_ascii_digit).count(); + if !(1..=20).contains(&n) || after.as_bytes().get(n) != Some(&b'>') { + return None; + } + let id = &after[..n]; + let m = match prefix { + "@&" => Mention::Role(id), + "#" => Mention::Channel(id), + _ => Mention::User(id), + }; + Some((m, 1 + prefix.len() + n + 1)) +} + +/// Message content as HTML: escaped text, with each mention replaced in place by a marked token. +/// No lookup of any kind: a token names the kind and the raw id (and a configured channel label). +fn content_html(text: &str, labels: &Labels) -> String { + let mut out = String::new(); + let mut plain = 0; + let mut i = 0; + while i < text.len() { + let rest = &text[i..]; + let found = if rest.starts_with(['<', '@']) { + mention_at(rest) + } else { + None + }; + match found { + Some((m, len)) => { + out.push_str(&escape(&text[plain..i])); + out.push_str(&mention_html(&m, labels)); + i += len; + plain = i; + } + None => i += rest.chars().next().map_or(1, char::len_utf8), + } + } + out.push_str(&escape(&text[plain..])); + out +} + +fn mention_html(m: &Mention<'_>, labels: &Labels) -> String { + match m { + Mention::User(id) => format!("[user mention · id {}]", escape(id)), + Mention::Role(id) => format!("[role mention · id {}]", escape(id)), + Mention::Channel(id) => match labels.get(*id) { + Some(l) => format!( + "[channel mention · id {} · {}]", + escape(id), + escape(l) + ), + None => format!("[channel mention · id {}]", escape(id)), }, - _ => None, + Mention::Everyone => { + "⚠ WARNING: @everyone mention, notifies many people" + .into() + } + Mention::Here => { + "⚠ WARNING: @here mention, notifies many people".into() + } } } +/// The channel id in a request path of the form `.../channels//...`. +fn channel_id(path: &str) -> Option<&str> { + let mut segs = path.split('/'); + segs.find(|s| *s == "channels")?; + let id = segs.next()?; + ((1..=20).contains(&id.len()) && id.bytes().all(|b| b.is_ascii_digit())).then_some(id) +} + +/// One embed as a plain-text block. URLs and every other value stay inert text. +fn embed_html(n: usize, e: &EmbedText) -> String { + let mut t = String::new(); + if let Some(x) = &e.title { + t.push_str(&format!("Title: {}\n", escape(x))); + } + if let Some(x) = &e.description { + t.push_str(&format!("Description: {}\n", escape(x))); + } + for (name, value) in &e.fields { + t.push_str(&format!("Field {}: {}\n", escape(name), escape(value))); + } + format!( + "

Embed {n}

\n
{}
\n", + t.trim_end() + ) +} + /// The top-level fields of a JSON object body other than `content`, as names only. serde_json /// without `preserve_order` keeps object keys sorted, so these are sorted, not in body order. /// Empty for anything that is not a JSON object. @@ -223,7 +414,9 @@ fn extra_fields_line(body: &str) -> String { /// The payload block: what will be sent, in large type. The message content is shown decoded when /// the body has one; otherwise the body is shown as it was received. Fields other than `content` /// are named in a line above the content, so they are visible without opening Details. -fn payload(c: &ViewContent) -> String { +// WYSIWYS: everything shown here is derived only from `c.body_text`, the held bytes that are +// forwarded unchanged after approval, and from the request path; labels are display-only. +fn payload(c: &ViewContent, labels: &Labels) -> String { let mut b = String::from("
\n"); b.push_str("

This request will be sent

\n"); b.push_str(&format!( @@ -232,13 +425,41 @@ fn payload(c: &ViewContent) -> String { escape(&c.route) )); b.push_str(&format!("

{}

\n", escape(&c.path))); + if let Some(id) = channel_id(&c.path) { + let shown = match labels.get(id) { + Some(l) => format!("{} (id {})", escape(l), escape(id)), + None => format!("id {}", escape(id)), + }; + b.push_str(&format!( + "

Channel

\n

{shown}

\n" + )); + } b.push_str("

Message content

\n"); if c.body_lossy { b.push_str("

The body is not valid UTF-8. Invalid bytes are shown as U+FFFD; Discord receives the original bytes.

\n"); } b.push_str(&extra_fields_line(&c.body_text)); - let shown = message_content(&c.body_text).unwrap_or_else(|| c.body_text.clone()); - b.push_str(&format!("
{}
\n", escape(&shown))); + match parse_body(&c.body_text) { + Some(p) => { + if p.truncated { + b.push_str("

Truncated. Some text is cut for display; the raw body in Details is complete.

\n"); + } + match &p.content { + Some(t) => b.push_str(&format!( + "
{}
\n", + content_html(t, labels) + )), + None => b.push_str("

(no text content)

\n"), + } + for (i, e) in p.embeds.iter().enumerate() { + b.push_str(&embed_html(i + 1, e)); + } + } + None => b.push_str(&format!( + "
{}
\n", + escape(&c.body_text) + )), + } b.push_str("
\n"); b } @@ -300,7 +521,7 @@ fn details(v: &View, c: &ViewContent) -> String { t.push_str(&row(&h.name, &value)); } t.push_str("
\n"); - if message_content(&c.body_text).is_some() { + if parse_body(&c.body_text).is_some() { t.push_str("

Raw body

\n"); t.push_str(&format!( "
{}
\n", @@ -313,7 +534,7 @@ fn details(v: &View, c: &ViewContent) -> String { /// The page for one entry. `csrf` is the token for the approve and deny forms; without it the /// buttons are disabled. -pub fn entry(v: &View, csrf: Option<&str>) -> String { +pub fn entry(v: &View, csrf: Option<&str>, labels: &Labels) -> String { let mut b = header(v); match v.state { State::Superseded => { @@ -333,7 +554,7 @@ pub fn entry(v: &View, csrf: Option<&str>) -> String { )), } if let Some(c) = &v.content { - b.push_str(&payload(c)); + b.push_str(&payload(c, labels)); } b.push_str(&actions(&v.id, csrf)); if let Some(c) = &v.content { @@ -345,11 +566,11 @@ pub fn entry(v: &View, csrf: Option<&str>) -> String { /// The read-only page for a `Pending` hold, reached by its one-time view link. It has no form, /// no buttons and no token: the owner decides in Telegram. -pub fn view_only(v: &View) -> String { +pub fn view_only(v: &View, labels: &Labels) -> String { let mut b = header(v); b.push_str("

Read only. Decide in Telegram.

\n"); if let Some(c) = &v.content { - b.push_str(&payload(c)); + b.push_str(&payload(c, labels)); b.push_str(&details(v, c)); } shell(&format!("Request {}", v.id), &b) @@ -457,7 +678,11 @@ mod tests { #[test] fn script_body_and_header_values_are_escaped() { - let html = entry(&pending(""), Some("tok")); + let html = entry( + &pending(""), + Some("tok"), + &Labels::new(), + ); assert!(!html.contains("","description":"d","fields":[{"name":"","value":""}]}]}"#; + let html = entry(&at(CH, body), Some("t"), &Labels::new()); + for raw in [ + "t", + "", + "", + "", + ] { + assert!(!html.contains(raw), "{raw}\n{html}"); + } + assert!(html.contains("Title: <script>t</script>")); + assert!(html.contains("Field <n>: <v>")); + } + + #[test] + fn embeds_are_plain_text_with_inert_urls_and_no_external_reference() { + let body = r#"{"embeds":[{"title":"T1","description":"see https://example.test/a?x=1","url":"https://example.test/u","image":{"url":"https://img.example.test/i.png"},"thumbnail":{"url":"https://img.example.test/t.png"},"fields":[{"name":"N","value":"V https://example.test/f"}]},{"title":"T2"}]}"#; + let html = entry(&at(CH, body), Some("t"), &Labels::new()); + assert!(html.contains("Title: T1\nDescription: see https://example.test/a?x=1\nField N: V https://example.test/f"), "{html}"); + assert!(html.contains("Embed 2") && html.contains("Title: T2")); + assert!( + html.contains("(no text content)"), + "embed-only body has no content text" + ); + let payload_end = html.find("
").unwrap(); + let shown = &html[..payload_end]; + for banned in [ + "= 2); + } + + #[test] + fn long_text_and_many_embeds_are_cut_with_a_marker() { + let long = "x".repeat(MAX_TEXT + 10); + let embeds: Vec = (0..MAX_EMBEDS + 3) + .map(|i| format!(r#"{{"title":"e{i}"}}"#)) + .collect(); + let body = format!(r#"{{"content":"{long}","embeds":[{}]}}"#, embeds.join(",")); + let html = entry(&at(CH, &body), Some("t"), &Labels::new()); + assert!(html.contains(&format!("{}{CUT}", "x".repeat(MAX_TEXT)))); + assert!(html.contains("Truncated.")); + assert!(html.contains(&format!("Embed {MAX_EMBEDS}"))); + assert!(!html.contains(&format!("Embed {}", MAX_EMBEDS + 1))); + // The raw body in Details is complete. + assert!(html.contains(&escape(&body))); + let fields: Vec = (0..MAX_FIELDS + 2) + .map(|i| format!(r#"{{"name":"n{i}","value":"v"}}"#)) + .collect(); + let body = format!(r#"{{"embeds":[{{"fields":[{}]}}]}}"#, fields.join(",")); + let html = entry(&at(CH, &body), None, &Labels::new()); + assert!(html.contains(&format!("Field n{}: v", MAX_FIELDS - 1))); + assert!(!html.contains(&format!("Field n{}: v", MAX_FIELDS))); + assert!(html.contains("Truncated.")); + } + + #[test] + fn odd_shapes_fall_back_without_error() { + for body in [ + r#"{"content":"x","embeds":"nope"}"#, + r#"{"content":"x","embeds":[1,null,{"title":5,"fields":[{"name":1}]}]}"#, + r#"{"embeds":[{"fields":7}]}"#, + &format!("{}1{}", "[".repeat(5000), "]".repeat(5000)), + ] { + let html = entry(&at(CH, body), Some("t"), &Labels::new()); + assert!(html.contains("
"), "{body}");
+        }
+        let html = entry(
+            &at(CH, r#"{"embeds":[{"fields":7}]}"#),
+            None,
+            &Labels::new(),
+        );
+        assert!(html.contains(&format!(
+            "
{}
", + escape(r#"{"embeds":[{"fields":7}]}"#) + ))); + } + + #[test] + fn no_token_hash_or_caller_key_is_on_the_page() { + let v = at(CH, r#"{"content":"hi"}"#); + let html = entry(&v, None, &labels()); + assert!(!html.contains("Bot ") && !html.contains("Bearer")); + // The only hash-like value is the body digest in Details; no credential value is shown. + assert!(html.contains("present (value not shown)")); + assert!(!html.contains("x-ap-caller-key")); + } + + #[test] + fn what_is_shown_is_what_is_parsed_from_the_held_bytes() { + // Forwarding of these same bytes unchanged is covered by the hold_tests forwarding test + // that asserts the upstream received body == the sent body. + let held = r#"{"content":"hello <@111> and @everyone <#4242>","embeds":[{"title":"Tt","description":"Dd","fields":[{"name":"Nn","value":"Vv"}]}]}"#; + let v = at(CH, held); + let c = v.content.as_ref().unwrap(); + assert_eq!(c.body_text.as_bytes(), held.as_bytes()); + let html = entry(&v, None, &labels()); + let j: Value = serde_json::from_slice(held.as_bytes()).unwrap(); + let content = j["content"].as_str().unwrap(); + let e = &j["embeds"][0]; + let parsed = parse_body(&c.body_text).unwrap(); + assert_eq!(parsed.content.as_deref(), Some(content)); + assert_eq!(parsed.embeds[0].title.as_deref(), e["title"].as_str()); + assert_eq!( + parsed.embeds[0].description.as_deref(), + e["description"].as_str() + ); + assert_eq!( + parsed.embeds[0].fields, + [( + e["fields"][0]["name"].as_str().unwrap().to_string(), + e["fields"][0]["value"].as_str().unwrap().to_string() + )] + ); + assert_eq!( + content_html(content, &labels()), + content_html(parsed.content.as_deref().unwrap(), &labels()) + ); + for want in [ + "hello [user mention · id 111] and ", + "@everyone mention", + "[channel mention · id 4242 · ops-alerts]", + "Title: Tt\nDescription: Dd\nField Nn: Vv", + "ops-alerts (id 4242)", + ] { + assert!(html.contains(want), "{want}\n{html}"); + } + assert_eq!(channel_id(&c.path), Some("4242")); + } } diff --git a/crates/ap-proxy/src/approval/tests.rs b/crates/ap-proxy/src/approval/tests.rs index 44e394b..f03384d 100644 --- a/crates/ap-proxy/src/approval/tests.rs +++ b/crates/ap-proxy/src/approval/tests.rs @@ -223,6 +223,7 @@ path_patterns = ["/hold/*", "/webhooks/*/*"] delay, app.policy_source(), view_links, + std::collections::BTreeMap::new(), ); let l = crate::listener::bind_loopback("127.0.0.1:0".parse().unwrap()) .await diff --git a/crates/ap-proxy/src/lib.rs b/crates/ap-proxy/src/lib.rs index f3112b0..d7d39ec 100644 --- a/crates/ap-proxy/src/lib.rs +++ b/crates/ap-proxy/src/lib.rs @@ -424,6 +424,7 @@ a passthrough-only config has no per-UID rules" &cfg, app.policy_source(), buttons_on, + pt.channel_labels.clone(), ); listener::approval::serve_approval(l, state, Default::default()).await; } diff --git a/docs/runbooks/muse-stage2.md b/docs/runbooks/muse-stage2.md index f372222..67100e5 100644 --- a/docs/runbooks/muse-stage2.md +++ b/docs/runbooks/muse-stage2.md @@ -213,6 +213,9 @@ Client rules: - A deny or an expiry starts the per-identity cooldown (default 60 s, `[passthrough] cooldown_secs`), so a quick new POST can get 503 `cooldown`. - Never log the poll token. +Optional channel labels: `[passthrough] channel_labels = { "" = "ops-alerts" }` (digits-only ids, at most 64 entries, labels 1..=64 printable characters without `<`, `>` or `&`). The view page then shows `ops-alerts (id )` for the channel in the request path, or the id alone without a label. A label is display only and never affects routing, grants or approval. +The view page shows the message text, each embed's title, description and fields as plain text (URLs stay inert, nothing is loaded), and marks mentions in place (`user`, `role`, `channel`, with the raw id; `@everyone` and `@here` carry a warning). The gate looks up no names. Long text and extra embeds are cut with a "truncated" marker; the raw JSON in Details is complete. + ## 8. Not claimed - Protection from the Muse platform or anything that holds the real token. From f8d0f9d01124d3f029801972de91807d86a349b4 Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Sat, 28 Nov 2026 08:54:39 -0500 Subject: [PATCH 2/4] fix: harden approval view labels and bound the summary (PR #52 review) - labels: explicit safe character set (letters, digits, space, - _ . , : # + / ( ) @); refuses control, format (bidi, zero-width), U+2028/2029, quotes, < > & - labels are read from the policy in force at each page render, so a label-only reload shows on pending holds - extra-fields banner lists at most 16 names of at most 64 chars, with a 'more not listed' / truncated marker - cut embeds and embed fields show an 'N more ... omitted' marker - runbook keeps only the short label note Verification: rustfmt applied on macmini (skip_children); cargo build and tests not run here, they run on macmini in the next step. --- crates/ap-core/src/config.rs | 59 +++++++++-- crates/ap-core/src/policy.rs | 20 +++- crates/ap-proxy/src/approval/mod.rs | 22 +++-- crates/ap-proxy/src/approval/page.rs | 137 ++++++++++++++++++++++---- crates/ap-proxy/src/approval/tests.rs | 63 +++++++++++- crates/ap-proxy/src/lib.rs | 1 - docs/runbooks/muse-stage2.md | 3 +- 7 files changed, 262 insertions(+), 43 deletions(-) diff --git a/crates/ap-core/src/config.rs b/crates/ap-core/src/config.rs index 83492d6..edf71de 100644 --- a/crates/ap-core/src/config.rs +++ b/crates/ap-core/src/config.rs @@ -689,14 +689,9 @@ fn validate_passthrough(p: &Passthrough) -> Result<(), ConfigError> { "passthrough.channel_labels ids must be 1..=20 digits", )); } - if label.is_empty() - || label.chars().count() > 64 - || label - .chars() - .any(|c| c.is_control() || matches!(c, '<' | '>' | '&')) - { + if label.is_empty() || label.chars().count() > 64 || !label.chars().all(label_char_ok) { return Err(invalid(format!( - "passthrough.channel_labels label for {id} must be 1..=64 printable characters without <, > or &" + "passthrough.channel_labels label for {id} must be 1..=64 letters, digits, spaces or - _ . , : # + / ( ) @" ))); } } @@ -711,6 +706,17 @@ fn validate_passthrough(p: &Passthrough) -> Result<(), ConfigError> { Ok(()) } +/// A character a channel label may carry: a letter or digit, an ASCII space, or one of +/// `- _ . , : # + / ( ) @`. Everything else is refused, which covers every control and format +/// character (bidi controls, zero-width characters, U+2028, U+2029), quotes and `< > &`. +fn label_char_ok(c: char) -> bool { + c.is_alphanumeric() + || matches!( + c, + ' ' | '-' | '_' | '.' | ',' | ':' | '#' | '+' | '/' | '(' | ')' | '@' + ) +} + fn validate_approval(a: &Approval, proxy: SocketAddr) -> Result<(), ConfigError> { if !a.listen.ip().is_loopback() { return Err(invalid("approval.listen must be a loopback address")); @@ -2234,6 +2240,11 @@ paths = ["/api/v10/channels/", "/api/v10/users/@me"] "channel_labels = { \"1\" = \"x\" }", "channel_labels = { \"1\" = \"a&b\" }", "channel_labels = { \"1\" = \"a\\nb\" }", + "channel_labels = { \"1\" = \"a\\\"b\" }", + "channel_labels = { \"1\" = \"a'b\" }", + "channel_labels = { \"1\" = \"a\\u2028b\" }", + "channel_labels = { \"1\" = \"a\\u2029b\" }", + "channel_labels = { \"1\" = \"a\\u00A0b\" }", ] { expect_invalid(&with(bad), "channel_labels"); } @@ -2249,6 +2260,40 @@ paths = ["/api/v10/channels/", "/api/v10/users/@me"] ); } + #[test] + fn channel_labels_refuse_bidi_and_zero_width_characters_and_keep_normal_text() { + let with = |label: &str| { + pt_base().replace( + "public_authority = \"gate.example.test\"", + &format!( + "public_authority = \"gate.example.test\"\nchannel_labels = {{ \"1\" = \"{label}\" }}" + ), + ) + }; + for bad in [ + "ops\\u202E", + "\\u202Aops", + "ops\\u202D", + "o\\u2066ps\\u2069", + "o\\u200Bps", + "o\\u200Cps", + "o\\u200Dps", + "o\\u200Eps", + "o\\u200Fps", + "o\\u2060ps", + "\\uFEFFops", + ] { + expect_invalid(&with(bad), "channel_labels"); + } + for good in [ + "ops alerts", + "caf\\u00E9 \\u65E5\\u672C #1 (a+b)/c_d-e.f,g:h@i", + ] { + let c = load(&with(good)).unwrap_or_else(|e| panic!("{good}: {e}")); + assert!(!c.passthrough.unwrap().channel_labels["1"].is_empty()); + } + } + #[test] fn rejects_hold_limits_out_of_range() { for (k, v) in [ diff --git a/crates/ap-core/src/policy.rs b/crates/ap-core/src/policy.rs index a94e0f4..5ae2acf 100644 --- a/crates/ap-core/src/policy.rs +++ b/crates/ap-core/src/policy.rs @@ -5,7 +5,7 @@ use crate::config::{Config, Decision, Grant, Route}; use crate::error::Code; -use std::collections::HashMap; +use std::collections::{BTreeMap, HashMap}; /// What a matching grant does with a request. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -82,6 +82,8 @@ pub(crate) fn patterns_overlap(a: &str, b: &str) -> bool { pub struct Snapshot { routes: HashMap, grants: HashMap>, + /// Display-only channel labels. They take no part in routing, grants or approval. + channel_labels: BTreeMap, } impl Snapshot { @@ -99,7 +101,21 @@ impl Snapshot { .or_default() .push(g.clone()); } - Snapshot { routes, grants } + let channel_labels = cfg + .passthrough + .as_ref() + .map(|p| p.channel_labels.clone()) + .unwrap_or_default(); + Snapshot { + routes, + grants, + channel_labels, + } + } + + /// The channel labels of the policy in force, for display only. + pub fn channel_labels(&self) -> &BTreeMap { + &self.channel_labels } /// The route with this name, if the snapshot has one. diff --git a/crates/ap-proxy/src/approval/mod.rs b/crates/ap-proxy/src/approval/mod.rs index 6ee51ee..8a1b948 100644 --- a/crates/ap-proxy/src/approval/mod.rs +++ b/crates/ap-proxy/src/approval/mod.rs @@ -17,7 +17,6 @@ pub mod csrf; pub mod page; pub mod telegram; -use std::collections::BTreeMap; use std::sync::Arc; use std::time::Duration; @@ -47,8 +46,6 @@ pub struct ApprovalApp { fail_delay: Duration, /// Serve `GET /view/` without Basic auth. Set only when the Telegram buttons are on. view_links: bool, - /// Display-only labels for channel ids, from `[passthrough].channel_labels`. - channel_labels: BTreeMap, } impl std::fmt::Debug for ApprovalApp { @@ -62,7 +59,7 @@ pub type PolicySource = Arc Option> + impl ApprovalApp { pub fn new(table: Arc, cfg: &Approval, policy: PolicySource) -> Arc { - Self::build(table, cfg, FAIL_DELAY, policy, false, BTreeMap::new()) + Self::build(table, cfg, FAIL_DELAY, policy, false) } /// Like [`ApprovalApp::new`], and with `view_links` also serves the no-login one-time view @@ -72,9 +69,8 @@ impl ApprovalApp { cfg: &Approval, policy: PolicySource, view_links: bool, - channel_labels: BTreeMap, ) -> Arc { - Self::build(table, cfg, FAIL_DELAY, policy, view_links, channel_labels) + Self::build(table, cfg, FAIL_DELAY, policy, view_links) } fn build( @@ -83,7 +79,6 @@ impl ApprovalApp { fail_delay: Duration, policy: PolicySource, view_links: bool, - channel_labels: BTreeMap, ) -> Arc { Arc::new(ApprovalApp { table, @@ -93,10 +88,17 @@ impl ApprovalApp { realm: cfg.realm.clone(), fail_delay, view_links, - channel_labels, }) } + /// The channel labels of the policy in force now, read at each page render so a reload + /// shows at once. No valid policy means no labels (the id alone is shown). + fn labels(&self) -> page::Labels { + (self.policy)() + .map(|s| s.channel_labels().clone()) + .unwrap_or_default() + } + fn new_token(&self, id: &str) -> String { let table = &self.table; self.csrf.issue(id, table.limits().hold, |e| { @@ -278,7 +280,7 @@ fn show(app: &ApprovalApp, id: &str, json_wanted: bool) -> Response { } else { html_response( StatusCode::OK, - page::entry(&view, token.as_deref(), &app.channel_labels), + page::entry(&view, token.as_deref(), &app.labels()), ) } } @@ -286,7 +288,7 @@ fn show(app: &ApprovalApp, id: &str, json_wanted: bool) -> Response { /// The read-only page for a `Pending` hold, or the generic 404. fn view_by_token(app: &ApprovalApp, token: &str) -> Response { match app.table.view_by_token(token) { - Some(view) => html_response(StatusCode::OK, page::view_only(&view, &app.channel_labels)), + Some(view) => html_response(StatusCode::OK, page::view_only(&view, &app.labels())), None => result(StatusCode::NOT_FOUND, false, "not_found", None), } } diff --git a/crates/ap-proxy/src/approval/page.rs b/crates/ap-proxy/src/approval/page.rs index bd495f7..bb98ba1 100644 --- a/crates/ap-proxy/src/approval/page.rs +++ b/crates/ap-proxy/src/approval/page.rs @@ -27,6 +27,9 @@ pub type Labels = BTreeMap; const MAX_EMBEDS: usize = 10; const MAX_FIELDS: usize = 25; const MAX_TEXT: usize = 4000; +/// Most top-level field names listed in the extra-fields banner, and characters shown per name. +const MAX_EXTRA_NAMES: usize = 16; +const MAX_NAME: usize = 64; const CUT: &str = "… [truncated]"; /// The stylesheet inlined in every page. The Content-Security-Policy allows this block by hash. @@ -190,6 +193,8 @@ fn header(v: &View) -> String { struct Parsed { content: Option, embeds: Vec, + /// Embeds past [`MAX_EMBEDS`], which are not shown. + omitted_embeds: usize, /// Some text, embed or field was cut for display. truncated: bool, } @@ -199,6 +204,8 @@ struct EmbedText { title: Option, description: Option, fields: Vec<(String, String)>, + /// Fields past [`MAX_FIELDS`], which are not shown. + omitted_fields: usize, } /// Cut `s` to [`MAX_TEXT`] characters; the second value says whether it was cut. @@ -225,17 +232,21 @@ fn parse_body(body: &str) -> Option { let mut truncated = false; let content = clip_str(fields.get("content"), &mut truncated); let mut embeds = Vec::new(); + let mut omitted_embeds = 0; if let Some(Value::Array(list)) = fields.get("embeds") { - truncated |= list.len() > MAX_EMBEDS; + omitted_embeds = list.len().saturating_sub(MAX_EMBEDS); + truncated |= omitted_embeds > 0; for e in list.iter().take(MAX_EMBEDS) { let Value::Object(e) = e else { continue }; let mut t = EmbedText { title: clip_str(e.get("title"), &mut truncated), description: clip_str(e.get("description"), &mut truncated), fields: Vec::new(), + omitted_fields: 0, }; if let Some(Value::Array(fl)) = e.get("fields") { - truncated |= fl.len() > MAX_FIELDS; + t.omitted_fields = fl.len().saturating_sub(MAX_FIELDS); + truncated |= t.omitted_fields > 0; for f in fl.iter().take(MAX_FIELDS) { let name = clip_str(f.get("name"), &mut truncated); let value = clip_str(f.get("value"), &mut truncated); @@ -256,6 +267,7 @@ fn parse_body(body: &str) -> Option { Some(Parsed { content, embeds, + omitted_embeds, truncated, }) } @@ -373,40 +385,62 @@ fn embed_html(n: usize, e: &EmbedText) -> String { for (name, value) in &e.fields { t.push_str(&format!("Field {}: {}\n", escape(name), escape(value))); } + if e.omitted_fields > 0 { + t.push_str(&format!( + "[{} more {} omitted]\n", + e.omitted_fields, + if e.omitted_fields == 1 { + "field" + } else { + "fields" + } + )); + } format!( "

Embed {n}

\n
{}
\n", t.trim_end() ) } -/// The top-level fields of a JSON object body other than `content`, as names only. serde_json -/// without `preserve_order` keeps object keys sorted, so these are sorted, not in body order. -/// Empty for anything that is not a JSON object. -fn extra_field_names(body: &str) -> Vec { - match serde_json::from_str::(body) { - Ok(Value::Object(fields)) => fields - .keys() - .filter(|k| k.as_str() != "content") - .cloned() - .collect(), - _ => Vec::new(), +/// The top-level fields of a JSON object body other than `content`: how many there are, and the +/// first [`MAX_EXTRA_NAMES`] names, each cut to [`MAX_NAME`] characters. serde_json without +/// `preserve_order` keeps object keys sorted, so these are sorted, not in body order. Zero names +/// for anything that is not a JSON object. +fn extra_field_names(body: &str) -> (usize, Vec) { + let Ok(Value::Object(fields)) = serde_json::from_str::(body) else { + return (0, Vec::new()); + }; + let mut total = 0; + let mut shown = Vec::new(); + for k in fields.keys().filter(|k| k.as_str() != "content") { + total += 1; + if shown.len() < MAX_EXTRA_NAMES { + shown.push(match k.char_indices().nth(MAX_NAME) { + Some((i, _)) => format!("{}{CUT}", &k[..i]), + None => k.clone(), + }); + } } + (total, shown) } -/// The visible line that names fields sent besides `content`. Empty when there are none. +/// The visible line that names fields sent besides `content`. Empty when there are none. The +/// line is bounded: names past the cap are counted, not listed. fn extra_fields_line(body: &str) -> String { - let names = extra_field_names(body); - if names.is_empty() { + let (total, names) = extra_field_names(body); + if total == 0 { return String::new(); } let escaped: Vec = names.iter().map(|n| escape(n)).collect(); - let (count, noun) = if names.len() == 1 { - (1, "field") + let noun = if total == 1 { "field" } else { "fields" }; + let rest = total - names.len(); + let more = if rest > 0 { + format!(", … and {rest} more not listed") } else { - (names.len(), "fields") + String::new() }; format!( - "

+ {count} more {noun} will be sent: {} (see Details)

\n", + "

+ {total} more {noun} will be sent: {}{more} (see Details)

\n", escaped.join(", ") ) } @@ -454,6 +488,13 @@ fn payload(c: &ViewContent, labels: &Labels) -> String { for (i, e) in p.embeds.iter().enumerate() { b.push_str(&embed_html(i + 1, e)); } + if p.omitted_embeds > 0 { + b.push_str(&format!( + "

{} more {} omitted. See the raw body in Details.

\n", + p.omitted_embeds, + if p.omitted_embeds == 1 { "embed" } else { "embeds" } + )); + } } None => b.push_str(&format!( "
{}
\n", @@ -927,6 +968,62 @@ mod tests { assert!(!html.contains("x"), "{html}"); } + #[test] + fn the_extra_fields_banner_is_bounded_and_marks_what_it_cuts() { + let long = format!("a{}", "y".repeat(5000)); + let keys: Vec = (0..300).map(|i| format!(r#""k{i:03}":1"#)).collect(); + let body = format!(r#"{{"content":"hi","{long}":1,{}}}"#, keys.join(",")); + let html = entry(&with_body(&body), Some("t"), &Labels::new()); + let start = html + .find("

") + .expect("indicator"); + let end = start + html[start..].find("

").unwrap(); + let line = &html[start..end]; + assert!(line.len() < 1500, "banner is {} bytes", line.len()); + assert!(line.contains("+ 301 more fields will be sent: "), "{line}"); + assert!( + line.contains(&format!("a{}{CUT}", "y".repeat(MAX_NAME - 1))), + "{line}" + ); + assert!(!line.contains(&"y".repeat(MAX_NAME + 1)), "{line}"); + assert!(line.contains("k014") && !line.contains("k015"), "{line}"); + assert!( + line.contains(", … and 285 more not listed (see Details)"), + "{line}" + ); + // The raw body in Details is complete. + assert!(html.contains(&escape(&long))); + assert!(html.contains("k299")); + } + + #[test] + fn cut_embeds_and_embed_fields_are_marked_as_omitted() { + let embeds: Vec = (0..MAX_EMBEDS + 3) + .map(|i| format!(r#"{{"title":"e{i}"}}"#)) + .collect(); + let body = format!(r#"{{"embeds":[{}]}}"#, embeds.join(",")); + let html = entry(&at(CH, &body), Some("t"), &Labels::new()); + assert!( + html.contains("3 more embeds omitted."), + "{html}" + ); + assert!(!html.contains(&format!("Embed {}", MAX_EMBEDS + 1))); + let fields: Vec = (0..MAX_FIELDS + 2) + .map(|i| format!(r#"{{"name":"n{i}","value":"v"}}"#)) + .collect(); + let body = format!(r#"{{"embeds":[{{"fields":[{}]}}]}}"#, fields.join(",")); + let html = entry(&at(CH, &body), None, &Labels::new()); + assert!(html.contains("[2 more fields omitted]"), "{html}"); + assert!(!html.contains(&format!("Field n{MAX_FIELDS}: v"))); + // Nothing is cut, so no marker. + let html = entry( + &at(CH, r#"{"embeds":[{"fields":[{"name":"a","value":"b"}]}]}"#), + None, + &Labels::new(), + ); + assert!(!html.contains("omitted"), "{html}"); + } + fn labels() -> Labels { Labels::from([("4242".to_string(), "ops-alerts".to_string())]) } diff --git a/crates/ap-proxy/src/approval/tests.rs b/crates/ap-proxy/src/approval/tests.rs index f03384d..4ac5e13 100644 --- a/crates/ap-proxy/src/approval/tests.rs +++ b/crates/ap-proxy/src/approval/tests.rs @@ -223,7 +223,6 @@ path_patterns = ["/hold/*", "/webhooks/*/*"] delay, app.policy_source(), view_links, - std::collections::BTreeMap::new(), ); let l = crate::listener::bind_loopback("127.0.0.1:0".parse().unwrap()) .await @@ -1325,6 +1324,68 @@ async fn view_token_serves_the_redacted_page_while_live_and_404_after_each_end() } } +/// The policy text of an `Env`, with a hold grant for `/hold/channels/*` and, when given, one +/// channel label for id 4242 under `[passthrough]`. +fn policy_with_label(base: &str, label: Option<&str>) -> String { + let labels = label.map_or(String::new(), |l| { + format!("channel_labels = {{ \"4242\" = \"{l}\" }}\n") + }); + let mut t = base.replace( + "cooldown_secs = 0\n", + &format!("cooldown_secs = 0\n{labels}"), + ); + t.push_str("\n[[grant]]\nidentity = \"muse-pilot\"\nroute = \"discord\"\nmethods = [\"POST\"]\ndecision = \"hold\"\npath_patterns = [\"/hold/channels/*\"]\n"); + t +} + +/// The one-time view page and the login page of one pending hold. +async fn pages(env: &Env, id: &str, token: &str) -> (Resp, Resp) { + let view = send(env.addr, &request("GET", &format!("/view/{token}"), "", "")).await; + let page = env.get(&format!("/pending/{id}"), "").await; + (view, page) +} + +#[tokio::test] +async fn a_label_only_reload_changes_the_label_on_the_pending_holds_pages() { + let env = Env::with_views("tg-label-reload").await; + let policy = env._s.path().join("policy.toml"); + let base = std::fs::read_to_string(&policy).unwrap(); + std::fs::write(&policy, policy_with_label(&base, Some("alpha-one"))).unwrap(); + let (h, id) = env + .hold("/discord/hold/channels/4242", br#"{"content":"hi"}"#) + .await; + let token = view_token_of(&env, &id); + let (v, p) = pages(&env, &id, &token).await; + for body in [&v.body, &p.body] { + assert!(body.contains("alpha-one (id 4242)"), "{body}"); + } + + // A label-only change: same grants, same routes. The hold survives the reload tick. + std::fs::write(&policy, policy_with_label(&base, Some("beta-two"))).unwrap(); + env.app.reload_tick(); + assert_eq!(env.app.hold.state(&id), Some(State::Pending)); + let (v, p) = pages(&env, &id, &token).await; + for body in [&v.body, &p.body] { + assert!(body.contains("beta-two (id 4242)"), "{body}"); + assert!(!body.contains("alpha-one"), "{body}"); + } + + // Removing the label shows the id alone. + std::fs::write(&policy, policy_with_label(&base, None)).unwrap(); + env.app.reload_tick(); + assert_eq!(env.app.hold.state(&id), Some(State::Pending)); + let (v, p) = pages(&env, &id, &token).await; + for body in [&v.body, &p.body] { + assert!( + body.contains("

id 4242

"), + "{body}" + ); + assert!(!body.contains("beta-two"), "{body}"); + } + env.app.hold.drop_all(); + let _ = h.await; +} + #[tokio::test] async fn view_links_off_have_no_view_route_and_pending_keeps_basic_auth() { let off = Env::new("tg-views-off").await; diff --git a/crates/ap-proxy/src/lib.rs b/crates/ap-proxy/src/lib.rs index d7d39ec..f3112b0 100644 --- a/crates/ap-proxy/src/lib.rs +++ b/crates/ap-proxy/src/lib.rs @@ -424,7 +424,6 @@ a passthrough-only config has no per-UID rules" &cfg, app.policy_source(), buttons_on, - pt.channel_labels.clone(), ); listener::approval::serve_approval(l, state, Default::default()).await; } diff --git a/docs/runbooks/muse-stage2.md b/docs/runbooks/muse-stage2.md index 67100e5..84e1acc 100644 --- a/docs/runbooks/muse-stage2.md +++ b/docs/runbooks/muse-stage2.md @@ -213,8 +213,7 @@ Client rules: - A deny or an expiry starts the per-identity cooldown (default 60 s, `[passthrough] cooldown_secs`), so a quick new POST can get 503 `cooldown`. - Never log the poll token. -Optional channel labels: `[passthrough] channel_labels = { "" = "ops-alerts" }` (digits-only ids, at most 64 entries, labels 1..=64 printable characters without `<`, `>` or `&`). The view page then shows `ops-alerts (id )` for the channel in the request path, or the id alone without a label. A label is display only and never affects routing, grants or approval. -The view page shows the message text, each embed's title, description and fields as plain text (URLs stay inert, nothing is loaded), and marks mentions in place (`user`, `role`, `channel`, with the raw id; `@everyone` and `@here` carry a warning). The gate looks up no names. Long text and extra embeds are cut with a "truncated" marker; the raw JSON in Details is complete. +Optional channel labels: `[passthrough] channel_labels = { "" = "ops-alerts" }` (digits-only ids, at most 64 entries, labels 1..=64 letters, digits, spaces or `- _ . , : # + / ( ) @`). The view page then shows `ops-alerts (id )` for the channel in the request path, or the id alone without a label. A label is display only and never affects routing, grants or approval. ## 8. Not claimed From 31cb853f1b40bfc1e6815bd2365966df75bc0bbd Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Sat, 28 Nov 2026 09:00:38 -0500 Subject: [PATCH 3/4] fix: name embed keys that the approval page does not render Each embed block now ends with 'not shown here: ' for keys other than title, description and fields (max 8 names, 32 chars each, '+N more'; names escaped, values never shown). Tests: embed_keys_that_are_not_rendered_are_named_without_their_values, the_unshown_keys_note_is_bounded_and_escaped, an_embed_with_only_title_description_and_fields_has_no_unshown_note. --- crates/ap-proxy/src/approval/page.rs | 80 ++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) diff --git a/crates/ap-proxy/src/approval/page.rs b/crates/ap-proxy/src/approval/page.rs index bb98ba1..175f37b 100644 --- a/crates/ap-proxy/src/approval/page.rs +++ b/crates/ap-proxy/src/approval/page.rs @@ -206,8 +206,17 @@ struct EmbedText { fields: Vec<(String, String)>, /// Fields past [`MAX_FIELDS`], which are not shown. omitted_fields: usize, + /// Keys of the embed other than title, description and fields: names only, cut to + /// [`MAX_UNSHOWN_NAMES`] names of [`MAX_UNSHOWN_NAME`] characters. + unshown: Vec, + /// Keys past [`MAX_UNSHOWN_NAMES`]. + unshown_more: usize, } +/// Most key names, and characters per name, listed in the "not shown here" note of an embed. +const MAX_UNSHOWN_NAMES: usize = 8; +const MAX_UNSHOWN_NAME: usize = 32; + /// Cut `s` to [`MAX_TEXT`] characters; the second value says whether it was cut. fn clip(s: &str) -> (String, bool) { match s.char_indices().nth(MAX_TEXT) { @@ -243,7 +252,22 @@ fn parse_body(body: &str) -> Option { description: clip_str(e.get("description"), &mut truncated), fields: Vec::new(), omitted_fields: 0, + unshown: Vec::new(), + unshown_more: 0, }; + let keys = e + .keys() + .filter(|k| !matches!(k.as_str(), "title" | "description" | "fields")); + for k in keys { + if t.unshown.len() < MAX_UNSHOWN_NAMES { + t.unshown.push(match k.char_indices().nth(MAX_UNSHOWN_NAME) { + Some((i, _)) => format!("{}{CUT}", &k[..i]), + None => k.clone(), + }); + } else { + t.unshown_more += 1; + } + } if let Some(Value::Array(fl)) = e.get("fields") { t.omitted_fields = fl.len().saturating_sub(MAX_FIELDS); truncated |= t.omitted_fields > 0; @@ -396,6 +420,15 @@ fn embed_html(n: usize, e: &EmbedText) -> String { } )); } + if !e.unshown.is_empty() { + let names: Vec = e.unshown.iter().map(|k| escape(k)).collect(); + let more = if e.unshown_more > 0 { + format!(", +{} more", e.unshown_more) + } else { + String::new() + }; + t.push_str(&format!("not shown here: {}{more}\n", names.join(", "))); + } format!( "

Embed {n}

\n
{}
\n", t.trim_end() @@ -1140,6 +1173,53 @@ mod tests { assert!(html[payload_end..].matches("img.example.test").count() >= 2); } + #[test] + fn embed_keys_that_are_not_rendered_are_named_without_their_values() { + let body = r#"{"embeds":[{"title":"T","author":{"name":"AUTHVAL"},"footer":{"text":"FOOTVAL"},"image":{"url":"https://img.example.test/i.png"},"thumbnail":{"url":"https://img.example.test/t.png"},"url":"https://example.test/u"},{"title":"Plain","description":"d","fields":[{"name":"a","value":"b"}]}]}"#; + let html = entry(&at(CH, body), Some("t"), &Labels::new()); + let shown = &html[..html.find("
").unwrap()]; + assert!( + shown.contains("not shown here: author, footer, image, thumbnail, url"), + "{shown}" + ); + assert_eq!(shown.matches("not shown here").count(), 1, "{shown}"); + for banned in ["AUTHVAL", "FOOTVAL", "example.test", "").unwrap()..].contains("AUTHVAL")); + // An embed with only unrendered keys is still shown, with the note. + let html = entry(&at(CH, r#"{"embeds":[{"image":{"url":"x"}}]}"#), None, &Labels::new()); + assert!(html.contains("Embed 1") && html.contains("not shown here: image"), "{html}"); + } + + #[test] + fn the_unshown_keys_note_is_bounded_and_escaped() { + let keys: Vec = (0..MAX_UNSHOWN_NAMES + 3) + .map(|i| format!(r#""k{i:02}":1"#)) + .collect(); + let body = format!(r#"{{"embeds":[{{"title":"T",{}}}]}}"#, keys.join(",")); + let html = entry(&at(CH, &body), None, &Labels::new()); + assert!(html.contains("not shown here: k00, k01"), "{html}"); + assert!(html.contains("k07, +3 more"), "{html}"); + assert!(!html.contains("k08, ") && !html.contains("k10, "), "{html}"); + let long = "z".repeat(MAX_UNSHOWN_NAME + 10); + let body = format!(r#"{{"embeds":[{{"title":"T","{long}":1,"x":1}}]}}"#); + let html = entry(&at(CH, &body), None, &Labels::new()); + let shown = &html[..html.find("
").unwrap()]; + assert!(shown.contains("<b>x</b>"), "{shown}"); + assert!(!shown.contains("x"), "{shown}"); + assert!(shown.contains(&format!("{}{CUT}", "z".repeat(MAX_UNSHOWN_NAME))), "{shown}"); + assert!(!shown.contains(&long), "{shown}"); + } + + #[test] + fn an_embed_with_only_title_description_and_fields_has_no_unshown_note() { + let body = r#"{"embeds":[{"title":"T","description":"d","fields":[{"name":"a","value":"b"}]}]}"#; + let html = entry(&at(CH, body), Some("t"), &Labels::new()); + assert!(!html.contains("not shown here"), "{html}"); + } + #[test] fn long_text_and_many_embeds_are_cut_with_a_marker() { let long = "x".repeat(MAX_TEXT + 10); From 5ac43fe95164d28bfdb564ed89b1e07fd7120147 Mon Sep 17 00:00:00 2001 From: chaodu-agent <274062505+chaodu-agent@users.noreply.github.com> Date: Sat, 28 Nov 2026 09:00:47 -0500 Subject: [PATCH 4/4] style: cargo fmt the unshown-keys tests Previous commit 31cb853 failed cargo fmt --all -- --check on macmini (exit 1); formatted only. --- crates/ap-proxy/src/approval/page.rs | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/crates/ap-proxy/src/approval/page.rs b/crates/ap-proxy/src/approval/page.rs index 175f37b..00ed33f 100644 --- a/crates/ap-proxy/src/approval/page.rs +++ b/crates/ap-proxy/src/approval/page.rs @@ -260,10 +260,11 @@ fn parse_body(body: &str) -> Option { .filter(|k| !matches!(k.as_str(), "title" | "description" | "fields")); for k in keys { if t.unshown.len() < MAX_UNSHOWN_NAMES { - t.unshown.push(match k.char_indices().nth(MAX_UNSHOWN_NAME) { - Some((i, _)) => format!("{}{CUT}", &k[..i]), - None => k.clone(), - }); + t.unshown + .push(match k.char_indices().nth(MAX_UNSHOWN_NAME) { + Some((i, _)) => format!("{}{CUT}", &k[..i]), + None => k.clone(), + }); } else { t.unshown_more += 1; } @@ -1189,8 +1190,15 @@ mod tests { // Raw JSON in Details stays complete. assert!(html[html.find("
").unwrap()..].contains("AUTHVAL")); // An embed with only unrendered keys is still shown, with the note. - let html = entry(&at(CH, r#"{"embeds":[{"image":{"url":"x"}}]}"#), None, &Labels::new()); - assert!(html.contains("Embed 1") && html.contains("not shown here: image"), "{html}"); + let html = entry( + &at(CH, r#"{"embeds":[{"image":{"url":"x"}}]}"#), + None, + &Labels::new(), + ); + assert!( + html.contains("Embed 1") && html.contains("not shown here: image"), + "{html}" + ); } #[test] @@ -1209,13 +1217,17 @@ mod tests { let shown = &html[..html.find("
").unwrap()]; assert!(shown.contains("<b>x</b>"), "{shown}"); assert!(!shown.contains("x"), "{shown}"); - assert!(shown.contains(&format!("{}{CUT}", "z".repeat(MAX_UNSHOWN_NAME))), "{shown}"); + assert!( + shown.contains(&format!("{}{CUT}", "z".repeat(MAX_UNSHOWN_NAME))), + "{shown}" + ); assert!(!shown.contains(&long), "{shown}"); } #[test] fn an_embed_with_only_title_description_and_fields_has_no_unshown_note() { - let body = r#"{"embeds":[{"title":"T","description":"d","fields":[{"name":"a","value":"b"}]}]}"#; + let body = + r#"{"embeds":[{"title":"T","description":"d","fields":[{"name":"a","value":"b"}]}]}"#; let html = entry(&at(CH, body), Some("t"), &Labels::new()); assert!(!html.contains("not shown here"), "{html}"); }