diff --git a/crates/ap-core/src/config.rs b/crates/ap-core/src/config.rs index 698076f..edf71de 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,21 @@ 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().all(label_char_ok) { + return Err(invalid(format!( + "passthrough.channel_labels label for {id} must be 1..=64 letters, digits, spaces or - _ . , : # + / ( ) @" + ))); + } + } if !(1..=1024).contains(&p.max_held_total) { return Err(invalid("passthrough.max_held_total must be in 1..=1024")); } @@ -686,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")); @@ -2185,6 +2216,84 @@ 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\" }", + "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"); + } + 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 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 ef91bf8..8a1b948 100644 --- a/crates/ap-proxy/src/approval/mod.rs +++ b/crates/ap-proxy/src/approval/mod.rs @@ -91,6 +91,14 @@ impl ApprovalApp { }) } + /// 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| { @@ -270,14 +278,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.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.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..00ed33f 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,18 @@ 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; +/// 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. const STYLE: &str = r#" *{box-sizing:border-box} @@ -175,47 +188,293 @@ 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, + /// Embeds past [`MAX_EMBEDS`], which are not shown. + omitted_embeds: usize, + /// 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)>, + /// 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) { + 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(); + let mut omitted_embeds = 0; + if let Some(Value::Array(list)) = fields.get("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, + 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; + 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, + omitted_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 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 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))); + } + if e.omitted_fields > 0 { + t.push_str(&format!( + "[{} more {} omitted]\n", + e.omitted_fields, + if e.omitted_fields == 1 { + "field" + } else { + "fields" + } + )); + } + 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() + ) } -/// The visible line that names fields sent besides `content`. Empty when there are none. +/// 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 +/// 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(", ") ) } @@ -223,7 +482,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 +493,48 @@ 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)); + } + 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", + escape(&c.body_text) + )), + } b.push_str("
\n"); b } @@ -300,7 +596,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 +609,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 +629,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 +641,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 +753,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 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); + 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..4ac5e13 100644 --- a/crates/ap-proxy/src/approval/tests.rs +++ b/crates/ap-proxy/src/approval/tests.rs @@ -1324,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/docs/runbooks/muse-stage2.md b/docs/runbooks/muse-stage2.md index f372222..84e1acc 100644 --- a/docs/runbooks/muse-stage2.md +++ b/docs/runbooks/muse-stage2.md @@ -213,6 +213,8 @@ 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 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 - Protection from the Muse platform or anything that holds the real token.