openlatch-client 0.1.18

OpenLatch runtime enforcement node — the capture-and-enforce client for the AI Operations Platform
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
//! `openlatch boundary <status|explain>` — read-only views onto the
//! model-boundary listener.
//!
//! There is deliberately no `enable` / `disable` here. The agent's
//! `ANTHROPIC_BASE_URL` is written by the daemon after it binds the pinned port
//! and removed when it lets go, so that the config never names a listener that
//! does not exist. A command that wrote it by hand would be a second owner of
//! that invariant, and two owners is how the config came to point at a port
//! nobody held. To route agents straight at the provider, stop the daemon; to
//! stop binding the port at all, set `[boundary] enabled = false` (or
//! `OPENLATCH_BOUNDARY_ENABLED=false`).

use crate::cli::output::{OutputConfig, OutputFormat};
use crate::cli::BoundaryCommands;
use crate::error::{OlError, ERR_BOUNDARY_FINDING_NOT_FOUND};

/// Dispatch `openlatch boundary <sub>`.
pub fn run(cmd: &BoundaryCommands, output: &OutputConfig) -> Result<(), OlError> {
    match cmd {
        BoundaryCommands::Status => status(output),
        BoundaryCommands::Explain { finding_id } => explain(finding_id, output),
    }
}

/// Who owns the pinned boundary port right now. Read by `openlatch status` and
/// by `openlatch doctor`'s wiring-coherence check, which classify boundary
/// liveness from this signature probe rather than from any disk marker.
#[derive(Debug, PartialEq)]
pub(crate) enum PortOwnership {
    /// A live OpenLatch boundary answered with our status signature — safe.
    Owned,
    /// Something is listening but it is NOT our boundary (wrong/missing
    /// signature). Wiring the agent here would leak its provider credential.
    Foreign,
    /// Nothing is holding the port — the daemon isn't up yet. Covers both a
    /// refused connection and one that never got answered, because which of
    /// the two a closed loopback port produces is a property of the host; see
    /// `verify_port_ownership`.
    Unreachable,
}

/// Budget for the TCP connect leg alone. Deliberately far shorter than
/// `PROBE_TIMEOUT`: a live listener on loopback accepts in microseconds, so
/// 100ms is three orders of magnitude of headroom for the only question this
/// leg asks — is anything there. Keeping it separate is what stops the two
/// legs from stacking into a ~1s worst case on a listener that accepts and
/// then stalls. Same split, same values, as `openlatch-hook`'s
/// `CONNECT_TIMEOUT` / `TOTAL_TIMEOUT`.
const CONNECT_TIMEOUT: std::time::Duration = std::time::Duration::from_millis(100);

/// Budget for the HTTP round-trip against the admin status endpoint.
const PROBE_TIMEOUT: std::time::Duration = std::time::Duration::from_millis(500);

/// GET the boundary's admin status endpoint.
///
/// The single place that knows the URL and the client configuration, because
/// `verify_port_ownership` and `probe_boundary` both need it and had already
/// drifted: the timeout was a named constant in one and a bare `500` literal
/// in the other. `None` is "no answer" — both callers treat a build failure
/// and a transport failure the same way, and neither can act on the
/// distinction.
fn get_admin_status(port: u16) -> Option<reqwest::blocking::Response> {
    let url = format!("http://127.0.0.1:{port}/admin/boundary/status");
    reqwest::blocking::Client::builder()
        .timeout(PROBE_TIMEOUT)
        .build()
        .ok()?
        .get(&url)
        .send()
        .ok()
}

/// Probe `http://127.0.0.1:{port}/admin/boundary/status` and classify who owns
/// the port. Ownership is proven by our JSON signature (`status` + `upstream`
/// keys) — reused from `boundary_status` so a foreign listener cannot forge it
/// by chance.
pub(crate) fn verify_port_ownership(port: u16) -> PortOwnership {
    // Liveness is decided by a raw TCP connect, deliberately BEFORE any HTTP,
    // and "could not connect" is `Unreachable` regardless of *why*.
    //
    // The previous version classified on reqwest's `is_connect()`, which is not
    // portable, for a reason worth recording because it is counter-intuitive:
    // the time a closed loopback port takes to report refused is a property of
    // the host, not of the protocol. Measured on Windows 11 with the firewall's
    // filter driver in the path, a closed 127.0.0.1 port answers
    // `ConnectionRefused` (WSAECONNREFUSED, os error 10061) only after ~2s of
    // SYN retries. Any probe on a sub-2s budget therefore never sees the
    // refusal — it sees its own timeout. reqwest surfaced that as
    // `is_connect() == false` / `is_timeout() == true`, so the closed port fell
    // through to the catch-all "no answer" case and was called `Foreign`.
    //
    // The user-visible result was not subtle: on every Windows host with the
    // daemon simply not running — the normal idle state — `openlatch status`
    // printed the boundary as "failed" rather than "down"
    // (`status.rs::boundary_state_from_ownership`) and `doctor` diagnosed a
    // port conflict that did not exist. It passed CI throughout because Linux
    // runners refuse instantly and stay inside the budget.
    //
    // Collapsing refused and timed-out into one verdict is what makes this
    // robust rather than merely re-tuned: the target is loopback, where a live
    // listener accepts in microseconds, so a connect that has neither been
    // accepted nor refused within the budget is not holding the port. The one
    // counter-case is a local listener with a saturated backlog, which is
    // pathological and still a refusal — "down" instead of "failed", both of
    // which decline. Only `Owned`, which requires our JSON signature below,
    // ever permits anything.
    let addr = std::net::SocketAddr::from(([127, 0, 0, 1], port));
    if std::net::TcpStream::connect_timeout(&addr, CONNECT_TIMEOUT).is_err() {
        return PortOwnership::Unreachable;
    }

    // Something is listening (proven above), so no answer here means it did
    // not answer *our* protocol.
    let Some(resp) = get_admin_status(port) else {
        return PortOwnership::Foreign;
    };
    if !resp.status().is_success() {
        return PortOwnership::Foreign;
    }
    match resp.json::<serde_json::Value>() {
        Ok(v) if v.get("status").is_some() && v.get("upstream").is_some() => PortOwnership::Owned,
        _ => PortOwnership::Foreign,
    }
}

/// `openlatch boundary status` — probe the running listener.
pub fn status(output: &OutputConfig) -> Result<(), OlError> {
    let port = crate::config::Config::load(None, None, false)
        .map(|c| c.boundary.port)
        .unwrap_or_else(|_| crate::boundary::resolve_boundary_port());
    let probe = probe_boundary(port);

    if output.format == OutputFormat::Json {
        output.print_json(&serde_json::json!({
            "port": port,
            "up": probe.is_some(),
            "detail": probe,
        }));
    } else {
        crate::cli::header::print(output, &["boundary status"]);
        match probe {
            Some(v) => {
                eprintln!("  Boundary: up (port {port})");
                if let Some(up) = v.get("upstream").and_then(|x| x.as_str()) {
                    eprintln!("  Upstream: {up}");
                }
                if let Some(f) = v.get("pass_through_failures").and_then(|x| x.as_u64()) {
                    eprintln!("  Pass-through failures: {f}");
                }
                // A listener being up no longer implies the agent is pointed at
                // it: the wiring is gated on a live round trip to the provider
                // (`boundary::preflight`). Printing "up" alone would read as
                // "everything is routed through me", which is exactly the
                // ambiguity the gate exists to remove.
                match v.get("preflight").and_then(|x| x.as_str()) {
                    Some("ok") => eprintln!("  Preflight: ok (agent wired)"),
                    Some("failed") => {
                        let why = v
                            .get("preflight_error")
                            .and_then(|x| x.as_str())
                            .unwrap_or("no round trip to the provider completed");
                        eprintln!("  Preflight: FAILED — {why}");
                        eprintln!(
                            "  Agent left unwired on purpose: model calls go straight to the \
                             provider and nothing is captured."
                        );
                    }
                    Some(other) => eprintln!("  Preflight: {other}"),
                    None => {}
                }
            }
            None => {
                eprintln!("  Boundary: down (pinned port {port})");
                eprintln!(
                    "  Suggestion: run 'openlatch start' to bring the listener up (it wires \
                     the agent once bound)."
                );
            }
        }
    }
    Ok(())
}

/// `openlatch boundary explain <finding_id>` — print a churning prefix block
/// LOCALLY (C-10b). The block content lives only in the on-disk retention store
/// on the originating host and is **never** emitted on the wire; this is the one
/// path that resolves a `finding_id` back to its content.
pub fn explain(finding_id: &str, output: &OutputConfig) -> Result<(), OlError> {
    let record = crate::boundary::retention::load(finding_id).ok_or_else(|| {
        OlError::new(
            ERR_BOUNDARY_FINDING_NOT_FOUND,
            format!("no local churn finding '{finding_id}'"),
        )
        .with_suggestion(
            "Findings resolve only on the host that produced them, and expire from the bounded \
             local store. Check the id from the `ai.openlatch.prefix.finding_id` field.",
        )
    })?;

    if output.format == OutputFormat::Json {
        output.print_json(&serde_json::json!({
            "finding_id": record.finding_id,
            "captured_at": record.captured_at,
            "churn_layer": record.churn_layer,
            "churn_class": record.churn_class,
            "divergence_offset": record.divergence_offset,
            "churn_byte_len": record.churn_byte_len,
            "churn_block_index": record.churn_block_index,
            "block": record.block,
        }));
    } else {
        crate::cli::header::print(output, &["boundary explain"]);
        eprintln!("  finding      : {}", record.finding_id);
        eprintln!("  captured     : {}", record.captured_at);
        eprintln!("  layer        : {}", record.churn_layer);
        eprintln!("  class        : {}", record.churn_class);
        eprintln!(
            "  offset/len   : {} / {} (block #{})",
            record.divergence_offset, record.churn_byte_len, record.churn_block_index
        );
        eprintln!("  block (local, never emitted):");
        println!("{}", record.block);
    }
    Ok(())
}

/// Blocking GET of the boundary's admin status endpoint. `None` when the
/// listener is not up.
pub fn probe_boundary(port: u16) -> Option<serde_json::Value> {
    let resp = get_admin_status(port)?;
    if !resp.status().is_success() {
        return None;
    }
    resp.json().ok()
}

/// What the model boundary is actually doing, as one classification.
///
/// `status` and `doctor` used to answer this question separately: `doctor`
/// combined config, agent wiring and a live probe, while `status` classified on
/// port ownership alone and never read `boundary.enabled`. With the boundary
/// switched off in config and an unrelated process on 7600, `status` printed
///
/// ```text
/// Boundary:    FAILED (port held by a non-OpenLatch process — agents misconfigured/exposed) (port 7600)
/// ```
///
/// seconds after the daemon logged `agent boundary wiring removed — agents
/// connect to the provider directly`. No agent was wired to that port: a
/// security-shaped alarm raised on a configuration that was deliberately, and
/// verifiably, safe. One classifier, consumed by both commands, is what makes
/// that disagreement impossible.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum BoundaryState {
    /// `[boundary] enabled = false`. Agents talk to the provider directly by
    /// design; whoever holds the port is not our business.
    Disabled,
    /// A non-default boundary port: this instance deliberately does not touch
    /// the machine-global agent config, so wiring and listening are not
    /// supposed to line up.
    Isolated,
    /// Agent wired to our listener, and our listener answered. The good state.
    Wired,
    /// Agent wired, nothing listening — model calls fail with ECONNREFUSED.
    WiredButDown,
    /// Agent wired to a port held by someone else. The provider credential is
    /// going to that process. The real security alarm.
    WiredToForeign,
    /// Listener up, agent unwired because the preflight round trip failed. Not
    /// broken for the user (calls go direct) but nothing is captured.
    PreflightFailed(String),
    /// Listener up, preflight still running — the wiring lands when it passes.
    PreflightPending,
    /// Listener up, agent unwired for some other reason.
    UpUnwired,
    /// Not wired, nothing listening — consistent, and what `stop` leaves.
    Down,
    /// Not wired, and the port belongs to another process. Consistent for us,
    /// but it is why the next `start` will refuse to bind.
    ForeignIdle,
}

impl BoundaryState {
    /// The one-word label the `status` dashboard prints.
    pub(crate) fn label(&self) -> &'static str {
        match self {
            BoundaryState::Disabled => "disabled",
            BoundaryState::Isolated => "isolated",
            BoundaryState::Wired => "up",
            BoundaryState::WiredButDown => "down",
            BoundaryState::WiredToForeign => "failed",
            BoundaryState::PreflightFailed(_) => "preflight-failed",
            BoundaryState::PreflightPending => "preflight-pending",
            BoundaryState::UpUnwired => "unwired",
            BoundaryState::Down => "down",
            BoundaryState::ForeignIdle => "down",
        }
    }
}

/// Classify the boundary from config, agent wiring, and a live probe.
///
/// `wired` is the agent's `ANTHROPIC_BASE_URL` when — and only when — it points
/// at our loopback; a customer's corporate gateway is not our wiring.
pub(crate) fn classify_boundary(cfg: &crate::config::Config, wired: Option<&str>) -> BoundaryState {
    if !cfg.boundary.enabled {
        return BoundaryState::Disabled;
    }
    if !cfg.boundary.owns_agent_wiring() {
        return BoundaryState::Isolated;
    }

    let port = cfg.boundary.port;
    match (wired, verify_port_ownership(port)) {
        (Some(_), PortOwnership::Owned) => BoundaryState::Wired,
        (Some(_), PortOwnership::Unreachable) => BoundaryState::WiredButDown,
        (Some(_), PortOwnership::Foreign) => BoundaryState::WiredToForeign,
        (None, PortOwnership::Owned) => {
            // "Up but unwired" stopped being a single condition once the wiring
            // was gated on a live round trip: the daemon leaves the agent
            // unwired ON PURPOSE when the boundary cannot forward, and telling
            // that operator to restart sends them in a circle. The listener
            // knows which case it is; ask it.
            let live = probe_boundary(port);
            match live
                .as_ref()
                .and_then(|v| v.get("preflight"))
                .and_then(|v| v.as_str())
            {
                Some("failed") => BoundaryState::PreflightFailed(
                    live.as_ref()
                        .and_then(|v| v.get("preflight_error"))
                        .and_then(|v| v.as_str())
                        .unwrap_or("no round trip to the provider completed")
                        .to_string(),
                ),
                Some("pending") => BoundaryState::PreflightPending,
                _ => BoundaryState::UpUnwired,
            }
        }
        (None, PortOwnership::Unreachable) => BoundaryState::Down,
        (None, PortOwnership::Foreign) => BoundaryState::ForeignIdle,
    }
}

/// Read `env.ANTHROPIC_BASE_URL` from the agent settings, but only when it is
/// OUR loopback URL — a customer's corporate gateway is not our wiring and must
/// not be reported as such.
pub(crate) fn read_boundary_base_url(settings_path: &std::path::Path) -> Option<String> {
    let raw = std::fs::read_to_string(settings_path).ok()?;
    let parsed = crate::hooks::jsonc::parse_settings_value(&raw).ok()?;
    let url = parsed
        .get("env")?
        .get("ANTHROPIC_BASE_URL")?
        .as_str()?
        .to_string();
    reqwest::Url::parse(url.trim())
        .ok()
        .filter(|u| u.host_str() == Some("127.0.0.1"))
        .map(|_| url)
}

#[cfg(test)]
mod tests {
    use super::{verify_port_ownership, PortOwnership};

    #[test]
    fn verify_port_ownership_refuses_closed_and_foreign_ports() {
        // Connection-refused branch: nothing is listening ⇒ Unreachable
        // (enable will tell the user to start the daemon first).
        //
        // This half is the platform regression gate, and it only ever fires
        // off-CI: Linux refuses a closed loopback port instantly, Windows can
        // take ~2s, so a budgeted probe there times out instead of seeing the
        // refusal — see the comment on the raw-TCP probe in
        // `verify_port_ownership`. Anything that reintroduces a
        // reason-sensitive classification (`is_connect()`, or splitting
        // timed-out back out of `Unreachable`) turns this red on Windows and
        // green on the runners.
        let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let closed = l.local_addr().unwrap().port();
        drop(l);
        assert_eq!(verify_port_ownership(closed), PortOwnership::Unreachable);

        // Wrong-signature branch: a NON-OpenLatch listener answers 200 with a
        // body lacking our `status`/`upstream` keys ⇒ Foreign (enable refuses,
        // so no provider credential is ever pointed at it).
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let foreign = listener.local_addr().unwrap().port();
        std::thread::spawn(move || {
            use std::io::{Read, Write};
            for mut s in listener.incoming().flatten() {
                let mut buf = [0u8; 1024];
                let _ = s.read(&mut buf);
                let body = br#"{"foo":"bar"}"#;
                let head = format!(
                    "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\
                     Content-Length: {}\r\nConnection: close\r\n\r\n",
                    body.len()
                );
                let _ = s.write_all(head.as_bytes());
                let _ = s.write_all(body);
                let _ = s.flush();
            }
        });
        // Give the listener a moment to be ready before probing.
        std::thread::sleep(std::time::Duration::from_millis(50));
        assert_eq!(verify_port_ownership(foreign), PortOwnership::Foreign);
    }

    /// The #165 regression: with `[boundary] enabled = false` and an unrelated
    /// process on the pinned port, `status` printed
    /// `FAILED (port held by a non-OpenLatch process — agents misconfigured/exposed)`
    /// seconds after the daemon logged that it had removed the agent wiring. No
    /// agent was pointed at that port. The classifier must short-circuit on the
    /// config switch and never probe the port at all — so this test can assert
    /// it without any listener, on a port nothing is bound to.
    #[test]
    fn disabled_in_config_short_circuits_before_any_probe() {
        use crate::cli::commands::boundary::{classify_boundary, BoundaryState};

        let mut cfg = crate::config::Config::defaults();
        cfg.boundary.enabled = false;

        assert_eq!(classify_boundary(&cfg, None), BoundaryState::Disabled);
        // Even a wired-looking agent config cannot turn a disabled boundary
        // into an alarm: the daemon does not bind, so nothing of ours is there.
        assert_eq!(
            classify_boundary(&cfg, Some("http://127.0.0.1:7600")),
            BoundaryState::Disabled
        );
        assert_eq!(BoundaryState::Disabled.label(), "disabled");
    }

    /// A non-default boundary port means the instance never touches the
    /// machine-global agent config, so wiring and listening are not supposed to
    /// line up — checked before the probe for the same reason.
    #[test]
    fn isolated_instance_short_circuits_before_any_probe() {
        use crate::cli::commands::boundary::{classify_boundary, BoundaryState};

        let mut cfg = crate::config::Config::defaults();
        cfg.boundary.enabled = true;
        cfg.boundary.port = crate::boundary::default_boundary_port() + 1;

        assert_eq!(classify_boundary(&cfg, None), BoundaryState::Isolated);
    }
}