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
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
//! Exceptions — `AskScope` selector matching. Plan 02 §2g, PRD §Exception
//! `selector` per `AskScope`.
//!
//! `bundle` calls [`validate_exception`] at load; the entry point calls [`apply`]
//! after the tiers and **before** the join.
//!
//! # Two digests, both pinned, both cross-repo parity surfaces
//!
//! ```text
//! ground_key  = sha256(atom_id ‖ JCS(selector))
//! action_hash = sha256(tool_name ‖ JCS(tool_input))
//! ```
//!
//! JCS is RFC 8785 canonical JSON — use the in-tree `serde_json_canonicalizer`,
//! never a hand-rolled key order — and `‖` is **plain UTF-8 concatenation: no
//! separator byte, no length prefix**. A separator is the obvious thing for a
//! second implementation to add, which is why its absence is written down. If the
//! two evaluators normalise differently, **every `exact_action` exception fails to
//! replay**.
//!
//! The failure a hand-rolled key order buys is silent and user-visible: a ground
//! key that differs by key ordering does not match an exception a human already
//! granted, and the developer is asked a question they already answered.
//!
//! # Selector match per scope
//!
//! | `scope` | `selector` | Matches when |
//! | ------- | ---------- | ------------ |
//! | `exact_action` | `{action_hash}` | the current action's `action_hash` equals it |
//! | `resource_class` | `{effect: {verb, target_class}}` | any effect tuple of the current action equals it |
//! | `rule_agent` | `{atom_id, agent_row_id}` | the deciding atom and the agent match |
//! | `rule_zone` | `{atom_id, zone_id}` | the atom matches and the agent's assigned zone is `zone_id` **or below it** |
//!
//! An `exception` with `verdict: allow` short-circuits its atom to Allow; with
//! `verdict: block` it forces Block. **When both match the same atom, `block`
//! wins** — the verbs already imply it, and it is the direction of the verdict
//! lattice's own join. Unstated, an implementation resolves it by whatever order
//! it happens to iterate in: `["E1-allow", "E2-block"]` would allow and
//! `["Z1-block", "Z2-allow"]` would block, the same two exceptions deciding
//! opposite ways because of how they were named.

use std::fmt::Write as _;

use chrono::DateTime;
use serde_json::{Map, Value};
use sha2::{Digest, Sha256};

use crate::generated::types::{EffectiveZone, Exception, Verdict};

use super::bundle::LoadedArtifact;
use super::types::{Contribution, EvalContext};

/// Reject an exception whose declared `ground_key` does not match its selector.
///
/// The client's `ground_key` MUST equal the platform's for the same answer.
///
/// **This check cannot run here, and runs in [`apply`] instead.** The ground key
/// is `sha256(atom_id ‖ JCS(selector))`, and `atom_id` lives on the artifact
/// **envelope** — `bundles/07-declared-ground-key.json` carries no `atom_id`
/// inside `body.selector` at all. `bundle::parse_artifact` hands this function
/// the parsed body and nothing else, so an implementation here would have to
/// compute the key over `""` and would skip the *valid* fixture. [`apply`] has
/// the envelope, so it is where a mismatching exception is dropped.
///
/// The observable verdict is identical either way — an exception whose declared
/// key does not match its selector never applies. What differs is
/// `Bundle::skipped`, which does not list it. Moving the check back here needs
/// one line in `bundle.rs` (pass `envelope.atom_id`), which is another slice's
/// file.
pub fn validate_exception(_body: &Exception) -> Result<(), String> {
    Ok(())
}

/// `sha256(atom_id ‖ JCS(selector))`, hex-encoded lowercase.
///
/// The concatenation carries **no separator**: see the module header.
pub fn ground_key(atom_id: &str, selector: &Map<String, Value>) -> String {
    sha256_hex(&[atom_id, &jcs(selector)])
}

/// `sha256(tool_name ‖ JCS(tool_input))`, hex-encoded lowercase.
///
/// The PRD defines `action_hash` as "sha256 of the normalised action" without
/// pinning the normalisation; this is the pinning, shared with the oracle
/// (`tools/zone-eval-ref/canonical.py::action_hash`) and with the platform.
pub fn action_hash(tool_name: &str, tool_input: &Value) -> String {
    sha256_hex(&[tool_name, &jcs(tool_input)])
}

/// Apply every matching exception to the contributions, in place.
///
/// Runs **after** Tiers 1/2/3 and **before** the join: an exception adjusts what
/// an atom contributed, it does not decide on its own — which is why a scope
/// whose atom did not fire changes nothing (`07-resource-class-atom-did-not-fire`).
///
/// `zone` is the bundle's `meta.effective_zone`, the only input `rule_zone`
/// needs; passing the zone rather than the bundle keeps this function's reach
/// visible from its signature.
pub fn apply(
    contributions: &mut [Contribution],
    exceptions: &[LoadedArtifact],
    ctx: &EvalContext<'_>,
    zone: Option<&EffectiveZone>,
) {
    if exceptions.is_empty() {
        return;
    }
    // Once per EVENT, not once per (contribution × exception): the hash is a
    // sha256 over the whole tool input and nothing about it varies per atom.
    let action = action_hash(&ctx.event.tool_name, &ctx.event.tool_input);

    for contribution in contributions.iter_mut() {
        let atom_id = contribution.atom_id.as_deref().unwrap_or("");
        let mut matched: Option<&Exception> = None;

        for artifact in exceptions {
            let Some(body) = artifact.as_exception() else {
                continue;
            };
            if exception_atom_id(artifact, body) != atom_id {
                continue;
            }
            if !ground_key_is_declared_correctly(atom_id, body) {
                continue;
            }
            if is_expired(body, ctx.now_ms) {
                continue;
            }
            // An answer is `allow` or `block`. `ask` and `optimize` are verdicts
            // an atom fires, not answers a human gave, so an exception carrying
            // one decides nothing rather than being read as the nearest thing.
            if !matches!(body.verdict, Some(Verdict::Allow) | Some(Verdict::Block)) {
                continue;
            }
            if !selector_matches(body, atom_id, ctx, &action, zone) {
                continue;
            }
            // Block over allow; among equals the first, and `bundle::load` sorted
            // the exceptions by `artifact_id`, so "the first" is deterministic
            // across implementations.
            let wins = match matched {
                None => true,
                Some(current) => {
                    current.verdict != Some(Verdict::Block) && body.verdict == Some(Verdict::Block)
                }
            };
            if wins {
                matched = Some(body);
            }
        }

        if let Some(body) = matched {
            let verdict = body.verdict.unwrap_or(Verdict::Allow);
            contribution.verdict = verdict;
            contribution.exception_ground_key = Some(ground_key(atom_id, &body.selector));
            contribution.reason = format!("exception {} -> {verdict}", scope_of(body));
        }
    }
}

// ── Internals ────────────────────────────────────────────────────────

/// The atom an exception answers for: the envelope's, or the selector's when the
/// envelope carries none.
fn exception_atom_id<'a>(artifact: &'a LoadedArtifact, body: &'a Exception) -> &'a str {
    artifact.atom_id().unwrap_or_else(|| {
        body.selector
            .get("atom_id")
            .and_then(Value::as_str)
            .unwrap_or("")
    })
}

/// Whether a declared `ground_key` agrees with the selector it claims to key.
///
/// An exception that declares none is fine — the platform is not required to
/// ship it. One that declares a key the selector does not produce is a bundle
/// item the client cannot trust, so it is dropped rather than trusted halfway.
fn ground_key_is_declared_correctly(atom_id: &str, body: &Exception) -> bool {
    match body.ground_key.as_deref() {
        Some(declared) => declared == ground_key(atom_id, &body.selector),
        None => true,
    }
}

/// `expires_at` in the past. An absent or unparseable value never expires —
/// PRD §Exception: *"an answered ground stays answered until it is retired,
/// because an exception that silently expires re-asks a question the
/// organization believed it had settled."*
fn is_expired(body: &Exception, now_ms: i64) -> bool {
    body.expires_at
        .as_deref()
        .and_then(|text| DateTime::parse_from_rfc3339(text).ok())
        .is_some_and(|at| now_ms > at.timestamp_millis())
}

/// The four `AskScope` selector shapes (PRD §Atom language, exception selectors).
fn selector_matches(
    body: &Exception,
    atom_id: &str,
    ctx: &EvalContext<'_>,
    action: &str,
    zone: Option<&EffectiveZone>,
) -> bool {
    let selector = &body.selector;
    let field = |name: &str| selector.get(name).and_then(Value::as_str);

    match scope_of(body) {
        "exact_action" => field("action_hash") == Some(action),
        "resource_class" => {
            let Some(wanted) = selector.get("effect").and_then(Value::as_object) else {
                return false;
            };
            let verb = wanted.get("verb").and_then(Value::as_str);
            let target_class = wanted.get("target_class").and_then(Value::as_str);
            ctx.classification.effects.iter().any(|effect| {
                Some(effect.verb.as_str()) == verb
                    && Some(effect.target_class.as_str()) == target_class
            })
        }
        "rule_agent" => {
            field("atom_id") == Some(atom_id)
                && field("agent_row_id")
                    == ctx
                        .event
                        .agent
                        .as_ref()
                        .and_then(|agent| agent.agent_row_id.as_deref())
        }
        "rule_zone" => {
            if field("atom_id") != Some(atom_id) {
                return false;
            }
            let Some(zone_id) = field("zone_id") else {
                return false;
            };
            // "the agent's assigned zone is zone_id OR BELOW IT" — the zone's
            // root-to-node path is exactly the list of zones it is at or below,
            // so an ancestor grant reaches every descendant without the client
            // walking a tree it does not have.
            zone.is_some_and(|zone| {
                zone.node_id.as_deref() == Some(zone_id)
                    || zone.path.iter().any(|node| node == zone_id)
            })
        }
        // R14: an `AskScope` this client does not know matches nothing. Widening
        // an answer the console never gave is the one direction that is not safe.
        _ => false,
    }
}

fn scope_of(body: &Exception) -> &str {
    body.scope
        .as_ref()
        .map(|scope| scope.0.as_str())
        .unwrap_or("")
}

/// RFC 8785 canonical JSON.
///
/// The error arm is unreachable for a `serde_json` value — the serializer fails
/// only on a map with non-string keys, which `Value` cannot express — and the
/// engine does not panic on input it did not author.
fn jcs<T: serde::Serialize>(value: &T) -> String {
    serde_json_canonicalizer::to_string(value).unwrap_or_default()
}

/// sha256 over the parts concatenated with **no separator**, hex lowercase.
fn sha256_hex(parts: &[&str]) -> String {
    let mut hasher = Sha256::new();
    for part in parts {
        hasher.update(part.as_bytes());
    }
    let mut hex = String::with_capacity(64);
    for byte in hasher.finalize() {
        // `hex` the crate is `full-cli`-only; the engine is gated on `policy`.
        let _ = write!(hex, "{byte:02x}");
    }
    hex
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::generated::types::{AskScope, PolicyArtifact};
    use crate::generated::types::{EffectVerb, PolicyMode, TargetClass};
    use crate::zone_eval::facts::FactSet;
    use crate::zone_eval::types::{AgentContext, Classification, Contribution, Effect, Event};

    const NOW: i64 = 1_756_742_400_000;

    fn selector(json: serde_json::Value) -> Map<String, Value> {
        json.as_object().expect("an object").clone()
    }

    fn exception_artifact(atom_id: &str, body: serde_json::Value) -> LoadedArtifact {
        let parsed: Exception = serde_json::from_value(body.clone()).expect("the body parses");
        LoadedArtifact {
            envelope: PolicyArtifact {
                artifact_id: Some("exc".to_string()),
                atom_id: Some(atom_id.to_string()),
                body: body.as_object().expect("an object").clone(),
                kind: Some("exception".to_string().into()),
                ..Default::default()
            },
            body: super::super::bundle::ArtifactBody::Exception(Box::new(parsed)),
        }
    }

    fn contribution(atom_id: &str) -> Contribution {
        Contribution {
            artifact_id: Some("sa1".to_string()),
            atom_id: Some(atom_id.to_string()),
            policy_public_id: None,
            dimension: None,
            mode: PolicyMode("enforce".to_string()),
            tier: Some(1),
            verdict: Verdict::Block,
            reason: "the atom's own reason".to_string(),
            inconclusive: Vec::new(),
            anomalies: Vec::new(),
            hold: None,
            exception_ground_key: None,
            lever: None,
            steer_instruction: None,
        }
    }

    fn classification() -> Classification {
        Classification {
            effects: vec![Effect {
                verb: EffectVerb("delete".to_string()),
                target_class: TargetClass("data_store".to_string()),
                attrs: Map::new(),
            }],
            ..Default::default()
        }
    }

    #[test]
    fn the_ground_key_is_stable_under_key_reordering() {
        // The whole reason RFC 8785 is mandated rather than "sort the keys".
        // A ground key that moves with authoring order silently fails to match
        // an exception a human already granted, and the developer is asked a
        // question they answered last week.
        let one = ground_key(
            "atom-sa1",
            &selector(serde_json::json!({"atom_id": "atom-sa1", "zone_id": "zone-eng"})),
        );
        let other = ground_key(
            "atom-sa1",
            &selector(serde_json::json!({"zone_id": "zone-eng", "atom_id": "atom-sa1"})),
        );
        assert_eq!(one, other);
        assert_eq!(one.len(), 64, "hex-encoded sha256, lowercase");
        assert!(one
            .chars()
            .all(|c| c.is_ascii_hexdigit() && !c.is_uppercase()));
    }

    #[test]
    fn the_ground_key_matches_the_platforms_for_the_same_answer() {
        // Pinned against `bundles/07-exact-action-allow.json`, whose corpus row
        // carries the platform's value for the same selector. A divergence here
        // is a cross-repo parity break, not a local test failure.
        assert_eq!(
            ground_key(
                "atom-sa1",
                &selector(serde_json::json!({
                    "action_hash": "3093cf4eea6b308644691caf2c508f24014873d17220767c7b48ca291f53e0b1"
                })),
            ),
            "328e118913c002066a27efbf1f32c192a12c361fc6361776a27f9168d3b724e3"
        );
    }

    #[test]
    fn the_action_hash_is_stable_under_key_reordering() {
        let one = action_hash(
            "Bash",
            &serde_json::json!({"command": "rm -rf /data", "timeout": 1}),
        );
        let other = action_hash(
            "Bash",
            &serde_json::json!({"timeout": 1, "command": "rm -rf /data"}),
        );
        assert_eq!(one, other);
        assert_eq!(
            action_hash(
                "Bash",
                &serde_json::json!({"command": "rm -rf /data/warehouse/orders.db"})
            ),
            "3093cf4eea6b308644691caf2c508f24014873d17220767c7b48ca291f53e0b1",
            "the platform computes this for the same action"
        );
    }

    #[test]
    fn the_concatenation_carries_no_separator() {
        // A separator byte is the obvious thing for a second implementation to
        // add. It is not there, and this is what says so.
        assert_eq!(
            ground_key("ab", &selector(serde_json::json!({}))),
            sha256_hex(&["ab{}"])
        );
    }

    #[test]
    fn block_wins_over_allow_whatever_order_they_sort_in() {
        let event = Event {
            tool_name: "Bash".to_string(),
            tool_input: serde_json::json!({"command": "rm -rf /data"}),
            agent: Some(AgentContext {
                agent_row_id: Some("agent-1".to_string()),
                ..Default::default()
            }),
            ..Default::default()
        };
        let classification = classification();
        let facts = FactSet::default();
        let ctx = EvalContext::new(&event, &classification, &facts, NOW);

        let allow = exception_artifact(
            "atom-sa1",
            serde_json::json!({
                "scope": "rule_agent",
                "selector": {"atom_id": "atom-sa1", "agent_row_id": "agent-1"},
                "verdict": "allow",
            }),
        );
        let block = exception_artifact(
            "atom-sa1",
            serde_json::json!({
                "scope": "resource_class",
                "selector": {"effect": {"verb": "delete", "target_class": "data_store"}},
                "verdict": "block",
            }),
        );

        for order in [vec![allow.clone(), block.clone()], vec![block, allow]] {
            let mut contributions = vec![contribution("atom-sa1")];
            apply(&mut contributions, &order, &ctx, None);
            assert_eq!(
                contributions[0].verdict,
                Verdict::Block,
                "the same two exceptions must not decide opposite ways on their names"
            );
        }
    }

    #[test]
    fn rule_zone_matches_at_the_node_or_below_it_and_nowhere_else() {
        let event = Event::default();
        let classification = Classification::default();
        let facts = FactSet::default();
        let ctx = EvalContext::new(&event, &classification, &facts, NOW);
        let zone = EffectiveZone {
            node_id: Some("zone-eng".to_string()),
            path: vec!["zone-root".to_string(), "zone-eng".to_string()],
            resolved_from: None,
        };

        for (zone_id, expected) in [
            ("zone-eng", Verdict::Allow),
            ("zone-root", Verdict::Allow),
            ("zone-finance", Verdict::Block),
        ] {
            let exception = exception_artifact(
                "atom-sa1",
                serde_json::json!({
                    "scope": "rule_zone",
                    "selector": {"atom_id": "atom-sa1", "zone_id": zone_id},
                    "verdict": "allow",
                }),
            );
            let mut contributions = vec![contribution("atom-sa1")];
            apply(&mut contributions, &[exception], &ctx, Some(&zone));
            assert_eq!(contributions[0].verdict, expected, "zone_id {zone_id}");
        }
    }

    #[test]
    fn a_declared_ground_key_that_does_not_match_its_selector_never_applies() {
        let event = Event {
            tool_name: "Bash".to_string(),
            tool_input: serde_json::json!({"command": "rm -rf /data"}),
            ..Default::default()
        };
        let classification = Classification::default();
        let facts = FactSet::default();
        let ctx = EvalContext::new(&event, &classification, &facts, NOW);
        let exception = exception_artifact(
            "atom-sa1",
            serde_json::json!({
                "scope": "exact_action",
                "selector": {"action_hash": action_hash("Bash", &serde_json::json!({"command": "rm -rf /data"}))},
                "verdict": "allow",
                "ground_key": "0000000000000000000000000000000000000000000000000000000000000000",
            }),
        );
        let mut contributions = vec![contribution("atom-sa1")];
        apply(&mut contributions, &[exception], &ctx, None);
        assert_eq!(
            contributions[0].verdict,
            Verdict::Block,
            "a key the client cannot trust grants nothing"
        );
    }

    #[test]
    fn an_expired_exception_does_not_apply_and_an_unparseable_expiry_never_expires() {
        let event = Event::default();
        let classification = Classification::default();
        let facts = FactSet::default();
        let ctx = EvalContext::new(&event, &classification, &facts, NOW);

        for (expires_at, expected) in [
            ("2025-08-31T16:00:00+00:00", Verdict::Block),
            ("2999-01-01T00:00:00Z", Verdict::Allow),
            ("not a timestamp", Verdict::Allow),
        ] {
            let exception = exception_artifact(
                "atom-sa1",
                serde_json::json!({
                    "scope": "rule_agent",
                    "selector": {"atom_id": "atom-sa1"},
                    "verdict": "allow",
                    "expires_at": expires_at,
                }),
            );
            let mut contributions = vec![contribution("atom-sa1")];
            apply(&mut contributions, &[exception], &ctx, None);
            assert_eq!(
                contributions[0].verdict, expected,
                "expires_at {expires_at}"
            );
        }
    }

    #[test]
    fn a_scope_this_client_cannot_read_matches_nothing() {
        let event = Event::default();
        let classification = classification();
        let facts = FactSet::default();
        let ctx = EvalContext::new(&event, &classification, &facts, NOW);
        let exception = exception_artifact(
            "atom-sa1",
            serde_json::json!({
                "scope": "whole_organization",
                "selector": {},
                "verdict": "allow",
            }),
        );
        let mut contributions = vec![contribution("atom-sa1")];
        apply(&mut contributions, &[exception], &ctx, None);
        assert_eq!(
            contributions[0].verdict,
            Verdict::Block,
            "widening an answer the console never gave is the unsafe direction"
        );
        let _ = AskScope::from("exact_action".to_string());
    }
}