| 1 | // Audit-write failure must route through `tracing::*`, not raw stderr — |
| 2 | // see `runtime_log` for the scroll-demon rationale. |
| 3 | #![deny(clippy::print_stdout)] |
| 4 | #![deny(clippy::print_stderr)] |
| 5 | |
| 6 | //! Per-domain network policy for outbound network calls (#135). |
| 7 | //! |
| 8 | //! Three small pieces: |
| 9 | //! |
| 10 | //! 1. [`Decision`] — `Allow | Deny | Prompt`. |
| 11 | //! 2. [`NetworkPolicy`] — a list of allow/deny hostnames + a default decision, |
| 12 | //! with **deny-wins precedence**: a host that matches an entry in `deny` |
| 13 | //! is denied even if it also matches `allow`. |
| 14 | //! 3. [`NetworkAuditor`] — appends one plaintext line per outbound call to |
| 15 | //! `~/.codewhale/audit.log` in the format described below. |
| 16 | //! |
| 17 | //! In addition, [`NetworkSessionCache`] holds in-process "approve once for |
| 18 | //! this session" state for the `Prompt` flow, and [`NetworkDenied`] is the |
| 19 | //! structured error surfaced to callers when a host is blocked. |
| 20 | //! |
| 21 | //! # Host-matching rules |
| 22 | //! |
| 23 | //! * **Exact match** — an entry like `api.deepseek.com` matches only the host |
| 24 | //! `api.deepseek.com` (case-insensitive). |
| 25 | //! * **Subdomain match** — an entry that **starts with a leading dot**, e.g. |
| 26 | //! `.example.com`, matches any subdomain (`api.example.com`, `a.b.example.com`) |
| 27 | //! but **not** the apex `example.com`. To match both, list both. |
| 28 | //! |
| 29 | //! Matching is case-insensitive and trims a single trailing dot from the host |
| 30 | //! (so `example.com.` and `example.com` are equivalent). |
| 31 | //! |
| 32 | //! # Audit-log format |
| 33 | //! |
| 34 | //! ```text |
| 35 | //! <RFC3339-timestamp> network <host> <tool> <Allow|Deny|Prompt-Approved|Prompt-Denied|TrustedProxyFakeIp-Allow> |
| 36 | //! ``` |
| 37 | //! |
| 38 | //! Plaintext, one line per call, appended to `<audit_path>` (defaults to |
| 39 | //! `~/.codewhale/audit.log`). Best-effort: write failures are logged but do |
| 40 | //! not block the call. |
| 41 | |
| 42 | use std::fs::{self, OpenOptions}; |
| 43 | use std::io::Write; |
| 44 | use std::net::{IpAddr, Ipv4Addr}; |
| 45 | use std::path::{Path, PathBuf}; |
| 46 | use std::sync::{Arc, Mutex}; |
| 47 | |
| 48 | use chrono::Utc; |
| 49 | use serde::{Deserialize, Serialize}; |
| 50 | use thiserror::Error; |
| 51 | |
| 52 | /// What the policy decided about an outbound network call. |
| 53 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 54 | pub enum Decision { |
| 55 | /// Allow the call without prompting. |
| 56 | Allow, |
| 57 | /// Deny the call. Surfaced to callers as [`NetworkDenied`]. |
| 58 | Deny, |
| 59 | /// Defer to the user via an approval prompt. |
| 60 | Prompt, |
| 61 | } |
| 62 | |
| 63 | impl Decision { |
| 64 | /// String form used in audit-log lines. |
| 65 | #[must_use] |
| 66 | pub fn as_str(self) -> &'static str { |
| 67 | match self { |
| 68 | Self::Allow => "Allow", |
| 69 | Self::Deny => "Deny", |
| 70 | Self::Prompt => "Prompt", |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | /// Parse a decision from a TOML string. Unknown values fall back to |
| 75 | /// `Prompt` so a typo never silently disables the policy. |
| 76 | #[must_use] |
| 77 | pub fn parse(value: &str) -> Self { |
| 78 | match value.trim().to_ascii_lowercase().as_str() { |
| 79 | "allow" => Self::Allow, |
| 80 | "deny" | "block" => Self::Deny, |
| 81 | _ => Self::Prompt, |
| 82 | } |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | /// Per-domain allow/deny list with a default fallback. |
| 87 | /// |
| 88 | /// See the module docs for [host-matching rules](self#host-matching-rules) |
| 89 | /// and [deny-wins precedence](self#deny-wins-precedence). |
| 90 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 91 | pub struct NetworkPolicy { |
| 92 | /// Decision for hosts that match neither `allow` nor `deny`. |
| 93 | #[serde(default = "default_decision")] |
| 94 | pub default: DecisionToml, |
| 95 | /// Hosts that should be allowed without prompting. |
| 96 | #[serde(default)] |
| 97 | pub allow: Vec<String>, |
| 98 | /// Hosts that should always be denied. |
| 99 | #[serde(default)] |
| 100 | pub deny: Vec<String>, |
| 101 | /// Hostnames whose DNS may resolve to fake-IP/private proxy ranges in an |
| 102 | /// explicitly trusted proxy setup. This does not affect literal IP URLs. |
| 103 | #[serde(default)] |
| 104 | pub proxy: Vec<String>, |
| 105 | /// Explicit fake-IP placeholder CIDRs used by the trusted proxy setup. |
| 106 | /// Only subnets contained by the IETF benchmark range `198.18.0.0/15` |
| 107 | /// are eligible; loopback, RFC1918, link-local, metadata, and ULA ranges |
| 108 | /// can never be trusted through this setting. |
| 109 | #[serde(default)] |
| 110 | pub proxy_fake_ip_cidrs: Vec<String>, |
| 111 | /// Whether to record one audit-log line per network call. Defaults to true. |
| 112 | #[serde(default = "default_audit")] |
| 113 | pub audit: bool, |
| 114 | } |
| 115 | |
| 116 | fn default_decision() -> DecisionToml { |
| 117 | DecisionToml::Prompt |
| 118 | } |
| 119 | |
| 120 | /// The stricter of two fallback decisions, ordering `Deny` < `Prompt` < `Allow`. |
| 121 | /// Used when a lower-precedence layer is folded onto a policy an authority set. |
| 122 | fn stricter_decision(left: DecisionToml, right: DecisionToml) -> DecisionToml { |
| 123 | fn rank(decision: DecisionToml) -> u8 { |
| 124 | match decision { |
| 125 | DecisionToml::Deny => 0, |
| 126 | DecisionToml::Prompt => 1, |
| 127 | DecisionToml::Allow => 2, |
| 128 | } |
| 129 | } |
| 130 | if rank(left) <= rank(right) { |
| 131 | left |
| 132 | } else { |
| 133 | right |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | fn default_audit() -> bool { |
| 138 | true |
| 139 | } |
| 140 | |
| 141 | impl Default for NetworkPolicy { |
| 142 | fn default() -> Self { |
| 143 | Self { |
| 144 | default: DecisionToml::Prompt, |
| 145 | allow: Vec::new(), |
| 146 | deny: Vec::new(), |
| 147 | proxy: Vec::new(), |
| 148 | proxy_fake_ip_cidrs: Vec::new(), |
| 149 | audit: true, |
| 150 | } |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | /// Wire-format wrapper for [`Decision`] used in serde-derived TOML/JSON. The |
| 155 | /// runtime API exposes [`Decision`] directly; this type only exists so |
| 156 | /// `default = "prompt"` round-trips cleanly through TOML. |
| 157 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 158 | #[serde(rename_all = "lowercase")] |
| 159 | pub enum DecisionToml { |
| 160 | Allow, |
| 161 | Deny, |
| 162 | Prompt, |
| 163 | } |
| 164 | |
| 165 | impl From<DecisionToml> for Decision { |
| 166 | fn from(value: DecisionToml) -> Self { |
| 167 | match value { |
| 168 | DecisionToml::Allow => Self::Allow, |
| 169 | DecisionToml::Deny => Self::Deny, |
| 170 | DecisionToml::Prompt => Self::Prompt, |
| 171 | } |
| 172 | } |
| 173 | } |
| 174 | |
| 175 | impl From<Decision> for DecisionToml { |
| 176 | fn from(value: Decision) -> Self { |
| 177 | match value { |
| 178 | Decision::Allow => Self::Allow, |
| 179 | Decision::Deny => Self::Deny, |
| 180 | Decision::Prompt => Self::Prompt, |
| 181 | } |
| 182 | } |
| 183 | } |
| 184 | |
| 185 | impl From<codewhale_config::NetworkPolicyToml> for NetworkPolicy { |
| 186 | fn from(toml: codewhale_config::NetworkPolicyToml) -> Self { |
| 187 | Self { |
| 188 | default: Decision::parse(&toml.default).into(), |
| 189 | allow: toml.allow, |
| 190 | deny: toml.deny, |
| 191 | proxy: toml.proxy, |
| 192 | proxy_fake_ip_cidrs: toml.proxy_fake_ip_cidrs, |
| 193 | audit: toml.audit, |
| 194 | } |
| 195 | } |
| 196 | } |
| 197 | |
| 198 | /// Re-read the `[network]` table from a configuration document. |
| 199 | /// |
| 200 | /// Deliberately narrower than `Config::load`: this runs on the tool-context |
| 201 | /// build path, where re-applying the environment, managed, and credential |
| 202 | /// layers would be both wasteful and wrong. Only the document's own table comes |
| 203 | /// back — the same table `/network allow <host>` edits. |
| 204 | /// |
| 205 | /// `None` means there is nothing usable to adopt: the document is missing, |
| 206 | /// unreadable, unparseable, or carries no `[network]` table. Callers keep the |
| 207 | /// policy they already hold, which is the conservative direction for an |
| 208 | /// allow/deny gate. |
| 209 | /// |
| 210 | /// Known limitation: `[profiles.<name>.network]` is not consulted. `/network` |
| 211 | /// does not write it either, so a live session and the command agree on this |
| 212 | /// base table. |
| 213 | #[must_use] |
| 214 | pub fn network_policy_from_document(path: &Path) -> Option<NetworkPolicy> { |
| 215 | use std::io::Read; |
| 216 | |
| 217 | #[derive(Deserialize)] |
| 218 | struct NetworkTable { |
| 219 | network: Option<codewhale_config::NetworkPolicyToml>, |
| 220 | } |
| 221 | |
| 222 | const MAX_POLICY_DOCUMENT_BYTES: u64 = 4 * 1024 * 1024; |
| 223 | let file = fs::File::open(path).ok()?; |
| 224 | let meta = file.metadata().ok()?; |
| 225 | if !meta.is_file() || meta.len() > MAX_POLICY_DOCUMENT_BYTES { |
| 226 | return None; |
| 227 | } |
| 228 | let mut raw = Vec::new(); |
| 229 | file.take(MAX_POLICY_DOCUMENT_BYTES + 1) |
| 230 | .read_to_end(&mut raw) |
| 231 | .ok()?; |
| 232 | if raw.len() as u64 > MAX_POLICY_DOCUMENT_BYTES { |
| 233 | return None; |
| 234 | } |
| 235 | let contents = String::from_utf8(raw).ok()?; |
| 236 | let parsed: NetworkTable = toml::from_str(&contents).ok()?; |
| 237 | parsed.network.map(NetworkPolicy::from) |
| 238 | } |
| 239 | |
| 240 | impl NetworkPolicy { |
| 241 | /// Fold a lower-precedence layer (the user's config document) onto this |
| 242 | /// policy without letting it widen what a higher authority set. |
| 243 | /// |
| 244 | /// The fold is deliberately asymmetric, because the two layers are not |
| 245 | /// peers: |
| 246 | /// |
| 247 | /// * `deny` is the **union**. Either layer saying no is a no. |
| 248 | /// * `default` keeps the **stricter** of the two. |
| 249 | /// * When the authority's fallback is `Deny`, the lower layer contributes |
| 250 | /// **nothing that can allow**: `allow`, `proxy`, and the fake-IP CIDRs |
| 251 | /// stay the authority's own. `decide` checks `allow` *before* falling back |
| 252 | /// to `default`, so adopting a lower `allow` entry under a |
| 253 | /// deny-by-default authority would let the document lift exactly the |
| 254 | /// denial the authority set. |
| 255 | /// * Otherwise the authority is prompt-by-default, and the lower layer may |
| 256 | /// do what `/network allow <host>` writes: name additional hosts. Those |
| 257 | /// merge with the authority's own rather than replacing them, so a |
| 258 | /// refresh cannot erase an administrator's allowances either. |
| 259 | /// * `audit` is the one field that widens by `true`: either layer asking for |
| 260 | /// the audit log keeps it, and a document cannot silence it under an |
| 261 | /// authority. |
| 262 | #[must_use] |
| 263 | pub fn folded_with_lower_layer(&self, lower: Self) -> Self { |
| 264 | fn union(mut base: Vec<String>, extra: Vec<String>) -> Vec<String> { |
| 265 | for entry in extra { |
| 266 | if !base.iter().any(|existing| existing == &entry) { |
| 267 | base.push(entry); |
| 268 | } |
| 269 | } |
| 270 | base |
| 271 | } |
| 272 | |
| 273 | let deny_by_default = self.default == DecisionToml::Deny; |
| 274 | let (allow, proxy, proxy_fake_ip_cidrs) = if deny_by_default { |
| 275 | ( |
| 276 | self.allow.clone(), |
| 277 | self.proxy.clone(), |
| 278 | self.proxy_fake_ip_cidrs.clone(), |
| 279 | ) |
| 280 | } else { |
| 281 | ( |
| 282 | union(self.allow.clone(), lower.allow), |
| 283 | union(self.proxy.clone(), lower.proxy), |
| 284 | union(self.proxy_fake_ip_cidrs.clone(), lower.proxy_fake_ip_cidrs), |
| 285 | ) |
| 286 | }; |
| 287 | Self { |
| 288 | default: stricter_decision(self.default, lower.default), |
| 289 | allow, |
| 290 | deny: union(self.deny.clone(), lower.deny), |
| 291 | proxy, |
| 292 | proxy_fake_ip_cidrs, |
| 293 | audit: self.audit || lower.audit, |
| 294 | } |
| 295 | } |
| 296 | |
| 297 | /// Decide what to do for a single outbound call to `host`. |
| 298 | /// |
| 299 | /// **Deny-wins precedence**: if `host` matches any entry in `deny`, the |
| 300 | /// answer is [`Decision::Deny`] regardless of `allow`. This makes deny |
| 301 | /// lists safe to combine with broad allow rules. |
| 302 | #[must_use] |
| 303 | pub fn decide(&self, host: &str) -> Decision { |
| 304 | let normalized = normalize_host(host); |
| 305 | if normalized.is_empty() { |
| 306 | // We don't pretend we can audit a malformed host; treat it as the |
| 307 | // default (prompt or deny). |
| 308 | return self.default.into(); |
| 309 | } |
| 310 | if self |
| 311 | .deny |
| 312 | .iter() |
| 313 | .any(|entry| host_matches(entry, &normalized)) |
| 314 | { |
| 315 | return Decision::Deny; |
| 316 | } |
| 317 | if self |
| 318 | .allow |
| 319 | .iter() |
| 320 | .any(|entry| host_matches(entry, &normalized)) |
| 321 | { |
| 322 | return Decision::Allow; |
| 323 | } |
| 324 | self.default.into() |
| 325 | } |
| 326 | |
| 327 | #[must_use] |
| 328 | pub fn explicitly_allows(&self, host: &str) -> bool { |
| 329 | let normalized = normalize_host(host); |
| 330 | if normalized.is_empty() { |
| 331 | return false; |
| 332 | } |
| 333 | if self |
| 334 | .deny |
| 335 | .iter() |
| 336 | .any(|entry| host_matches(entry, &normalized)) |
| 337 | { |
| 338 | return false; |
| 339 | } |
| 340 | self.allow |
| 341 | .iter() |
| 342 | .any(|entry| host_matches(entry, &normalized)) |
| 343 | } |
| 344 | |
| 345 | /// Append `host` to the allow list (de-duplicated, case-insensitive). |
| 346 | /// Used by the prompt flow when the user picks "always for this host". |
| 347 | pub fn add_allow(&mut self, host: &str) { |
| 348 | let normalized = normalize_host(host); |
| 349 | if normalized.is_empty() { |
| 350 | return; |
| 351 | } |
| 352 | if !self |
| 353 | .allow |
| 354 | .iter() |
| 355 | .any(|existing| normalize_host(existing) == normalized) |
| 356 | { |
| 357 | self.allow.push(normalized); |
| 358 | } |
| 359 | } |
| 360 | |
| 361 | /// Whether audit logging is enabled. |
| 362 | #[must_use] |
| 363 | pub fn audit_enabled(&self) -> bool { |
| 364 | self.audit |
| 365 | } |
| 366 | |
| 367 | /// Whether `host` is explicitly trusted to resolve through a local |
| 368 | /// fake-IP proxy. Deny entries still win over this list. |
| 369 | #[must_use] |
| 370 | pub fn trusts_proxy_fakeip_host(&self, host: &str) -> bool { |
| 371 | let normalized = normalize_host(host); |
| 372 | if normalized.is_empty() { |
| 373 | return false; |
| 374 | } |
| 375 | if self |
| 376 | .deny |
| 377 | .iter() |
| 378 | .any(|entry| host_matches(entry, &normalized)) |
| 379 | { |
| 380 | return false; |
| 381 | } |
| 382 | self.proxy |
| 383 | .iter() |
| 384 | .any(|entry| host_matches(entry, &normalized)) |
| 385 | } |
| 386 | } |
| 387 | |
| 388 | /// Normalize a host for matching: lowercase, trim whitespace, strip a single |
| 389 | /// trailing dot (FQDN form), and strip a leading `*.` or `.` for entries that |
| 390 | /// are written that way in config (we treat both as subdomain wildcards on |
| 391 | /// the *match* side, but on input normalization we keep the leading dot so |
| 392 | /// `host_matches` can detect the wildcard intent). |
| 393 | fn normalize_host(host: &str) -> String { |
| 394 | let trimmed = host.trim().trim_end_matches('.').to_ascii_lowercase(); |
| 395 | let (wildcard, name) = match trimmed.strip_prefix("*.") { |
| 396 | Some(rest) => (".", rest), |
| 397 | None => match trimmed.strip_prefix('.') { |
| 398 | Some(rest) => (".", rest), |
| 399 | None => ("", trimmed.as_str()), |
| 400 | }, |
| 401 | }; |
| 402 | if wildcard.is_empty() { |
| 403 | let unbracketed = name |
| 404 | .strip_prefix('[') |
| 405 | .and_then(|rest| rest.strip_suffix(']')) |
| 406 | .unwrap_or(name); |
| 407 | if let Ok(v6) = unbracketed.parse::<std::net::Ipv6Addr>() { |
| 408 | return v6.to_string(); |
| 409 | } |
| 410 | } |
| 411 | // Only a bare host goes through the URL parser: an entry with URL syntax |
| 412 | // in it would otherwise turn into a different host (`例子.com@evil.com` |
| 413 | // into `evil.com`), so it keeps matching nothing, as it did before. |
| 414 | if name.is_ascii() |
| 415 | || name.contains(['@', '/', '\\', '?', '#', ':']) |
| 416 | || name.chars().any(char::is_whitespace) |
| 417 | { |
| 418 | return format!("{wildcard}{name}"); |
| 419 | } |
| 420 | let ascii = reqwest::Url::parse(&format!("http://{name}/")) |
| 421 | .ok() |
| 422 | .and_then(|url| { |
| 423 | url.host_str() |
| 424 | .map(|host| host.trim_end_matches('.').to_owned()) |
| 425 | }) |
| 426 | .unwrap_or_else(|| name.to_string()); |
| 427 | format!("{wildcard}{ascii}") |
| 428 | } |
| 429 | |
| 430 | /// Match a single allow/deny entry against an already-normalized host. |
| 431 | fn host_matches(entry: &str, normalized_host: &str) -> bool { |
| 432 | let entry_norm = normalize_host(entry); |
| 433 | if let Some(suffix) = entry_norm.strip_prefix('.') { |
| 434 | // Wildcard subdomain rule. Match any host ending in `.suffix`, but |
| 435 | // *not* the bare `suffix` itself (per spec). |
| 436 | if suffix.is_empty() || normalized_host.parse::<IpAddr>().is_ok() { |
| 437 | return false; |
| 438 | } |
| 439 | normalized_host.ends_with(&format!(".{suffix}")) |
| 440 | } else { |
| 441 | entry_norm == normalized_host |
| 442 | } |
| 443 | } |
| 444 | |
| 445 | /// Parse an IPv4 CIDR string such as `"198.18.0.0/15"` into `(base, prefix)`. |
| 446 | /// Returns `None` for malformed input or a prefix length above 32. |
| 447 | fn parse_ipv4_cidr(cidr: &str) -> Option<(Ipv4Addr, u8)> { |
| 448 | let (addr, prefix) = cidr.split_once('/')?; |
| 449 | let base: Ipv4Addr = addr.trim().parse().ok()?; |
| 450 | let prefix: u8 = prefix.trim().parse().ok()?; |
| 451 | if prefix > 32 { |
| 452 | return None; |
| 453 | } |
| 454 | Some((base, prefix)) |
| 455 | } |
| 456 | |
| 457 | /// Parse only fake-IP networks that are fully contained by the IETF benchmark |
| 458 | /// block. This keeps an overly broad or mistaken config entry from weakening |
| 459 | /// the unconditional loopback/private/link-local/metadata protections. |
| 460 | fn parse_trusted_fakeip_cidr(cidr: &str) -> Option<(Ipv4Addr, u8)> { |
| 461 | let (base, prefix) = parse_ipv4_cidr(cidr)?; |
| 462 | let octets = base.octets(); |
| 463 | (prefix >= 15 && octets[0] == 198 && matches!(octets[1], 18..=19)).then_some((base, prefix)) |
| 464 | } |
| 465 | |
| 466 | /// Whether `ip` is contained in the `base/prefix` IPv4 CIDR block. |
| 467 | fn ipv4_in_cidr(ip: Ipv4Addr, base: Ipv4Addr, prefix: u8) -> bool { |
| 468 | if prefix == 0 { |
| 469 | return true; |
| 470 | } |
| 471 | let mask: u32 = u32::MAX << (32 - prefix); |
| 472 | (u32::from(ip) & mask) == (u32::from(base) & mask) |
| 473 | } |
| 474 | |
| 475 | /// Best-effort writer for the network audit log. |
| 476 | #[derive(Debug, Clone)] |
| 477 | pub struct NetworkAuditor { |
| 478 | path: PathBuf, |
| 479 | enabled: bool, |
| 480 | } |
| 481 | |
| 482 | impl NetworkAuditor { |
| 483 | /// New auditor that writes to `path`. `enabled = false` turns it into a no-op. |
| 484 | #[must_use] |
| 485 | pub fn new(path: PathBuf, enabled: bool) -> Self { |
| 486 | Self { path, enabled } |
| 487 | } |
| 488 | |
| 489 | /// Auditor pointing at the same `audit.log` every other audit event uses: |
| 490 | /// `$CODEWHALE_HOME/audit.log`, else `~/.codewhale/audit.log`. It used to |
| 491 | /// join `$HOME/.codewhale` itself, which ignored `CODEWHALE_HOME` and let |
| 492 | /// test processes append to the developer's real log. Returns `None` if |
| 493 | /// no Codewhale home resolves. |
| 494 | #[must_use] |
| 495 | pub fn default_path(enabled: bool) -> Option<Self> { |
| 496 | Some(Self::new( |
| 497 | codewhale_runtime::audit::audit_log_path()?, |
| 498 | enabled, |
| 499 | )) |
| 500 | } |
| 501 | |
| 502 | /// Append one line. Best-effort: errors are logged via `tracing` but |
| 503 | /// never bubble back to the caller. |
| 504 | pub fn record(&self, host: &str, tool: &str, decision_label: &str) { |
| 505 | if !self.enabled { |
| 506 | return; |
| 507 | } |
| 508 | if let Err(err) = self.try_record(host, tool, decision_label) { |
| 509 | // Routed through tracing so it lands in |
| 510 | // `~/.codewhale/logs/tui-YYYY-MM-DD.log` rather than the |
| 511 | // alt-screen — see `runtime_log` for the scroll-demon |
| 512 | // rationale. |
| 513 | tracing::warn!(target: "network_policy", ?err, host, tool, "network audit write failed"); |
| 514 | } |
| 515 | } |
| 516 | |
| 517 | fn try_record(&self, host: &str, tool: &str, decision_label: &str) -> std::io::Result<()> { |
| 518 | if let Some(parent) = self.path.parent() |
| 519 | && !parent.as_os_str().is_empty() |
| 520 | { |
| 521 | fs::create_dir_all(parent)?; |
| 522 | } |
| 523 | let mut file = OpenOptions::new() |
| 524 | .create(true) |
| 525 | .append(true) |
| 526 | .open(&self.path)?; |
| 527 | writeln!( |
| 528 | file, |
| 529 | "{ts} network {host} {tool} {decision}", |
| 530 | ts = Utc::now().to_rfc3339(), |
| 531 | host = sanitize_field(host), |
| 532 | tool = sanitize_field(tool), |
| 533 | decision = decision_label, |
| 534 | ) |
| 535 | } |
| 536 | |
| 537 | /// Path the auditor would write to. Mostly useful for tests. |
| 538 | #[must_use] |
| 539 | pub fn path(&self) -> &Path { |
| 540 | &self.path |
| 541 | } |
| 542 | } |
| 543 | |
| 544 | /// Replace whitespace in a token so the line stays parseable. |
| 545 | fn sanitize_field(s: &str) -> String { |
| 546 | s.chars() |
| 547 | .map(|c| if c.is_whitespace() { '_' } else { c }) |
| 548 | .collect() |
| 549 | } |
| 550 | |
| 551 | /// In-process cache of "approve once for this session" decisions. Keyed by |
| 552 | /// normalized host. Thread-safe. |
| 553 | #[derive(Debug, Default, Clone)] |
| 554 | pub struct NetworkSessionCache { |
| 555 | inner: Arc<Mutex<NetworkSessionCacheInner>>, |
| 556 | } |
| 557 | |
| 558 | #[derive(Debug, Default)] |
| 559 | struct NetworkSessionCacheInner { |
| 560 | approved: std::collections::HashSet<String>, |
| 561 | denied: std::collections::HashSet<String>, |
| 562 | } |
| 563 | |
| 564 | impl NetworkSessionCache { |
| 565 | /// New empty cache. |
| 566 | #[must_use] |
| 567 | pub fn new() -> Self { |
| 568 | Self::default() |
| 569 | } |
| 570 | |
| 571 | /// `true` if the host was previously approved this session. |
| 572 | #[must_use] |
| 573 | pub fn is_approved(&self, host: &str) -> bool { |
| 574 | let normalized = normalize_host(host); |
| 575 | self.inner |
| 576 | .lock() |
| 577 | .map(|guard| guard.approved.contains(&normalized)) |
| 578 | .unwrap_or(false) |
| 579 | } |
| 580 | |
| 581 | /// `true` if the host was previously denied this session. |
| 582 | #[must_use] |
| 583 | pub fn is_denied(&self, host: &str) -> bool { |
| 584 | let normalized = normalize_host(host); |
| 585 | self.inner |
| 586 | .lock() |
| 587 | .map(|guard| guard.denied.contains(&normalized)) |
| 588 | .unwrap_or(false) |
| 589 | } |
| 590 | |
| 591 | /// Mark the host as approved for the rest of this session. |
| 592 | pub fn approve(&self, host: &str) { |
| 593 | let normalized = normalize_host(host); |
| 594 | if let Ok(mut guard) = self.inner.lock() { |
| 595 | guard.denied.remove(&normalized); |
| 596 | guard.approved.insert(normalized); |
| 597 | } |
| 598 | } |
| 599 | |
| 600 | /// Mark the host as denied for the rest of this session. |
| 601 | pub fn deny(&self, host: &str) { |
| 602 | let normalized = normalize_host(host); |
| 603 | if let Ok(mut guard) = self.inner.lock() { |
| 604 | guard.approved.remove(&normalized); |
| 605 | guard.denied.insert(normalized); |
| 606 | } |
| 607 | } |
| 608 | } |
| 609 | |
| 610 | /// Structured error surfaced to callers when an outbound call is blocked. |
| 611 | #[derive(Debug, Clone, Error)] |
| 612 | #[error("network call to '{0}' blocked by network policy")] |
| 613 | pub struct NetworkDenied(pub String); |
| 614 | |
| 615 | impl NetworkDenied { |
| 616 | /// The host that was denied. |
| 617 | #[must_use] |
| 618 | pub fn host(&self) -> &str { |
| 619 | &self.0 |
| 620 | } |
| 621 | } |
| 622 | |
| 623 | /// Glue type that bundles a [`NetworkPolicy`] with a session cache and an |
| 624 | /// auditor. Tools call [`NetworkPolicyDecider::evaluate`] before any HTTP |
| 625 | /// transport is constructed; the result decides whether to proceed, deny, |
| 626 | /// or prompt the user. |
| 627 | #[derive(Debug, Clone)] |
| 628 | pub struct NetworkPolicyDecider { |
| 629 | policy: NetworkPolicy, |
| 630 | cache: NetworkSessionCache, |
| 631 | auditor: Option<NetworkAuditor>, |
| 632 | /// IPv4 CIDR ranges that are treated as benign fake-IP placeholders (e.g. |
| 633 | /// a transparent-proxy / TUN setup running in `fake-ip` mode, where DNS |
| 634 | /// resolves every hostname into a reserved range like `198.18.0.0/15`). |
| 635 | /// A resolved IP inside one of these ranges bypasses the restricted-IP SSRF |
| 636 | /// block; real private/loopback/link-local/metadata IPs are unaffected. |
| 637 | trusted_fakeip_cidrs: Vec<(Ipv4Addr, u8)>, |
| 638 | /// The policy was produced by an authority the user's config document may |
| 639 | /// not override — a managed layer, or a Fleet denial the user is not |
| 640 | /// allowed to widen. A mid-session re-read of that document then folds onto |
| 641 | /// this policy instead of replacing it. See |
| 642 | /// [`NetworkPolicy::folded_with_lower_layer`]. |
| 643 | authoritative: bool, |
| 644 | } |
| 645 | |
| 646 | impl NetworkPolicyDecider { |
| 647 | /// Build a decider from a policy. The session cache starts empty. |
| 648 | #[must_use] |
| 649 | pub fn new(policy: NetworkPolicy, auditor: Option<NetworkAuditor>) -> Self { |
| 650 | let trusted_fakeip_cidrs = policy |
| 651 | .proxy_fake_ip_cidrs |
| 652 | .iter() |
| 653 | .filter_map(|cidr| parse_trusted_fakeip_cidr(cidr)) |
| 654 | .collect(); |
| 655 | Self { |
| 656 | policy, |
| 657 | cache: NetworkSessionCache::new(), |
| 658 | auditor, |
| 659 | trusted_fakeip_cidrs, |
| 660 | authoritative: false, |
| 661 | } |
| 662 | } |
| 663 | |
| 664 | /// Mark this policy as set by an authority the user document may not |
| 665 | /// override. See the `authoritative` field. |
| 666 | #[must_use] |
| 667 | pub fn with_authoritative(mut self) -> Self { |
| 668 | self.authoritative = true; |
| 669 | self |
| 670 | } |
| 671 | |
| 672 | /// Whether an authority set this policy rather than the user document. |
| 673 | #[must_use] |
| 674 | pub fn is_authoritative(&self) -> bool { |
| 675 | self.authoritative |
| 676 | } |
| 677 | |
| 678 | /// Register IPv4 CIDR ranges to treat as benign fake-IP placeholders. |
| 679 | /// Invalid CIDR strings are skipped. See [`Self::is_trusted_fakeip_addr`]. |
| 680 | #[must_use] |
| 681 | pub fn with_trusted_fakeip_cidrs(mut self, cidrs: &[&str]) -> Self { |
| 682 | for cidr in cidrs { |
| 683 | if let Some(parsed) = parse_trusted_fakeip_cidr(cidr) { |
| 684 | self.trusted_fakeip_cidrs.push(parsed); |
| 685 | } |
| 686 | } |
| 687 | self |
| 688 | } |
| 689 | |
| 690 | /// Whether `ip` falls inside a configured fake-IP placeholder range. |
| 691 | /// |
| 692 | /// In `fake-ip` proxy/TUN setups the local resolver maps every hostname to |
| 693 | /// a reserved range (commonly `198.18.0.0/15`), so the DNS-resolution SSRF |
| 694 | /// check would otherwise reject every request. This narrowly trusts only |
| 695 | /// those placeholder addresses — real private/loopback/link-local/cloud- |
| 696 | /// metadata IPs are *not* matched and stay blocked. |
| 697 | #[must_use] |
| 698 | pub fn is_trusted_fakeip_addr(&self, ip: &IpAddr) -> bool { |
| 699 | match ip { |
| 700 | IpAddr::V4(v4) => self |
| 701 | .trusted_fakeip_cidrs |
| 702 | .iter() |
| 703 | .any(|(base, prefix)| ipv4_in_cidr(*v4, *base, *prefix)), |
| 704 | // fake-ip placeholders are IPv4-only in practice. |
| 705 | IpAddr::V6(_) => false, |
| 706 | } |
| 707 | } |
| 708 | |
| 709 | /// Convenience: build a decider with default audit logging at |
| 710 | /// `~/.codewhale/audit.log`, if `policy.audit` is true. |
| 711 | #[must_use] |
| 712 | pub fn with_default_audit(policy: NetworkPolicy) -> Self { |
| 713 | let audit_enabled = policy.audit_enabled(); |
| 714 | let auditor = if audit_enabled { |
| 715 | NetworkAuditor::default_path(true) |
| 716 | } else { |
| 717 | None |
| 718 | }; |
| 719 | Self::new(policy, auditor) |
| 720 | } |
| 721 | |
| 722 | /// Rebuild this decider against a policy re-read from disk, keeping the |
| 723 | /// session cache so an approval already granted in this session survives |
| 724 | /// the refresh. |
| 725 | /// |
| 726 | /// The engine snapshots its policy when it is spawned, and `/network allow |
| 727 | /// <host>` only edits the configuration document — it cannot reach that |
| 728 | /// snapshot. Callers hand the re-read table here instead of waiting for a |
| 729 | /// restart. The auditor keeps its log path and follows the new policy's |
| 730 | /// `audit` switch. |
| 731 | /// |
| 732 | /// Extra CIDRs registered through [`Self::with_trusted_fakeip_cidrs`] are |
| 733 | /// not carried over; the refresh re-derives them from `policy`. Configured |
| 734 | /// fake-IP ranges already ride in the policy, and no production caller |
| 735 | /// registers extras. |
| 736 | #[must_use] |
| 737 | pub fn with_policy_refreshed(&self, policy: NetworkPolicy) -> Self { |
| 738 | let auditor = match self.auditor.as_ref() { |
| 739 | Some(existing) => Some(NetworkAuditor::new( |
| 740 | existing.path().to_path_buf(), |
| 741 | policy.audit_enabled(), |
| 742 | )), |
| 743 | None if policy.audit_enabled() => NetworkAuditor::default_path(true), |
| 744 | None => None, |
| 745 | }; |
| 746 | Self { |
| 747 | trusted_fakeip_cidrs: policy |
| 748 | .proxy_fake_ip_cidrs |
| 749 | .iter() |
| 750 | .filter_map(|cidr| parse_trusted_fakeip_cidr(cidr)) |
| 751 | .collect(), |
| 752 | policy, |
| 753 | cache: self.cache.clone(), |
| 754 | auditor, |
| 755 | authoritative: self.authoritative, |
| 756 | } |
| 757 | } |
| 758 | |
| 759 | /// Inspect the policy. |
| 760 | #[must_use] |
| 761 | pub fn policy(&self) -> &NetworkPolicy { |
| 762 | &self.policy |
| 763 | } |
| 764 | |
| 765 | #[must_use] |
| 766 | pub fn denies_by_default(&self) -> bool { |
| 767 | self.policy.default == DecisionToml::Deny |
| 768 | } |
| 769 | |
| 770 | /// Inspect the session cache. |
| 771 | #[must_use] |
| 772 | pub fn cache(&self) -> &NetworkSessionCache { |
| 773 | &self.cache |
| 774 | } |
| 775 | |
| 776 | /// Decide for `host`, consulting the session cache first. |
| 777 | /// |
| 778 | /// Audit logging happens **only** for terminal decisions (Allow / Deny). |
| 779 | /// `Prompt` is intentionally not logged here — the caller is responsible |
| 780 | /// for recording the user's eventual answer with `record_prompt_outcome`. |
| 781 | #[must_use] |
| 782 | pub fn evaluate(&self, host: &str, tool: &str) -> Decision { |
| 783 | let normalized = normalize_host(host); |
| 784 | if normalized.is_empty() { |
| 785 | return self.policy.default.into(); |
| 786 | } |
| 787 | if self.cache.is_denied(&normalized) { |
| 788 | self.audit_record(&normalized, tool, "Deny"); |
| 789 | return Decision::Deny; |
| 790 | } |
| 791 | if self.cache.is_approved(&normalized) { |
| 792 | self.audit_record(&normalized, tool, "Allow"); |
| 793 | return Decision::Allow; |
| 794 | } |
| 795 | let decision = self.policy.decide(&normalized); |
| 796 | match decision { |
| 797 | Decision::Allow => self.audit_record(&normalized, tool, "Allow"), |
| 798 | Decision::Deny => self.audit_record(&normalized, tool, "Deny"), |
| 799 | Decision::Prompt => {} |
| 800 | } |
| 801 | decision |
| 802 | } |
| 803 | |
| 804 | /// Approve `host` for the rest of the session (one-shot). Audit log gets |
| 805 | /// `Prompt-Approved`. |
| 806 | pub fn approve_session(&self, host: &str, tool: &str) { |
| 807 | self.cache.approve(host); |
| 808 | self.audit_record(host, tool, "Prompt-Approved"); |
| 809 | } |
| 810 | |
| 811 | /// Deny `host` for the rest of the session. Audit log gets `Prompt-Denied`. |
| 812 | pub fn deny_session(&self, host: &str, tool: &str) { |
| 813 | self.cache.deny(host); |
| 814 | self.audit_record(host, tool, "Prompt-Denied"); |
| 815 | } |
| 816 | |
| 817 | /// Persist `host` into the policy's allow list (so it survives the session) |
| 818 | /// **and** approve it in-session. Returns the updated policy so callers can |
| 819 | /// write it back to disk. |
| 820 | pub fn approve_persistent(&mut self, host: &str, tool: &str) -> &NetworkPolicy { |
| 821 | self.policy.add_allow(host); |
| 822 | self.cache.approve(host); |
| 823 | self.audit_record(host, tool, "Prompt-Approved"); |
| 824 | &self.policy |
| 825 | } |
| 826 | |
| 827 | /// Whether this host is explicitly configured for trusted proxy fake-IP |
| 828 | /// DNS handling. |
| 829 | #[must_use] |
| 830 | pub fn trusts_proxy_fakeip_host(&self, host: &str) -> bool { |
| 831 | self.policy.trusts_proxy_fakeip_host(host) |
| 832 | } |
| 833 | |
| 834 | /// Record that a restricted DNS result was allowed because the host is in |
| 835 | /// the trusted proxy fake-IP list. |
| 836 | pub fn record_trusted_proxy_fakeip_allow(&self, host: &str, tool: &str) { |
| 837 | self.audit_record(host, tool, "TrustedProxyFakeIp-Allow"); |
| 838 | } |
| 839 | |
| 840 | fn audit_record(&self, host: &str, tool: &str, label: &str) { |
| 841 | if let Some(auditor) = self.auditor.as_ref() { |
| 842 | auditor.record(host, tool, label); |
| 843 | } |
| 844 | } |
| 845 | } |
| 846 | |
| 847 | /// Extract the host portion of a URL, lowercased. Returns `None` if the URL |
| 848 | /// can't be parsed or has no host. |
| 849 | #[must_use] |
| 850 | pub fn host_from_url(url: &str) -> Option<String> { |
| 851 | let parsed = reqwest::Url::parse(url.trim()).ok()?; |
| 852 | parsed.host_str().map(str::to_ascii_lowercase) |
| 853 | } |
| 854 | |
| 855 | #[cfg(test)] |
| 856 | mod tests { |
| 857 | use super::*; |
| 858 | use tempfile::tempdir; |
| 859 | |
| 860 | fn mk(default: Decision, allow: &[&str], deny: &[&str]) -> NetworkPolicy { |
| 861 | NetworkPolicy { |
| 862 | default: default.into(), |
| 863 | allow: allow.iter().map(|s| (*s).to_string()).collect(), |
| 864 | deny: deny.iter().map(|s| (*s).to_string()).collect(), |
| 865 | proxy: Vec::new(), |
| 866 | proxy_fake_ip_cidrs: Vec::new(), |
| 867 | audit: false, |
| 868 | } |
| 869 | } |
| 870 | |
| 871 | #[test] |
| 872 | fn deny_entries_match_internationalized_domain_names() { |
| 873 | let policy = mk(Decision::Allow, &[], &["例子.com", "*.中国", "BÜCHER.de"]); |
| 874 | for url in [ |
| 875 | "https://例子.com/", |
| 876 | "https://www.例子.中国/", |
| 877 | "https://bücher.de/", |
| 878 | ] { |
| 879 | let host = host_from_url(url).expect("host"); |
| 880 | assert_eq!(policy.decide(&host), Decision::Deny, "{url}"); |
| 881 | } |
| 882 | |
| 883 | // A full stop typed with an IME still names the same host. |
| 884 | let policy = mk(Decision::Allow, &[], &["例子.com。"]); |
| 885 | let host = host_from_url("https://例子.com/").expect("host"); |
| 886 | assert_eq!(policy.decide(&host), Decision::Deny); |
| 887 | |
| 888 | // An entry with URL syntax in it must not turn into another host. |
| 889 | for entry in [ |
| 890 | "例子.com@evil.com", |
| 891 | "evil.com/例", |
| 892 | "evil.com#例", |
| 893 | "evil.com?例", |
| 894 | "evil.com\\例", |
| 895 | "例子.com:8080", |
| 896 | "evil\t.com。", |
| 897 | ] { |
| 898 | let policy = mk(Decision::Prompt, &[entry], &[]); |
| 899 | for url in ["https://evil.com/", "https://例子.com/"] { |
| 900 | let host = host_from_url(url).expect("host"); |
| 901 | assert_eq!(policy.decide(&host), Decision::Prompt, "{entry} {url}"); |
| 902 | } |
| 903 | } |
| 904 | } |
| 905 | |
| 906 | /// The network auditor writes to the one `audit.log` (which follows |
| 907 | /// `CODEWHALE_HOME`); it used to join `$HOME/.codewhale` itself. |
| 908 | #[test] |
| 909 | fn default_auditor_writes_to_the_shared_audit_log() { |
| 910 | assert_eq!( |
| 911 | NetworkAuditor::default_path(true).map(|auditor| auditor.path), |
| 912 | codewhale_runtime::audit::audit_log_path() |
| 913 | ); |
| 914 | } |
| 915 | |
| 916 | #[test] |
| 917 | fn exact_match_in_allow_returns_allow() { |
| 918 | let p = mk(Decision::Deny, &["api.deepseek.com"], &[]); |
| 919 | assert_eq!(p.decide("api.deepseek.com"), Decision::Allow); |
| 920 | } |
| 921 | |
| 922 | #[test] |
| 923 | fn unknown_host_returns_default() { |
| 924 | let p = mk(Decision::Deny, &["api.deepseek.com"], &[]); |
| 925 | assert_eq!(p.decide("evil.example.com"), Decision::Deny); |
| 926 | |
| 927 | let p2 = mk(Decision::Prompt, &[], &[]); |
| 928 | assert_eq!(p2.decide("anything.example"), Decision::Prompt); |
| 929 | } |
| 930 | |
| 931 | #[test] |
| 932 | fn deny_wins_precedence() { |
| 933 | // Acceptance criterion: a host in both allow and deny is denied. |
| 934 | let p = mk(Decision::Prompt, &["api.example.com"], &["api.example.com"]); |
| 935 | assert_eq!(p.decide("api.example.com"), Decision::Deny); |
| 936 | } |
| 937 | |
| 938 | #[test] |
| 939 | fn deny_wins_across_ipv6_spellings() { |
| 940 | for (allow, deny) in [ |
| 941 | ("[fd00::1]", "fd00::1"), |
| 942 | ("fd00::1", "[fd00::1]"), |
| 943 | ("[fd00:0::1]", "fd00::1"), |
| 944 | ("[::1]", "0:0:0:0:0:0:0:1"), |
| 945 | ] { |
| 946 | let p = mk(Decision::Prompt, &[allow], &[deny]); |
| 947 | for probe in [allow, deny] { |
| 948 | assert_eq!( |
| 949 | p.decide(probe), |
| 950 | Decision::Deny, |
| 951 | "{allow} vs {deny} on {probe}" |
| 952 | ); |
| 953 | assert!( |
| 954 | !p.explicitly_allows(probe), |
| 955 | "{allow} vs {deny} must not explicitly allow {probe}" |
| 956 | ); |
| 957 | } |
| 958 | } |
| 959 | } |
| 960 | |
| 961 | #[test] |
| 962 | fn deny_wins_with_subdomain_rules() { |
| 963 | // Deny-wins applies even when the deny is a wildcard and the allow is exact. |
| 964 | let p = mk(Decision::Allow, &["api.example.com"], &[".example.com"]); |
| 965 | assert_eq!(p.decide("api.example.com"), Decision::Deny); |
| 966 | } |
| 967 | |
| 968 | #[test] |
| 969 | fn subdomain_wildcard_matches_subdomain_only() { |
| 970 | let p = mk(Decision::Deny, &[".example.com"], &[]); |
| 971 | assert_eq!(p.decide("api.example.com"), Decision::Allow); |
| 972 | assert_eq!(p.decide("a.b.example.com"), Decision::Allow); |
| 973 | // The bare apex is *not* matched by `.example.com` per the rule. |
| 974 | assert_eq!(p.decide("example.com"), Decision::Deny); |
| 975 | } |
| 976 | |
| 977 | #[test] |
| 978 | fn star_dot_subdomain_alias_is_accepted() { |
| 979 | let p = mk(Decision::Deny, &["*.example.com"], &[]); |
| 980 | assert_eq!(p.decide("api.example.com"), Decision::Allow); |
| 981 | assert_eq!(p.decide("example.com"), Decision::Deny); |
| 982 | } |
| 983 | |
| 984 | #[test] |
| 985 | fn wildcard_rules_never_match_ip_literals() { |
| 986 | let p = mk(Decision::Prompt, &[".1", "*.0.0.1", ".0.0.1"], &[]); |
| 987 | for ip in ["127.0.0.1", "10.0.0.1", "192.168.1.1", "::1"] { |
| 988 | assert!(!p.explicitly_allows(ip), "{ip} must not match wildcard"); |
| 989 | assert_eq!(p.decide(ip), Decision::Prompt, "{ip} must not be allowed"); |
| 990 | } |
| 991 | } |
| 992 | |
| 993 | #[test] |
| 994 | fn host_match_is_case_insensitive() { |
| 995 | let p = mk(Decision::Deny, &["API.DeepSeek.com"], &[]); |
| 996 | assert_eq!(p.decide("api.deepseek.com"), Decision::Allow); |
| 997 | } |
| 998 | |
| 999 | #[test] |
| 1000 | fn trailing_dot_is_ignored() { |
| 1001 | let p = mk(Decision::Deny, &["api.deepseek.com"], &[]); |
| 1002 | assert_eq!(p.decide("api.deepseek.com."), Decision::Allow); |
| 1003 | } |
| 1004 | |
| 1005 | #[test] |
| 1006 | fn empty_host_uses_default() { |
| 1007 | let p = mk(Decision::Deny, &["api.example.com"], &[]); |
| 1008 | assert_eq!(p.decide(""), Decision::Deny); |
| 1009 | assert_eq!(p.decide(" "), Decision::Deny); |
| 1010 | } |
| 1011 | |
| 1012 | #[test] |
| 1013 | fn add_allow_dedupes_case_insensitively() { |
| 1014 | let mut p = mk(Decision::Deny, &[], &[]); |
| 1015 | p.add_allow("Example.COM"); |
| 1016 | p.add_allow("example.com"); |
| 1017 | assert_eq!(p.allow.len(), 1); |
| 1018 | assert_eq!(p.allow[0], "example.com"); |
| 1019 | } |
| 1020 | |
| 1021 | #[test] |
| 1022 | fn trusted_proxy_fakeip_hosts_match_exact_and_subdomains() { |
| 1023 | let mut p = mk(Decision::Deny, &[], &[]); |
| 1024 | p.proxy = vec![ |
| 1025 | "github.com".to_string(), |
| 1026 | ".githubusercontent.com".to_string(), |
| 1027 | ]; |
| 1028 | |
| 1029 | assert!(p.trusts_proxy_fakeip_host("github.com")); |
| 1030 | assert!(p.trusts_proxy_fakeip_host("raw.githubusercontent.com")); |
| 1031 | assert!(!p.trusts_proxy_fakeip_host("githubusercontent.com")); |
| 1032 | assert!(!p.trusts_proxy_fakeip_host("example.com")); |
| 1033 | } |
| 1034 | |
| 1035 | #[test] |
| 1036 | fn trusted_proxy_fakeip_hosts_respect_deny_precedence() { |
| 1037 | let mut p = mk(Decision::Allow, &[], &["raw.githubusercontent.com"]); |
| 1038 | p.proxy = vec![".githubusercontent.com".to_string()]; |
| 1039 | |
| 1040 | assert!(!p.trusts_proxy_fakeip_host("raw.githubusercontent.com")); |
| 1041 | assert!(p.trusts_proxy_fakeip_host("avatars.githubusercontent.com")); |
| 1042 | } |
| 1043 | |
| 1044 | #[test] |
| 1045 | fn trusted_fakeip_cidr_allows_placeholder_but_not_real_private() { |
| 1046 | let decider = NetworkPolicyDecider::new(NetworkPolicy::default(), None) |
| 1047 | .with_trusted_fakeip_cidrs(&[ |
| 1048 | "198.18.0.0/15", |
| 1049 | "127.0.0.0/8", |
| 1050 | "10.0.0.0/8", |
| 1051 | "169.254.0.0/16", |
| 1052 | ]); |
| 1053 | |
| 1054 | // fake-ip placeholder range (clash default / IETF benchmark) is trusted |
| 1055 | assert!(decider.is_trusted_fakeip_addr(&"198.18.0.5".parse::<std::net::IpAddr>().unwrap())); |
| 1056 | assert!( |
| 1057 | decider.is_trusted_fakeip_addr(&"198.19.255.255".parse::<std::net::IpAddr>().unwrap()) |
| 1058 | ); |
| 1059 | |
| 1060 | // real private / loopback / link-local / cloud-metadata are NOT trusted |
| 1061 | for ip in ["192.168.1.1", "10.0.0.1", "127.0.0.1", "169.254.169.254"] { |
| 1062 | assert!( |
| 1063 | !decider.is_trusted_fakeip_addr(&ip.parse::<std::net::IpAddr>().unwrap()), |
| 1064 | "{ip} must not be treated as a fake-ip placeholder" |
| 1065 | ); |
| 1066 | } |
| 1067 | |
| 1068 | // no ranges configured → nothing trusted |
| 1069 | let bare = NetworkPolicyDecider::new(NetworkPolicy::default(), None); |
| 1070 | assert!(!bare.is_trusted_fakeip_addr(&"198.18.0.5".parse::<std::net::IpAddr>().unwrap())); |
| 1071 | } |
| 1072 | |
| 1073 | #[test] |
| 1074 | fn configured_fakeip_cidrs_are_loaded_but_unsafe_ranges_are_ignored() { |
| 1075 | let policy = NetworkPolicy { |
| 1076 | proxy_fake_ip_cidrs: vec![ |
| 1077 | "198.18.0.0/15".to_string(), |
| 1078 | "127.0.0.0/8".to_string(), |
| 1079 | "10.0.0.0/8".to_string(), |
| 1080 | ], |
| 1081 | ..NetworkPolicy::default() |
| 1082 | }; |
| 1083 | let decider = NetworkPolicyDecider::new(policy, None); |
| 1084 | |
| 1085 | assert!(decider.is_trusted_fakeip_addr(&"198.19.0.5".parse().unwrap())); |
| 1086 | assert!(!decider.is_trusted_fakeip_addr(&"127.0.0.1".parse().unwrap())); |
| 1087 | assert!(!decider.is_trusted_fakeip_addr(&"10.0.0.1".parse().unwrap())); |
| 1088 | } |
| 1089 | |
| 1090 | #[test] |
| 1091 | fn host_from_url_extracts_host() { |
| 1092 | assert_eq!( |
| 1093 | host_from_url("https://api.deepseek.com/health"), |
| 1094 | Some("api.deepseek.com".to_string()) |
| 1095 | ); |
| 1096 | assert_eq!( |
| 1097 | host_from_url("http://Example.COM:8080/x"), |
| 1098 | Some("example.com".to_string()) |
| 1099 | ); |
| 1100 | assert_eq!(host_from_url("not a url"), None); |
| 1101 | } |
| 1102 | |
| 1103 | #[test] |
| 1104 | fn auditor_writes_one_line_per_call() { |
| 1105 | let dir = tempdir().expect("tempdir"); |
| 1106 | let path = dir.path().join("audit.log"); |
| 1107 | let auditor = NetworkAuditor::new(path.clone(), true); |
| 1108 | auditor.record("api.example.com", "fetch_url", "Allow"); |
| 1109 | auditor.record("evil.example.com", "fetch_url", "Deny"); |
| 1110 | let body = std::fs::read_to_string(&path).expect("read"); |
| 1111 | let lines: Vec<&str> = body.lines().collect(); |
| 1112 | assert_eq!(lines.len(), 2); |
| 1113 | for line in &lines { |
| 1114 | // <ts> network <host> <tool> <decision> |
| 1115 | let parts: Vec<&str> = line.split_whitespace().collect(); |
| 1116 | assert!(parts.len() >= 5, "line shape: {line}"); |
| 1117 | assert_eq!(parts[1], "network"); |
| 1118 | } |
| 1119 | assert!(lines[0].contains("api.example.com")); |
| 1120 | assert!(lines[0].ends_with("Allow")); |
| 1121 | assert!(lines[1].contains("evil.example.com")); |
| 1122 | assert!(lines[1].ends_with("Deny")); |
| 1123 | } |
| 1124 | |
| 1125 | #[test] |
| 1126 | fn auditor_disabled_writes_nothing() { |
| 1127 | let dir = tempdir().expect("tempdir"); |
| 1128 | let path = dir.path().join("audit.log"); |
| 1129 | let auditor = NetworkAuditor::new(path.clone(), false); |
| 1130 | auditor.record("api.example.com", "fetch_url", "Allow"); |
| 1131 | assert!(!path.exists() || std::fs::read_to_string(&path).unwrap().is_empty()); |
| 1132 | } |
| 1133 | |
| 1134 | #[test] |
| 1135 | fn session_cache_short_circuits_evaluate() { |
| 1136 | let policy = mk(Decision::Prompt, &[], &[]); |
| 1137 | let decider = NetworkPolicyDecider::new(policy, None); |
| 1138 | // First call returns Prompt. |
| 1139 | assert_eq!( |
| 1140 | decider.evaluate("api.example.com", "fetch_url"), |
| 1141 | Decision::Prompt |
| 1142 | ); |
| 1143 | decider.approve_session("api.example.com", "fetch_url"); |
| 1144 | // After approve_session, the same host returns Allow without prompting. |
| 1145 | assert_eq!( |
| 1146 | decider.evaluate("api.example.com", "fetch_url"), |
| 1147 | Decision::Allow |
| 1148 | ); |
| 1149 | } |
| 1150 | |
| 1151 | #[test] |
| 1152 | fn refreshed_policy_adopts_new_table_without_retracting_session_approvals() { |
| 1153 | let decider = NetworkPolicyDecider::new(mk(Decision::Prompt, &[], &[]), None); |
| 1154 | decider.approve_session("approved.example.com", "fetch_url"); |
| 1155 | |
| 1156 | // Mid-session `/network allow api.github.com` reaches the session as a |
| 1157 | // re-read table rather than a restart. |
| 1158 | let refreshed = |
| 1159 | decider.with_policy_refreshed(mk(Decision::Prompt, &["api.github.com"], &[])); |
| 1160 | |
| 1161 | assert_eq!( |
| 1162 | refreshed.evaluate("api.github.com", "Bash"), |
| 1163 | Decision::Allow, |
| 1164 | "the re-read table is in force" |
| 1165 | ); |
| 1166 | assert_eq!( |
| 1167 | refreshed.evaluate("approved.example.com", "fetch_url"), |
| 1168 | Decision::Allow, |
| 1169 | "an approval already granted this session survives the refresh" |
| 1170 | ); |
| 1171 | assert_eq!( |
| 1172 | refreshed.evaluate("unlisted.example.com", "Bash"), |
| 1173 | Decision::Prompt, |
| 1174 | "hosts the table does not name keep the default" |
| 1175 | ); |
| 1176 | } |
| 1177 | |
| 1178 | #[test] |
| 1179 | fn refreshed_policy_honours_a_new_deny_list() { |
| 1180 | let decider = NetworkPolicyDecider::new(mk(Decision::Allow, &[], &[]), None); |
| 1181 | assert_eq!( |
| 1182 | decider.evaluate("evil.example.com", "fetch_url"), |
| 1183 | Decision::Allow |
| 1184 | ); |
| 1185 | |
| 1186 | let refreshed = |
| 1187 | decider.with_policy_refreshed(mk(Decision::Allow, &[], &["evil.example.com"])); |
| 1188 | |
| 1189 | assert_eq!( |
| 1190 | refreshed.evaluate("evil.example.com", "fetch_url"), |
| 1191 | Decision::Deny, |
| 1192 | "a deny entry written after spawn is enforced without a restart" |
| 1193 | ); |
| 1194 | } |
| 1195 | |
| 1196 | #[test] |
| 1197 | fn refreshed_policy_keeps_the_authority_marking() { |
| 1198 | let decider = |
| 1199 | NetworkPolicyDecider::new(mk(Decision::Deny, &[], &[]), None).with_authoritative(); |
| 1200 | assert!(decider.is_authoritative()); |
| 1201 | let refreshed = decider.with_policy_refreshed(mk(Decision::Allow, &[], &[])); |
| 1202 | assert!( |
| 1203 | refreshed.is_authoritative(), |
| 1204 | "a refreshed authority is still an authority" |
| 1205 | ); |
| 1206 | } |
| 1207 | |
| 1208 | #[test] |
| 1209 | fn folding_a_document_never_widens_an_authority() { |
| 1210 | // Assert what the folded policy *decides*, not the shape of its fields: |
| 1211 | // `decide` checks `allow` before falling back to `default`, so a field |
| 1212 | // assertion can look safe while the verdict is `Allow`. |
| 1213 | |
| 1214 | // What a Fleet denial or a managed overlay resolved to: deny by default. |
| 1215 | let authority = NetworkPolicy { |
| 1216 | default: DecisionToml::Deny, |
| 1217 | deny: vec!["blocked.example.com".to_string()], |
| 1218 | ..NetworkPolicy::default() |
| 1219 | }; |
| 1220 | // What the user's document asks for on a mid-session re-read. |
| 1221 | let document = NetworkPolicy { |
| 1222 | default: DecisionToml::Allow, |
| 1223 | allow: vec!["api.github.com".to_string()], |
| 1224 | proxy: vec!["proxy.example.com".to_string()], |
| 1225 | proxy_fake_ip_cidrs: vec!["198.18.0.0/15".to_string()], |
| 1226 | audit: false, |
| 1227 | ..NetworkPolicy::default() |
| 1228 | }; |
| 1229 | |
| 1230 | let folded = authority.folded_with_lower_layer(document); |
| 1231 | |
| 1232 | assert_eq!( |
| 1233 | folded.decide("api.github.com"), |
| 1234 | Decision::Deny, |
| 1235 | "a document cannot lift a deny-by-default authority's denial" |
| 1236 | ); |
| 1237 | assert_eq!( |
| 1238 | folded.decide("blocked.example.com"), |
| 1239 | Decision::Deny, |
| 1240 | "a denial the authority set survives the fold" |
| 1241 | ); |
| 1242 | assert_eq!( |
| 1243 | folded.decide("unlisted.example.com"), |
| 1244 | Decision::Deny, |
| 1245 | "an unlisted host still falls back to the authority's denial" |
| 1246 | ); |
| 1247 | assert!( |
| 1248 | folded.proxy.is_empty() && folded.proxy_fake_ip_cidrs.is_empty(), |
| 1249 | "a document cannot hand itself a fake-IP SSRF exception under a denial" |
| 1250 | ); |
| 1251 | assert!( |
| 1252 | folded.audit, |
| 1253 | "a document cannot silence the audit log under an authority" |
| 1254 | ); |
| 1255 | |
| 1256 | // A prompt-by-default authority is the case `/network allow` exists for: |
| 1257 | // the document may name hosts, and it may not erase the authority's own. |
| 1258 | let prompt_authority = NetworkPolicy { |
| 1259 | default: DecisionToml::Prompt, |
| 1260 | allow: vec!["internal.example.com".to_string()], |
| 1261 | deny: vec!["blocked.example.com".to_string()], |
| 1262 | ..NetworkPolicy::default() |
| 1263 | }; |
| 1264 | let folded = prompt_authority.folded_with_lower_layer(NetworkPolicy { |
| 1265 | default: DecisionToml::Allow, |
| 1266 | allow: vec!["api.github.com".to_string()], |
| 1267 | ..NetworkPolicy::default() |
| 1268 | }); |
| 1269 | assert_eq!( |
| 1270 | folded.decide("api.github.com"), |
| 1271 | Decision::Allow, |
| 1272 | "the document may still name hosts when the authority prompts" |
| 1273 | ); |
| 1274 | assert_eq!( |
| 1275 | folded.decide("internal.example.com"), |
| 1276 | Decision::Allow, |
| 1277 | "the authority's own allowance survives the fold" |
| 1278 | ); |
| 1279 | assert_eq!( |
| 1280 | folded.decide("unlisted.example.com"), |
| 1281 | Decision::Prompt, |
| 1282 | "the document cannot widen the authority's fallback to allow" |
| 1283 | ); |
| 1284 | assert_eq!( |
| 1285 | folded.decide("blocked.example.com"), |
| 1286 | Decision::Deny, |
| 1287 | "either layer's denial wins" |
| 1288 | ); |
| 1289 | |
| 1290 | // The plain user path replaces the policy outright, so |
| 1291 | // `/network default allow` still lands there. |
| 1292 | let plain = NetworkPolicy { |
| 1293 | default: DecisionToml::Prompt, |
| 1294 | ..NetworkPolicy::default() |
| 1295 | }; |
| 1296 | assert_eq!( |
| 1297 | plain |
| 1298 | .folded_with_lower_layer(NetworkPolicy { |
| 1299 | default: DecisionToml::Allow, |
| 1300 | ..NetworkPolicy::default() |
| 1301 | }) |
| 1302 | .default, |
| 1303 | DecisionToml::Prompt |
| 1304 | ); |
| 1305 | } |
| 1306 | |
| 1307 | /// A managed overlay may legitimately resolve `default = "allow"`. Its fold |
| 1308 | /// takes the union branch, and the document's own fallback can only narrow |
| 1309 | /// it — nothing there is more permissive than the authority's own policy, |
| 1310 | /// because that policy already allowed everything. |
| 1311 | #[test] |
| 1312 | fn folding_an_allow_by_default_authority_only_narrows() { |
| 1313 | let authority = NetworkPolicy { |
| 1314 | default: DecisionToml::Allow, |
| 1315 | ..NetworkPolicy::default() |
| 1316 | }; |
| 1317 | let folded = authority.folded_with_lower_layer(NetworkPolicy { |
| 1318 | default: DecisionToml::Deny, |
| 1319 | allow: vec!["named.example.com".to_string()], |
| 1320 | ..NetworkPolicy::default() |
| 1321 | }); |
| 1322 | |
| 1323 | assert_eq!( |
| 1324 | folded.decide("named.example.com"), |
| 1325 | Decision::Allow, |
| 1326 | "the authority allowed everything already; naming a host is not a widening" |
| 1327 | ); |
| 1328 | assert_eq!( |
| 1329 | folded.decide("other.example.com"), |
| 1330 | Decision::Deny, |
| 1331 | "the document narrowed the fallback, which is the direction it may move" |
| 1332 | ); |
| 1333 | } |
| 1334 | |
| 1335 | #[test] |
| 1336 | fn approve_persistent_writes_back_to_policy() { |
| 1337 | let policy = mk(Decision::Prompt, &[], &[]); |
| 1338 | let mut decider = NetworkPolicyDecider::new(policy, None); |
| 1339 | decider.approve_persistent("api.example.com", "fetch_url"); |
| 1340 | assert!( |
| 1341 | decider |
| 1342 | .policy() |
| 1343 | .allow |
| 1344 | .iter() |
| 1345 | .any(|h| h == "api.example.com") |
| 1346 | ); |
| 1347 | // And the session cache also got updated, so fresh evaluate returns Allow. |
| 1348 | assert_eq!( |
| 1349 | decider.evaluate("api.example.com", "fetch_url"), |
| 1350 | Decision::Allow |
| 1351 | ); |
| 1352 | } |
| 1353 | |
| 1354 | #[test] |
| 1355 | fn deny_session_blocks_subsequent_evaluate() { |
| 1356 | let policy = mk(Decision::Allow, &[], &[]); |
| 1357 | let decider = NetworkPolicyDecider::new(policy, None); |
| 1358 | decider.deny_session("evil.example.com", "fetch_url"); |
| 1359 | assert_eq!( |
| 1360 | decider.evaluate("evil.example.com", "fetch_url"), |
| 1361 | Decision::Deny |
| 1362 | ); |
| 1363 | } |
| 1364 | |
| 1365 | #[test] |
| 1366 | fn audit_records_terminal_decisions_through_decider() { |
| 1367 | let dir = tempdir().expect("tempdir"); |
| 1368 | let auditor = NetworkAuditor::new(dir.path().join("audit.log"), true); |
| 1369 | let policy = mk(Decision::Deny, &["api.deepseek.com"], &[]); |
| 1370 | let decider = NetworkPolicyDecider::new(policy, Some(auditor)); |
| 1371 | |
| 1372 | let allow = decider.evaluate("api.deepseek.com", "fetch_url"); |
| 1373 | let deny = decider.evaluate("evil.example.com", "fetch_url"); |
| 1374 | assert_eq!(allow, Decision::Allow); |
| 1375 | assert_eq!(deny, Decision::Deny); |
| 1376 | |
| 1377 | let body = std::fs::read_to_string(dir.path().join("audit.log")).expect("read"); |
| 1378 | let lines: Vec<&str> = body.lines().collect(); |
| 1379 | assert_eq!(lines.len(), 2); |
| 1380 | assert!(lines[0].ends_with("Allow")); |
| 1381 | assert!(lines[1].ends_with("Deny")); |
| 1382 | } |
| 1383 | |
| 1384 | #[test] |
| 1385 | fn decision_parse_unknown_falls_back_to_prompt() { |
| 1386 | assert_eq!(Decision::parse("allow"), Decision::Allow); |
| 1387 | assert_eq!(Decision::parse("Deny"), Decision::Deny); |
| 1388 | assert_eq!(Decision::parse("BLOCK"), Decision::Deny); |
| 1389 | assert_eq!(Decision::parse("prompt"), Decision::Prompt); |
| 1390 | assert_eq!(Decision::parse("garbage"), Decision::Prompt); |
| 1391 | } |
| 1392 | |
| 1393 | #[test] |
| 1394 | fn network_denied_carries_host() { |
| 1395 | let err = NetworkDenied("api.example.com".to_string()); |
| 1396 | assert_eq!(err.host(), "api.example.com"); |
| 1397 | assert!(format!("{err}").contains("api.example.com")); |
| 1398 | } |
| 1399 | |
| 1400 | #[test] |
| 1401 | fn network_policy_from_document_refuses_oversized_files() { |
| 1402 | let dir = tempdir().expect("tempdir"); |
| 1403 | let path = dir.path().join("huge.toml"); |
| 1404 | let oversize = vec![b'#'; (4 * 1024 * 1024) + 1]; |
| 1405 | fs::write(&path, oversize).expect("write oversized file"); |
| 1406 | assert!(network_policy_from_document(&path).is_none()); |
| 1407 | } |
| 1408 | } |
| 1409 |