Skip to main content

lean_ctx_cloud/bus/
exchange.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Agent exchange through LeanCTX Cloud (Welle 4, contract §40): the rules
3//! every knowledge item (`finding`) and task hand-over (`handoff`, with its
4//! `question`, `offer` and `answer` conversation) passes when it leaves this
5//! machine for another machine's agent or person, or arrives from one, and
6//! the audit record each exchange leaves.
7//!
8//! Outbound ([`super::messages_v2::send`]), in this order:
9//! 1. account: a device enrolled in a personal account exchanges nothing
10//!    (team knowledge needs a team, as for `cloud decisions push`);
11//! 2. policy: an expired or damaged team policy refuses; the vault's
12//!    effective policy decides with `sharing.allowed_vaults` (when set, the
13//!    vault must be listed) and `sharing.agent_exchange` (the exchange kinds
14//!    that may leave; absent: all, malformed: none);
15//! 3. content: the installation screen over every field that leaves (text,
16//!    handoff resource, every ref target);
17//! 4. the always-enforced person rules and the C0 message validation.
18//!
19//! Inbound (relay `message.deliver` from another machine): person rules,
20//! the content screen over every body string and ref, and the same team
21//! policy. A refused delivery moves the cursor only; it never reaches the
22//! local bus.
23//!
24//! The audit ledger (`<cloud data>/bus/exchange-audit.jsonl`, 0600: a header
25//! line, then one appended JSON line per record; read as its newest
26//! [`AUDIT_MAX`] entries) keeps for each exchange its direction, outcome,
27//! kind, address, ids, the refusing rule and a digest of the body — never
28//! its content.
29
30use std::collections::BTreeSet;
31use std::path::Path;
32
33use lean_ctx_protocol::cloud::effective_policy::EffectivePolicyV1;
34use serde::{Deserialize, Serialize};
35use serde_json::Value;
36use sha2::{Digest, Sha256};
37
38use super::v2::MessageType;
39use crate::CloudError;
40use crate::effective_floor;
41use crate::knowledge::screening::Screen;
42use crate::state::{lock_state, write_private};
43
44/// The `sharing` member naming the exchange kinds that may leave a machine.
45pub const KINDS_MEMBER: &str = "agent_exchange";
46/// The audit ledger file under `<cloud data>/bus/`.
47pub const AUDIT_FILE: &str = "exchange-audit.jsonl";
48/// Schema of the audit ledger.
49pub const AUDIT_SCHEMA: &str = "leanctx.exchange-audit/v1";
50/// Entries kept (the newest).
51pub const AUDIT_MAX: usize = 2000;
52
53/// Whether `kind` is an exchange (`progress` is a status line, not one).
54pub fn is_exchange(kind: MessageType) -> bool {
55    kind != MessageType::Progress
56}
57
58/// The wire name of `kind` (`finding`, `handoff`, …).
59pub fn kind_name(kind: MessageType) -> String {
60    serde_json::to_value(kind)
61        .ok()
62        .and_then(|v| v.as_str().map(str::to_owned))
63        .unwrap_or_default()
64}
65
66/// Why an exchange is refused: the rule and a reason that never quotes the
67/// content.
68#[derive(Debug, Clone, PartialEq, Eq)]
69pub struct Refusal {
70    pub rule: &'static str,
71    pub why: String,
72}
73
74impl Refusal {
75    pub fn new(rule: &'static str, why: impl Into<String>) -> Self {
76        Self {
77            rule,
78            why: why.into(),
79        }
80    }
81}
82
83impl std::fmt::Display for Refusal {
84    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
85        write!(f, "{} (rule: {})", self.why, self.rule)
86    }
87}
88
89/// Rule 1: a personal account keeps its own memory.
90pub fn account_refusal(org_kind: Option<&str>) -> Option<Refusal> {
91    (org_kind == Some("personal")).then(|| {
92        Refusal::new(
93            "account",
94            "knowledge and tasks are exchanged with a team: this device is connected to a personal account, which keeps its own memory",
95        )
96    })
97}
98
99/// The exchange kinds `policy` lets leave: `Ok(None)` when it does not set
100/// [`KINDS_MEMBER`]; `Err` when the value is not a sorted list of exchange
101/// kinds. Read through JSON so it works whether the protocol types name the
102/// member or keep it among the unknown members.
103pub(crate) fn allowed_kinds(
104    policy: &EffectivePolicyV1,
105) -> Result<Option<BTreeSet<MessageType>>, ()> {
106    let sharing = serde_json::to_value(&policy.sharing).map_err(|_| ())?;
107    let Some(value) = sharing.get(KINDS_MEMBER) else {
108        return Ok(None);
109    };
110    let names = value.as_array().ok_or(())?;
111    let mut kinds = BTreeSet::new();
112    let mut last: Option<&str> = None;
113    for name in names {
114        let name = name.as_str().ok_or(())?;
115        if last.is_some_and(|prev| prev >= name) {
116            return Err(());
117        }
118        last = Some(name);
119        let kind = MessageType::parse(name)
120            .filter(|k| is_exchange(*k))
121            .ok_or(())?;
122        kinds.insert(kind);
123    }
124    Ok(Some(kinds))
125}
126
127/// Whether `vault_id` (UUID or 32 lower hex) is among `allowed`.
128fn vault_listed(allowed: &[String], vault_id: &str) -> bool {
129    let compact: String = vault_id
130        .chars()
131        .filter(|c| *c != '-')
132        .collect::<String>()
133        .to_ascii_lowercase();
134    allowed.iter().any(|v| v == vault_id || *v == compact)
135}
136
137/// Rule 2 on one effective policy: the vault and the kind.
138pub fn policy_refusal(
139    policy: &EffectivePolicyV1,
140    vault_id: &str,
141    kind: MessageType,
142) -> Option<Refusal> {
143    if let Some(allowed) = &policy.sharing.allowed_vaults
144        && !vault_listed(allowed, vault_id)
145    {
146        return Some(Refusal::new(
147            "policy",
148            "the team policy does not allow sharing with this vault (sharing.allowed_vaults)",
149        ));
150    }
151    match allowed_kinds(policy) {
152        Ok(None) => None,
153        Ok(Some(kinds)) if kinds.contains(&kind) => None,
154        Ok(Some(_)) => Some(Refusal::new(
155            "policy",
156            format!(
157                "the team policy does not allow exchanging a {} (sharing.{KINDS_MEMBER})",
158                kind_name(kind)
159            ),
160        )),
161        Err(()) => Some(Refusal::new(
162            "policy",
163            format!(
164                "the team policy's sharing.{KINDS_MEMBER} is not a sorted list of message types; nothing is exchanged until it is repaired"
165            ),
166        )),
167    }
168}
169
170/// Rule 2 against the floor installed under `cloud_data`: an expired or
171/// damaged policy refuses; no installed policy leaves the decision to Cloud.
172pub fn floor_refusal(
173    cloud_data: &Path,
174    vault_id: &str,
175    kind: MessageType,
176    now: lean_ctx_time::UtcDateTime,
177) -> Option<Refusal> {
178    if let Err(why) = crate::effective_policy::sensitive_gate(cloud_data, now) {
179        return Some(Refusal::new("policy", why));
180    }
181    let floor = effective_floor::read(&effective_floor::floor_dir_in(cloud_data)).and_then(
182        |(floor, required)| effective_floor::check(floor.as_deref(), required.as_deref()),
183    );
184    match floor {
185        Ok(None) => None,
186        Ok(Some(floor)) => policy_refusal(floor.policy.for_vault(Some(vault_id)), vault_id, kind),
187        Err(why) => Some(Refusal::new(
188            "policy",
189            format!("{why}; nothing is exchanged until the team policy is repaired"),
190        )),
191    }
192}
193
194/// Rule 3: every field that leaves passes the screen.
195pub fn screen_fields(screen: &mut Screen, fields: &[&str]) -> Result<(), Refusal> {
196    for field in fields.iter().filter(|f| !f.is_empty()) {
197        screen
198            .check(field)
199            .map_err(|blocked| Refusal::new("content", format!("it contains a {blocked}")))?;
200    }
201    Ok(())
202}
203
204/// Every string in `value`, depth first.
205fn strings_of<'a>(value: &'a Value, out: &mut Vec<&'a str>) {
206    match value {
207        Value::String(s) => out.push(s),
208        Value::Array(items) => items.iter().for_each(|v| strings_of(v, out)),
209        Value::Object(map) => map.values().for_each(|v| strings_of(v, out)),
210        _ => {}
211    }
212}
213
214/// The inbound rules for a delivered `message` of an exchange kind (other
215/// messages pass): person rules, the content screen over body and refs,
216/// and the team policy of `vault_id` (when the vault is linked here).
217pub fn inbound_refusal(
218    cloud_data: &Path,
219    screen: &mut Screen,
220    message: &Value,
221    vault_id: Option<&str>,
222    now: lean_ctx_time::UtcDateTime,
223) -> Option<Refusal> {
224    let kind = MessageType::parse(message["type"].as_str()?)?;
225    if !is_exchange(kind) {
226        return None;
227    }
228    let body = &message["body"];
229    if message["sender"]["kind"].as_str() == Some("worker")
230        && let Err(invalid) = super::person_rules::check_agent_body(kind, body)
231    {
232        return Some(Refusal::new("person_rules", invalid.to_string()));
233    }
234    let mut fields = Vec::new();
235    strings_of(body, &mut fields);
236    strings_of(&message["refs"], &mut fields);
237    if let Err(refusal) = screen_fields(screen, &fields) {
238        return Some(refusal);
239    }
240    vault_id.and_then(|vault| floor_refusal(cloud_data, vault, kind, now))
241}
242
243/// What the exchange rules make of one delivered message.
244#[derive(Debug, Clone, PartialEq, Eq)]
245pub enum Delivery {
246    /// Not an exchange from another machine (a replay, a status line, this
247    /// machine's own message coming back): the relay decides as before.
248    Pass,
249    /// An exchange the rules admit, with its audit record.
250    Allowed(Box<Entry>),
251    /// An exchange the rules refuse: only the cursor moves to `seq`.
252    Refused {
253        address: String,
254        seq: u64,
255        entry: Box<Entry>,
256    },
257}
258
259/// The inbound decision for a `message.deliver` (`local_workers`: the
260/// workers of this machine, whose own messages come back and pass).
261#[cfg_attr(not(feature = "http-server"), allow(dead_code))]
262pub(crate) fn delivered(
263    cloud_data: &Path,
264    map: &crate::vault::VaultMap,
265    state: &super::relay_v2::StateV2,
266    message: &Value,
267    local_workers: &BTreeSet<String>,
268    now: lean_ctx_time::UtcDateTime,
269) -> Delivery {
270    let Some((address, seq, record)) = super::relay_v2::new_delivery(map, state, message) else {
271        return Delivery::Pass;
272    };
273    let Some(kind) = message["type"]
274        .as_str()
275        .and_then(MessageType::parse)
276        .filter(|k| is_exchange(*k))
277    else {
278        return Delivery::Pass;
279    };
280    let sender = &message["sender"];
281    let peer = match sender["kind"].as_str() {
282        Some("worker") => sender["worker_id"].as_str().map(str::to_owned),
283        Some("person") => sender["handle"].as_str().map(|h| format!("person:{h}")),
284        _ => None,
285    };
286    if peer.as_ref().is_some_and(|p| local_workers.contains(p)) {
287        return Delivery::Pass;
288    }
289    let mut entry = Entry::now(now, "in", "delivered", kind, &address);
290    entry.msg_id = message["id"].as_str().map(str::to_owned);
291    entry.peer = peer;
292    entry.digest = Some(digest(&message["body"]));
293    let refusal = inbound_refusal(
294        cloud_data,
295        &mut Screen::for_installation(),
296        message,
297        record.map(|r| r.vault_id.as_str()),
298        now,
299    );
300    match refusal {
301        None => Delivery::Allowed(Box::new(entry)),
302        Some(refusal) => {
303            entry.outcome = "dropped".into();
304            Delivery::Refused {
305                address,
306                seq,
307                entry: Box::new(entry.refused_by(&refusal)),
308            }
309        }
310    }
311}
312
313/// `sha256:<hex>` of `body` as canonical JSON: what was exchanged, without
314/// the content.
315pub fn digest(body: &Value) -> String {
316    let canonical = lean_ctx_protocol::cloud::canonical_json(body)
317        .unwrap_or_else(|_| body.to_string().into_bytes());
318    format!("sha256:{}", hex::encode(Sha256::digest(&canonical)))
319}
320
321/// One audit record.
322#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
323pub struct Entry {
324    /// RFC 3339, seconds, UTC.
325    pub at: String,
326    /// `out` | `in`.
327    pub direction: String,
328    /// `queued` | `refused` (out), `delivered` | `dropped` (in).
329    pub outcome: String,
330    /// `finding`, `handoff`, `question`, `offer`, `answer`.
331    pub kind: String,
332    /// `#<workspace>/<vault>`.
333    pub address: String,
334    /// `client_msg_id` (out) or Cloud `msg_…` id (in).
335    #[serde(default, skip_serializing_if = "Option::is_none")]
336    pub msg_id: Option<String>,
337    /// The local agent that sent it (out).
338    #[serde(default, skip_serializing_if = "Option::is_none")]
339    pub agent: Option<String>,
340    /// The other side: addressed worker (out) or sender (in).
341    #[serde(default, skip_serializing_if = "Option::is_none")]
342    pub peer: Option<String>,
343    #[serde(default, skip_serializing_if = "Option::is_none")]
344    pub rule: Option<String>,
345    #[serde(default, skip_serializing_if = "Option::is_none")]
346    pub reason: Option<String>,
347    #[serde(default, skip_serializing_if = "Option::is_none")]
348    pub digest: Option<String>,
349}
350
351/// Longest refusal reason kept in a record (characters): a record stays
352/// small, so the ledger's size follows from its entry count.
353pub const REASON_MAX: usize = 300;
354
355impl Entry {
356    /// An entry stamped at `now`.
357    pub fn now(
358        now: lean_ctx_time::UtcDateTime,
359        direction: &str,
360        outcome: &str,
361        kind: MessageType,
362        address: &str,
363    ) -> Self {
364        Self {
365            at: now.to_rfc3339_opts(lean_ctx_time::SecondsFormat::Secs, true),
366            direction: direction.into(),
367            outcome: outcome.into(),
368            kind: kind_name(kind),
369            address: address.into(),
370            msg_id: None,
371            agent: None,
372            peer: None,
373            rule: None,
374            reason: None,
375            digest: None,
376        }
377    }
378
379    /// The same entry carrying `refusal` (its reason cut to [`REASON_MAX`]).
380    pub fn refused_by(mut self, refusal: &Refusal) -> Self {
381        self.rule = Some(refusal.rule.into());
382        self.reason = Some(refusal.why.chars().take(REASON_MAX).collect());
383        self
384    }
385}
386
387/// The first line of the ledger.
388#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
389struct Header {
390    schema: String,
391}
392
393/// A ledger file this size or larger is compacted to its newest
394/// [`AUDIT_MAX`] entries on the next append.
395pub const COMPACT_BYTES: u64 = 4 << 20;
396
397fn local(path: &Path, e: impl std::fmt::Display) -> CloudError {
398    CloudError::Local(format!("{}: {e}", path.display()))
399}
400
401/// The ledger's header line followed by `entries`, one JSON line each.
402fn ledger_bytes<'a>(entries: impl IntoIterator<Item = &'a Entry>) -> Result<Vec<u8>, CloudError> {
403    let encode = |e: serde_json::Error| CloudError::Local(e.to_string());
404    let mut bytes = serde_json::to_vec(&Header {
405        schema: AUDIT_SCHEMA.into(),
406    })
407    .map_err(encode)?;
408    bytes.push(b'\n');
409    for entry in entries {
410        bytes.extend(serde_json::to_vec(entry).map_err(encode)?);
411        bytes.push(b'\n');
412    }
413    Ok(bytes)
414}
415
416/// Whether the regular file at `path` is an intact ledger: our header
417/// first, and the last append complete (ends with a newline). Reads the
418/// first line and the last byte only.
419fn intact(path: &Path) -> Result<bool, CloudError> {
420    use std::io::{BufRead, Read, Seek, SeekFrom};
421    let mut file = std::fs::File::open(path).map_err(|e| local(path, e))?;
422    let mut last = [0u8; 1];
423    if file.seek(SeekFrom::End(-1)).is_err() || file.read_exact(&mut last).is_err() {
424        return Ok(false);
425    }
426    file.seek(SeekFrom::Start(0)).map_err(|e| local(path, e))?;
427    let mut first = String::new();
428    std::io::BufReader::new(file.take(4096))
429        .read_line(&mut first)
430        .map_err(|e| local(path, e))?;
431    Ok(last[0] == b'\n'
432        && serde_json::from_str::<Header>(first.trim_end()).is_ok_and(|h| h.schema == AUDIT_SCHEMA))
433}
434
435/// Append one line to the existing ledger at `path`; never creates it (a
436/// new ledger is written private by [`write_private`]).
437fn append_line(path: &Path, line: &[u8]) -> Result<u64, CloudError> {
438    use std::io::Write;
439    let mut options = std::fs::OpenOptions::new();
440    options.append(true);
441    let mut file = options.open(path).map_err(|e| local(path, e))?;
442    file.write_all(line).map_err(|e| local(path, e))?;
443    file.sync_data().map_err(|e| local(path, e))?;
444    Ok(file.metadata().map_err(|e| local(path, e))?.len())
445}
446
447/// Append `entry` to the ledger under `data_dir`, under the state lock: one
448/// line is written, the ledger is never rewritten for it. A damaged ledger
449/// is moved aside first and a new one started; a ledger past
450/// [`COMPACT_BYTES`] is compacted to its newest [`AUDIT_MAX`] entries.
451pub fn record(data_dir: &Path, entry: &Entry) -> Result<(), CloudError> {
452    record_bounded(data_dir, entry, COMPACT_BYTES)
453}
454
455pub(crate) fn record_bounded(
456    data_dir: &Path,
457    entry: &Entry,
458    compact_bytes: u64,
459) -> Result<(), CloudError> {
460    let dir = data_dir.join("bus");
461    let _lock = lock_state(&dir, AUDIT_FILE)?;
462    let path = dir.join(AUDIT_FILE);
463    let existing = match std::fs::symlink_metadata(&path) {
464        Ok(meta) if meta.file_type().is_file() => true,
465        Ok(_) => return Err(local(&path, "not a regular file; nothing is recorded")),
466        Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,
467        Err(e) => return Err(local(&path, e)),
468    };
469    if existing && !intact(&path)? {
470        set_aside(&path)?;
471    } else if existing {
472        let mut line = serde_json::to_vec(entry).map_err(|e| CloudError::Local(e.to_string()))?;
473        line.push(b'\n');
474        if append_line(&path, &line)? < compact_bytes {
475            return Ok(());
476        }
477        // Compaction reads every line: a line damaged anywhere (not only
478        // the header or the last append) sets the ledger aside too, so a
479        // damaged ledger never stops recording or grows past the bound.
480        let bytes = std::fs::read(&path).map_err(|e| local(&path, e))?;
481        match parse_entries(&bytes) {
482            Some(kept) => return write_private(&dir, AUDIT_FILE, &ledger_bytes(newest(&kept))?),
483            None => set_aside(&path)?,
484        }
485    }
486    write_private(&dir, AUDIT_FILE, &ledger_bytes([entry])?)
487}
488
489/// Move the damaged ledger at `path` aside; the caller starts a new one.
490fn set_aside(path: &Path) -> Result<(), CloudError> {
491    let moved = crate::state::quarantine(path)?;
492    tracing::warn!(
493        "cloud exchange audit: {} is damaged; moved to {}",
494        path.display(),
495        moved.display()
496    );
497    Ok(())
498}
499
500/// The newest [`AUDIT_MAX`] of `entries`.
501fn newest(entries: &[Entry]) -> &[Entry] {
502    &entries[entries.len().saturating_sub(AUDIT_MAX)..]
503}
504
505/// Every entry of the ledger at `path`, oldest first.
506fn read_entries(path: &Path) -> Result<Vec<Entry>, CloudError> {
507    let bytes = std::fs::read(path).map_err(|e| local(path, e))?;
508    parse_entries(&bytes).ok_or_else(|| CloudError::Local(format!("{} is damaged", path.display())))
509}
510
511/// The entries of ledger `bytes`, oldest first; `None` when any line (the
512/// header included) is damaged.
513fn parse_entries(bytes: &[u8]) -> Option<Vec<Entry>> {
514    let body = std::str::from_utf8(bytes).ok()?.strip_suffix('\n')?;
515    let mut lines = body.split('\n');
516    let header: Header = serde_json::from_str(lines.next()?).ok()?;
517    if header.schema != AUDIT_SCHEMA {
518        return None;
519    }
520    lines
521        .map(|l| serde_json::from_str::<Entry>(l).ok())
522        .collect()
523}
524
525/// The ledger's newest [`AUDIT_MAX`] entries under `data_dir`, oldest first
526/// (none yet: empty).
527pub fn entries(data_dir: &Path) -> Result<Vec<Entry>, CloudError> {
528    let path = data_dir.join("bus").join(AUDIT_FILE);
529    if !path.exists() {
530        return Ok(Vec::new());
531    }
532    let mut all = read_entries(&path)?;
533    let excess = all.len().saturating_sub(AUDIT_MAX);
534    all.drain(..excess);
535    Ok(all)
536}
537
538/// The exchange rules' verdict on one delivered `message`, recorded: `Ok(true)`
539/// when it goes on to the local bus, `Ok(false)` when it was refused and
540/// only the cursor moved. When its audit record cannot be written the
541/// delivery is neither applied nor skipped (`Err`): the cursor stays, so it
542/// comes again.
543#[cfg_attr(not(feature = "http-server"), allow(dead_code))]
544pub(crate) fn admit(
545    cloud_data: &Path,
546    map: &crate::vault::VaultMap,
547    state: &mut super::relay_v2::StateV2,
548    message: &Value,
549    local_workers: &BTreeSet<String>,
550    now: lean_ctx_time::UtcDateTime,
551) -> Result<bool, CloudError> {
552    match delivered(cloud_data, map, state, message, local_workers, now) {
553        Delivery::Pass => Ok(true),
554        Delivery::Allowed(entry) => record(cloud_data, &entry).map(|()| true),
555        Delivery::Refused {
556            address,
557            seq,
558            entry,
559        } => {
560            record(cloud_data, &entry)?;
561            super::relay_v2::skip_delivery(state, &address, seq);
562            Ok(false)
563        }
564    }
565}
566
567#[cfg(test)]
568#[path = "exchange_tests.rs"]
569mod tests;