A small, fast container runtime for macOS, Windows and Linux
Rust
Keep the update switch off, send only new crashes, redact more secrets (#5)
Alex Idowu5f666ad873ad
diff --git a/crates/kiri-win/src/engine.rs b/crates/kiri-win/src/engine.rsindex d9506e7..48f4994 100644--- a/crates/kiri-win/src/engine.rs+++ b/crates/kiri-win/src/engine.rs@@ -777,7 +777,7 @@ pub fn prefs() -> Value {}fn set_pref(name: &str, value: Value) {- if !matches!(name, "font" | "mono" | "scale" | "domainsAsked" | "theme" | "accent" | "starAsked") {+ if !matches!(name, "font" | "mono" | "scale" | "domainsAsked" | "theme" | "accent" | "starAsked" | "updateAuto") {return;}let Some(path) = prefs_path() else { return };diff --git a/crates/kiri-win/src/update.rs b/crates/kiri-win/src/update.rsindex 0859160..864e7d8 100644--- a/crates/kiri-win/src/update.rs+++ b/crates/kiri-win/src/update.rs@@ -92,12 +92,15 @@ fn curl() -> Command {std::os::windows::process::CommandExt::creation_flags(&mut c, CREATE_NO_WINDOW);c.stdin(Stdio::null());c.arg("-A").arg(format!("kiri-win/{CURRENT}"));+ // Redirects stay on HTTPS too: by default curl follows one down to HTTP.+ c.args(["--proto", if cfg!(debug_assertions) { "=https,file" } else { "=https" }, "--proto-redir", "=https"]);c}-/// Only HTTPS carries a release; `file:` is for trying a feed on disk.+/// Only HTTPS carries a release; in a debug build, `file:` is for trying a+/// feed on disk.fn allowed_url(url: &str) -> io::Result<()> {- if url.starts_with("https://") || url.starts_with("file:///") {+ if url.starts_with("https://") || (cfg!(debug_assertions) && url.starts_with("file:///")) {Ok(())} else {Err(io::Error::other(format!("the update feed points at {url}, which is not https")))@@ -603,7 +606,7 @@ mod tests {#[test]fn only_https_feeds() {assert!(super::allowed_url("https://download.runkiri.com/latest-windows-x86_64.json").is_ok());- assert!(super::allowed_url("file:///C:/t/latest.json").is_ok());+ assert_eq!(super::allowed_url("file:///C:/t/latest.json").is_ok(), cfg!(debug_assertions));assert!(super::allowed_url("http://download.runkiri.com/latest-windows-x86_64.json").is_err());assert!(super::allowed_url("ftp://x/y").is_err());}diff --git a/crates/kiri/src/diag/redact.rs b/crates/kiri/src/diag/redact.rsindex 6b1362e..3ce283b 100644--- a/crates/kiri/src/diag/redact.rs+++ b/crates/kiri/src/diag/redact.rs@@ -1,7 +1,8 @@//! Takes out of logs and reports what must not leave the Mac: the home-//! folder's path (it names the person), bearer tokens, the values of-//! token, password and secret keys in JSON, query strings and `KEY=value`-//! pairs, and Kiri share tokens (`ks_…`).+//! folder's path (it names the person), bearer and other `Authorization`+//! values, the values of token, password and secret keys in JSON, query+//! strings, `KEY=value` pairs and `--flag value`, passwords in URLs, private+//! keys, and tokens that say what they are (`ks_…`, `ghp_…`, `glpat-…`).//!//! Patterns, not parsing: it runs over any text (log lines, panic//! messages, macOS crash reports), so it errs towards taking out too much.@@ -46,12 +47,16 @@ impl Redactor {/// The patterns alone (no home, no known secrets): cheap enough for every/// log line.pub fn patterns(s: &str) -> String {- let s = bearer(s);+ let s = private_keys(s);+ let s = url_userinfo(&s);+ let s = bearer(&s);+ let s = authorization(&s);let s = json_values(&s, "\"");// The same inside a JSON string: `{\"token\":\"…\"}`.let s = json_values(&s, "\\\"");let s = assignments(&s);- share_tokens(&s)+ let s = flags(&s);+ TOKEN_PREFIXES.iter().fold(s, |s, prefix| prefixed_tokens(&s, prefix))}fn is_word(b: u8) -> bool {@@ -59,10 +64,99 @@ fn is_word(b: u8) -> bool {}/// A key whose value is secret: `token`, `access_token`, `PASSWORD`,-/// `client_secret`, docker's `auth`, `identitytoken`…+/// `client_secret`, `API-KEY`, `PGPASS`, docker's `auth`, `identitytoken`…fn sensitive(key: &str) -> bool {- let k = key.trim_start_matches('-').to_ascii_lowercase();- k == "auth" || ["token", "password", "passwd", "secret", "apikey", "api_key", "credential", "crashreporterkey"].iter().any(|w| k.contains(w))+ let k = key.trim_start_matches('-').to_ascii_lowercase().replace(['-', '.'], "_");+ matches!(k.as_str(), "auth" | "authorization" | "pass" | "pgpass")+ || k.ends_with("_pass")+ || ["token", "password", "passwd", "passphrase", "secret", "apikey", "api_key", "access_key", "private_key", "credential", "crashreporterkey"].iter().any(|w| k.contains(w))+}++/// A PEM private key, whole; without its end line, everything after its+/// start, since the rest of the key may be in there.+fn private_keys(s: &str) -> String {+ const BEGIN: &str = "-----BEGIN ";+ const DASHES: &str = "-----";+ let (mut out, mut rest) = (String::with_capacity(s.len()), s);+ while let Some(i) = rest.find(BEGIN) {+ let after = &rest[i + BEGIN.len()..];+ let Some(label_len) = after.find(DASHES) else { break };+ let label = &after[..label_len];+ if !label.ends_with("PRIVATE KEY") {+ out.push_str(&rest[..i + BEGIN.len()]);+ rest = after;+ continue;+ }+ out.push_str(&rest[..i]);+ out.push_str(MARK);+ let body = &after[label_len + DASHES.len()..];+ let end = format!("-----END {label}-----");+ rest = body.find(&end).map_or("", |n| &body[n + end.len()..]);+ }+ out.push_str(rest);+ out+}++/// `postgres://app:hunter2@db/x` → `postgres://[redacted]@db/x`: all of the+/// part before the `@`, since a token can stand where the user name goes.+fn url_userinfo(s: &str) -> String {+ let (mut out, mut rest) = (String::with_capacity(s.len()), s);+ while let Some(i) = rest.find("://") {+ let start = i + 3;+ out.push_str(&rest[..start]);+ let after = &rest[start..];+ let end = after.find(|c: char| c.is_whitespace() || "/?#\"'<>\\".contains(c)).unwrap_or(after.len());+ match after[..end].rfind('@') {+ Some(at) if &after[..at] != MARK => {+ out.push_str(MARK);+ rest = &after[at..];+ }+ _ => rest = after,+ }+ }+ out.push_str(rest);+ out+}++/// `Authorization: Basic abc` → `Authorization: Basic [redacted]`, whatever+/// the scheme, and the value alone when it has none. `Basic` isn't matched+/// by itself as `Bearer` is: "basic authentication" is ordinary text.+fn authorization(s: &str) -> String {+ const KEY: &str = "authorization:";+ let lower = s.to_ascii_lowercase();+ let b = s.as_bytes();+ let skip = |mut j: usize| {+ while j < b.len() && (b[j] == b' ' || b[j] == b'\t') {+ j += 1;+ }+ j+ };+ let word = |mut j: usize| {+ while j < b.len() && (b[j].is_ascii_alphanumeric() || b"-._~+/=".contains(&b[j])) {+ j += 1;+ }+ j+ };+ let (mut out, mut last, mut from) = (String::with_capacity(s.len()), 0, 0);+ while let Some(i) = lower[from..].find(KEY).map(|i| i + from) {+ from = i + KEY.len();+ let first = skip(from);+ let first_end = word(first);+ let second = skip(first_end);+ let second_end = word(second);+ if s[second..].starts_with(MARK) {+ continue;+ }+ let (start, end) = if second_end > second { (second, second_end) } else { (first, first_end) };+ if end > start {+ out.push_str(&s[last..start]);+ out.push_str(MARK);+ last = end;+ from = end;+ }+ }+ out.push_str(&s[last..]);+ out}/// `/Users/ada/x` → `~/x`, but not `/Users/adam`.@@ -156,8 +250,8 @@ fn json_values(s: &str, q: &str) -> String {out}-/// `?token=…&`, `PASSWORD=…`, `--password "…"` is left, `--password=…` is-/// not: the value after a sensitive key and `=`.+/// `?token=…&`, `PASSWORD=…`, `--password=…`: the value after a sensitive key+/// and `=`. [`flags`] has `--password …`.fn assignments(s: &str) -> String {let b = s.as_bytes();let key_byte = |c: u8| is_word(c) || c == b'-' || c == b'.';@@ -195,18 +289,66 @@ fn assignments(s: &str) -> String {out}-/// `ks_…`, a Kiri share token, wherever it appears.-fn share_tokens(s: &str) -> String {+/// `--password hunter2`, `--token "two words"`: the value after a sensitive+/// long flag and spaces. The next flag isn't a value.+fn flags(s: &str) -> String {+ let b = s.as_bytes();+ let key_byte = |c: u8| is_word(c) || c == b'-' || c == b'.';+ let (mut out, mut last, mut from) = (String::with_capacity(s.len()), 0, 0);+ while let Some(i) = s[from..].find("--").map(|i| i + from) {+ let mut k = i + 2;+ while k < b.len() && key_byte(b[k]) {+ k += 1;+ }+ from = k;+ let mut start = k;+ while start < b.len() && (b[start] == b' ' || b[start] == b'\t') {+ start += 1;+ }+ if (i > 0 && key_byte(b[i - 1])) || !sensitive(&s[i..k]) || start == k || start == b.len() {+ continue;+ }+ let quote = matches!(b[start], b'"' | b'\'').then_some(b[start] as char);+ let end = match quote {+ Some(q) => s[start + 1..].find(q).map_or(b.len(), |n| start + 1 + n + 1),+ None => s[start..].find(char::is_whitespace).map_or(b.len(), |n| start + n),+ };+ let value = &s[start..end];+ if value.starts_with('-') || value.trim_matches(['"', '\'']) == MARK {+ continue;+ }+ out.push_str(&s[last..start]);+ match quote {+ Some(q) => {+ out.push(q);+ out.push_str(MARK);+ out.push(q);+ }+ None => out.push_str(MARK),+ }+ last = end;+ from = end;+ }+ out.push_str(&s[last..]);+ out+}++/// What starts a token that says what it is: Kiri share's, GitHub's, GitLab's,+/// Docker Hub's, and an AWS access key id.+const TOKEN_PREFIXES: [&str; 10] = ["ks_", "ghp_", "gho_", "ghu_", "ghs_", "ghr_", "github_pat_", "glpat-", "dckr_pat_", "AKIA"];++/// `prefix…`, a token of that kind, wherever it appears.+fn prefixed_tokens(s: &str, prefix: &str) -> String {let b = s.as_bytes();let tail = |c: u8| is_word(c) || c == b'-';let (mut out, mut last, mut from) = (String::with_capacity(s.len()), 0, 0);- while let Some(i) = s[from..].find("ks_").map(|i| i + from) {- let mut j = i + 3;+ while let Some(i) = s[from..].find(prefix).map(|i| i + from) {+ let mut j = i + prefix.len();while j < b.len() && tail(b[j]) {j += 1;}- if (i == 0 || !is_word(b[i - 1])) && j - (i + 3) >= 12 {- out.push_str(&s[last..i + 3]);+ if (i == 0 || !is_word(b[i - 1])) && j - (i + prefix.len()) >= 12 {+ out.push_str(&s[last..i + prefix.len()]);out.push_str(MARK);last = j;}@@ -276,9 +418,69 @@ mod tests {assert_eq!(patterns("ks_x and thanks_0123456789abcdef"), "ks_x and thanks_0123456789abcdef");}+ #[test]+ fn passwords_in_urls() {+ assert_eq!(patterns("DATABASE_URL=postgres://app:[email protected]/prod"), "DATABASE_URL=postgres://[redacted]@db.internal/prod");+ assert_eq!(patterns("proxy failed: http://bob:p@[email protected]:3128, retrying"), "proxy failed: http://[redacted]@proxy.corp:3128, retrying");+ assert_eq!(patterns("https://[email protected]/a/b.git"), "https://[redacted]@github.com/a/b.git");+ // No password in these.+ for text in ["https://example.com/a@b", "[email protected]:a/b.git", "http://localhost:8080/[email protected]", "see https://runkiri.com."] {+ assert_eq!(patterns(text), text);+ }+ }++ #[test]+ fn authorization_values() {+ assert_eq!(patterns("Authorization: Basic Ym9iOmh1bnRlcjI="), "Authorization: Basic [redacted]");+ assert_eq!(patterns("proxy-authorization: Basic Ym9i, next"), "proxy-authorization: Basic [redacted], next");+ assert_eq!(patterns("Authorization: abc123"), "Authorization: [redacted]");+ assert_eq!(patterns(r#"{"Authorization":"Basic Ym9i"}"#), r#"{"Authorization":"[redacted]"}"#);+ assert_eq!(patterns("basic authentication failed"), "basic authentication failed");+ }++ #[test]+ fn private_key_blocks() {+ let key = "-----BEGIN RSA PRIVATE KEY-----\nMIIEvQIBADANBg\n-----END RSA PRIVATE KEY-----";+ assert_eq!(patterns(&format!("before {key} after")), "before [redacted] after");+ assert_eq!(patterns("x -----BEGIN PRIVATE KEY----- MIIEvQIBADANBg"), "x [redacted]");+ let cert = "-----BEGIN CERTIFICATE-----\nMIIB\n-----END CERTIFICATE-----";+ assert_eq!(patterns(cert), cert);+ }++ #[test]+ fn secret_flags() {+ assert_eq!(patterns("--password hunter2 --verbose"), "--password [redacted] --verbose");+ assert_eq!(patterns("login --token 'two words' x"), "login --token '[redacted]' x");+ assert_eq!(patterns("--api-key abc"), "--api-key [redacted]");+ // The next flag, or nothing, isn't a value; other flags are left.+ for text in ["--password --verbose", "--password", "--name web", "pre--token x"] {+ assert_eq!(patterns(text), text);+ }+ }++ #[test]+ fn more_secret_keys() {+ for key in ["PGPASS", "MYSQL_PASS", "API-KEY", "X.API.KEY", "SSH_PRIVATE_KEY", "AWS_ACCESS_KEY_ID", "GPG_PASSPHRASE"] {+ assert_eq!(patterns(&format!("{key}=abc123")), format!("{key}=[redacted]"));+ }+ for text in ["bypass=1", "compass=north", "passed=3", "MONKEY=1"] {+ assert_eq!(patterns(text), text);+ }+ }++ #[test]+ fn tokens_that_say_what_they_are() {+ assert_eq!(patterns("pushed with ghp_abcdefghijklmnopqrstuvwxyz0123456789 ok"), "pushed with ghp_[redacted] ok");+ assert_eq!(patterns("github_pat_11ABCDEFG0abcdefghij_klmn"), "github_pat_[redacted]");+ assert_eq!(patterns("glpat-abcdef123456xyz"), "glpat-[redacted]");+ assert_eq!(patterns("dckr_pat_abcdefghijklmnop"), "dckr_pat_[redacted]");+ assert_eq!(patterns("key AKIAIOSFODNN7EXAMPLE"), "key AKIA[redacted]");+ assert_eq!(patterns("ghp_short and aghp_abcdefghijklmnop"), "ghp_short and aghp_abcdefghijklmnop");+ }+#[test]fn redacting_twice_changes_nothing() {- let text = r#"Bearer abcdefghijkl token=abc {"token":"x"} ks_0123456789abcdef /Users/ada/x"#;+ let text = r#"Bearer abcdefghijkl token=abc {"token":"x"} ks_0123456789abcdef /Users/ada/x postgres://a:b@h/d Authorization: Basic Ym9i --password hunter2 --token "two words" ghp_abcdefghijklmnop -----BEGIN PRIVATE KEY-----k-----END PRIVATE KEY----- end"#;let once = r().apply(text);assert_eq!(r().apply(&once), once);assert!(!once.contains("abcdefghijkl") && !once.contains("0123456789abcdef") && !once.contains("/Users/ada"), "{once}");diff --git a/crates/kiri/src/diag/report.rs b/crates/kiri/src/diag/report.rsindex 1a5e711..947bd23 100644--- a/crates/kiri/src/diag/report.rs+++ b/crates/kiri/src/diag/report.rs@@ -558,9 +558,24 @@ pub fn crash_reports_on() -> bool {false}-/// Crash files waiting to go, oldest first: not sent, not being sent.-fn pending(dir: &Path) -> Vec<String> {- let mut names: Vec<String> = crash_files(dir).into_iter().filter(|n| !n.ends_with(".sent.txt") && !n.ends_with(".sending")).collect();+/// When crash reports were turned on, in Unix seconds. 0 for a setting from+/// before this was kept: those people's waiting crashes still go.+#[cfg(any(target_os = "macos", all(target_os = "linux", feature = "window")))]+fn crash_reports_since() -> u64 {+ crate::ui::prefs()["crashReportsSince"].as_u64().unwrap_or(0)+}++#[cfg(not(any(target_os = "macos", all(target_os = "linux", feature = "window"))))]+fn crash_reports_since() -> u64 {+ 0+}++/// Crash files waiting to go, oldest first: not sent, not being sent, and not+/// from before `since`. Turning reports on doesn't send what came earlier,+/// which includes crashes the person answered "Not now" to.+fn pending(dir: &Path, since: u64) -> Vec<String> {+ let waiting = |n: &String| !n.ends_with(".sent.txt") && !n.ends_with(".sending") && crash_name(n).is_some_and(|(t, _)| t >= since);+ let mut names: Vec<String> = crash_files(dir).into_iter().filter(waiting).collect();names.reverse();names}@@ -579,7 +594,7 @@ pub fn send_crashes() {}}let redactor = Redactor::for_user();- for name in pending(&dir) {+ for name in pending(&dir, crash_reports_since()) {// Another process (the window and the engine both try) has it.let Some(claimed) = claim(&dir, &name) else { continue };if let Err(e) = send_claimed(&dir, &name, &claimed, &redactor) {@@ -893,7 +908,11 @@ mod tests {for n in ["1792800000-daemon.txt", "1792700000-ui.txt", "1792600000-cli.sent.txt", "1792500000-ui.txt.sending", ".window-opened"] {std::fs::write(home.join(n), "x").unwrap();}- assert_eq!(pending(&home), ["1792700000-ui.txt", "1792800000-daemon.txt"]);+ assert_eq!(pending(&home, 0), ["1792700000-ui.txt", "1792800000-daemon.txt"]);+ // Crashes from before they were turned on stay here.+ assert_eq!(pending(&home, 1_792_700_001), ["1792800000-daemon.txt"]);+ assert_eq!(pending(&home, 1_792_800_000), ["1792800000-daemon.txt"]);+ assert!(pending(&home, 1_792_800_001).is_empty());let _ = std::fs::remove_dir_all(&home);}}diff --git a/crates/kiri/src/ui/mod.rs b/crates/kiri/src/ui/mod.rsindex ad45635..114b1f1 100644--- a/crates/kiri/src/ui/mod.rs+++ b/crates/kiri/src/ui/mod.rs@@ -438,7 +438,7 @@ pub(crate) fn prefs() -> serde_json::Value {}fn set_pref(name: &str, value: serde_json::Value) {- if !matches!(name, "font" | "mono" | "scale" | "domainsAsked" | "theme" | "accent" | "importSeen" | "updateSkip" | "updateSnoozeUntil" | "columnWidths" | "crashReports" | "ctxSnooze" | "ctxBack" | "logSize" | "starAsked" | "setupSkip") {+ if !matches!(name, "font" | "mono" | "scale" | "domainsAsked" | "theme" | "accent" | "importSeen" | "updateAuto" | "updateSkip" | "updateSnoozeUntil" | "columnWidths" | "crashReports" | "ctxSnooze" | "ctxBack" | "logSize" | "starAsked" | "setupSkip") {return;}let Some(path) = prefs_path() else { return };@@ -446,6 +446,17 @@ fn set_pref(name: &str, value: serde_json::Value) {if !all.is_object() {all = serde_json::json!({});}+ // Crash reports go from when they're turned on: crashes from before that+ // wait for the person to pick them.+ if name == "crashReports" {+ if value != true {+ if let Some(o) = all.as_object_mut() {+ o.remove("crashReportsSince");+ }+ } else if all[name] != true {+ all["crashReportsSince"] = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs()).into();+ }+ }all[name] = value;let tmp = path.with_extension("json.tmp");if std::fs::write(&tmp, all.to_string()).and_then(|()| std::fs::rename(&tmp, &path)).is_err() {@@ -1274,6 +1285,21 @@ mod tests {let p = super::prefs();assert_eq!((p["font"].as_str(), p["scale"].as_f64(), p.get("script")), (Some("Georgia"), Some(1.1), None));assert_eq!(p["starAsked"], true);+ // Check for updates automatically stays off across launches.+ super::set_pref("updateAuto", false.into());+ assert_eq!(super::prefs()["updateAuto"], false);+ // Crash reports remember when they were turned on, and only the+ // setting itself can say so.+ super::set_pref("crashReportsSince", 1.into());+ assert_eq!(super::prefs().get("crashReportsSince"), None);+ super::set_pref("crashReports", true.into());+ let since = super::prefs()["crashReportsSince"].as_u64().unwrap();+ assert!(since > 1);+ std::fs::write(dir.join("ui.json"), super::prefs().to_string().replace(&since.to_string(), "5")).unwrap();+ super::set_pref("crashReports", true.into());+ assert_eq!(super::prefs()["crashReportsSince"], 5, "already on: its time stays");+ super::set_pref("crashReports", false.into());+ assert_eq!(super::prefs().get("crashReportsSince"), None);let _ = std::fs::remove_dir_all(&dir);}