| 1 | //! Install identity and the constant half of the batch envelope. |
| 2 | |
| 3 | use std::path::Path; |
| 4 | |
| 5 | use anyhow::{Context, Result}; |
| 6 | use serde::{Deserialize, Serialize}; |
| 7 | |
| 8 | use crate::buffer; |
| 9 | use crate::event::{Arch, Libc, Os}; |
| 10 | |
| 11 | /// How long an install id may live before it is replaced. |
| 12 | /// |
| 13 | /// A never-rotating id plus one batch per session from the user's IP is a |
| 14 | /// longitudinal IP and travel trace. Rotation bounds that join. It costs |
| 15 | /// longitudinal accuracy, and the docs say so in those words: **no count derived |
| 16 | /// from `install_id` is a user count.** |
| 17 | pub const ROTATION_DAYS: i64 = 90; |
| 18 | |
| 19 | const MAX_METADATA_BYTES: u64 = 4096; |
| 20 | |
| 21 | fn read_bounded_json<T: serde::de::DeserializeOwned>(path: &Path) -> Option<T> { |
| 22 | use std::io::Read as _; |
| 23 | let file = std::fs::File::open(path).ok()?; |
| 24 | if file |
| 25 | .metadata() |
| 26 | .ok() |
| 27 | .is_some_and(|meta| meta.len() > MAX_METADATA_BYTES) |
| 28 | { |
| 29 | return None; |
| 30 | } |
| 31 | let mut bytes = Vec::new(); |
| 32 | file.take(MAX_METADATA_BYTES + 1) |
| 33 | .read_to_end(&mut bytes) |
| 34 | .ok()?; |
| 35 | if bytes.len() as u64 > MAX_METADATA_BYTES { |
| 36 | return None; |
| 37 | } |
| 38 | serde_json::from_slice(&bytes).ok() |
| 39 | } |
| 40 | |
| 41 | /// The on-disk install identity. |
| 42 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 43 | pub struct InstallId { |
| 44 | /// Format version of this file. |
| 45 | pub schema_version: u32, |
| 46 | /// A random v4 UUID. |
| 47 | /// |
| 48 | /// Never derived from hostname, MAC, `machine-id`, `$HOME`, username, or |
| 49 | /// executable path. A derived id is a device fingerprint: it survives |
| 50 | /// reinstall and re-identifies a user across their own opt-out, which is the |
| 51 | /// single thing an install id must never do. |
| 52 | pub install_id: String, |
| 53 | /// When this id was minted, RFC3339 UTC. |
| 54 | pub rotated_at: String, |
| 55 | } |
| 56 | |
| 57 | /// Per-machine telemetry bookkeeping. Never contains anything about the user's |
| 58 | /// work — only what this crate needs to avoid re-reporting an install and to |
| 59 | /// rate-limit its own flushes. |
| 60 | #[derive(Debug, Clone, Default, Serialize, Deserialize)] |
| 61 | pub struct TelemetryState { |
| 62 | /// Format version of this file. |
| 63 | #[serde(default)] |
| 64 | pub schema_version: u32, |
| 65 | /// The app version last seen on this machine. |
| 66 | #[serde(default)] |
| 67 | pub last_version: Option<String>, |
| 68 | /// When a flush was last *attempted*, RFC3339 UTC. Attempt, not success, so |
| 69 | /// a permanently offline machine tries at most once per interval. |
| 70 | #[serde(default)] |
| 71 | pub last_flush: Option<String>, |
| 72 | } |
| 73 | |
| 74 | /// Read the install id, minting a fresh one if it is missing, unreadable, |
| 75 | /// **not a UUID**, or older than [`ROTATION_DAYS`]. |
| 76 | /// |
| 77 | /// The UUID check is not a formatting nicety. `install_id` is the one |
| 78 | /// envelope field read verbatim off disk into a batch, so without it the file |
| 79 | /// is a free-form string slot on the wire for anything that can write |
| 80 | /// `$CODEWHALE_HOME/telemetry/install_id.json`. Minting a fresh random id is |
| 81 | /// always the safe direction — the cost is one rotation, and the docs already |
| 82 | /// say no count derived from `install_id` is a user count. |
| 83 | pub fn read_or_create_install_id(root: &Path) -> Result<InstallId> { |
| 84 | buffer::try_with_lock_in_turn(root, || { |
| 85 | if buffer::tombstone_present(root) { |
| 86 | anyhow::bail!("telemetry is disabled"); |
| 87 | } |
| 88 | let path = buffer::install_id_path(root); |
| 89 | let existing = read_bounded_json::<InstallId>(&path) |
| 90 | .filter(|record| is_canonical_random_uuid(&record.install_id)) |
| 91 | .filter(|record| !is_expired(&record.rotated_at)); |
| 92 | if let Some(record) = existing { |
| 93 | return Ok(record); |
| 94 | } |
| 95 | let record = InstallId { |
| 96 | schema_version: 1, |
| 97 | install_id: uuid::Uuid::new_v4().to_string(), |
| 98 | rotated_at: now_rfc3339(), |
| 99 | }; |
| 100 | codewhale_config::persistence::atomic_write_json(&path, &record) |
| 101 | .with_context(|| format!("failed to write {}", path.display()))?; |
| 102 | Ok(record) |
| 103 | })? |
| 104 | .ok_or_else(|| anyhow::anyhow!("telemetry privacy lock is held")) |
| 105 | } |
| 106 | |
| 107 | /// Exactly what [`read_or_create_install_id`] mints: a random (v4, RFC 4122 |
| 108 | /// variant) UUID in lowercase hyphenated form, byte for byte. |
| 109 | /// |
| 110 | /// `Uuid::parse_str` alone also accepts surrounding whitespace after a trim, |
| 111 | /// braced/URN/simple spellings (each a different wire string for one id), |
| 112 | /// the nil UUID, and v1 ids, which embed a MAC address and a clock — a device |
| 113 | /// fingerprint, the one thing an install id must never be. |
| 114 | fn is_canonical_random_uuid(value: &str) -> bool { |
| 115 | uuid::Uuid::parse_str(value).is_ok_and(|id| { |
| 116 | id.get_version() == Some(uuid::Version::Random) |
| 117 | && id.get_variant() == uuid::Variant::RFC4122 |
| 118 | && id.hyphenated().to_string() == value |
| 119 | }) |
| 120 | } |
| 121 | |
| 122 | fn is_expired(rotated_at: &str) -> bool { |
| 123 | let Ok(parsed) = chrono::DateTime::parse_from_rfc3339(rotated_at) else { |
| 124 | // An unreadable timestamp is treated as expired: minting a fresh random |
| 125 | // id is always the safe direction. |
| 126 | return true; |
| 127 | }; |
| 128 | let age = chrono::Utc::now().signed_duration_since(parsed.with_timezone(&chrono::Utc)); |
| 129 | // A future `rotated_at` has a negative age that would never reach the |
| 130 | // rotation window, pinning the id forever. It is expired, not fresh. |
| 131 | age < chrono::TimeDelta::zero() || age.num_days() >= ROTATION_DAYS |
| 132 | } |
| 133 | |
| 134 | /// Read `state.json`, or a default when it is missing or unreadable. |
| 135 | #[must_use] |
| 136 | pub fn read_state(root: &Path) -> TelemetryState { |
| 137 | read_bounded_json::<TelemetryState>(&buffer::state_path(root)).unwrap_or_default() |
| 138 | } |
| 139 | |
| 140 | /// Write `state.json`. |
| 141 | pub fn write_state(root: &Path, state: &TelemetryState) -> Result<()> { |
| 142 | buffer::try_with_lock_in_turn(root, || { |
| 143 | if buffer::tombstone_present(root) { |
| 144 | anyhow::bail!("telemetry is disabled"); |
| 145 | } |
| 146 | let path = buffer::state_path(root); |
| 147 | codewhale_config::persistence::atomic_write_json(&path, state) |
| 148 | .with_context(|| format!("failed to write {}", path.display())) |
| 149 | })? |
| 150 | .ok_or_else(|| anyhow::anyhow!("telemetry privacy lock is held")) |
| 151 | } |
| 152 | |
| 153 | /// RFC3339 UTC at second precision. The only timestamp this crate produces, and |
| 154 | /// it is per-**batch**: individual events carry no timestamps at all. |
| 155 | #[must_use] |
| 156 | pub fn now_rfc3339() -> String { |
| 157 | chrono::Utc::now() |
| 158 | .to_rfc3339_opts(chrono::SecondsFormat::Secs, true) |
| 159 | .to_string() |
| 160 | } |
| 161 | |
| 162 | /// The build sha of a release-CI binary, or `None`. |
| 163 | /// |
| 164 | /// Sourced from `CODEWHALE_RELEASE_BUILD_SHA`, a rustc-env this crate's build |
| 165 | /// script emits **only** when `CODEWHALE_BUILD_SHA` or its legacy build-only |
| 166 | /// alias was present in the build environment (never the ambient |
| 167 | /// `GITHUB_SHA` every Actions job carries). `null` for |
| 168 | /// every locally built binary, unconditionally, with no runtime lookup of any |
| 169 | /// kind. |
| 170 | /// |
| 171 | /// Never `CODEWHALE_BUILD_COMMIT` — that falls back to the builder's own `HEAD` |
| 172 | /// on a local build. Never `Thread.git_sha` — that is the *user's* workspace |
| 173 | /// commit and a red line, one identifier away by name. |
| 174 | #[must_use] |
| 175 | pub fn release_build_sha() -> Option<String> { |
| 176 | option_env!("CODEWHALE_RELEASE_BUILD_SHA").and_then(short_hex_sha) |
| 177 | } |
| 178 | |
| 179 | /// Reduce a full sha to the first 12 lowercase hex characters, rejecting |
| 180 | /// anything that is not a sha. |
| 181 | #[must_use] |
| 182 | pub fn short_hex_sha(value: &str) -> Option<String> { |
| 183 | let trimmed = value.trim().to_ascii_lowercase(); |
| 184 | if trimmed.len() < 12 || !trimmed.bytes().all(|b| b.is_ascii_hexdigit()) { |
| 185 | return None; |
| 186 | } |
| 187 | Some(trimmed.chars().take(12).collect()) |
| 188 | } |
| 189 | |
| 190 | /// The OS family this binary is running on, mapped onto the closed whitelist. |
| 191 | #[must_use] |
| 192 | pub fn current_os() -> Os { |
| 193 | match std::env::consts::OS { |
| 194 | "linux" => Os::Linux, |
| 195 | "macos" => Os::Macos, |
| 196 | "windows" => Os::Windows, |
| 197 | "freebsd" => Os::Freebsd, |
| 198 | "android" => Os::Android, |
| 199 | _ => Os::Other, |
| 200 | } |
| 201 | } |
| 202 | |
| 203 | /// The CPU family, mapped onto the closed whitelist. |
| 204 | #[must_use] |
| 205 | pub fn current_arch() -> Arch { |
| 206 | match std::env::consts::ARCH { |
| 207 | "x86_64" => Arch::X86_64, |
| 208 | "aarch64" => Arch::Aarch64, |
| 209 | _ => Arch::Other, |
| 210 | } |
| 211 | } |
| 212 | |
| 213 | /// The libc this binary was **compiled** against. |
| 214 | #[must_use] |
| 215 | pub fn current_libc() -> Libc { |
| 216 | if cfg!(target_env = "gnu") { |
| 217 | Libc::Gnu |
| 218 | } else if cfg!(target_env = "musl") { |
| 219 | Libc::Musl |
| 220 | } else { |
| 221 | Libc::None |
| 222 | } |
| 223 | } |
| 224 | |
| 225 | /// Whether both stdin and stdout are terminals. |
| 226 | /// |
| 227 | /// This varies because consent is machine-scoped: a decision recorded on a TTY |
| 228 | /// authorizes later headless runs on the same home. |
| 229 | #[must_use] |
| 230 | pub fn current_tty() -> bool { |
| 231 | use std::io::IsTerminal as _; |
| 232 | std::io::stdin().is_terminal() && std::io::stdout().is_terminal() |
| 233 | } |
| 234 | |
| 235 | /// Reduce a panic location to something that is safe to send. |
| 236 | /// |
| 237 | /// Emit a `crates/…` path verbatim; reduce **everything else** to the literal |
| 238 | /// `<dep>`. There is no `--remap-path-prefix` in this repo, so a panic inside a |
| 239 | /// registry dependency yields |
| 240 | /// `/Users/<builder>/.cargo/registry/src/…/ratatui-0.29.0/src/…` — the build |
| 241 | /// machine's username, shipped from every user's binary. |
| 242 | /// The allowlist itself lives in [`crate::event::is_reduced_panic_site`], and |
| 243 | /// this function is defined as "the candidate if the predicate accepts it". |
| 244 | /// Two copies of one charset would drift, and the drain path re-checks the |
| 245 | /// predicate against events read back off disk — a reducer that could emit |
| 246 | /// something the checker rejects would silently delete real panics. |
| 247 | #[must_use] |
| 248 | pub fn reduce_panic_site(file: &str, line: u32, column: u32) -> String { |
| 249 | let candidate = format!("{}:{line}:{column}", file.replace('\\', "/")); |
| 250 | if crate::event::is_reduced_panic_site(&candidate) { |
| 251 | candidate |
| 252 | } else { |
| 253 | "<dep>".to_string() |
| 254 | } |
| 255 | } |
| 256 | |
| 257 | #[cfg(test)] |
| 258 | mod tests { |
| 259 | use super::*; |
| 260 | |
| 261 | #[test] |
| 262 | fn oversized_install_id_file_is_ignored_and_replaced() { |
| 263 | let dir = tempfile::tempdir().unwrap(); |
| 264 | let root = dir.path(); |
| 265 | buffer::ensure_dir(root).unwrap(); |
| 266 | let injected = uuid::Uuid::new_v4().to_string(); |
| 267 | let payload = serde_json::json!({ |
| 268 | "schema_version": 1, |
| 269 | "install_id": injected, |
| 270 | "rotated_at": now_rfc3339(), |
| 271 | }); |
| 272 | let padding = " ".repeat(MAX_METADATA_BYTES as usize + 64); |
| 273 | std::fs::write(buffer::install_id_path(root), format!("{padding}{payload}")).unwrap(); |
| 274 | |
| 275 | let record = read_or_create_install_id(root).unwrap(); |
| 276 | assert_ne!(record.install_id, injected); |
| 277 | assert!(is_canonical_random_uuid(&record.install_id)); |
| 278 | } |
| 279 | |
| 280 | #[test] |
| 281 | fn oversized_state_file_returns_default() { |
| 282 | let dir = tempfile::tempdir().unwrap(); |
| 283 | let root = dir.path(); |
| 284 | buffer::ensure_dir(root).unwrap(); |
| 285 | let payload = serde_json::json!({ |
| 286 | "schema_version": 1, |
| 287 | "last_version": "9.9.9", |
| 288 | "last_flush": now_rfc3339(), |
| 289 | }); |
| 290 | let padding = " ".repeat(MAX_METADATA_BYTES as usize + 64); |
| 291 | std::fs::write(buffer::state_path(root), format!("{padding}{payload}")).unwrap(); |
| 292 | |
| 293 | let state = read_state(root); |
| 294 | assert_eq!(state.schema_version, 0); |
| 295 | assert!(state.last_version.is_none()); |
| 296 | assert!(state.last_flush.is_none()); |
| 297 | } |
| 298 | } |
| 299 |