Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Import QA fixes: wider key scrub, parse-based plain-text check, clearer 16k notice, no hidden characters in names
Lin (kwant bot)7bb25ac608a3
diff --git a/src/import/mod.rs b/src/import/mod.rsindex 2fe81c6a..bc188ef9 100644--- a/src/import/mod.rs+++ b/src/import/mod.rs@@ -224,10 +224,24 @@ pub(crate) fn cut(s: &str, max: usize) -> String {s.chars().take(max).collect()}-/// A bot name kwant accepts: no spaces or `@`, at most [`MAX_NAME_CHARS`].+/// Control characters, and characters that draw nothing or turn text around (zero-width+/// spaces, U+202E right-to-left override and the other bidi controls, soft hyphens).+pub(crate) fn is_hidden(c: char) -> bool {+ c.is_control()+ || matches!(c, '\u{00AD}' | '\u{061C}' | '\u{180E}' | '\u{200B}'..='\u{200F}' | '\u{202A}'..='\u{202E}'+ | '\u{2060}'..='\u{2064}' | '\u{2066}'..='\u{2069}' | '\u{FEFF}' | '\u{FFF9}'..='\u{FFFB}')+}++/// A one-line label (title, team or routine name): whitespace collapsed, hidden characters gone.+fn one_line(raw: &str, max: usize) -> String {+ let visible: String = raw.chars().map(|c| if c.is_whitespace() { ' ' } else { c }).filter(|c| !is_hidden(*c)).collect();+ cut(visible.split_whitespace().collect::<Vec<_>>().join(" ").as_str(), max)+}++/// A bot name kwant accepts: no spaces, `@` or hidden characters, at most [`MAX_NAME_CHARS`].pub fn clean_bot_name(raw: &str) -> String {let joined = raw.split_whitespace().collect::<Vec<_>>().join("-");- let name: String = joined.chars().filter(|c| *c != '@' && !c.is_control()).collect();+ let name: String = joined.chars().filter(|c| *c != '@' && !is_hidden(*c)).collect();let name = cut(name.trim_matches('-'), MAX_NAME_CHARS);if name.is_empty() {"Imported-bot".into()@@ -405,12 +419,20 @@ pub fn normalize(mut bundle: Bundle, existing: &[String]) -> Checked {if name != wanted {renames.push(Rename { ref_: r.clone(), from: wanted.clone(), to: name.clone() });} else if wanted != bot.name.trim() {- warnings.push(Notice::new(who, format!("Bot names can't have spaces or @, so \"{}\" becomes {wanted}.", bot.name.trim())));+ let shown: String = bot.name.trim().chars().filter(|c| !is_hidden(*c)).collect();+ warnings.push(Notice::new(+ who,+ if shown == wanted {+ format!("We removed hidden characters from the name {wanted}.")+ } else {+ format!("Bot names can't have spaces or @, so \"{shown}\" becomes {wanted}.")+ },+ ));}taken.insert(name.to_lowercase());bot.name = name;- bot.title = cut(bot.title.split_whitespace().collect::<Vec<_>>().join(" ").as_str(), MAX_TITLE_CHARS);+ bot.title = one_line(&bot.title, MAX_TITLE_CHARS);if bot.title.is_empty() {bot.title = "Imported bot".into();}@@ -422,7 +444,7 @@ pub fn normalize(mut bundle: Bundle, existing: &[String]) -> Checked {for (field, text) in [("instructions", &bot.persona_prompt), ("soul", &bot.soul)] {let n = text.chars().count();if n > MAX_PERSONA_CHARS {- problems.push(Notice::new(who, format!("{} ({n} now). Shorten it here before importing.", persona_too_long(&format!("{}'s {field}", bot.name)))));+ problems.push(Notice::new(who, format!("{} ({n} now). Shorten it where it came from (or in the pasted reply), then try the import again.", persona_too_long(&format!("{}'s {field}", bot.name)))));}for why in suspicious(text) {warnings.push(Notice::new(who, format!("The {field} {why}. Read it before importing.")));@@ -468,7 +490,7 @@ pub fn normalize(mut bundle: Bundle, existing: &[String]) -> Checked {let mut team_names = HashSet::new();let teams = std::mem::take(&mut bundle.teams);for mut team in teams {- team.name = cut(team.name.split_whitespace().collect::<Vec<_>>().join(" ").as_str(), MAX_TEAM_NAME_CHARS);+ team.name = one_line(&team.name, MAX_TEAM_NAME_CHARS);let mut members: Vec<String> = Vec::new();for m in team.lead.iter().chain(team.members.iter()) {let m = m.trim().to_string();@@ -553,7 +575,7 @@ fn tidy_routines() -> Vec<RoutineSpec> {let mut out = Vec::new();for r in routines {- let name = cut(r.name.split_whitespace().collect::<Vec<_>>().join(" ").as_str(), MAX_ROUTINE_NAME_CHARS);+ let name = one_line(&r.name, MAX_ROUTINE_NAME_CHARS);let instructions = r.instructions.trim().to_string();let label = if name.is_empty() { "(unnamed)".to_string() } else { name.clone() };if name.is_empty() || instructions.is_empty() {@@ -634,6 +656,9 @@ mod tests {fn names_are_cleaned_and_renamed_on_clash() {assert_eq!(clean_bot_name(" Code Reviewer @x "), "Code-Reviewer-x");assert_eq!(clean_bot_name(" "), "Imported-bot");+ // IMPORT-QA.md F5: right-to-left override, zero-width and control characters go.+ assert_eq!(clean_bot_name("Evil\u{202E}Name\u{200B}\u{7}"), "EvilName");+ assert_eq!(one_line(" Team\u{2066} A\u{202E}\tB ", 40), "Team A B");let taken: HashSet<String> = ["ada".into(), "ada-2".into()].into_iter().collect();assert_eq!(free_name("Ada", &taken), "Ada-3");}diff --git a/src/import/parsers.rs b/src/import/parsers.rsindex 21f1f037..73e42325 100644--- a/src/import/parsers.rs+++ b/src/import/parsers.rs@@ -70,16 +70,53 @@ pub fn parse_pasted(text: &str) -> Result<Bundle, ImportError> {return Err(invalid("There's nothing to import in this text. Paste your bot's reply or its instructions."));}match from_text(text, None) {- Err(ImportError::Invalid(_) | ImportError::Unsupported(_)) if !looks_structured(text) => Ok(from_plain_text(text)),+ Err(ImportError::Invalid(_) | ImportError::Unsupported(_)) if !means_export(text) => Ok(from_plain_text(text)),+ Err(ImportError::Unsupported(_)) => Err(invalid(+ "This looks like a bot export, but not one kwant reads. Paste the whole reply to the export prompt, \+ starting at the ```json line.",+ )),other => other,}}-/// Whether pasted text means to be JSON or front matter, so a broken reply still gets its error-/// instead of being taken as instructions.-fn looks_structured(text: &str) -> bool {+/// Fields that only an export has; a broken JSON object naming one of them was meant as one.+const EXPORT_KEYS: [&str; 4] = ["format", "spec", "bots", "bot"];++/// Whether pasted text that didn't import was meant as an export, so it gets its error instead+/// of being taken as instructions: front matter with fields, or a JSON object (the whole text or+/// a fenced block) that is shaped like a bundle, or doesn't parse but has an export's fields.+/// Instructions that mention `"format"`, start with `{` or show a JSON example are not.+fn means_export(text: &str) -> bool {let t = text.trim_start();- t.starts_with('{') || t.starts_with("---") || t.contains("```json") || t.contains("\"format\"") || t.contains("kwant.bundle/")+ if let Some(rest) = t.strip_prefix("---") {+ if let Some(end) = rest.find("\n---") {+ return rest[..end].lines().any(|l| {+ let l = l.trim_start();+ l.split_once(':').is_some_and(|(k, _)| !k.is_empty() && k.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-'))+ });+ }+ }+ let whole = t.starts_with('{').then_some(t);+ whole.into_iter().chain(fenced_objects(text)).any(|obj| match serde_json::from_str::<Value>(obj) {+ Ok(v) => bundle_shaped(&v),+ Err(_) => EXPORT_KEYS.iter().any(|k| has_json_key(obj, k)),+ })+}++/// A JSON object naming a format kwant reads, or carrying bots.+fn bundle_shaped(v: &Value) -> bool {+ let format = v.get("format").and_then(Value::as_str).unwrap_or("");+ let spec = v.get("spec").and_then(Value::as_str).unwrap_or("");+ ["kwant.bundle/", "grokbot-bundle/", "openmaus."].iter().any(|p| format.starts_with(p))+ || spec.starts_with("chara_card")+ || v.get("bots").is_some()+ || v.get("bot").is_some()+}++/// Whether `obj` has `"key"` followed by a colon, as a JSON field.+fn has_json_key(obj: &str, key: &str) -> bool {+ let quoted = format!("\"{key}\"");+ obj.match_indices("ed).any(|(i, _)| obj[i + quoted.len()..].trim_start().starts_with(':'))}/// One bot whose instructions are the whole text. Its name and title are the defaults@@ -114,21 +151,31 @@ fn from_text(text: &str, filename: Option<&str>) -> Result<Bundle, ImportError>Ok(b)}-/// The JSON in a pasted reply: a ```json fence (or any fence starting with `{`), else the span-/// from the first `{` to the last `}`.-pub fn json_block(text: &str) -> Option<&str> {+/// Every fenced block in `text` whose body starts with `{`, up to its last `}`. An unclosed+/// fence runs to the end of the reply; the object still ends at its last brace.+fn fenced_objects(text: &str) -> impl Iterator<Item = &str> {let mut rest = text;- while let Some(open) = rest.find("```") {- let after = &rest[open + 3..];- let body_start = after.find('\n').map(|i| i + 1).unwrap_or(after.len());- let body = &after[body_start..];- let close = body.find("```").unwrap_or(body.len());- let inner = body[..close].trim();- // An unclosed fence runs to the end of the reply; the object still ends at its last brace.- if let (true, Some(end)) = (inner.starts_with('{'), inner.rfind('}')) {- return Some(&inner[..=end]);+ std::iter::from_fn(move || {+ while let Some(open) = rest.find("```") {+ let after = &rest[open + 3..];+ let body_start = after.find('\n').map(|i| i + 1).unwrap_or(after.len());+ let body = &after[body_start..];+ let close = body.find("```").unwrap_or(body.len());+ let inner = body[..close].trim();+ rest = &body[(close + 3).min(body.len())..];+ if let (true, Some(end)) = (inner.starts_with('{'), inner.rfind('}')) {+ return Some(&inner[..=end]);+ }}- rest = &body[(close + 3).min(body.len())..];+ None+ })+}++/// The JSON in a pasted reply: the first fenced block that is an object, else the span from the+/// first `{` to the last `}`.+pub fn json_block(text: &str) -> Option<&str> {+ if let Some(obj) = fenced_objects(text).next() {+ return Some(obj);}let (a, b) = (text.find('{')?, text.rfind('}')?);(a < b).then(|| &text[a..=b])@@ -633,11 +680,35 @@ mod tests {assert_eq!(parse_pasted("Greet {user} by name.").unwrap().bots[0].persona_prompt, "Greet {user} by name.");assert!(matches!(parse_pasted(" \n"), Err(ImportError::Invalid(_))));assert!(matches!(parse_pasted("{ \"format\": "), Err(ImportError::Invalid(_))));- assert!(matches!(parse_pasted("Here:\n```json\n{ nope }\n```"), Err(ImportError::Invalid(_))));+ assert!(matches!(parse_pasted("Here:\n```json\n{ \"format\": \"kwant.bundle/1\", nope }\n```"), Err(ImportError::Invalid(_))));+ assert!(matches!(parse_pasted("```json\n{\"bots\": [{\"name\": \"x\"}]}\n```"), Err(ImportError::Invalid(_))));+ assert!(matches!(parse_pasted("---\nname: x\nfoo: [unclosed\n---\nBody"), Err(ImportError::Invalid(_))));// A file upload doesn't fall back: an unknown file stays unknown.assert!(parse_file(b"just words", Some("notes.txt")).is_err());}+ #[test]+ fn instructions_that_look_a_bit_like_json_are_plain_text() {+ // IMPORT-QA.md F2: each of these got a 422 or 415.+ for text in [+ "Always answer in the \"format\" the user asks for.",+ "I like the kwant.bundle/1 format.",+ "{Be nice} to everyone.",+ "Reply with JSON like this:\n```json\n{\"answer\": 1}\n```\nNothing else.",+ "Reply with JSON like:\n```json\n{ \"answer\": ... }\n```",+ "{\"a\": 1}",+ "Use \"format\": \"markdown\" when asked.",+ "---\nA horizontal rule, then instructions.",+ ] {+ let b = parse_pasted(text).unwrap_or_else(|e| panic!("{text:?}: {e}"));+ assert_eq!(b.source.kind, crate::import::PLAIN_TEXT_KIND, "{text:?}");+ assert_eq!(b.bots[0].persona_prompt, text);+ }+ // A real reply after a JSON example still imports as the reply.+ let reply = "```json\n{\"format\": \"kwant.bundle/1\", \"bots\": [{\"name\": \"Ok\"}]}\n```";+ assert_eq!(parse_pasted(reply).unwrap().bots[0].name, "Ok");+ }+#[test]fn memory_markdown() {let m = memories_from_markdown("# Memory\n- likes tea\n- lives in\n Kyiv\n\nA paragraph\nover lines.");diff --git a/src/import/scrub.rs b/src/import/scrub.rsindex 8a008f3e..2a9d7f8c 100644--- a/src/import/scrub.rs+++ b/src/import/scrub.rs@@ -42,7 +42,7 @@ fn looks_like_key(t: &str) -> bool {|| prefixed(&["AIza"], 30)|| prefixed(&["ghp_", "gho_", "ghu_", "ghs_", "ghr_", "github_pat_", "glpat-"], 24)|| prefixed(&["xoxb-", "xoxp-", "xoxa-", "xoxr-", "xoxs-"], 20)- || prefixed(&["hf_"], 30)+ || prefixed(&["hf_", "npm_", "ya29."], 30){return true;}@@ -72,12 +72,191 @@ fn labelled_secret(before: &str, t: &str) -> bool {(changed || label.ends_with("bearer")) && SECRET_LABELS.iter().any(|l| label.ends_with(l))}-/// `text` with key-like words replaced by [`REDACTED`], and how many there were.-pub fn scrub_text(text: &str) -> (String, usize) {- let bytes = text.as_bytes();+/// `text` with the byte ranges in `spans` (sorted, not overlapping) replaced by [`REDACTED`].+fn redact(text: &str, spans: &[(usize, usize)]) -> String {let mut out = String::with_capacity(text.len());- let mut count = 0;let mut last = 0;+ for &(a, b) in spans {+ out.push_str(&text[last..a]);+ out.push_str(REDACTED);+ last = b;+ }+ out.push_str(&text[last..]);+ out+}++/// Zero-width and direction characters inside a run of ASCII, where they can only be there to+/// split a key (`sk-abc\u{200B}def`), removed. Elsewhere (emoji joiners) they stay.+fn join_hidden(text: &str) -> String {+ let chars: Vec<char> = text.chars().collect();+ let hidden = |c: char| super::is_hidden(c) && !c.is_control();+ let mut out = String::with_capacity(text.len());+ for (i, &c) in chars.iter().enumerate() {+ if hidden(c) {+ let prev = out.chars().last();+ let next = chars[i + 1..].iter().copied().find(|&n| !hidden(n));+ if prev.is_some_and(|p| p.is_ascii_graphic()) && next.is_some_and(|n| n.is_ascii_graphic()) {+ continue;+ }+ }+ out.push(c);+ }+ out+}++/// PEM private key blocks, `-----BEGIN … PRIVATE KEY-----` to the matching END line (or to the+/// end of the text when the END is missing).+fn pem_blocks(text: &str) -> Vec<(usize, usize)> {+ let mut spans = Vec::new();+ let mut from = 0;+ while let Some(i) = text[from..].find("-----BEGIN ") {+ let start = from + i;+ let header_end = text[start + 11..].find("-----").map(|j| start + 11 + j + 5);+ let Some(header_end) = header_end.filter(|&h| text[start..h].contains("PRIVATE KEY") && !text[start..h].contains('\n')) else {+ from = start + 11;+ continue;+ };+ let end = text[header_end..]+ .find("-----END ")+ .and_then(|j| {+ let e = header_end + j + 9;+ text[e..].find("-----").map(|k| e + k + 5)+ })+ .unwrap_or(text.len());+ spans.push((start, end));+ from = end;+ }+ spans+}++/// The `user:password` part of `scheme://user:password@host`; the host stays.+fn url_credentials(text: &str) -> Vec<(usize, usize)> {+ let mut spans = Vec::new();+ let mut from = 0;+ while let Some(i) = text[from..].find("://") {+ let start = from + i + 3;+ let len = text[start..]+ .find(|c: char| c.is_whitespace() || matches!(c, '/' | '?' | '#' | '"' | '\'' | '<' | '>' | ')' | ']' | '`'))+ .unwrap_or(text.len() - start);+ let authority = &text[start..start + len];+ if let Some(at) = authority.rfind('@') {+ let userinfo = &authority[..at];+ if userinfo.split_once(':').is_some_and(|(_, pass)| !pass.is_empty()) {+ spans.push((start, start + at));+ }+ }+ from = start + len;+ }+ spans+}++/// Labels that, followed by `:` or `=`, mean the value after them is a secret.+const VALUE_LABELS: [&str; 10] =+ ["password", "passwd", "pwd", "passphrase", "secret", "token", "api_key", "api-key", "apikey", "api key"];++/// Whether a value written after a secret label is a secret: long enough, with a letter and a+/// digit or symbol, and not a path, address, template or something already removed.+fn secret_value(v: &str) -> bool {+ v.chars().count() >= 8+ && v.chars().any(|c| c.is_alphabetic())+ && v.chars().any(|c| !c.is_alphabetic() && c != ' ')+ && !["[removed key]", "http", "/", "<", "{", "$", "~"].iter().any(|p| v.starts_with(p))+}++/// Values after secret labels, symbols and all: `password: p@ssw0rd!`, `"secret" = "Tr0ub&4"`,+/// `aws_secret_access_key=wJal…`. Quoted values run to the closing quote, others to whitespace.+fn labelled_values(text: &str) -> Vec<(usize, usize)> {+ let lower = text.to_ascii_lowercase();+ let b = lower.as_bytes();+ let n = b.len();+ let mut spans = Vec::new();+ let mut i = 0;+ while i < n {+ let at_word = i == 0 || !b[i - 1].is_ascii_alphanumeric();+ let Some(label) = VALUE_LABELS.iter().find(|l| at_word && b[i..].starts_with(l.as_bytes())) else {+ i += 1;+ continue;+ };+ let mut j = i + label.len();+ // the rest of a longer key name: `secret_access_key`, `token_v2`+ let name_end = (j + 30).min(n);+ while j < name_end && (b[j].is_ascii_alphanumeric() || matches!(b[j], b'_' | b'-')) {+ j += 1;+ }+ if j < n && matches!(b[j], b'"' | b'\'') {+ j += 1;+ }+ while j < n && matches!(b[j], b' ' | b'\t') {+ j += 1;+ }+ if j >= n || !matches!(b[j], b':' | b'=') {+ i += 1;+ continue;+ }+ j += 1;+ while j < n && matches!(b[j], b' ' | b'\t' | b'=' | b'>') {+ j += 1;+ }+ let (start, end) = if j < n && matches!(b[j], b'"' | b'\'' | b'`') {+ let q = b[j];+ match b[j + 1..].iter().take(300).position(|&c| c == q || c == b'\n') {+ Some(k) if b[j + 1 + k] == q => (j + 1, j + 1 + k),+ _ => {+ i += 1;+ continue;+ }+ }+ } else {+ let end = b[j..].iter().position(|c| c.is_ascii_whitespace()).map_or(n, |k| j + k);+ let value = text[j..end].trim_end_matches(['.', ',', ';', ':', ')', ']', '}']);+ (j, j + value.len())+ };+ if start < end && secret_value(&text[start..end]) {+ spans.push((start, end));+ i = end;+ } else {+ i += 1;+ }+ }+ spans+}++/// A bare 40-character AWS secret access key, only where the 80 characters before it mention+/// AWS or a secret, so ordinary long words and paths stay.+fn aws_secrets(text: &str) -> Vec<(usize, usize)> {+ let b = text.as_bytes();+ let is_b64 = |c: u8| c.is_ascii_alphanumeric() || matches!(c, b'/' | b'+');+ let mut spans = Vec::new();+ let mut i = 0;+ while i < b.len() {+ if !is_b64(b[i]) {+ i += 1;+ continue;+ }+ let start = i;+ while i < b.len() && is_b64(b[i]) {+ i += 1;+ }+ let run = &b[start..i];+ let mixed = run.iter().any(u8::is_ascii_uppercase) && run.iter().any(u8::is_ascii_lowercase) && run.iter().any(u8::is_ascii_digit);+ if run.len() == 40 && mixed {+ let mut from = start.saturating_sub(80);+ while !text.is_char_boundary(from) {+ from += 1;+ }+ let context = text[from..start].to_ascii_lowercase();+ if context.contains("aws") || context.contains("secret") {+ spans.push((start, i));+ }+ }+ }+ spans+}++/// Key-shaped words: provider prefixes, AWS key ids, JWTs, and long values after a label.+fn key_words(text: &str) -> Vec<(usize, usize)> {+ let bytes = text.as_bytes();+ let mut spans = Vec::new();let mut i = 0;while i < bytes.len() {if !is_token_byte(bytes[i]) {@@ -90,21 +269,38 @@ pub fn scrub_text(text: &str) -> (String, usize) {}// Token bytes are ASCII, so these are char boundaries.let word = text[start..i].trim_end_matches(['.', '-']);- let end = start + word.len();let mut from = start.saturating_sub(40);while !text.is_char_boundary(from) {from += 1;}- let before = &text[from..start];- if looks_like_key(word) || labelled_secret(before, word) {- out.push_str(&text[last..start]);- out.push_str(REDACTED);- last = end;- count += 1;+ if looks_like_key(word) || labelled_secret(&text[from..start], word) {+ spans.push((start, start + word.len()));}}- out.push_str(&text[last..]);- (out, count)+ spans+}++/// One kind of secret: the byte ranges in a text that hold it.+type Pass = fn(&str) -> Vec<(usize, usize)>;++/// `text` with secrets replaced by [`REDACTED`], and how many there were. Text with none comes+/// back exactly as it was.+pub fn scrub_text(text: &str) -> (String, usize) {+ let passes: [Pass; 5] = [pem_blocks, url_credentials, labelled_values, aws_secrets, key_words];+ let mut out = join_hidden(text);+ let mut count = 0;+ for pass in passes {+ let spans = pass(&out);+ if !spans.is_empty() {+ count += spans.len();+ out = redact(&out, &spans);+ }+ }+ if count == 0 {+ (text.to_string(), 0)+ } else {+ (out, count)+ }}fn scrub_in_place(s: &mut String) -> usize {@@ -192,6 +388,61 @@ mod tests {assert_eq!(scrub_text(text), (text.to_string(), 0));}+ #[test]+ fn rigels_shapes_are_removed() {+ // IMPORT-QA.md F1: each of these survived the first scrubber.+ let cases = [+ ("pem", "Key:\n-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASC\nabcdEFGH1234\n-----END PRIVATE KEY-----\nThanks.", "MIIE"),+ ("rsa pem", "-----BEGIN RSA PRIVATE KEY-----\nMIIEpAIBAAKCAQEA7\n-----END RSA PRIVATE KEY-----", "MIIEp"),+ ("pem without end", "-----BEGIN OPENSSH PRIVATE KEY-----\nb3BlbnNzaC1rZXktdjEAAAAA", "b3Bl"),+ ("password symbols", "password: p@ssw0rd!Secret#99 then more", "p@ssw0rd"),+ ("quoted password", "password=\"Tr0ub4dor&3xyz\"", "Tr0ub4dor"),+ ("passwd", "passwd = s3cr3t!pass", "s3cr3t"),+ ("pwd", "pwd: Hunter#2024x", "Hunter#"),+ ("secret label", "secret: 9f8e7d6c5b4a!", "9f8e7d"),+ ("json token", "{\"token\": \"abc123/def456+ghi\"}", "abc123"),+ ("url creds", "Clone https://user:[email protected]/x.git", "SuperSecret"),+ ("aws secret", "aws_secret_access_key = wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", "wJalr"),+ ("bare aws secret", "My AWS keys: AKIAIOSFODNN7EXAMPLE and wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY", "wJalr"),+ ("npm", "npm_aBcDeFgHiJkLmNoPqRsTuVwXyZ0123456789 is the publish token", "npm_aB"),+ ("google oauth", "Use ya29.a0AfH6SMBx-EXAMPLE_token_value_1234567890 for Drive", "ya29"),+ ("zero-width split", "sk-proj-abcdefgh\u{200B}ijklmnopqrstuvwxyz0123", "ijklmnop"),+ ];+ for (what, text, secret) in cases {+ let (out, n) = scrub_text(text);+ assert!(n >= 1 && !out.contains(secret), "{what}: {out}");+ }+ let (out, _) = scrub_text("Clone https://user:[email protected]/x.git");+ assert_eq!(out, "Clone https://[removed key]@git.example.com/x.git");+ let (out, n) = scrub_text("Key:\n-----BEGIN PRIVATE KEY-----\nMIIE\n-----END PRIVATE KEY-----\nThanks.");+ assert_eq!((out.as_str(), n), ("Key:\n[removed key]\nThanks.", 1));+ }++ #[test]+ fn ordinary_prose_survives_unchanged() {+ let text = "You are a friendly tutor. Answer in the \"format\" the student asks for.\n\+ Password rules: at least 12 characters. The secret: keep answers short.\n\+ Token limits: 4096 tokens. \"max_tokens\": 4096, \"password_min_length\": 12.\n\+ Docs live at https://docs.example.com/guide?x=1 and mail me at [email protected].\n\+ pwd: /home/maus/work. Use ${API_KEY} from the environment; token = <your token>.\n\+ AWS regions: us-east-1. A long path: /usr/share/doc/packages/something/really/long/x.\n\+ Family emoji 👨\u{200D}👩\u{200D}👧 stays, and so does the sk-learn library.\n\+ -----BEGIN CERTIFICATE----- is public, fine to keep.";+ assert_eq!(scrub_text(text), (text.to_string(), 0));+ }++ #[test]+ fn multibyte_text_around_labels_never_panics() {+ for lead in ["", "é", "👨", "ж", "\u{200B}", "\u{202E}"] {+ for body in ["password: ", "token=\"", "https://u:", "aws ", "-----BEGIN PRIVATE KEY-----", "sk-"] {+ for tail in ["", "é", "Пароль123!", "👨\u{200D}👩", "\u{200B}abc"] {+ let text = format!("{lead}{body}{lead}{tail}{lead}");+ let _ = scrub_text(&text);+ }+ }+ }+ }+#[test]fn secret_fields_are_dropped() {let mut v = serde_json::json!({"name": "x", "apiKey": "abc", "nested": [{"env": {"A": "b"}, "Authorization": "c", "ok": 1}]});diff --git a/tests/fixtures/import/hostile/keys-qa.json b/tests/fixtures/import/hostile/keys-qa.jsonnew file mode 100644index 00000000..7184bf1a--- /dev/null+++ b/tests/fixtures/import/hostile/keys-qa.json@@ -0,0 +1,17 @@+{+ "format": "kwant.bundle/1",+ "source": { "kind": "other", "label": "fake secrets only (IMPORT-QA.md F1), none of these are real" },+ "bots": [+ {+ "ref": "leaky",+ "name": "EvilName",+ "title": "Has fake secrets everywhere",+ "persona_prompt": "Sign with this:\n-----BEGIN PRIVATE KEY-----\nMIIEvFAKEPEMBODYFAKEPEMBODY0123\nFAKEPEMBODYFAKE==\n-----END PRIVATE KEY-----\nThe admin password: p@ssFAKE!Secret#99 and clone https://deploy:[email protected]/repo.git",+ "soul": "Config: password=\"Tr0ubFAKE&3xyz\". My AWS keys: AKIAIOSFODNN7EXAMPLE and wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",+ "memories": ["Publish with npm_FAKEFAKEFAKEfakefake0123456789abcdef", "Drive token ya29.FAKE_fake-token-0123456789abcdefgh"],+ "skills": [{ "name": "deploy", "description": "Deploy", "body": "Use sk-proj-FAKEFAKEFAKEFAKEtailFAKE0123456789 to deploy." }],+ "routines": [{ "name": "Backup", "instructions": "Log in with secret: FAKEs3cret!value then back up.", "schedule_text": "09:00" }]+ }+ ],+ "teams": [{ "name": "Ops Team", "lead": "leaky", "members": ["leaky"], "instructions": "DB at postgres://ops:[email protected]:5432/app" }]+}diff --git a/tests/import_test.rs b/tests/import_test.rsindex c49f5632..eb36109e 100644--- a/tests/import_test.rs+++ b/tests/import_test.rs@@ -541,3 +541,109 @@ async fn space_export_is_named_after_the_space() {assert_eq!(cd, format!("attachment; filename=\"{want}\""));}}++/// Every byte under the data dir, as lossy text, for "is this anywhere on disk" checks.+fn everything_on_disk(tmp: &TempDir) -> String {+ let mut out = String::new();+ let mut dirs = vec![tmp.path().to_path_buf()];+ while let Some(d) = dirs.pop() {+ for entry in std::fs::read_dir(d).unwrap().flatten() {+ let p = entry.path();+ if p.is_dir() {+ dirs.push(p);+ } else if let Ok(bytes) = std::fs::read(&p) {+ out.push_str(&String::from_utf8_lossy(&bytes));+ }+ }+ }+ out+}++/// IMPORT-QA.md F1: secret shapes the first scrubber missed, in every field, never reach the+/// preview, the database or an export.+#[tokio::test]+async fn qa_f1_pem_passwords_url_credentials_aws_npm_and_split_keys_are_removed() {+ let e = setup().await;+ let secrets = [+ "FAKEPEMBODY",+ "p@ssFAKE!Secret#99",+ "SuperFAKESecret123",+ "Tr0ubFAKE&3xyz",+ "AKIAIOSFODNN7EXAMPLE",+ "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",+ "npm_FAKE",+ "ya29.FAKE",+ "FAKEtailFAKE",+ "FAKEs3cret!value",+ "FAKEdbPass99",+ ];+ let (status, preview) = preview_file(&e.app, "hostile/keys-qa.json", &dflt()).await;+ assert_eq!(status, StatusCode::OK, "{preview}");+ let text = preview["bundle"].to_string();+ for s in secrets {+ assert!(!text.contains(s), "{s} survived the preview: {text}");+ }+ // Hosts stay readable; only the credentials go.+ assert!(text.contains("https://[removed key]@git.example.com/repo.git"), "{text}");+ assert!(text.contains("postgres://[removed key]@db.example.com:5432/app"), "{text}");++ let (status, applied) = apply(&e.app, &dflt(), &preview["bundle"], &[]).await;+ assert_eq!(status, StatusCode::CREATED, "{applied}");+ let id = applied["import"]["created"]["kwants"][0]["id"].as_str().unwrap();+ let (_, exported) = get(&e.app, &format!("/api/kwants/{id}/export")).await;+ let on_disk = everything_on_disk(&e.tmp);+ for s in secrets {+ assert!(!exported.to_string().contains(s), "{s} in the export");+ assert!(!on_disk.contains(s), "{s} stored on disk");+ }+}++/// IMPORT-QA.md F2: instructions that mention "format", start with `{` or show a JSON example+/// import as plain text; pasted text never gets a 415; a broken export reply keeps its 422.+#[tokio::test]+async fn qa_f2_instruction_like_text_imports_as_plain_text() {+ let e = setup().await;+ for text in [+ "Always answer in the \"format\" the user asks for.",+ "I like the kwant.bundle/1 format.",+ "{Be nice} to everyone.",+ "When asked for data, reply like this:\n```json\n{\"a\": 1}\n```\nand nothing else.",+ ] {+ let (status, p) = json_call(&e.app, "POST", "/api/import/preview", json!({ "text": text })).await;+ assert_eq!(status, StatusCode::OK, "{text:?}: {p}");+ assert_eq!(p["bundle"]["source"]["kind"], "plain-text", "{text:?}");+ assert_eq!(p["bundle"]["bots"][0]["persona_prompt"], text);+ assert_eq!(p["can_apply"], true);+ }+ for broken in [+ "Here you go:\n```json\n{\"format\": \"kwant.bundle/1\", \"bots\": [{\"name\": \"A\",}\n```",+ "```json\n{\"bots\": [{\"name\": \"A\"}]}\n```",+ ] {+ let (status, p) = json_call(&e.app, "POST", "/api/import/preview", json!({ "text": broken })).await;+ assert_eq!(status, StatusCode::UNPROCESSABLE_ENTITY, "{broken:?}: {p}");+ }+}++/// IMPORT-QA.md F4 and F5: the over-16k problem says where to shorten it, and hidden or+/// direction characters never reach a bot, team or routine name.+#[tokio::test]+async fn qa_f4_f5_cap_wording_and_hidden_characters_in_names() {+ let e = setup().await;+ let (_, p) = json_call(&e.app, "POST", "/api/import/preview", json!({ "text": "x".repeat(16_001) })).await;+ let problem = p["problems"][0]["message"].as_str().unwrap();+ assert!(problem.contains("Shorten it where it came from") && !problem.contains("here before"), "{problem}");++ let (status, preview) = preview_file(&e.app, "hostile/keys-qa.json", &dflt()).await;+ assert_eq!(status, StatusCode::OK, "{preview}");+ let (status, applied) = apply(&e.app, &dflt(), &preview["bundle"], &[]).await;+ assert_eq!(status, StatusCode::CREATED, "{applied}");+ let sid = SpaceId::default_space();+ let bot = e.state.db.list_kwants(&sid).await.unwrap().into_iter().find(|k| k.name.starts_with("Evil")).unwrap();+ assert_eq!(bot.name, "EvilName");+ assert!(preview["warnings"].to_string().contains("We removed hidden characters from the name EvilName"), "{}", preview["warnings"]);+ assert_eq!(bot.title, "Has fake secrets everywhere");+ let teams = e.state.db.list_teams(&sid).await.unwrap();+ assert!(teams.iter().any(|t| t.name == "Ops Team"), "{:?}", teams.iter().map(|t| &t.name).collect::<Vec<_>>());+ let routines = e.state.db.list_routines(&sid).await.unwrap();+ assert!(routines.iter().any(|r| r.name == "Backup"), "{:?}", routines.iter().map(|r| &r.name).collect::<Vec<_>>());+}