Skip to main content

kian_plugin/hooks/
wire.rs

1//! View-building helpers for the interception-port call sites
2//! (PLUGIN-SPEC §4's nine rows, P2).
3//!
4//! The bounds here are the §3.2 byte bounds and §7.6's frame bound,
5//! enforced **before** serialization; the digests are the §3.2
6//! `*_sha256` fields. They live in `kian-plugin` because K10 allows
7//! exactly one new dependency this round (`sha2`, here) — every call
8//! site (`kian-loop`, `kian-cli`) digests through these functions
9//! instead of growing its own `sha2` edge, and `kian-dsh` (which may
10//! not depend on this crate at all, §3.5) ships its own local
11//! implementation over the same constants.
12//!
13//! Redaction is deliberately absent: tier-0 handlers receive the
14//! **unredacted** view (§3.2 — same process, same authority), and the
15//! secret redactor runs at the sidecar wire (P3), not at these call
16//! sites.
17
18use serde_json::Value;
19
20/// §3.2's `content_preview` bound: ≤4096 bytes of the head of the
21/// content, cut at a UTF-8 character boundary.
22pub const PREVIEW_MAX_BYTES: usize = 4096;
23
24/// §7.6's frame bound: one line, either direction, is at most
25/// `max_payload_kib` (256 KiB) — the bound a §3.2.5 `arguments` value
26/// must fit to ride parsed.
27pub const FRAME_PAYLOAD_MAX_BYTES: usize = 256 * 1024;
28
29/// The §3.2 `*_sha256` digest fields: SHA-256 over the exact bytes,
30/// lowercase hex.
31pub fn sha256_hex(data: &[u8]) -> String {
32    use sha2::{Digest, Sha256};
33    let mut hasher = Sha256::new();
34    hasher.update(data);
35    let out = hasher.finalize();
36    let mut hex = String::with_capacity(out.len() * 2);
37    for byte in out {
38        use std::fmt::Write as _;
39        let _ = write!(hex, "{byte:02x}");
40    }
41    hex
42}
43
44/// The exact serialized form a digest or byte count describes
45/// (§3.2: `content_bytes` is the *serialized* length). Compact JSON —
46/// the same bytes `serde_json::to_string` produces everywhere else.
47///
48/// `serde_json::to_vec` over a `Value` cannot fail (a `Value` is by
49/// construction valid JSON: no non-string map keys, no non-finite
50/// floats), and an audit digest must never silently describe the empty
51/// input — so the invariant is asserted, the same convention
52/// `subscriptions.rs` uses, rather than defaulted.
53pub fn serialized(v: &Value) -> Vec<u8> {
54    serde_json::to_vec(v).expect("serializing a serde_json::Value cannot fail")
55}
56
57/// §3.2's preview rule: the head of `content`, at most
58/// [`PREVIEW_MAX_BYTES`] bytes, cut at a UTF-8 character boundary;
59/// the flag is true when the preview is shorter than the content.
60pub fn preview(content: &str) -> (String, bool) {
61    if content.len() <= PREVIEW_MAX_BYTES {
62        return (content.to_string(), false);
63    }
64    let mut cut = PREVIEW_MAX_BYTES;
65    while cut > 0 && !content.is_char_boundary(cut) {
66        cut -= 1;
67    }
68    (content[..cut].to_string(), true)
69}
70
71/// §3.2.5's exhaustive two-form rule for `arguments`: the parsed value
72/// when its serialization fits the frame bound, else the longest
73/// character-boundary prefix that fits, as a **string** — never a
74/// partially serialized object. Returns `(arguments, truncated)`.
75pub fn bounded_value(v: &Value) -> (Value, bool) {
76    let bytes = serialized(v);
77    if bytes.len() <= FRAME_PAYLOAD_MAX_BYTES {
78        return (v.clone(), false);
79    }
80    let text = String::from_utf8_lossy(&bytes);
81    let mut cut = FRAME_PAYLOAD_MAX_BYTES;
82    // `text` borrows widened bytes; index on its own chars only.
83    while cut > 0 && !text.is_char_boundary(cut) {
84        cut -= 1;
85    }
86    (Value::String(text[..cut].to_string()), true)
87}
88
89#[cfg(test)]
90mod tests {
91    use super::*;
92    use serde_json::json;
93
94    #[test]
95    fn sha256_hex_matches_known_vectors() {
96        assert_eq!(
97            sha256_hex(b""),
98            "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
99        );
100        assert_eq!(
101            sha256_hex(b"abc"),
102            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
103        );
104    }
105
106    #[test]
107    fn preview_truncates_on_a_character_boundary() {
108        let short = "hello";
109        assert_eq!(preview(short), (short.to_string(), false));
110
111        // 4096 ASCII bytes + a two-byte char: the cut backs up to the
112        // boundary, never splitting the char.
113        let long = "é".repeat(3000);
114        let (head, truncated) = preview(&long);
115        assert!(truncated);
116        assert!(head.len() <= PREVIEW_MAX_BYTES);
117        assert!(head.chars().all(|c| c == 'é'));
118        assert_eq!(head.len() % 2, 0, "cut on a char boundary");
119
120        // Exactly at the bound: not truncated.
121        let exact = "a".repeat(PREVIEW_MAX_BYTES);
122        assert_eq!(preview(&exact), (exact.clone(), false));
123    }
124
125    #[test]
126    fn bounded_value_is_parsed_or_prefix_never_both() {
127        let small = json!({"cmd": ["ls"]});
128        assert_eq!(bounded_value(&small), (small.clone(), false));
129
130        // Over the frame bound: a string prefix + the flag.
131        let big_text = "x".repeat(FRAME_PAYLOAD_MAX_BYTES + 10);
132        let big = json!(big_text);
133        let (view, truncated) = bounded_value(&big);
134        assert!(truncated);
135        assert!(view.is_string());
136        let s = view.as_str().unwrap();
137        assert!(s.len() <= FRAME_PAYLOAD_MAX_BYTES);
138
139        // A multi-byte char straddling the cut is not split.
140        let straddle = json!("é".repeat(FRAME_PAYLOAD_MAX_BYTES / 2 + 3));
141        let (view, truncated) = bounded_value(&straddle);
142        assert!(truncated);
143        let s = view.as_str().unwrap();
144        assert!(s.len() <= FRAME_PAYLOAD_MAX_BYTES);
145        // The serialized form opens with a `"` byte, so the char-boundary
146        // cut backs up to `1 + 2k`: the head is the quote plus whole é's.
147        assert!(s.starts_with('"'));
148        assert_eq!((s.len() - 1) % 2, 0);
149        assert!(s[1..].chars().all(|c| c == 'é'));
150    }
151}