openlatch-client 0.6.1

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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
//! `CONNECT host:port` from an agent pointed at the relay through its proxy setting (I-2 plan
//! 01, §3). Answer 200, then either terminate TLS inside the upgraded tunnel and serve
//! HTTP/1.1 into the same router, or copy bytes to an opaque tunnel opened through the egress
//! route. Never a refusal on the host: an undeclared host is the normal case (the agent's
//! auth, telemetry and updates), not an error.

use std::collections::BTreeMap;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use axum::body::Body;
use axum::extract::Request;
use axum::http::StatusCode;
use axum::response::Response;
use hyper::upgrade::Upgraded;
use hyper_util::rt::TokioIo;

use super::ca;
use super::{proxy, ModelRelayState};
use crate::error::OlError;

/// Request extension the inner service sets on every request that arrived inside an
/// intercepted tunnel. `proxy::upstream_url` reads it. Absent on the redirect path.
#[derive(Clone, Debug)]
pub(crate) struct ConnectAuthority {
    pub(crate) host: String,
    pub(crate) port: u16,
}

const INTERCEPT_HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10);

/// What `handle_connect` decided before it answers `200` and returns: either the CONNECT
/// authority is declared and gets TLS terminated in-process, or it is opaque and gets a plain
/// byte tunnel through the egress route.
enum Plan {
    Intercept(Arc<ca::Interceptor>),
    Tunnel(crate::egress::tunnel::TunnelStream),
}

/// `CONNECT host:port`, on the relay's main listener only (`proxy_any` already checked
/// `st.endpoint.is_none()`). Answers `200` immediately and finishes the work after hyper
/// completes the upgrade — hyper's `examples/http_proxy.rs` shape, with one deliberate
/// difference: an opaque tunnel is OPENED BEFORE the `200`, so a route failure is a `502` the
/// client sees, never a `200` then a dead socket.
pub async fn handle_connect(st: Arc<ModelRelayState>, mut req: Request<Body>) -> Response {
    let Some(authority) = req.uri().authority().cloned() else {
        let mut resp = Response::new(Body::empty());
        *resp.status_mut() = StatusCode::BAD_REQUEST;
        return resp;
    };
    // 01-20: IPv6 is BARE ("::1") for the socket connect, the no_proxy match and minting (an IP
    // SAN); brackets come back only where an authority string is written (§2 step 4, §5's
    // `https://{host}:{port}` URL, and the PAC target URL).
    let host = authority
        .host()
        .trim_start_matches('[')
        .trim_end_matches(']')
        .to_ascii_lowercase();
    let port = authority.port_u16().unwrap_or(443);
    // Our own probe (plan 02's `probe_intercept`) marks its CONNECT head with this header; its
    // handshake must never reset an agent's D-32 count.
    let preflight = proxy::is_preflight(req.headers());

    // Clone the Arc and drop the read guard before anything else runs — never held across an
    // await (the "Lock order" note in plan 01 §1).
    let slot = st
        .intercept
        .read()
        .unwrap_or_else(|e| e.into_inner())
        .clone();
    // D-02 is host-only: no `port == 443` test. The leaf carries the host, not a port, and the
    // forward leg (`upstream_url`) keeps the authority's port.
    let plan = match slot.filter(|ic| ic.intercepts(&host)) {
        Some(ic) => Plan::Intercept(ic),
        None => match open_upstream(&st, &host, port).await {
            Ok(up) => Plan::Tunnel(up),
            Err(e) => {
                tracing::warn!(
                    code = %e.code,
                    host = %host,
                    port,
                    "CONNECT tunnel could not be opened"
                );
                // Bumps the process-wide `upstream_failures()` counter the wiring supervisor
                // re-probes on: "the agent got nothing back", and a re-probe is cheap.
                return proxy::synth_502(&st);
            }
        },
    };

    // BEFORE the response leaves this function — hyper completes the upgrade only after the
    // `200` has been sent.
    let upgrade = hyper::upgrade::on(&mut req);
    tokio::spawn(async move {
        let upgraded = match upgrade.await {
            Ok(u) => u,
            Err(e) => {
                tracing::debug!(error = %e, "model relay CONNECT upgrade failed");
                return;
            }
        };
        let io = TokioIo::new(upgraded);
        match plan {
            Plan::Intercept(ic) => terminate(st, ic, io, host, port, preflight).await,
            Plan::Tunnel(mut upstream) => {
                let mut io = io;
                let _ = tokio::io::copy_bidirectional(&mut io, &mut upstream).await;
            }
        }
    });

    Response::new(Body::empty())
}

/// The tunnel's far end for an undeclared (or slot-empty) CONNECT authority: the test seam
/// first, then the real egress route. `st.egress` is the same `EgressReporter` the forward
/// client was built from — the two legs share one route with no new field.
async fn open_upstream(
    st: &Arc<ModelRelayState>,
    host: &str,
    port: u16,
) -> Result<crate::egress::tunnel::TunnelStream, OlError> {
    // Empty in production (`with_resolve_override` is a test seam): skip the lookup key
    // allocation on every CONNECT rather than build and hash a `(String, u16)` for a map
    // nothing ever populated.
    if !st.resolve_override.is_empty() {
        if let Some(addr) = st.resolve_override.get(&(host.to_string(), port)) {
            return crate::egress::tunnel::connect_with_timeout(*addr, host, port).await;
        }
    }
    crate::egress::tunnel::open(st.egress.config(), host, port).await
}

/// Terminate TLS inside the upgraded tunnel for a DECLARED host, then serve HTTP/1.1 on the
/// decrypted stream into the same router the main listener uses.
///
/// A server handshake completes only on the client's Finished, which a client that rejects our
/// certificate never sends — so a refusal always surfaces HERE, never after a success.
async fn terminate(
    st: Arc<ModelRelayState>,
    ic: Arc<ca::Interceptor>,
    io: TokioIo<Upgraded>,
    host: String,
    port: u16,
    preflight: bool,
) {
    // Read the ClientHello WITHOUT committing to a config.
    let start = match tokio::time::timeout(
        INTERCEPT_HANDSHAKE_TIMEOUT,
        tokio_rustls::LazyConfigAcceptor::new(rustls::server::Acceptor::default(), io),
    )
    .await
    {
        Ok(Ok(start)) => start,
        // Timeout or a closed socket: the client never saw our leaf. NOT a refusal.
        _ => {
            tracing::debug!(host = %host, "model relay intercept closed before a ClientHello");
            return;
        }
    };

    // D-02, decided here and not counted: the pinned resolver would refuse a mismatched SNI
    // too, but deciding it HERE is what keeps our own refusal out of the D-32 count without
    // matching rustls's error string.
    let sni_ok = start
        .client_hello()
        .server_name()
        .is_none_or(|s| s.eq_ignore_ascii_case(&host));
    let config = if sni_ok {
        ic.pinned_config(&host)
    } else {
        None
    };
    let Some(config) = config else {
        tracing::debug!(
            host = %host,
            "model relay intercept SNI does not match the CONNECT authority"
        );
        return;
    };

    // Offer the leaf. From here a failure is the PEER refusing it (D-32). A preflight probe's
    // three outcome arms below record NOTHING on `st.refusals` (neither success nor refusal);
    // the pass-through-failure counter and the return are unchanged.
    let tls =
        match tokio::time::timeout(INTERCEPT_HANDSHAKE_TIMEOUT, start.into_stream(config)).await {
            Ok(Ok(tls)) => {
                if !preflight {
                    st.refusals.record_success(&host);
                }
                tls
            }
            Ok(Err(e)) => {
                if !preflight {
                    st.refusals.record_refusal(&host, classify_refusal(&e));
                }
                proxy::record_pass_through_failure("intercept_handshake");
                return;
            }
            Err(_) => {
                if !preflight {
                    st.refusals
                        .record_refusal(&host, RefusalKind::Other("handshake timed out".into()));
                }
                proxy::record_pass_through_failure("intercept_handshake");
                return;
            }
        };

    // Serve HTTP/1.1 on the decrypted stream INTO THE SAME ROUTER. `tower` is not a dependency;
    // axum's own `Extension` layer inserts the value into every request reaching this router.
    let svc = super::router(st).layer(axum::Extension(ConnectAuthority { host, port }));
    if let Err(e) = hyper::server::conn::http1::Builder::new()
        .serve_connection(
            TokioIo::new(tls),
            hyper_util::service::TowerToHyperService::new(svc),
        )
        .with_upgrades()
        .await
    {
        // A client hanging up mid-stream is normal — never a refusal, never a 502.
        tracing::debug!(error = %e, "model relay intercept connection ended");
    }
    // A CONNECT that arrives INSIDE a tunnel reaches `proxy_any` again through this same
    // router and is handled like any other — it cannot loop (each hop is a new upgrade on the
    // agent's own connection).
}

/// How a peer refused our leaf. The signatures the POC observed (PR #463,
/// `tools/mitm-relay-poc/proof/README.md`): VS Code's Node path closes mid-handshake with no
/// alert (tokio-rustls: `UnexpectedEof`, "tls handshake eof"); Bun resets the connection;
/// Chromium and rustls send `UnknownCA`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RefusalKind {
    Alert(String),
    HandshakeEof,
    Reset,
    Other(String),
}

/// Classify a server-side handshake failure into a [`RefusalKind`]. Total, never panics.
fn classify_refusal(e: &std::io::Error) -> RefusalKind {
    if let Some(rustls::Error::AlertReceived(d)) =
        e.get_ref().and_then(|i| i.downcast_ref::<rustls::Error>())
    {
        return RefusalKind::Alert(format!("{d:?}"));
    }
    match e.kind() {
        std::io::ErrorKind::UnexpectedEof => RefusalKind::HandshakeEof,
        std::io::ErrorKind::ConnectionReset
        | std::io::ErrorKind::ConnectionAborted
        | std::io::ErrorKind::BrokenPipe => RefusalKind::Reset,
        _ => RefusalKind::Other(e.to_string()),
    }
}

/// A host trips after this many consecutive refusals with no success in [`SUCCESS_WINDOW`].
const TRIP_AFTER: u32 = 3;
const SUCCESS_WINDOW: Duration = Duration::from_secs(10 * 60);

#[derive(Default)]
struct HostRecord {
    consecutive: u32,
    last_success: Option<Instant>,
    tripped_logged: bool,
}

/// D-32's counting half. Plan 04 reads [`RefusalLedger::tripped_hosts`] and reacts; this
/// module never releases, renders or unwires anything.
#[derive(Default)]
pub struct RefusalLedger {
    hosts: Mutex<BTreeMap<String, HostRecord>>,
}

impl RefusalLedger {
    /// Record a refusal for `host` (case-insensitive). Warns once when the host first trips.
    pub fn record_refusal(&self, host: &str, kind: RefusalKind) {
        let host = host.to_ascii_lowercase();
        let mut hosts = self.hosts.lock().unwrap_or_else(|e| e.into_inner());
        let record = hosts.entry(host.clone()).or_default();
        record.consecutive += 1;
        tracing::debug!(host = %host, kind = ?kind, "model relay intercept handshake refused");
        if record.consecutive >= TRIP_AFTER && !record.tripped_logged {
            record.tripped_logged = true;
            tracing::warn!(host = %host, kind = ?kind, "model relay intercept host tripped");
        }
    }

    /// Record a completed handshake for `host` (case-insensitive), resetting its count.
    pub fn record_success(&self, host: &str) {
        self.record_success_at(host, Instant::now());
    }

    /// Every host with `>= TRIP_AFTER` consecutive refusals and no success within
    /// [`SUCCESS_WINDOW`], sorted.
    pub fn tripped_hosts(&self) -> Vec<String> {
        self.tripped_hosts_at(Instant::now())
    }

    /// Forget `host` entirely. Kept for the INDEX contract; plan 04 does not call it — a
    /// tripped host is re-armed by a daemon restart (a fresh `RefusalLedger`), not by `clear`.
    pub fn clear(&self, host: &str) {
        let host = host.to_ascii_lowercase();
        self.hosts
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .remove(&host);
    }

    fn record_success_at(&self, host: &str, at: Instant) {
        let host = host.to_ascii_lowercase();
        let mut hosts = self.hosts.lock().unwrap_or_else(|e| e.into_inner());
        let record = hosts.entry(host).or_default();
        record.consecutive = 0;
        record.last_success = Some(at);
        record.tripped_logged = false;
    }

    fn tripped_hosts_at(&self, now: Instant) -> Vec<String> {
        let hosts = self.hosts.lock().unwrap_or_else(|e| e.into_inner());
        hosts
            .iter()
            .filter(|(_, r)| {
                r.consecutive >= TRIP_AFTER
                    && r.last_success
                        .is_none_or(|t| now.saturating_duration_since(t) > SUCCESS_WINDOW)
            })
            .map(|(h, _)| h.clone())
            .collect()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use rustls::pki_types::pem::PemObject;

    #[test]
    fn a_tls_alert_is_classified_by_its_description() {
        let err = std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            rustls::Error::AlertReceived(rustls::AlertDescription::UnknownCA),
        );
        assert_eq!(
            classify_refusal(&err),
            RefusalKind::Alert("UnknownCA".to_string())
        );
    }

    #[test]
    fn eof_reset_and_other_are_classified() {
        let eof = std::io::Error::from(std::io::ErrorKind::UnexpectedEof);
        assert_eq!(classify_refusal(&eof), RefusalKind::HandshakeEof);

        for kind in [
            std::io::ErrorKind::ConnectionReset,
            std::io::ErrorKind::ConnectionAborted,
            std::io::ErrorKind::BrokenPipe,
        ] {
            assert_eq!(
                classify_refusal(&std::io::Error::from(kind)),
                RefusalKind::Reset
            );
        }

        let other = std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            rustls::Error::NoApplicationProtocol,
        );
        assert!(matches!(classify_refusal(&other), RefusalKind::Other(_)));
    }

    #[test]
    fn three_consecutive_refusals_trip_a_host() {
        let ledger = RefusalLedger::default();
        ledger.record_refusal("a.test", RefusalKind::Reset);
        ledger.record_refusal("a.test", RefusalKind::Reset);
        assert!(ledger.tripped_hosts().is_empty());
        ledger.record_refusal("a.test", RefusalKind::Reset);
        assert_eq!(ledger.tripped_hosts(), vec!["a.test".to_string()]);
        ledger.record_refusal("b.test", RefusalKind::Reset);
        assert_eq!(ledger.tripped_hosts(), vec!["a.test".to_string()]);
    }

    #[test]
    fn a_success_within_ten_minutes_holds_the_trip() {
        let ledger = RefusalLedger::default();
        let t0 = Instant::now();
        ledger.record_success_at("a.test", t0);
        ledger.record_refusal("a.test", RefusalKind::Reset);
        ledger.record_refusal("a.test", RefusalKind::Reset);
        ledger.record_refusal("a.test", RefusalKind::Reset);
        assert!(ledger
            .tripped_hosts_at(t0 + Duration::from_secs(9 * 60 + 59))
            .is_empty());
        assert_eq!(
            ledger.tripped_hosts_at(t0 + Duration::from_secs(10 * 60 + 1)),
            vec!["a.test".to_string()]
        );
    }

    #[test]
    fn a_success_resets_the_count() {
        let ledger = RefusalLedger::default();
        ledger.record_refusal("a.test", RefusalKind::Reset);
        ledger.record_refusal("a.test", RefusalKind::Reset);
        ledger.record_success("a.test");
        ledger.record_refusal("a.test", RefusalKind::Reset);
        ledger.record_refusal("a.test", RefusalKind::Reset);
        assert!(ledger
            .tripped_hosts_at(Instant::now() + Duration::from_secs(11 * 60))
            .is_empty());
    }

    #[test]
    fn clear_forgets_a_host() {
        let ledger = RefusalLedger::default();
        ledger.record_refusal("a.test", RefusalKind::Reset);
        ledger.record_refusal("a.test", RefusalKind::Reset);
        ledger.record_refusal("a.test", RefusalKind::Reset);
        assert_eq!(ledger.tripped_hosts(), vec!["a.test".to_string()]);
        ledger.clear("a.test");
        assert!(ledger.tripped_hosts().is_empty());
        ledger.record_refusal("a.test", RefusalKind::Reset);
        assert!(ledger.tripped_hosts().is_empty());
    }

    /// A raw CONNECT carrying our own preflight header, against a DECLARED host whose
    /// forward leg is pinned to a closed port (hermetic 502 on the inner request): three
    /// refusals trip the host directly; the preflight's own successful handshake — proven by
    /// reading a response, any status, over the decrypted stream — must not clear that trip.
    /// The control (no header) resets the count.
    #[tokio::test]
    async fn a_preflight_connect_is_not_counted() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let interceptor =
            Arc::new(ca::Interceptor::new(&tmp.path().join("ca"), ["a.test"]).expect("new"));
        let ledger = Arc::new(RefusalLedger::default());

        let closed = crate::model_relay::mock::closed_port().await;
        let mut resolve = BTreeMap::new();
        resolve.insert(
            ("a.test".to_string(), 443u16),
            std::net::SocketAddr::from(([127, 0, 0, 1], closed)),
        );

        let slot: super::super::InterceptSlot =
            Arc::new(std::sync::RwLock::new(Some(interceptor.clone())));
        let state = Arc::new(
            ModelRelayState::new(
                reqwest::Url::parse("http://127.0.0.1:1").unwrap(),
                0,
                8,
                &[],
            )
            .with_intercept(slot)
            .with_refusals(ledger.clone())
            .with_resolve_override(resolve),
        );
        let port = super::super::serve_ephemeral(state).await;

        // Trip the host directly, then prove a preflight CONNECT's own successful
        // handshake — proven by reading a response over the decrypted stream — leaves the
        // trip alone.
        ledger.record_refusal("a.test", RefusalKind::Reset);
        ledger.record_refusal("a.test", RefusalKind::Reset);
        ledger.record_refusal("a.test", RefusalKind::Reset);
        assert_eq!(ledger.tripped_hosts(), vec!["a.test".to_string()]);
        probe(port, &interceptor.ca().pem_path(), true).await;
        assert_eq!(
            ledger.tripped_hosts(),
            vec!["a.test".to_string()],
            "a preflight connect's handshake must not be recorded, success or refusal"
        );

        // Control: the SAME connect with no header is a real success and resets the count.
        probe(port, &interceptor.ca().pem_path(), false).await;
        assert!(ledger.tripped_hosts().is_empty());
    }

    /// `CONNECT a.test:443` to the relay at `port`, then a completed TLS handshake trusting
    /// `ca_pem_path`, then one `GET /` whose response (any status) is read to the end — so the
    /// server's handshake-success arm has certainly run before this returns.
    async fn probe(port: u16, ca_pem_path: &std::path::Path, preflight: bool) {
        use tokio::io::{AsyncReadExt, AsyncWriteExt};

        let mut stream = tokio::net::TcpStream::connect(("127.0.0.1", port))
            .await
            .expect("dial relay");
        let mut head = "CONNECT a.test:443 HTTP/1.1\r\nHost: a.test:443\r\n".to_string();
        if preflight {
            head.push_str(&format!(
                "{}: 1\r\n",
                super::super::preflight::PREFLIGHT_HEADER
            ));
        }
        head.push_str("\r\n");
        stream
            .write_all(head.as_bytes())
            .await
            .expect("write CONNECT");

        let mut buf = Vec::new();
        let mut byte = [0u8; 1];
        while !buf.ends_with(b"\r\n\r\n") {
            stream
                .read_exact(&mut byte)
                .await
                .expect("read CONNECT response");
            buf.push(byte[0]);
        }
        assert!(
            String::from_utf8_lossy(&buf).starts_with("HTTP/1.1 200"),
            "unexpected CONNECT response: {}",
            String::from_utf8_lossy(&buf)
        );

        let ca_pem = std::fs::read_to_string(ca_pem_path).expect("read ca pem");
        let ca_der =
            rustls::pki_types::CertificateDer::from_pem_slice(ca_pem.as_bytes()).expect("parse");
        let mut roots = rustls::RootCertStore::empty();
        roots.add(ca_der).expect("trust the CA");
        let client_config = rustls::ClientConfig::builder()
            .with_root_certificates(roots)
            .with_no_client_auth();
        let connector = tokio_rustls::TlsConnector::from(Arc::new(client_config));
        let server_name = rustls::pki_types::ServerName::try_from("a.test").expect("server name");
        let mut tls = connector
            .connect(server_name, stream)
            .await
            .expect("tls handshake against our own leaf must succeed");

        tls.write_all(b"GET / HTTP/1.1\r\nHost: a.test\r\nConnection: close\r\n\r\n")
            .await
            .expect("write GET");
        let mut response = Vec::new();
        let _ = tls.read_to_end(&mut response).await;
    }
}