lion-core 0.3.0

Lion microkernel — production types, state machine, and kernel API
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
// Copyright (C) 2026 HaiyangLi
// SPDX-License-Identifier: AGPL-3.0-or-later
//! Lion Step Plugin Internal
//!
//! Corresponds to: Lion/Step/PluginInternal.lean
//!
//! Plugin-internal computation (sandboxed, untrusted).

use crate::state::State;
use crate::types::{MemAddr, PluginId, Size};

use super::{PluginPrecondition, StepError};

/// Plugin internal computation descriptor
///
/// Corresponds to Lean: `structure PluginInternal`
///
/// Describes what a plugin's internal WASM computation does:
/// - Memory regions read
/// - Memory regions written
/// - Whether to consume from mailbox
#[derive(Debug, Clone, Default)]
pub struct PluginInternal {
    /// Memory regions read
    ///
    /// Corresponds to Lean: `reads : List (MemAddr x Size)`
    pub reads: Vec<(MemAddr, Size)>,

    /// Memory regions written
    ///
    /// Corresponds to Lean: `writes : List (MemAddr x Size)`
    pub writes: Vec<(MemAddr, Size)>,

    /// Whether to consume from mailbox
    ///
    /// Corresponds to Lean: `consume_mailbox : Bool`
    pub consume_mailbox: bool,
}

impl PluginInternal {
    /// Create a new plugin internal computation descriptor
    pub fn new(
        reads: Vec<(MemAddr, Size)>,
        writes: Vec<(MemAddr, Size)>,
        consume_mailbox: bool,
    ) -> Self {
        PluginInternal {
            reads,
            writes,
            consume_mailbox,
        }
    }

    /// Create a computation that just computes (no I/O)
    pub fn compute() -> Self {
        PluginInternal {
            reads: Vec::new(),
            writes: Vec::new(),
            consume_mailbox: false,
        }
    }

    /// Create a computation that reads memory
    pub fn with_reads(reads: Vec<(MemAddr, Size)>) -> Self {
        PluginInternal {
            reads,
            writes: Vec::new(),
            consume_mailbox: false,
        }
    }

    /// Create a computation that writes memory
    pub fn with_writes(writes: Vec<(MemAddr, Size)>) -> Self {
        PluginInternal {
            reads: Vec::new(),
            writes,
            consume_mailbox: false,
        }
    }

    /// Check preconditions for plugin internal execution
    ///
    /// Corresponds to Lean: `def plugin_internal_pre`
    ///
    /// Preconditions:
    /// 1. Plugin is not blocked on another actor
    /// 2. Read regions are in bounds
    /// 3. Write regions are in bounds
    /// 4. If consuming mailbox, mailbox must not be empty
    ///
    /// # Errors
    ///
    /// Returns `StepError::PluginNotFound` if the plugin does not exist.
    /// Returns `StepError::PluginPreconditionFailed` if the plugin's actor is blocked.
    /// Returns `StepError::PluginPreconditionFailed` if a read region is out of bounds.
    /// Returns `StepError::PluginPreconditionFailed` if a write region is out of bounds.
    /// Returns `StepError::PluginPreconditionFailed` if consuming mailbox but the mailbox is empty.
    pub fn check_preconditions(&self, state: &State, pid: PluginId) -> Result<(), StepError> {
        // Check plugin exists
        let plugin = state
            .get_plugin(pid)
            .ok_or(StepError::PluginNotFound(pid))?;

        // Check not blocked
        if let Some(actor) = state.get_actor(pid) {
            if actor.is_blocked() {
                return Err(StepError::PluginPreconditionFailed(
                    PluginPrecondition::Blocked {
                        pid,
                        blocked_on: actor.blocked_on(),
                    },
                ));
            }
        }

        // Check read regions in bounds
        if let Some(err) = self.find_oob_read(plugin) {
            return Err(err);
        }

        // Check write regions in bounds
        if let Some(err) = self.find_oob_write(plugin) {
            return Err(err);
        }

        // Check mailbox if consuming
        if self.consume_mailbox {
            if let Some(actor) = state.get_actor(pid) {
                if !actor.can_receive() {
                    return Err(StepError::PluginPreconditionFailed(
                        PluginPrecondition::MailboxEmpty,
                    ));
                }
            }
        }

        Ok(())
    }

    /// Helper: find first out-of-bounds read region
    fn find_oob_read(&self, plugin: &crate::state::PluginState) -> Option<StepError> {
        self.reads.iter().find_map(|&(addr, size)| {
            if plugin.memory().addr_in_bounds(addr, size) {
                None
            } else {
                Some(StepError::PluginPreconditionFailed(
                    PluginPrecondition::ReadOutOfBounds {
                        addr,
                        size,
                        bounds: plugin.memory_bounds(),
                    },
                ))
            }
        })
    }

    /// Helper: find first out-of-bounds write region
    fn find_oob_write(&self, plugin: &crate::state::PluginState) -> Option<StepError> {
        self.writes.iter().find_map(|&(addr, size)| {
            if plugin.memory().addr_in_bounds(addr, size) {
                None
            } else {
                Some(StepError::PluginPreconditionFailed(
                    PluginPrecondition::WriteOutOfBounds {
                        addr,
                        size,
                        bounds: plugin.memory_bounds(),
                    },
                ))
            }
        })
    }
}

// ============== FRAME THEOREMS ==============
//
// These correspond to Lean's comprehensive frame theorem:
// plugin_internal_comprehensive_frame
//
// Plugin internal execution (WASM sandbox) only affects:
// - The executing plugin's memory contents
// - The executing plugin's local state
//
// It CANNOT modify:
// - Other plugins' state
// - Kernel state
// - Actor state (except mailbox consumption)
// - Resources
// - Workflows
// - Ghost state
// - Time
// - Security-critical fields (level, heldCaps, memory.bounds)

#[cfg(test)]
mod tests {
    use super::*;
    use crate::state::{ActorRuntime, Message, PluginState};
    use crate::types::SecurityLevel;

    #[test]
    fn test_plugin_internal_default() {
        let pi = PluginInternal::default();
        assert!(pi.reads.is_empty());
        assert!(pi.writes.is_empty());
        assert!(!pi.consume_mailbox);
    }

    #[test]
    fn test_plugin_internal_compute() {
        let pi = PluginInternal::compute();
        assert!(pi.reads.is_empty());
        assert!(pi.writes.is_empty());
        assert!(!pi.consume_mailbox);
    }

    #[test]
    fn test_plugin_internal_with_reads() {
        let pi = PluginInternal::with_reads(vec![(0, 100), (200, 50)]);
        assert_eq!(pi.reads.len(), 2);
        assert!(pi.writes.is_empty());
    }

    #[test]
    fn test_plugin_internal_with_writes() {
        let pi = PluginInternal::with_writes(vec![(0, 100)]);
        assert!(pi.reads.is_empty());
        assert_eq!(pi.writes.len(), 1);
    }

    #[test]
    fn test_check_preconditions_plugin_not_found() {
        let state = State::empty();
        let pi = PluginInternal::compute();

        let result = pi.check_preconditions(&state, 1);
        assert!(matches!(result, Err(StepError::PluginNotFound(1))));
    }

    #[test]
    fn test_check_preconditions_blocked() {
        let mut state = State::empty();
        let _ = state.insert_plugin(1, PluginState::empty(SecurityLevel::Public, 1024));

        let mut actor = ActorRuntime::empty(10);
        actor.set_blocked_mut(42);
        state.insert_actor(1, actor).unwrap();

        let pi = PluginInternal::compute();
        let result = pi.check_preconditions(&state, 1);

        assert!(matches!(
            result,
            Err(StepError::PluginPreconditionFailed(_))
        ));
    }

    #[test]
    fn test_check_preconditions_read_out_of_bounds() {
        let mut state = State::empty();
        let _ = state.insert_plugin(1, PluginState::empty(SecurityLevel::Public, 100));

        // Read region beyond memory bounds
        let pi = PluginInternal::with_reads(vec![(0, 200)]);
        let result = pi.check_preconditions(&state, 1);

        assert!(matches!(
            result,
            Err(StepError::PluginPreconditionFailed(_))
        ));
    }

    #[test]
    fn test_check_preconditions_write_out_of_bounds() {
        let mut state = State::empty();
        let _ = state.insert_plugin(1, PluginState::empty(SecurityLevel::Public, 100));

        // Write region beyond memory bounds
        let pi = PluginInternal::with_writes(vec![(50, 100)]);
        let result = pi.check_preconditions(&state, 1);

        assert!(matches!(
            result,
            Err(StepError::PluginPreconditionFailed(_))
        ));
    }

    #[test]
    fn test_check_preconditions_consume_empty_mailbox() {
        let mut state = State::empty();
        let _ = state.insert_plugin(1, PluginState::empty(SecurityLevel::Public, 1024));
        let _ = state.insert_actor(1, ActorRuntime::empty(10));

        let pi = PluginInternal {
            reads: Vec::new(),
            writes: Vec::new(),
            consume_mailbox: true,
        };
        let result = pi.check_preconditions(&state, 1);

        assert!(matches!(
            result,
            Err(StepError::PluginPreconditionFailed(_))
        ));
    }

    #[test]
    fn test_check_preconditions_success() {
        let mut state = State::empty();
        let _ = state.insert_plugin(1, PluginState::empty(SecurityLevel::Public, 1024));
        let _ = state.insert_actor(1, ActorRuntime::empty(10));

        let pi = PluginInternal::with_reads(vec![(0, 100), (500, 200)]);
        let result = pi.check_preconditions(&state, 1);

        assert!(result.is_ok());
    }

    #[test]
    fn test_check_preconditions_consume_non_empty_mailbox() {
        let mut state = State::empty();
        let _ = state.insert_plugin(1, PluginState::empty(SecurityLevel::Public, 1024));

        let mut actor = ActorRuntime::empty(10);
        let msg = Message::new(1, 2, 1, SecurityLevel::Public, vec![]);
        actor.enqueue_pending_mut(msg);
        let _ = actor.deliver_mut();
        state.insert_actor(1, actor).unwrap();

        let pi = PluginInternal {
            reads: Vec::new(),
            writes: Vec::new(),
            consume_mailbox: true,
        };
        let result = pi.check_preconditions(&state, 1);

        assert!(result.is_ok());
    }

    // ============== FRAME PROPERTY TESTS ==============

    #[test]
    fn test_frame_other_plugins_unchanged() {
        // Corresponds to Lean: plugin_internal_frame
        // Other plugins should be unchanged after plugin internal execution
        let mut state = State::empty();
        let _ = state.insert_plugin(1, PluginState::empty(SecurityLevel::Public, 1024));
        let _ = state.insert_plugin(2, PluginState::empty(SecurityLevel::Secret, 2048));
        let _ = state.insert_actor(1, ActorRuntime::empty(10));

        let initial_plugin2 = state.get_plugin(2).cloned();

        // Execute plugin 1 internal
        let step = super::super::Step::PluginInternal {
            pid: 1,
            pi: PluginInternal::compute(),
        };
        let new_state = step.execute(&state).expect("should succeed");

        // Plugin 2 should be unchanged
        assert_eq!(new_state.get_plugin(2), initial_plugin2.as_ref());
    }

    #[test]
    fn test_frame_kernel_unchanged() {
        // Corresponds to Lean: plugin_internal_kernel_unchanged
        let mut state = State::empty();
        let _ = state.insert_plugin(1, PluginState::empty(SecurityLevel::Public, 1024));
        let _ = state.insert_actor(1, ActorRuntime::empty(10));

        let initial_kernel_now = state.kernel().now();

        let step = super::super::Step::PluginInternal {
            pid: 1,
            pi: PluginInternal::compute(),
        };
        let new_state = step.execute(&state).expect("should succeed");

        // Kernel time should be unchanged
        assert_eq!(new_state.kernel().now(), initial_kernel_now);
    }

    #[test]
    fn test_frame_time_unchanged() {
        // Corresponds to Lean: plugin_internal_time_unchanged
        let mut state = State::empty();
        let _ = state.insert_plugin(1, PluginState::empty(SecurityLevel::Public, 1024));
        let _ = state.insert_actor(1, ActorRuntime::empty(10));

        let initial_time = state.time();

        let step = super::super::Step::PluginInternal {
            pid: 1,
            pi: PluginInternal::compute(),
        };
        let new_state = step.execute(&state).expect("should succeed");

        // Time should be unchanged
        assert_eq!(new_state.time(), initial_time);
    }

    #[test]
    fn test_security_invariant_level_preserved() {
        // Corresponds to Lean: plugin_internal_level_preserved
        let mut state = State::empty();
        let _ = state.insert_plugin(1, PluginState::empty(SecurityLevel::Confidential, 1024));
        let _ = state.insert_actor(1, ActorRuntime::empty(10));

        let step = super::super::Step::PluginInternal {
            pid: 1,
            pi: PluginInternal::with_writes(vec![(0, 100)]),
        };
        let new_state = step.execute(&state).expect("should succeed");

        // Security level should be preserved
        assert_eq!(new_state.plugin_level(1), Some(SecurityLevel::Confidential));
    }

    #[test]
    fn test_security_invariant_caps_preserved() {
        // Corresponds to Lean: plugin_internal_caps_preserved
        let mut state = State::empty();
        let mut ps = PluginState::empty(SecurityLevel::Public, 1024);
        ps.grant_cap_mut(42);
        ps.grant_cap_mut(43);
        state.insert_plugin(1, ps).unwrap();
        let _ = state.insert_actor(1, ActorRuntime::empty(10));

        let step = super::super::Step::PluginInternal {
            pid: 1,
            pi: PluginInternal::compute(),
        };
        let new_state = step.execute(&state).expect("should succeed");

        // Held caps should be preserved
        assert!(new_state.plugin_holds(1, 42));
        assert!(new_state.plugin_holds(1, 43));
    }

    #[test]
    fn test_security_invariant_bounds_preserved() {
        // Corresponds to Lean: plugin_internal_bounds_preserved
        let mut state = State::empty();
        let _ = state.insert_plugin(1, PluginState::empty(SecurityLevel::Public, 1024));
        let _ = state.insert_actor(1, ActorRuntime::empty(10));

        let step = super::super::Step::PluginInternal {
            pid: 1,
            pi: PluginInternal::with_writes(vec![(0, 100)]),
        };
        let new_state = step.execute(&state).expect("should succeed");

        // Memory bounds should be preserved
        assert_eq!(
            new_state.get_plugin(1).map(|p| p.memory_bounds()),
            Some(1024)
        );
    }
}