openlatch-client 0.3.3

OpenLatch runtime enforcement node — the capture-and-enforce adapter that evaluates every covered action against a coding agent's Autonomy Zone before it runs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
//! macOS discovery rungs.
//!
//! One ladder for both contexts, frozen by the PRD's resolver table: `SCDynamicStore`
//! statics — *including the `__SCOPED__` per-interface entries* — then PAC, then WPAD, and
//! WPAD only when "Auto proxy discovery" is on.
//!
//! The one rule that is easy to get wrong, and expensive when you do:
//! **a scoped entry replaces the global dictionary wholesale.** That is Apple's own
//! `SCNetworkProxiesCopyMatching` semantics, not a simplification of them. Field-merging a
//! VPN's scoped entry over the global one produces a route that exists nowhere in the
//! host's configuration — typically the VPN's PAC with the corporate LAN's static proxy —
//! and it fails in a way that looks like a network problem rather than a bug here.
//!
//! The rung logic is pure over [`MacSource`] so it compiles and is tested on every host.
//!
//! # State of the backend
//!
//! The seam is implemented; the native reader behind it is not. [`native`] returns a source
//! that reports nothing, so on macOS the ladder currently runs and finds no OS settings —
//! it never returns a wrong answer, and tiers 1 through 4 are unaffected. Filling it in is
//! a self-contained change to this file, and needs a macOS host to compile against:
//!
//! | Rung | Call |
//! | --- | --- |
//! | `sc-static` / `sc-scoped` | `SCDynamicStoreCopyProxies` via the `system-configuration` crate, reading the `HTTPSEnable`/`HTTPSProxy`/`HTTPSPort` family, `ProxyAutoConfigEnable`/`ProxyAutoConfigURLString`, `ProxyAutoDiscoveryEnable`, and the `__SCOPED__` sub-dictionary |
//! | `cfnet-pac` | `CFNetworkCopyProxiesForURL` + `CFNetworkExecuteProxyAutoConfigurationURL`, on a `CFRunLoop` bounded at 5 s |
//!
//! Three CFNetwork hazards the fill-in must carry, all of them documented by Chromium's
//! `proxy_resolver_apple.cc`: the rdar://5530166 warm-up call before the first real use;
//! FB12170226, where each execution leaks a `CFRunLoopSourceRef` (which is what makes the
//! TTL dedupe in [`super::pac_route_for`] load-bearing rather than an optimisation); and
//! one process-wide lock, because concurrent executions are not safe.

use std::collections::BTreeMap;

use reqwest::Url;

use crate::core::egress::config::ProxySource;
use crate::core::error::{OlError, ERR_PAC_UNAVAILABLE};

use super::{rung, Context, Ladder, PacAnswer, PacBinding, Route, RungResult};

/// One `host` + `port` pair out of the proxy dictionary.
///
/// Ports arrive pre-normalised: `configd` fills in the protocol default when the user left
/// the field empty, so there is no default-port logic here and there must not be — a port
/// invented on this side would not be the one the OS uses.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HostPort {
    /// The proxy host.
    pub host: String,
    /// The proxy port.
    pub port: u16,
}

/// The `SCDynamicStore` proxy dictionary, flattened to what the ladder reads.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ProxyDict {
    /// `HTTPSEnable` + `HTTPSProxy` + `HTTPSPort`.
    pub https: Option<HostPort>,
    /// `HTTPEnable` + `HTTPProxy` + `HTTPPort`.
    pub http: Option<HostPort>,
    /// `SOCKSEnable` + `SOCKSProxy` + `SOCKSPort`.
    pub socks: Option<HostPort>,
    /// `ProxyAutoConfigEnable`.
    pub pac_enabled: bool,
    /// `ProxyAutoConfigURLString`.
    pub pac_url: Option<String>,
    /// `ProxyAutoDiscoveryEnable` — the "Auto proxy discovery" checkbox, and the only gate
    /// that lets the WPAD variant of the PAC rung run.
    pub auto_discovery: bool,
    /// `__SCOPED__`, keyed by BSD interface name. A `BTreeMap` so the interface choice is
    /// deterministic rather than hash-order.
    pub scoped: BTreeMap<String, ProxyDict>,
}

impl ProxyDict {
    /// Does this dictionary configure anything at all?
    fn is_configured(&self) -> bool {
        self.https.is_some()
            || self.http.is_some()
            || self.socks.is_some()
            || (self.pac_enabled && self.pac_url.is_some())
            || self.auto_discovery
    }

    /// The static route this dictionary names, if any.
    ///
    /// `https` first because every destination in the egress inventory is https; then
    /// `http`; then SOCKS, as `socks5h` so the proxy resolves the name — on a network where
    /// the proxy is the only resolver that can see internal hosts, resolving locally is the
    /// one way to be wrong.
    fn static_route(&self) -> Option<Url> {
        let (hp, scheme) = if let Some(hp) = &self.https {
            (hp, "http")
        } else if let Some(hp) = &self.http {
            (hp, "http")
        } else if let Some(hp) = &self.socks {
            (hp, "socks5h")
        } else {
            return None;
        };
        // `HTTPSProxy` names the proxy used *for* https traffic; the proxy itself is
        // reached over plain HTTP. Reading it the other way sends a ClientHello at a proxy
        // that speaks none.
        Url::parse(&format!("{scheme}://{}:{}", hp.host, hp.port)).ok()
    }
}

/// Everything the macOS ladder needs from the OS, behind one seam.
pub trait MacSource {
    /// The global proxy dictionary, `__SCOPED__` included.
    fn proxies(&self) -> Option<ProxyDict>;
    /// Evaluate a PAC for one destination. `pac` is `None` for the WPAD variant, where
    /// CFNetwork discovers the script itself.
    fn eval_pac(&self, pac: Option<&Url>, target: &Url) -> Result<PacAnswer, OlError>;
}

/// Walk the macOS ladder. Both contexts see the same settings, so `ctx` does not branch it.
pub fn walk(ladder: &mut Ladder, ctx: Context, src: &dyn MacSource, target: &Url) {
    let _ = ctx;
    let global = src.proxies().unwrap_or_default();
    let scope = active_scope(&global);

    if ladder.offer(rung::SC_SCOPED, scoped_rung(scope)) {
        return;
    }
    if ladder.offer(rung::SC_STATIC, static_rung(&global, scope.is_some())) {
        return;
    }
    // Whichever dictionary won the static decision is also the one that owns the PAC
    // settings. Reading the PAC out of the global dictionary while a scoped entry is
    // active is precisely the field-merge this module refuses to do.
    let effective = scope.map_or(&global, |(_, d)| d);
    ladder.offer(rung::CFNET_PAC, pac_rung(src, effective, target));
}

/// The scoped dictionary that applies, if any.
///
/// A tunnel interface is preferred because that is what a VPN installs and what the user
/// expects to win while it is up. Beyond that the choice is best-effort — the OS does not
/// hand out "the active interface" through this API — and the probe is what decides whether
/// the guess was right.
fn active_scope(global: &ProxyDict) -> Option<(&str, &ProxyDict)> {
    let usable = || {
        global
            .scoped
            .iter()
            .filter(|(_, d)| d.is_configured())
            .map(|(k, d)| (k.as_str(), d))
    };
    usable()
        .find(|(iface, _)| iface.starts_with("utun") || iface.starts_with("ppp"))
        .or_else(|| usable().next())
}

fn scoped_rung(scope: Option<(&str, &ProxyDict)>) -> RungResult {
    let Some((iface, dict)) = scope else {
        return RungResult::empty(ProxySource::Macos);
    };
    match dict.static_route() {
        Some(url) => RungResult::static_route(ProxySource::Macos, url),
        None => RungResult::empty_with(
            ProxySource::Macos,
            format!("the __SCOPED__ entry for {iface} names no static proxy"),
        ),
    }
}

fn static_rung(global: &ProxyDict, superseded: bool) -> RungResult {
    if superseded {
        // Not a failure and not a gate: the host really does have a global proxy, and it
        // really is not the one that applies. Saying so is what turns "my system proxy is
        // ignored" into a five-second answer.
        return RungResult::empty_with(
            ProxySource::Macos,
            "the global dictionary is superseded wholesale by a __SCOPED__ entry",
        );
    }
    match global.static_route() {
        Some(url) => RungResult::static_route(ProxySource::Macos, url),
        None => RungResult::empty(ProxySource::Macos),
    }
}

fn pac_rung(src: &dyn MacSource, dict: &ProxyDict, target: &Url) -> RungResult {
    let (source, pac_url) = if dict.pac_enabled {
        match dict.pac_url.as_deref().and_then(|u| Url::parse(u).ok()) {
            Some(u) => (ProxySource::Pac, Some(u)),
            None => {
                return RungResult::skipped(
                    ProxySource::Pac,
                    crate::core::error::ERR_PROXY_CONFIG_INVALID,
                    "ProxyAutoConfigEnable is on but ProxyAutoConfigURLString is not a URL",
                )
            }
        }
    } else if dict.auto_discovery {
        (ProxySource::Wpad, None)
    } else {
        return RungResult::empty_with(
            ProxySource::Pac,
            "neither ProxyAutoConfigEnable nor ProxyAutoDiscoveryEnable is set",
        );
    };

    match src.eval_pac(pac_url.as_ref(), target) {
        Ok(answer) => {
            let probe_via = answer.first_route();
            if probe_via.is_none() && answer.names_a_proxy() {
                return RungResult::skipped(
                    source,
                    crate::core::error::ERR_PROXY_CONFIG_INVALID,
                    format!("the PAC named no usable proxy: {:?}", answer.proxies),
                );
            }
            RungResult::Candidate {
                source,
                route: Route::PacSource { pac_url },
                probe_via,
            }
        }
        Err(e) => RungResult::skipped(source, e.code, e.message),
    }
}

/// The per-destination PAC answer, for the factory's custom-proxy closure.
pub fn eval_pac(
    src: &dyn MacSource,
    target: &Url,
    binding: &PacBinding,
) -> Result<Option<Url>, OlError> {
    let answer = src.eval_pac(binding.pac_url.as_ref(), target)?;
    Ok(answer.first_route())
}

/// The macOS backend.
///
/// See the module note: the seam is real, the reader behind it is not yet. Reporting
/// nothing is the safe absence — the ladder simply moves on — where guessing at
/// CoreFoundation call shapes that cannot be compiled here would not be.
pub fn native() -> UnreadSystemConfiguration {
    UnreadSystemConfiguration
}

/// A [`MacSource`] that reads nothing. See [`native`].
#[derive(Debug, Clone, Copy, Default)]
pub struct UnreadSystemConfiguration;

impl MacSource for UnreadSystemConfiguration {
    fn proxies(&self) -> Option<ProxyDict> {
        None
    }

    fn eval_pac(&self, _pac: Option<&Url>, _target: &Url) -> Result<PacAnswer, OlError> {
        Err(OlError::new(
            ERR_PAC_UNAVAILABLE,
            "this build has no CFNetwork PAC evaluator",
        )
        .with_suggestion(
            "Set an explicit proxy with `openlatch proxy set <url>`, or [proxy] url in \
             config.toml.",
        ))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::egress::discovery::tests::ScriptedProbe;
    use crate::core::egress::discovery::{CandidateAttempt, CandidateOutcome};
    use std::cell::RefCell;

    #[derive(Default)]
    struct FakeMac {
        dict: Option<ProxyDict>,
        answer: Option<PacAnswer>,
        error: Option<&'static str>,
        calls: RefCell<Vec<Option<String>>>,
    }

    impl MacSource for FakeMac {
        fn proxies(&self) -> Option<ProxyDict> {
            self.dict.clone()
        }
        fn eval_pac(&self, pac: Option<&Url>, _target: &Url) -> Result<PacAnswer, OlError> {
            self.calls.borrow_mut().push(pac.map(Url::to_string));
            match self.error {
                Some(code) => Err(OlError::new(code, "fixture PAC failure")),
                None => Ok(self.answer.clone().unwrap_or_default()),
            }
        }
    }

    fn hp(host: &str, port: u16) -> Option<HostPort> {
        Some(HostPort {
            host: host.to_string(),
            port,
        })
    }

    fn target() -> Url {
        Url::parse("https://app.openlatch.ai/api/v1/health").expect("target")
    }

    fn walk_with(src: &FakeMac, probe: &ScriptedProbe) -> Vec<CandidateAttempt> {
        let mut ladder = Ladder::new(probe);
        walk(&mut ladder, Context::UserSession, src, &target());
        ladder.finish().1
    }

    #[test]
    fn the_global_static_rung_wins_when_nothing_is_scoped() {
        let src = FakeMac {
            dict: Some(ProxyDict {
                https: hp("global.corp", 8080),
                ..Default::default()
            }),
            ..Default::default()
        };
        let probe = ScriptedProbe::new(vec![Ok(6)]);
        let mut ladder = Ladder::new(&probe);
        walk(&mut ladder, Context::UserSession, &src, &target());
        let (won, trace) = ladder.finish();
        let won = won.expect("static win");
        assert_eq!(won.source, ProxySource::Macos);
        assert_eq!(
            won.route,
            Route::Static(Url::parse("http://global.corp:8080").expect("url"))
        );
        // The scoped rung is still recorded, empty — "we looked and there was nothing".
        assert_eq!(trace[0].rung, rung::SC_SCOPED);
        assert_eq!(trace[0].probe, CandidateOutcome::NotConfigured);
    }

    #[test]
    fn a_scoped_entry_replaces_the_global_dictionary_wholesale() {
        // The regression this pins: field-merging would produce `http://global.corp:8080`
        // for a host whose VPN is up, which exists in neither configuration.
        let mut scoped = BTreeMap::new();
        scoped.insert(
            "utun3".to_string(),
            ProxyDict {
                https: hp("vpn.corp", 3128),
                ..Default::default()
            },
        );
        let src = FakeMac {
            dict: Some(ProxyDict {
                https: hp("global.corp", 8080),
                http: hp("global-http.corp", 80),
                pac_enabled: true,
                pac_url: Some("http://global.corp/proxy.pac".into()),
                scoped,
                ..Default::default()
            }),
            ..Default::default()
        };
        let probe = ScriptedProbe::new(vec![Ok(4)]);
        let mut ladder = Ladder::new(&probe);
        walk(&mut ladder, Context::UserSession, &src, &target());
        let (won, trace) = ladder.finish();
        let won = won.expect("the scoped entry wins");
        assert_eq!(
            won.route,
            Route::Static(Url::parse("http://vpn.corp:3128").expect("url"))
        );
        let rendered = format!("{trace:?}");
        assert!(
            !rendered.contains("global"),
            "a field from the superseded global dictionary leaked: {rendered}"
        );
    }

    #[test]
    fn a_superseded_global_rung_says_so() {
        let mut scoped = BTreeMap::new();
        scoped.insert(
            "utun3".to_string(),
            ProxyDict {
                pac_enabled: true,
                pac_url: Some("http://vpn.corp/proxy.pac".into()),
                ..Default::default()
            },
        );
        let src = FakeMac {
            dict: Some(ProxyDict {
                https: hp("global.corp", 8080),
                scoped,
                ..Default::default()
            }),
            answer: Some(PacAnswer {
                proxies: vec!["PROXY vpnpac.corp:3128".into()],
            }),
            ..Default::default()
        };
        let probe = ScriptedProbe::new(vec![Ok(3)]);
        let mut ladder = Ladder::new(&probe);
        walk(&mut ladder, Context::UserSession, &src, &target());
        let (won, trace) = ladder.finish();
        let global_row = trace
            .iter()
            .find(|a| a.rung == rung::SC_STATIC)
            .expect("static row");
        assert_eq!(global_row.probe, CandidateOutcome::NotConfigured);
        assert!(global_row
            .detail
            .as_deref()
            .is_some_and(|d| d.contains("superseded")));
        // And the PAC read came from the scoped dictionary, not the global one.
        assert_eq!(
            src.calls.borrow().as_slice(),
            &[Some("http://vpn.corp/proxy.pac".to_string())]
        );
        assert_eq!(won.expect("pac win").source, ProxySource::Pac);
    }

    #[test]
    fn wpad_runs_only_when_auto_discovery_is_enabled() {
        let src = FakeMac {
            dict: Some(ProxyDict::default()),
            ..Default::default()
        };
        let probe = ScriptedProbe::always_fails();
        let trace = walk_with(&src, &probe);
        let pac = trace
            .iter()
            .find(|a| a.rung == rung::CFNET_PAC)
            .expect("pac row");
        assert_eq!(pac.probe, CandidateOutcome::NotConfigured);
        assert!(
            src.calls.borrow().is_empty(),
            "auto-discovery is off; nothing may touch the network"
        );

        let src = FakeMac {
            dict: Some(ProxyDict {
                auto_discovery: true,
                ..Default::default()
            }),
            answer: Some(PacAnswer {
                proxies: vec!["PROXY wpad.corp:3128".into()],
            }),
            ..Default::default()
        };
        let probe = ScriptedProbe::new(vec![Ok(8)]);
        let mut ladder = Ladder::new(&probe);
        walk(&mut ladder, Context::UserSession, &src, &target());
        let won = ladder.finish().0.expect("wpad win");
        assert_eq!(won.source, ProxySource::Wpad);
        assert_eq!(won.route, Route::PacSource { pac_url: None });
    }

    #[test]
    fn a_pac_win_persists_the_script_never_its_answer() {
        let src = FakeMac {
            dict: Some(ProxyDict {
                pac_enabled: true,
                pac_url: Some("http://corp/proxy.pac".into()),
                ..Default::default()
            }),
            answer: Some(PacAnswer {
                proxies: vec!["PROXY chosen.corp:3128".into(), "DIRECT".into()],
            }),
            ..Default::default()
        };
        let probe = ScriptedProbe::new(vec![Ok(9)]);
        let mut ladder = Ladder::new(&probe);
        walk(&mut ladder, Context::UserSession, &src, &target());
        let (won, trace) = ladder.finish();
        let won = won.expect("pac win");
        assert!(matches!(won.route, Route::PacSource { .. }));
        let row = trace
            .iter()
            .find(|a| a.rung == rung::CFNET_PAC)
            .expect("pac row");
        assert_eq!(row.url_masked, "pac:http://corp/proxy.pac");
        assert!(
            !row.url_masked.contains("chosen.corp"),
            "the PAC's answer must never be what the trace persists"
        );
    }

    #[test]
    fn socks_is_normalised_to_socks5h() {
        let dict = ProxyDict {
            socks: hp("socks.corp", 1080),
            ..Default::default()
        };
        assert_eq!(
            dict.static_route().map(|u| u.to_string()),
            Some("socks5h://socks.corp:1080".to_string())
        );
    }

    #[test]
    fn the_unread_backend_finds_nothing_and_says_why() {
        let src = native();
        assert!(src.proxies().is_none());
        let err = src
            .eval_pac(None, &target())
            .expect_err("there is no evaluator to succeed");
        assert_eq!(err.code, ERR_PAC_UNAVAILABLE);
        assert!(err.suggestion.is_some(), "a refusal owes a remedy");
    }
}