sim-lib-core 0.2.0

Shared manifest and registry installation substrate for SIM libraries.
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
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
//! Explicit read-eval admission through one diminished gate.

mod config;
mod decision;

use std::{fmt, sync::Arc};

use sim_codec::{Input, decode_with_codec};
use sim_kernel::{
    AbiVersion, CapabilityName, CapabilitySet, Cx, Datum, Diagnostic, Error, Event, Export, Expr,
    Lib, LibManifest, LibTarget, Linker, LoadCx, Object, ReadPolicy, Ref, Result, Shape, ShapeId,
    Symbol, Value, Version, diminish, read_eval_capability,
};
use sim_shape::expected_shape_diagnostic;

pub use config::{
    ConfigEvalNode, HostConfigEvalOptIn, config_eval_node_symbol, config_eval_origin_tag,
    parse_config_eval_node, realize_config_expr,
};
pub use decision::{ReadEvalDecision, ReadEvalOutcome, read_eval_decision_run};

#[cfg(test)]
trait GrantOutcome {
    fn expect_granted(self);
}

#[cfg(test)]
impl GrantOutcome for () {
    fn expect_granted(self) {}
}

#[cfg(test)]
impl GrantOutcome for Result<()> {
    fn expect_granted(self) {
        self.unwrap();
    }
}

#[cfg(test)]
macro_rules! expect_granted {
    ($grant:expr) => {{
        #[allow(clippy::let_unit_value)]
        let grant_result = $grant;
        #[allow(clippy::unit_arg)]
        grant_result.expect_granted();
    }};
}

/// Open origin data for an explicit read-eval request.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RequestOrigin {
    /// Open tag for the request origin, such as `config/node` or `repl`.
    pub tag: Symbol,
    /// Optional origin detail carried as data for callers and ledger records.
    pub detail: Option<Expr>,
}

impl RequestOrigin {
    /// Builds origin data from a tag with no detail.
    pub fn new(tag: Symbol) -> Self {
        Self { tag, detail: None }
    }

    /// Builds origin data from a tag and detail expression.
    pub fn with_detail(tag: Symbol, detail: Expr) -> Self {
        Self {
            tag,
            detail: Some(detail),
        }
    }
}

/// Source accepted by the read-eval broker.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ReadEvalSource {
    /// Decode this text through the request codec before evaluation.
    Text(String),
    /// Decode these bytes through the request codec before evaluation.
    Bytes(Vec<u8>),
    /// Evaluate an already-decoded expression.
    Expr(Expr),
}

/// Immutable host authority shared by requests that load or evaluate source.
///
/// Construction is deliberately available only from trusted Rust code. Source
/// data has no decoder or read-constructor for this value, and its data
/// projection omits the trusted read policy.
#[derive(Clone, PartialEq, Eq)]
pub struct SourceAuthority {
    read_policy: ReadPolicy,
    requires: Vec<CapabilityName>,
    allow: CapabilitySet,
}

impl fmt::Debug for SourceAuthority {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("SourceAuthority")
            .field("read_policy", &"<redacted>")
            .field("requires", &self.requires)
            .field("allow", &self.allow)
            .finish()
    }
}

impl SourceAuthority {
    /// Builds authority after checking that its read policy admits explicit
    /// evaluation. Required powers retain caller order; allowed powers retain
    /// set semantics.
    pub fn new(
        read_policy: ReadPolicy,
        requires: Vec<CapabilityName>,
        allow: CapabilitySet,
    ) -> Result<Self> {
        read_policy.require(&read_eval_capability())?;
        Ok(Self {
            read_policy,
            requires,
            allow,
        })
    }

    /// Returns the trusted policy governing source decoding.
    pub fn read_policy(&self) -> &ReadPolicy {
        &self.read_policy
    }

    /// Returns the caller powers required before source evaluation.
    pub fn requires(&self) -> &[CapabilityName] {
        &self.requires
    }

    /// Returns the maximum powers allowed during source evaluation.
    pub fn allow(&self) -> &CapabilitySet {
        &self.allow
    }

    /// Projects authority for decision data without exposing read-policy
    /// trust or capability internals.
    pub fn decision_datum(&self) -> Datum {
        Datum::Node {
            tag: Symbol::qualified("source", "authority"),
            fields: vec![
                (
                    Symbol::new("requires"),
                    capability_names_datum(self.requires()),
                ),
                (
                    Symbol::new("allow"),
                    capability_names_datum(self.allow().iter()),
                ),
                (
                    Symbol::new("read-policy"),
                    Datum::Symbol(Symbol::new("redacted")),
                ),
            ],
        }
    }
}

/// A single explicit, host-authorized read-eval admission request.
pub struct ReadEvalRequest {
    /// Open origin data describing who asked for eval.
    pub origin: RequestOrigin,
    /// Codec symbol used to decode text or bytes sources.
    pub codec: Symbol,
    /// Source to decode and evaluate, or an already-decoded expression.
    pub source: ReadEvalSource,
    /// Trusted host authority governing source admission and evaluation.
    pub authority: SourceAuthority,
    /// Shape the evaluated result must satisfy before it is admitted.
    pub expected_shape: Arc<dyn Shape>,
}

impl ReadEvalRequest {
    /// Builds a request whose source authority is explicit and indivisible.
    pub fn new(
        origin: RequestOrigin,
        codec: Symbol,
        source: ReadEvalSource,
        authority: SourceAuthority,
        expected_shape: Arc<dyn Shape>,
    ) -> Self {
        Self {
            origin,
            codec,
            source,
            authority,
            expected_shape,
        }
    }
}

// sim-non-citizen(reason = "host admission gate object; explicit request data is not a read-constructor surface", kind = "runtime", descriptor = "")
/// The one runtime admission gate for explicit diminished read-eval.
#[derive(Clone, Default)]
pub struct ReadEvalBroker {
    ledger: decision::ReadEvalLedger,
}

/// The value-or-error and the single ledger event produced by one admission.
pub struct ReadEvalAdmission {
    /// Evaluation result returned to the caller.
    pub result: Result<Value>,
    /// Decision recorded for this admission.
    pub decision: ReadEvalDecision,
    /// Exact event carrying `decision` in the broker ledger.
    pub event: Event,
}

impl ReadEvalBroker {
    /// Creates a broker with an empty decision ledger.
    pub fn new() -> Self {
        Self::default()
    }

    /// Admits one explicit read-eval request or fails closed.
    pub fn admit(&self, cx: &mut Cx, request: ReadEvalRequest) -> Result<Value> {
        self.admit_with_event(cx, request)?.result
    }

    /// Admits one request and returns the exact decision event alongside its result.
    pub fn admit_with_event(
        &self,
        cx: &mut Cx,
        request: ReadEvalRequest,
    ) -> Result<ReadEvalAdmission> {
        if let Err(err) = request
            .authority
            .read_policy()
            .require(&read_eval_capability())
        {
            let outcome = match err {
                Error::TrustDenied { .. } => ReadEvalOutcome::TrustDenied,
                _ => ReadEvalOutcome::CapDenied,
            };
            return self.admission(cx, &request, &CapabilitySet::new(), outcome, Err(err));
        }
        if let Err(err) = cx.require_all(request.authority.requires()) {
            return self.admission(
                cx,
                &request,
                &CapabilitySet::new(),
                ReadEvalOutcome::MissingPower,
                Err(err),
            );
        }

        let active = diminish(cx.capabilities(), request.authority.allow());
        let expr = match cx.with_capabilities(active.clone(), |cx| {
            decode_source(
                cx,
                &request.codec,
                request.source.clone(),
                request.authority.read_policy().clone(),
            )
        }) {
            Ok(expr) => expr,
            Err(err) => {
                return self.admission(
                    cx,
                    &request,
                    &active,
                    ReadEvalOutcome::DecodeFailed,
                    Err(err),
                );
            }
        };
        let value = match cx.with_capabilities(active.clone(), |cx| cx.eval_expr(expr)) {
            Ok(value) => value,
            Err(err) => {
                return self.admission(
                    cx,
                    &request,
                    &active,
                    ReadEvalOutcome::EvalFailed,
                    Err(err),
                );
            }
        };

        let matched = match request.expected_shape.check_value(cx, value.clone()) {
            Ok(matched) => matched,
            Err(err) => {
                return self.admission(
                    cx,
                    &request,
                    &active,
                    ReadEvalOutcome::ShapeError,
                    Err(err),
                );
            }
        };
        if matched.accepted {
            return self.admission(cx, &request, &active, ReadEvalOutcome::Admitted, Ok(value));
        }

        let diagnostics =
            match shape_diagnostics(cx, request.expected_shape.as_ref(), matched.diagnostics) {
                Ok(diagnostics) => diagnostics,
                Err(err) => {
                    return self.admission(
                        cx,
                        &request,
                        &active,
                        ReadEvalOutcome::ShapeError,
                        Err(err),
                    );
                }
            };
        self.admission(
            cx,
            &request,
            &active,
            ReadEvalOutcome::ShapeDenied,
            Err(Error::WrongShape {
                expected: request.expected_shape.id().unwrap_or(ShapeId(0)),
                diagnostics,
            }),
        )
    }

    /// Returns read-eval decisions recorded in the broker's default run.
    pub fn decisions(&self, cx: &Cx) -> Result<Vec<ReadEvalDecision>> {
        self.ledger.decisions(cx)
    }

    /// Returns read-eval decisions recorded for `run`.
    pub fn decisions_for_run(&self, cx: &Cx, run: &Ref) -> Result<Vec<ReadEvalDecision>> {
        self.ledger.decisions_for_run(cx, run)
    }

    /// Returns raw ledger events recorded for `run`.
    pub fn events_for_run(&self, run: &Ref) -> Result<Vec<Event>> {
        self.ledger.events_for_run(run)
    }

    fn admission(
        &self,
        cx: &mut Cx,
        request: &ReadEvalRequest,
        active: &CapabilitySet,
        outcome: ReadEvalOutcome,
        result: Result<Value>,
    ) -> Result<ReadEvalAdmission> {
        let decision = decision::decision_from_request(request, active, outcome);
        let event = self.ledger.record(cx, &decision)?;
        Ok(ReadEvalAdmission {
            result,
            decision,
            event,
        })
    }
}

/// Reusable policy for dynamic source evaluated through a named codec.
///
/// The policy fixes only the source provenance and codec. Authority and the
/// expected result shape remain explicit inputs to every evaluation, so a
/// guest-language wrapper cannot accidentally retain or widen either one.
/// Callers that need origin detail must provide it in [`RequestOrigin`] when
/// constructing the policy.
#[derive(Clone)]
pub struct DynamicSourcePolicy {
    broker: ReadEvalBroker,
    codec: Symbol,
    origin: RequestOrigin,
}

impl DynamicSourcePolicy {
    /// Builds a policy with its own decision ledger.
    pub fn new(codec: Symbol, origin: RequestOrigin) -> Self {
        Self::with_broker(ReadEvalBroker::new(), codec, origin)
    }

    /// Builds a policy over an existing broker.
    ///
    /// Cloned brokers share their ledger, allowing several origin/codec
    /// policies to expose one ordered decision stream.
    pub fn with_broker(broker: ReadEvalBroker, codec: Symbol, origin: RequestOrigin) -> Self {
        Self {
            broker,
            codec,
            origin,
        }
    }

    /// Evaluates text decoded through this policy's codec.
    pub fn evaluate_text(
        &self,
        cx: &mut Cx,
        text: impl Into<String>,
        authority: SourceAuthority,
        expected_shape: Arc<dyn Shape>,
    ) -> Result<Value> {
        self.evaluate(
            cx,
            ReadEvalSource::Text(text.into()),
            authority,
            expected_shape,
        )
    }

    /// Evaluates bytes decoded through this policy's codec.
    pub fn evaluate_bytes(
        &self,
        cx: &mut Cx,
        bytes: impl Into<Vec<u8>>,
        authority: SourceAuthority,
        expected_shape: Arc<dyn Shape>,
    ) -> Result<Value> {
        self.evaluate(
            cx,
            ReadEvalSource::Bytes(bytes.into()),
            authority,
            expected_shape,
        )
    }

    /// Evaluates an already-decoded expression through the same admission gate.
    pub fn evaluate_expr(
        &self,
        cx: &mut Cx,
        expr: Expr,
        authority: SourceAuthority,
        expected_shape: Arc<dyn Shape>,
    ) -> Result<Value> {
        self.evaluate(cx, ReadEvalSource::Expr(expr), authority, expected_shape)
    }

    /// Evaluates any supported source form through the shared broker law.
    pub fn evaluate(
        &self,
        cx: &mut Cx,
        source: ReadEvalSource,
        authority: SourceAuthority,
        expected_shape: Arc<dyn Shape>,
    ) -> Result<Value> {
        self.broker.admit(
            cx,
            ReadEvalRequest::new(
                self.origin.clone(),
                self.codec.clone(),
                source,
                authority,
                expected_shape,
            ),
        )
    }

    /// Returns decisions recorded in the policy's default run.
    pub fn decisions(&self, cx: &Cx) -> Result<Vec<ReadEvalDecision>> {
        self.broker.decisions(cx)
    }

    /// Returns decisions recorded for `run`.
    pub fn decisions_for_run(&self, cx: &Cx, run: &Ref) -> Result<Vec<ReadEvalDecision>> {
        self.broker.decisions_for_run(cx, run)
    }

    /// Returns raw ledger events recorded for `run`.
    pub fn events_for_run(&self, run: &Ref) -> Result<Vec<Event>> {
        self.broker.events_for_run(run)
    }
}

impl Object for ReadEvalBroker {
    fn display(&self, _cx: &mut Cx) -> Result<String> {
        Ok("#<read-eval-broker>".to_owned())
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

impl sim_kernel::ObjectCompat for ReadEvalBroker {
    fn class(&self, cx: &mut Cx) -> Result<sim_kernel::ClassRef> {
        cx.factory().class_stub(
            sim_kernel::ClassId(0),
            Symbol::qualified("read-eval", "Broker"),
        )
    }
}

/// Returns the broker value symbol exported by [`ReadEvalBrokerLib`].
pub fn read_eval_broker_symbol() -> Symbol {
    Symbol::qualified("read-eval", "broker")
}

/// Returns the manifest id for the read-eval broker library.
pub fn read_eval_broker_lib_id() -> Symbol {
    Symbol::qualified("sim", "read-eval-broker")
}

/// Loadable library that registers the read-eval broker value.
pub struct ReadEvalBrokerLib;

impl Lib for ReadEvalBrokerLib {
    fn manifest(&self) -> LibManifest {
        LibManifest {
            id: read_eval_broker_lib_id(),
            version: Version(env!("CARGO_PKG_VERSION").to_owned()),
            abi: AbiVersion { major: 0, minor: 1 },
            target: LibTarget::HostRegistered,
            requires: Vec::new(),
            capabilities: Vec::new(),
            exports: vec![Export::Value {
                symbol: read_eval_broker_symbol(),
            }],
        }
    }

    fn load(&self, cx: &mut LoadCx, linker: &mut Linker<'_>) -> Result<()> {
        linker.value(
            read_eval_broker_symbol(),
            cx.factory().opaque(Arc::new(ReadEvalBroker::new()))?,
        )?;
        Ok(())
    }
}

/// Installs the read-eval broker library if it is not already loaded.
pub fn install_read_eval_broker(cx: &mut Cx) -> Result<bool> {
    crate::install_once(cx, &ReadEvalBrokerLib)
}

fn decode_source(
    cx: &mut Cx,
    codec: &Symbol,
    source: ReadEvalSource,
    read_policy: ReadPolicy,
) -> Result<Expr> {
    match source {
        ReadEvalSource::Text(text) => decode_with_codec(cx, codec, Input::Text(text), read_policy),
        ReadEvalSource::Bytes(bytes) => {
            decode_with_codec(cx, codec, Input::Bytes(bytes), read_policy)
        }
        ReadEvalSource::Expr(expr) => Ok(expr),
    }
}

fn capability_names_datum<'a>(capabilities: impl IntoIterator<Item = &'a CapabilityName>) -> Datum {
    Datum::Vector(
        capabilities
            .into_iter()
            .map(|capability| Datum::String(capability.as_str().to_owned()))
            .collect(),
    )
}

fn shape_diagnostics(
    cx: &mut Cx,
    shape: &dyn Shape,
    diagnostics: Vec<Diagnostic>,
) -> Result<Vec<Diagnostic>> {
    if !diagnostics.is_empty() {
        return Ok(diagnostics);
    }
    let expected = match shape.symbol() {
        Some(symbol) => symbol.to_string(),
        None => shape.describe(cx)?.name,
    };
    Ok(vec![expected_shape_diagnostic(
        expected,
        "read-eval result",
    )])
}

#[cfg(test)]
mod config_tests;

#[cfg(test)]
mod ledger_tests;

#[cfg(test)]
mod tests;