barycenters 1.0.0

Govern any agent, and see what /admit would have blocked. Shadow mode by default. Zero dependencies (transport injected).
Documentation
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
//! barycenters — govern any agent, and see what `/admit` would have blocked.
//!
//! Ships in **shadow** mode by default: it never blocks anything, it only records what the `/admit`
//! boundary WOULD have refused. Read [`Client::shadow_report`] for the artifact you screenshot.
//! Flipping to [`Mode::Enforce`] (a refusal becomes an error; an unreachable endpoint fails closed)
//! is a deliberate, human act — authority_effect 0 → 1 — not something this library decides.
//!
//! **Zero dependencies.** The HTTP call is injected via the [`Transport`] trait, so you wire your own
//! client (reqwest, ureq, or std) behind it and the crate needs no HTTP dependency of its own.
//!
//! ```ignore
//! let mut c = Client::new(Config { endpoint: Some("https://…".into()), ..Default::default() }, my_transport);
//! let d = c.admit("deploy_prod", "{\"env\":\"production\"}")?; // shadow: never errors; d.would_block tells you
//! println!("{}", c.shadow_report().summary);
//! ```

use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{SystemTime, UNIX_EPOCH};

/// Shadow never blocks; Enforce makes a refusal an error.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Mode {
    Shadow,
    Enforce,
}

/// A raw HTTP response from the injected transport.
pub struct Resp {
    pub status: u16,
    pub body: String,
}

/// The one thing you implement: POST a body to a URL with an idempotency key.
pub trait Transport {
    fn post(&self, url: &str, body: &str, idempotency_key: &str) -> Result<Resp, ()>;
}

/// Client configuration. Use `..Default::default()` for anything you don't set.
pub struct Config {
    pub api_key: Option<String>,
    pub endpoint: Option<String>,
    pub namespace: String,
    pub mode: Mode,
    pub retries: u32,
    pub backoff_ms: u64,
}

impl Default for Config {
    fn default() -> Self {
        Config {
            api_key: None,
            endpoint: std::env::var("ADMIT_ENDPOINT").ok(),
            namespace: "default".to_string(),
            mode: Mode::Shadow,
            retries: 3,
            backoff_ms: 200,
        }
    }
}

/// The result of a single [`Client::admit`] call.
#[derive(Clone, Debug)]
pub struct Decision {
    pub decision: String,
    pub reason_code: Option<String>,
    pub token: Option<String>,
    pub mode: Mode,
    pub would_block: bool,
    pub awaiting: bool,
}

impl Decision {
    pub fn accepted(&self) -> bool {
        self.decision == "ACCEPT"
    }
    pub fn refused(&self) -> bool {
        self.decision == "REFUSE"
    }
    /// Whether this call actually blocked (only ever true in Enforce mode).
    pub fn blocked(&self) -> bool {
        self.mode == Mode::Enforce && self.would_block
    }
}

/// Returned by `admit` in Enforce mode.
#[derive(Debug)]
pub enum AdmitError {
    Refused {
        action: String,
        reason_code: Option<String>,
    },
    /// Enforce mode with no wired endpoint — refusing to run ungoverned.
    Ungoverned,
}

struct Rec {
    action: String,
    would_block: bool,
    reason_code: Option<String>,
    awaiting: bool,
}

/// What `/admit` would have blocked this session.
pub struct ShadowReport {
    pub total: usize,
    pub would_block_count: usize,
    pub awaiting: usize,
    pub would_have_blocked: Vec<(String, Option<String>)>,
    pub summary: String,
}

pub struct Client<T: Transport> {
    cfg: Config,
    transport: T,
    log: Vec<Rec>,
}

static COUNTER: AtomicU64 = AtomicU64::new(0);

impl<T: Transport> Client<T> {
    pub fn new(mut cfg: Config, transport: T) -> Self {
        if let Some(e) = cfg.endpoint.take() {
            cfg.endpoint = Some(e.trim_end_matches('/').to_string());
        }
        Client {
            cfg,
            transport,
            log: Vec::new(),
        }
    }

    /// Ask `/admit` whether an action may proceed. `metadata_json` is a JSON object string (or "{}").
    /// Shadow: never returns a refusal error. Enforce: a refusal returns [`AdmitError::Refused`].
    pub fn admit(&mut self, action: &str, metadata_json: &str) -> Result<Decision, AdmitError> {
        let md = if metadata_json.trim().is_empty() {
            "{}"
        } else {
            metadata_json
        };
        let body = format!(
            "{{\"action\":{},\"namespace\":{},\"metadata\":{}}}",
            json_str(action),
            json_str(&self.cfg.namespace),
            md
        );

        let has_ep = self
            .cfg
            .endpoint
            .as_deref()
            .map(|e| !e.is_empty())
            .unwrap_or(false);
        let raw = if has_ep {
            let ep = self.cfg.endpoint.clone().unwrap();
            self.call(&ep, &body)
        } else {
            Raw {
                decision: "AWAITING".to_string(),
                reason_code: Some("NO_ENDPOINT".to_string()),
                token: None,
            }
        };

        let would_block = raw.decision == "REFUSE";
        let awaiting = raw.decision == "AWAITING";
        self.log.push(Rec {
            action: action.to_string(),
            would_block,
            reason_code: raw.reason_code.clone(),
            awaiting,
        });

        let d = Decision {
            decision: raw.decision.clone(),
            reason_code: raw.reason_code.clone(),
            token: raw.token.clone(),
            mode: self.cfg.mode,
            would_block,
            awaiting,
        };

        if self.cfg.mode == Mode::Enforce {
            if would_block {
                return Err(AdmitError::Refused {
                    action: action.to_string(),
                    reason_code: raw.reason_code,
                });
            }
            if awaiting {
                return Err(AdmitError::Ungoverned);
            }
        }
        Ok(d)
    }

    pub fn shadow_report(&self) -> ShadowReport {
        let total = self.log.len();
        let awaiting = self.log.iter().filter(|r| r.awaiting).count();
        let would_have_blocked: Vec<(String, Option<String>)> = self
            .log
            .iter()
            .filter(|r| r.would_block)
            .map(|r| (r.action.clone(), r.reason_code.clone()))
            .collect();
        let summary = if awaiting == total && total > 0 {
            format!(
                "{} action(s) observed — /admit endpoint not wired yet; set ADMIT_ENDPOINT to see what would be blocked",
                total
            )
        } else {
            format!(
                "{} of {} action(s) would have been blocked by /admit",
                would_have_blocked.len(),
                total
            )
        };
        ShadowReport {
            total,
            would_block_count: would_have_blocked.len(),
            awaiting,
            would_have_blocked,
            summary,
        }
    }

    fn call(&self, endpoint: &str, body: &str) -> Raw {
        let url = format!("{}/admit", endpoint);
        let idem = idempotency_key();
        let mut attempt: u32 = 0;
        loop {
            if attempt > 0 {
                let ms = self.cfg.backoff_ms.saturating_mul(1u64 << (attempt - 1));
                std::thread::sleep(std::time::Duration::from_millis(ms));
            }
            match self.transport.post(&url, body, &idem) {
                Ok(resp) => {
                    // Retry only transient gateway/unavailable; a decision is terminal.
                    if resp.status == 502 || resp.status == 503 || resp.status == 504 {
                        if attempt < self.cfg.retries {
                            attempt += 1;
                            continue;
                        }
                        return unreachable_raw();
                    }
                    let mut decision = extract(&resp.body, "decision").unwrap_or_default();
                    let mut reason_code = extract(&resp.body, "reason_code");
                    if decision.is_empty() {
                        decision = if (200..300).contains(&resp.status) {
                            "ACCEPT".to_string()
                        } else {
                            // An HTTP error with no decision body is NOT an adjudicated REFUSE --
                            // the service never ruled. Report AWAITING honestly (enforce mode still
                            // fails closed at the caller); a fabricated REFUSE would make the shadow
                            // report claim a block the service never made. Matches the JS SDK fix and
                            // this SDK's README ("-> AWAITING; never fabricates a block it can't prove").
                            if reason_code.is_none() {
                                reason_code = Some(format!("HTTP_{}", resp.status));
                            }
                            "AWAITING".to_string()
                        };
                    }
                    if decision == "ACCEPT_ESCROW" {
                        decision = "ACCEPT".to_string();
                    }
                    return Raw {
                        decision: decision.to_uppercase(),
                        reason_code,
                        token: extract(&resp.body, "token"),
                    };
                }
                Err(_) => {
                    if attempt < self.cfg.retries {
                        attempt += 1;
                        continue;
                    }
                    return unreachable_raw();
                }
            }
        }
    }
}

struct Raw {
    decision: String,
    reason_code: Option<String>,
    token: Option<String>,
}

fn unreachable_raw() -> Raw {
    Raw {
        decision: "AWAITING".to_string(),
        reason_code: Some("UNREACHABLE".to_string()),
        token: None,
    }
}

fn json_str(s: &str) -> String {
    let esc = s.replace('\\', "\\\\").replace('"', "\\\"");
    format!("\"{}\"", esc)
}

/// Minimal, dependency-free extraction of a JSON string field `"key":"value"`. Returns None for a
/// missing key or a non-string (e.g. null) value.
fn extract(json: &str, key: &str) -> Option<String> {
    let pat = format!("\"{}\"", key);
    let i = json.find(&pat)? + pat.len();
    let rest = &json[i..];
    let colon = rest.find(':')?;
    let after = rest[colon + 1..].trim_start();
    let after = after.strip_prefix('"')?;
    let end = after.find('"')?;
    Some(after[..end].to_string())
}

fn idempotency_key() -> String {
    let n = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_nanos())
        .unwrap_or(0);
    let c = COUNTER.fetch_add(1, Ordering::Relaxed);
    format!("idem_{:x}_{:x}", n, c)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::cell::{Cell, RefCell};
    use std::collections::HashSet;
    use std::rc::Rc;

    struct Fake;
    impl Transport for Fake {
        fn post(&self, _url: &str, body: &str, _idem: &str) -> Result<Resp, ()> {
            if body.contains("prod") {
                Ok(Resp {
                    status: 403,
                    body: "{\"decision\":\"REFUSE\",\"reason_code\":\"POLICY_DENIED\"}".to_string(),
                })
            } else {
                Ok(Resp {
                    status: 200,
                    body: "{\"decision\":\"ACCEPT\",\"token\":\"t\"}".to_string(),
                })
            }
        }
    }

    fn client(mode: Mode) -> Client<Fake> {
        Client::new(
            Config {
                endpoint: Some("https://x".to_string()),
                mode,
                ..Default::default()
            },
            Fake,
        )
    }

    #[test]
    fn shadow_never_blocks_even_on_refuse() {
        let mut c = client(Mode::Shadow);
        let d = c.admit("deploy_prod", "{}").unwrap();
        assert!(d.refused() && d.would_block && !d.blocked());
    }

    #[test]
    fn the_shadow_report() {
        let mut c = client(Mode::Shadow);
        let _ = c.admit("read_config", "{}");
        let _ = c.admit("deploy_prod", "{}");
        let _ = c.admit("delete_prod_db", "{}");
        let r = c.shadow_report();
        assert_eq!(r.total, 3);
        assert_eq!(r.would_block_count, 2);
        assert_eq!(
            r.summary,
            "2 of 3 action(s) would have been blocked by /admit"
        );
    }

    #[test]
    fn enforce_refusal_is_an_error() {
        let mut c = client(Mode::Enforce);
        match c.admit("deploy_prod", "{}") {
            Err(AdmitError::Refused { .. }) => {}
            other => panic!("want Refused, got {:?}", other),
        }
        assert!(c.admit("read_config", "{}").unwrap().accepted());
    }

    #[test]
    fn no_endpoint_is_honest_awaiting() {
        let mut c = Client::new(
            Config {
                endpoint: None,
                ..Default::default()
            },
            Fake,
        );
        let d = c.admit("deploy_prod", "{}").unwrap();
        assert!(d.awaiting && !d.would_block);
    }

    struct Flaky {
        calls: Rc<Cell<u32>>,
        keys: Rc<RefCell<HashSet<String>>>,
    }
    impl Transport for Flaky {
        fn post(&self, _url: &str, _body: &str, idem: &str) -> Result<Resp, ()> {
            self.keys.borrow_mut().insert(idem.to_string());
            let c = self.calls.get() + 1;
            self.calls.set(c);
            if c < 3 {
                Ok(Resp {
                    status: 503,
                    body: String::new(),
                })
            } else {
                Ok(Resp {
                    status: 200,
                    body: "{\"decision\":\"ACCEPT\"}".to_string(),
                })
            }
        }
    }

    #[test]
    fn retries_transient_503_under_one_idempotency_key() {
        let calls = Rc::new(Cell::new(0u32));
        let keys = Rc::new(RefCell::new(HashSet::new()));
        let f = Flaky {
            calls: calls.clone(),
            keys: keys.clone(),
        };
        let mut c = Client::new(
            Config {
                endpoint: Some("https://x".to_string()),
                backoff_ms: 1,
                retries: 3,
                ..Default::default()
            },
            f,
        );
        let d = c.admit("read_config", "{}").unwrap();
        assert!(d.accepted());
        assert_eq!(calls.get(), 3);
        assert_eq!(keys.borrow().len(), 1); // at-most-once
    }
}