openlatch-client 0.6.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
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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
use chrono::{DateTime, Utc};
use serde::Serialize;

use super::CloudEvent;

#[derive(Debug, Clone, Serialize)]
pub struct TamperEvent {
    pub ocsf: OcsfHeader,
    pub tamper: TamperPayload,
}

#[derive(Debug, Clone, Serialize)]
pub struct OcsfHeader {
    pub class_uid: u32,
    pub activity_id: u32,
    pub type_uid: u32,
    pub severity_id: u32,
    pub time: DateTime<Utc>,
}

#[derive(Debug, Clone, Serialize)]
pub struct TamperPayload {
    pub event_id: String,
    pub entry_id: String,
    pub agent_type: String,
    pub settings_path_hash: String,
    pub hook_event: String,
    pub detection_method: String,
    /// Which OpenLatch artefact moved: one of the `COMPONENT_*` constants. A
    /// hook entry, the relay wiring, the agent's hook trust, the relay CA or
    /// OpenLatch's own state. Paired with `detection_method`, it is what tells
    /// a hook rewrite apart from a repointed base URL on the platform.
    pub component: String,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub field_deltas: Vec<FieldDelta>,
    pub heal: HealOutcome,
    /// Set on the follow-up `tamper_healed` event to the detection event's
    /// `event_id` so the platform can stitch the two halves together.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub related_event_id: Option<String>,
}

#[derive(Debug, Clone, Serialize)]
pub struct FieldDelta {
    /// Dotted path of the changed field (e.g. `"hooks[0].url"`, `"timeout"`).
    /// Paths only — values are never serialised so the wire message cannot
    /// leak URLs, tokens, or other entry contents.
    pub field: String,
    /// One of `"modified" | "added" | "removed"`.
    pub change: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct HealOutcome {
    pub outcome: String,
    pub attempt: u32,
    pub circuit: String,
}

/// Which half of the tamper event pair is being emitted. The OCSF `type_uid`
/// stays `200402` for both — differentiation is purely at the CloudEvent
/// `type` attribute so the platform can route them separately.
#[derive(Debug, Clone, Copy)]
pub enum TamperCloudEventKind {
    Detected,
    Healed,
}

impl TamperCloudEventKind {
    fn type_string(self) -> &'static str {
        match self {
            Self::Detected => "ai.openlatch.security.tamper_detected",
            Self::Healed => "ai.openlatch.security.tamper_healed",
        }
    }
}

/// A hook registration: a JSON entry, a hook script, the enforcement plugin, or
/// the switch that turns one of them off.
pub const COMPONENT_HOOK_ENTRY: &str = "hook_entry";

/// The wiring that points an agent's model traffic at the relay: a base URL,
/// a provider table, a proxy setting or a shell wrapper.
pub const COMPONENT_MODEL_RELAY_WIRING: &str = "model_relay_wiring";

/// The agent's own trust in the hooks OpenLatch wrote (Codex `[hooks.state]`).
pub const COMPONENT_HOOK_TRUST: &str = "hook_trust";

/// The relay's CA in the user's trust store.
pub const COMPONENT_RELAY_CA: &str = "relay_ca";

/// OpenLatch's own record of what it installed: `hook-state.json`, `hmac.key`.
pub const COMPONENT_OPENLATCH_STATE: &str = "openlatch_state";

/// A provider slot was wired to its relay endpoint, but the running editor
/// still holds the URL it read at start. Informational; healed once the editor
/// is proven to use the endpoint.
pub const DETECTION_RELAY_WIRING_PENDING: &str = "relay_wiring_pending";

/// Something put a provider slot's old URL back over the relay URL — a running
/// editor saving its in-memory settings, most often. Healed when the relay URL
/// is re-applied.
pub const DETECTION_RELAY_URL_REVERTED: &str = "relay_url_reverted";

/// The editor provably loaded the relay URL and is using the provider, yet no
/// traffic reaches the endpoint: something upstream of the file (an
/// organisation's remote configuration) is overriding it.
pub const DETECTION_RELAY_WIRING_MISCONFIGURED: &str = "relay_wiring_misconfigured";

/// The relay wiring the daemon wrote is gone from the agent's config.
pub const DETECTION_RELAY_UNWIRED: &str = "relay_unwired";

/// The relay wiring is present but points somewhere else.
pub const DETECTION_RELAY_MODIFIED: &str = "relay_modified";

/// The agent no longer records trust for a hook of ours.
pub const DETECTION_TRUST_REVOKED: &str = "trust_revoked";

/// The agent records a trust hash for our hook that is not the one granted.
pub const DETECTION_TRUST_STALE: &str = "trust_stale";

/// A hook of ours was switched off in the agent's own config: Codex
/// `enabled = false`, Cline `disabledPlugins`.
pub const DETECTION_HOOK_DISABLED: &str = "hook_disabled";

/// The relay CA is no longer trusted by the user's store.
pub const DETECTION_CA_UNTRUSTED: &str = "ca_untrusted";

/// OpenLatch's own install record was deleted under a live install.
pub const DETECTION_STATE_DELETED: &str = "state_deleted";

/// The `hook_event` a relay wiring event carries. The slot is not a hook
/// registration; the slot key rides in `entry_id`.
pub const RELAY_WIRING_HOOK_EVENT: &str = "model_relay_endpoint";

/// OCSF severity for a detection method: 1 informational, 3 medium, 4 high.
///
/// High is reserved for a state in which enforcement or capture silently does
/// not happen and that OpenLatch cannot undo on its own terms: a switch the
/// developer turned off, a CA they untrusted, wiring provably overridden. A
/// wiring waiting on an editor restart is expected.
pub fn severity_for(detection_method: &str) -> u32 {
    match detection_method {
        "legacy_marker_upgrade" | DETECTION_RELAY_WIRING_PENDING => 1,
        DETECTION_HOOK_DISABLED | DETECTION_CA_UNTRUSTED | DETECTION_RELAY_WIRING_MISCONFIGURED => {
            4
        }
        _ => 3,
    }
}

/// Whether a logged `tamper` object describes a hook entry — the one thing
/// `doctor`'s integrity section counts as "hook entries still unhealed".
///
/// Every other component shares the log, not the meaning: wiring, trust, the
/// CA and OpenLatch's own state are reported by their own rows. A record
/// written before `component` existed is a hook entry unless its method names
/// relay wiring, which was the only other producer then.
pub fn is_hook_entry_tamper(tamper: &serde_json::Value) -> bool {
    match tamper.get("component").and_then(serde_json::Value::as_str) {
        Some(component) => component == COMPONENT_HOOK_ENTRY,
        None => !matches!(
            tamper
                .get("detection_method")
                .and_then(serde_json::Value::as_str),
            Some(
                DETECTION_RELAY_WIRING_PENDING
                    | DETECTION_RELAY_URL_REVERTED
                    | DETECTION_RELAY_WIRING_MISCONFIGURED
            )
        ),
    }
}

impl TamperEvent {
    pub fn new(
        entry_id: String,
        agent_type: String,
        settings_path_hash: String,
        hook_event: String,
        detection_method: String,
    ) -> Self {
        let severity = severity_for(&detection_method);

        Self {
            ocsf: OcsfHeader {
                class_uid: 2004,
                activity_id: 2,
                type_uid: 200402,
                severity_id: severity,
                time: Utc::now(),
            },
            tamper: TamperPayload {
                event_id: uuid::Uuid::now_v7().to_string(),
                entry_id,
                agent_type,
                settings_path_hash,
                hook_event,
                detection_method,
                component: COMPONENT_HOOK_ENTRY.to_string(),
                field_deltas: Vec::new(),
                heal: HealOutcome {
                    outcome: "pending".into(),
                    attempt: 0,
                    circuit: "closed".into(),
                },
                related_event_id: None,
            },
        }
    }

    pub fn with_heal(mut self, outcome: &str, attempt: u32, circuit: &str) -> Self {
        self.tamper.heal = HealOutcome {
            outcome: outcome.into(),
            attempt,
            circuit: circuit.into(),
        };
        self
    }

    /// Carry `event_id` instead of a fresh one.
    ///
    /// For re-building a detection event a previous process emitted, so its
    /// heal can link to it after a restart: the wiring pass persists the
    /// pending event's id, never the event.
    pub fn with_event_id(mut self, event_id: &str) -> Self {
        self.tamper.event_id = event_id.to_string();
        self
    }

    /// Name the artefact that moved; [`COMPONENT_HOOK_ENTRY`] when not set.
    pub fn with_component(mut self, component: &str) -> Self {
        self.tamper.component = component.to_string();
        self
    }

    pub fn with_field_deltas(mut self, deltas: Vec<FieldDelta>) -> Self {
        self.tamper.field_deltas = deltas;
        self
    }

    /// Build the follow-up heal-outcome event from a detection event. Keeps
    /// `entry_id`, `agent_type`, `settings_path_hash`, `hook_event`, and
    /// `detection_method` aligned; assigns a fresh `event_id`; links back to
    /// the detection event via `related_event_id`.
    pub fn new_healed(original: &TamperEvent, outcome: &str, attempt: u32, circuit: &str) -> Self {
        Self {
            ocsf: OcsfHeader {
                time: Utc::now(),
                ..original.ocsf.clone()
            },
            tamper: TamperPayload {
                event_id: uuid::Uuid::now_v7().to_string(),
                heal: HealOutcome {
                    outcome: outcome.into(),
                    attempt,
                    circuit: circuit.into(),
                },
                related_event_id: Some(original.tamper.event_id.clone()),
                ..original.tamper.clone()
            },
        }
    }

    /// Wrap the tamper event in a CloudEvents v1.0.2 structured-mode envelope
    /// so it can travel through the existing cloud forwarding pipeline. The
    /// worker will stamp the `agentid` extension just before POST — we only
    /// populate the passthrough fields here.
    ///
    /// **No `subject`.** It used to carry `entry_id`, which is the id of a hook
    /// *registration*, not of a session — and the platform indexes `subject` as
    /// the session (`idx_unified_events_org_subject`), so every tamper event
    /// minted a fresh phantom session that nothing else could ever join. The id
    /// is not lost: it stays in `data.tamper.entry_id`, and a detected/healed
    /// pair still links through `data.tamper.related_event_id`. Leaving the
    /// attribute absent is also what lets the single egress
    /// (`cloud::worker::stamp_extensions`) fill it with a real session id —
    /// that stamp never overwrites a subject a producer set.
    pub fn to_cloud_event(
        &self,
        agent_id: &str,
        client_version: &str,
        os: &str,
        kind: TamperCloudEventKind,
    ) -> CloudEvent {
        let payload = serde_json::json!({
            "ocsf": self.ocsf,
            "tamper": self.tamper,
        });

        let envelope = serde_json::json!({
            "specversion": "1.0",
            "id": format!("evt_{}", self.tamper.event_id),
            "source": self.tamper.agent_type.as_str(),
            "type": kind.type_string(),
            "time": self.ocsf.time.to_rfc3339(),
            "datacontenttype": "application/json",
            "data": payload,
            "clientversion": client_version,
            "os": os,
        });

        CloudEvent {
            envelope,
            agent_id: agent_id.to_string(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn make_event() -> TamperEvent {
        TamperEvent::new(
            "entry-id-123".into(),
            "claude-code".into(),
            "sha256:abc123".into(),
            "PreToolUse".into(),
            "hmac_mismatch".into(),
        )
    }

    #[test]
    fn ocsf_class_uid_is_2004() {
        let e = make_event();
        assert_eq!(e.ocsf.class_uid, 2004);
        assert_eq!(e.ocsf.activity_id, 2);
        assert_eq!(e.ocsf.type_uid, 200402);
    }

    #[test]
    fn severity_is_info_for_legacy_upgrade() {
        let e = TamperEvent::new(
            "id".into(),
            "claude-code".into(),
            "sha256:x".into(),
            "PreToolUse".into(),
            "legacy_marker_upgrade".into(),
        );
        assert_eq!(e.ocsf.severity_id, 1);
    }

    #[test]
    fn relay_wiring_severities_follow_what_they_mean() {
        let of = |method: &str| {
            TamperEvent::new(
                "cline:gs:shared:geminiBaseUrl".into(),
                "cline".into(),
                "sha256:x".into(),
                RELAY_WIRING_HOOK_EVENT.into(),
                method.into(),
            )
            .ocsf
            .severity_id
        };
        assert_eq!(of(DETECTION_RELAY_WIRING_PENDING), 1);
        assert_eq!(of(DETECTION_RELAY_URL_REVERTED), 3);
        assert_eq!(of(DETECTION_RELAY_WIRING_MISCONFIGURED), 4);
    }

    #[test]
    fn severity_for_every_method() {
        for (method, want) in [
            ("legacy_marker_upgrade", 1),
            (DETECTION_RELAY_WIRING_PENDING, 1),
            (DETECTION_HOOK_DISABLED, 4),
            (DETECTION_CA_UNTRUSTED, 4),
            (DETECTION_RELAY_WIRING_MISCONFIGURED, 4),
            (DETECTION_RELAY_UNWIRED, 3),
            (DETECTION_RELAY_MODIFIED, 3),
            (DETECTION_RELAY_URL_REVERTED, 3),
            (DETECTION_TRUST_REVOKED, 3),
            (DETECTION_TRUST_STALE, 3),
            (DETECTION_STATE_DELETED, 3),
            ("hmac_mismatch", 3),
            ("file_hash_mismatch", 3),
        ] {
            assert_eq!(severity_for(method), want, "{method}");
        }
    }

    #[test]
    fn component_defaults_to_hook_entry_and_is_serialised() {
        let e = make_event();
        let json = serde_json::to_value(&e).unwrap();
        assert_eq!(json["tamper"]["component"], COMPONENT_HOOK_ENTRY);
        let e = make_event().with_component(COMPONENT_HOOK_TRUST);
        let healed = TamperEvent::new_healed(&e, "succeeded", 1, "closed");
        assert_eq!(healed.tamper.component, COMPONENT_HOOK_TRUST);
    }

    #[test]
    fn only_hook_entries_count_as_hook_entry_tamper() {
        let of = |v: serde_json::Value| is_hook_entry_tamper(&v);
        assert!(of(serde_json::json!({"component": "hook_entry"})));
        assert!(!of(serde_json::json!({"component": "model_relay_wiring"})));
        assert!(!of(serde_json::json!({"component": "hook_trust"})));
        // A record written before `component` existed.
        assert!(of(serde_json::json!({"detection_method": "hmac_mismatch"})));
        assert!(!of(
            serde_json::json!({"detection_method": DETECTION_RELAY_URL_REVERTED})
        ));
    }

    #[test]
    fn severity_is_medium_for_hmac_mismatch() {
        let e = make_event();
        assert_eq!(e.ocsf.severity_id, 3);
    }

    #[test]
    fn no_settings_values_in_serialized_event() {
        let e = make_event();
        let json = serde_json::to_string(&e).unwrap();
        assert!(!json.contains("http://attacker"));
        assert!(!json.contains("Bearer "));
        assert!(!json.contains("OPENLATCH_TOKEN"));
    }

    #[test]
    fn no_settings_path_literal_in_serialized_event() {
        let e = TamperEvent::new(
            "id".into(),
            "claude-code".into(),
            "sha256:abc123def456".into(),
            "PreToolUse".into(),
            "hmac_mismatch".into(),
        );
        let json = serde_json::to_string(&e).unwrap();
        assert!(!json.contains(".claude"));
        assert!(!json.contains("settings.json"));
        assert!(json.contains("sha256:abc123def456"));
    }

    #[test]
    fn with_heal_sets_outcome() {
        let e = make_event().with_heal("succeeded", 2, "closed");
        assert_eq!(e.tamper.heal.outcome, "succeeded");
        assert_eq!(e.tamper.heal.attempt, 2);
    }

    #[test]
    fn event_id_is_uuid_v7() {
        let e = make_event();
        assert!(!e.tamper.event_id.is_empty());
    }

    #[test]
    fn related_event_id_absent_on_detection_event() {
        let e = make_event();
        let json = serde_json::to_string(&e).unwrap();
        assert!(
            !json.contains("related_event_id"),
            "detection events must not serialise related_event_id"
        );
    }

    #[test]
    fn new_healed_links_to_original() {
        let original = make_event();
        let healed = TamperEvent::new_healed(&original, "succeeded", 1, "closed");
        assert_eq!(
            healed.tamper.related_event_id.as_deref(),
            Some(original.tamper.event_id.as_str())
        );
        assert_ne!(healed.tamper.event_id, original.tamper.event_id);
        assert_eq!(healed.tamper.entry_id, original.tamper.entry_id);
        assert_eq!(healed.tamper.heal.outcome, "succeeded");
    }

    #[test]
    fn new_healed_preserves_detection_metadata() {
        let original = make_event();
        let healed = TamperEvent::new_healed(&original, "failed", 3, "open");
        assert_eq!(
            healed.tamper.detection_method,
            original.tamper.detection_method
        );
        assert_eq!(healed.tamper.agent_type, original.tamper.agent_type);
        assert_eq!(healed.tamper.hook_event, original.tamper.hook_event);
        assert_eq!(
            healed.tamper.settings_path_hash,
            original.tamper.settings_path_hash
        );
    }

    #[test]
    fn with_field_deltas_populates_vec() {
        let deltas = vec![
            FieldDelta {
                field: "hooks[0].url".into(),
                change: "modified".into(),
            },
            FieldDelta {
                field: "timeout".into(),
                change: "removed".into(),
            },
        ];
        let e = make_event().with_field_deltas(deltas);
        assert_eq!(e.tamper.field_deltas.len(), 2);
        assert_eq!(e.tamper.field_deltas[0].field, "hooks[0].url");
        assert_eq!(e.tamper.field_deltas[0].change, "modified");

        let json = serde_json::to_string(&e).unwrap();
        assert!(json.contains("hooks[0].url"));
        assert!(json.contains("modified"));
    }

    #[test]
    fn field_deltas_omitted_when_empty() {
        let e = make_event();
        let json = serde_json::to_string(&e).unwrap();
        assert!(
            !json.contains("field_deltas"),
            "empty field_deltas must be skipped in serialisation"
        );
    }

    #[test]
    fn to_cloud_event_detected_has_correct_type() {
        let e = make_event();
        let ce = e.to_cloud_event("agt_xyz", "0.2.0", "linux", TamperCloudEventKind::Detected);

        assert_eq!(ce.agent_id, "agt_xyz");
        assert_eq!(
            ce.envelope["type"].as_str(),
            Some("ai.openlatch.security.tamper_detected")
        );
        assert_eq!(ce.envelope["specversion"].as_str(), Some("1.0"));
        assert_eq!(ce.envelope["source"].as_str(), Some("claude-code"));
        // No subject from the builder: a hook-registration id is not a session
        // id, and the egress fills the field with one that is.
        assert!(ce.envelope.get("subject").is_none());
        assert_eq!(
            ce.envelope["data"]["tamper"]["entry_id"].as_str(),
            Some("entry-id-123"),
            "the entry id is kept where it belongs, in the payload"
        );
        assert_eq!(ce.envelope["clientversion"].as_str(), Some("0.2.0"));
        assert_eq!(ce.envelope["os"].as_str(), Some("linux"));
        assert_eq!(
            ce.envelope["datacontenttype"].as_str(),
            Some("application/json")
        );
    }

    #[test]
    fn to_cloud_event_healed_has_correct_type() {
        let e = TamperEvent::new_healed(&make_event(), "succeeded", 1, "closed");
        let ce = e.to_cloud_event("agt_xyz", "0.2.0", "macos", TamperCloudEventKind::Healed);
        assert_eq!(
            ce.envelope["type"].as_str(),
            Some("ai.openlatch.security.tamper_healed")
        );
    }

    #[test]
    fn to_cloud_event_id_has_evt_prefix() {
        let e = make_event();
        let ce = e.to_cloud_event("agt_xyz", "0.2.0", "linux", TamperCloudEventKind::Detected);
        let id = ce.envelope["id"].as_str().unwrap();
        assert!(
            id.starts_with("evt_"),
            "CloudEvent id must have evt_ prefix: {id}"
        );
        assert!(id.contains(&e.tamper.event_id));
    }

    #[test]
    fn to_cloud_event_payload_contains_ocsf_and_tamper() {
        let e = make_event();
        let ce = e.to_cloud_event("agt_xyz", "0.2.0", "linux", TamperCloudEventKind::Detected);
        let data = &ce.envelope["data"];
        assert_eq!(data["ocsf"]["class_uid"].as_u64(), Some(2004));
        assert_eq!(
            data["tamper"]["detection_method"].as_str(),
            Some("hmac_mismatch")
        );
        assert_eq!(data["tamper"]["entry_id"].as_str(), Some("entry-id-123"));
    }

    #[test]
    fn to_cloud_event_never_stamps_agentid_in_envelope() {
        // The worker stamps `agentid` onto the envelope immediately before
        // POST. If we stamped it here too, the worker's insert would be a
        // no-op instead of the expected overwrite — and more importantly, the
        // tamper CloudEvent would diverge from how hook CloudEvents are shaped
        // on their way into the channel.
        let e = make_event();
        let ce = e.to_cloud_event("agt_xyz", "0.2.0", "linux", TamperCloudEventKind::Detected);
        assert!(
            ce.envelope.get("agentid").is_none(),
            "to_cloud_event must leave agentid stamping to the worker"
        );
    }
}