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
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
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
// Copyright (C) 2026 HaiyangLi
// SPDX-License-Identifier: AGPL-3.0-or-later
//! Lion Step Module
//!
//! Step relation and all step constructors for the Lion microkernel state machine.

mod authorization;
mod host_call;
mod kernel_op;
mod plugin_internal;

pub use authorization::{AuthorizationError, Authorized};
pub use host_call::{HostCall, HostFunction, HostResult, ResourceType};
pub use kernel_op::KernelOp;
pub use plugin_internal::PluginInternal;

use crate::state::{State, StateError};
use crate::types::{ActorId, CapId, MemAddr, PluginId, SecurityLevel, Size, WorkflowId};

/// Reasons a plugin precondition check can fail.
#[derive(Debug)]
pub enum PluginPrecondition {
    /// Plugin's actor is blocked on another actor
    Blocked {
        /// The plugin that is blocked
        pid: PluginId,
        /// The actor it is blocked on (if known)
        blocked_on: Option<ActorId>,
    },
    /// A read memory region is out of bounds
    ReadOutOfBounds {
        /// Start address of the region
        addr: MemAddr,
        /// Size of the region
        size: Size,
        /// Memory bounds of the plugin
        bounds: Size,
    },
    /// A write memory region is out of bounds
    WriteOutOfBounds {
        /// Start address of the region
        addr: MemAddr,
        /// Size of the region
        size: Size,
        /// Memory bounds of the plugin
        bounds: Size,
    },
    /// Attempted to consume from an empty mailbox
    MailboxEmpty,
}

impl std::fmt::Display for PluginPrecondition {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            PluginPrecondition::Blocked { pid, blocked_on } => {
                write!(f, "Plugin {pid} is blocked on {blocked_on:?}")
            }
            PluginPrecondition::ReadOutOfBounds { addr, size, bounds } => {
                write!(
                    f,
                    "Read region {addr}+{size} out of bounds (memory size {bounds})"
                )
            }
            PluginPrecondition::WriteOutOfBounds { addr, size, bounds } => {
                write!(
                    f,
                    "Write region {addr}+{size} out of bounds (memory size {bounds})"
                )
            }
            PluginPrecondition::MailboxEmpty => {
                write!(f, "Cannot consume mailbox: mailbox is empty")
            }
        }
    }
}

/// Reasons a host call precondition check can fail.
#[derive(Debug)]
pub enum HostCallPrecondition {
    /// A read memory region is out of bounds
    ReadOutOfBounds {
        /// Start address of the region
        addr: MemAddr,
        /// Size of the region
        size: Size,
    },
    /// A write memory region is out of bounds
    WriteOutOfBounds {
        /// Start address of the region
        addr: MemAddr,
        /// Size of the region
        size: Size,
    },
    /// No valid capability is held by the caller
    NoValidCapability,
    /// No message provided for send operation
    NoMessage,
    /// Message source does not match the caller
    SourceMismatch,
    /// Destination mailbox is full
    MailboxFull,
    /// Invalid security level value
    InvalidSecurityLevel {
        /// The invalid level value
        value: u64,
    },
    /// Cannot classify up (only declassification is allowed)
    CannotClassifyUp,
    /// No address argument provided for free operation
    NoAddress,
    /// No capability ID argument provided for revoke operation
    NoCapabilityId,
    /// Underlying free operation failed
    FreeFailed {
        /// The state error that caused the failure
        source: StateError,
    },
    /// Operation requires Phase 3 State extension (threads/scheduler)
    NotImplemented {
        /// Description of the unimplemented operation
        operation: &'static str,
    },
}

impl std::fmt::Display for HostCallPrecondition {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            HostCallPrecondition::ReadOutOfBounds { addr, size } => {
                write!(f, "Read region {addr}+{size} out of bounds")
            }
            HostCallPrecondition::WriteOutOfBounds { addr, size } => {
                write!(f, "Write region {addr}+{size} out of bounds")
            }
            HostCallPrecondition::NoValidCapability => write!(f, "No valid capability held"),
            HostCallPrecondition::NoMessage => write!(f, "No message to send"),
            HostCallPrecondition::SourceMismatch => {
                write!(f, "Message source doesn't match caller")
            }
            HostCallPrecondition::MailboxFull => write!(f, "Destination mailbox full"),
            HostCallPrecondition::InvalidSecurityLevel { value } => {
                write!(f, "Invalid security level: {value}")
            }
            HostCallPrecondition::CannotClassifyUp => write!(f, "Cannot classify up"),
            HostCallPrecondition::NoAddress => write!(f, "No address to free"),
            HostCallPrecondition::NoCapabilityId => write!(f, "No capability ID to revoke"),
            HostCallPrecondition::FreeFailed { source } => {
                write!(f, "Free failed: {source:?}")
            }
            HostCallPrecondition::NotImplemented { operation } => {
                write!(
                    f,
                    "{operation} requires Phase 3 State extension (threads/scheduler)"
                )
            }
        }
    }
}

/// Reasons a kernel operation can fail.
#[derive(Debug)]
pub enum KernelOpError {
    /// Actor has no pending messages to route
    NoPendingMessages {
        /// The destination actor
        dst: ActorId,
    },
    /// Actor mailbox is at capacity
    MailboxAtCapacity {
        /// The destination actor
        dst: ActorId,
    },
    /// Workflow not found
    WorkflowNotFound {
        /// The workflow ID
        wid: WorkflowId,
    },
    /// Workflow is not in the running state
    WorkflowNotRunning {
        /// The workflow ID
        wid: WorkflowId,
    },
    /// Operation requires Phase 3 State extension (threads/scheduler)
    NotImplemented {
        /// Description of the unimplemented operation
        operation: &'static str,
    },
    /// Counter overflow (time or epoch would exceed u64::MAX)
    CounterOverflow(String),
}

impl std::fmt::Display for KernelOpError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            KernelOpError::NoPendingMessages { dst } => {
                write!(f, "Actor {dst} has no pending messages")
            }
            KernelOpError::MailboxAtCapacity { dst } => {
                write!(f, "Actor {dst} mailbox at capacity")
            }
            KernelOpError::WorkflowNotFound { wid } => write!(f, "Workflow {wid} not found"),
            KernelOpError::WorkflowNotRunning { wid } => {
                write!(f, "Workflow {wid} is not running")
            }
            KernelOpError::NotImplemented { operation } => {
                write!(
                    f,
                    "{operation} requires Phase 3 State extension (threads/scheduler)"
                )
            }
            KernelOpError::CounterOverflow(msg) => {
                write!(f, "counter overflow: {msg}")
            }
        }
    }
}

/// Reasons a state transition can be invalid.
#[derive(Debug)]
pub enum InvalidTransitionReason {
    /// Attempted transition between incompatible states
    IncompatibleStates {
        /// Description of what was expected
        expected: &'static str,
        /// Description of what was found
        found: &'static str,
    },
}

impl std::fmt::Display for InvalidTransitionReason {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            InvalidTransitionReason::IncompatibleStates { expected, found } => {
                write!(f, "expected {expected}, found {found}")
            }
        }
    }
}

/// Error type for step operations.
#[derive(Debug)]
pub enum StepError {
    /// Plugin not found
    PluginNotFound(PluginId),
    /// Actor not found
    ActorNotFound(PluginId),
    /// Memory address already freed (double-free prevention)
    AddressAlreadyFreed(MemAddr),
    /// Capability targets this address (temporal safety violation)
    CapabilityTargetsAddress(CapId, MemAddr),
    /// Capability not found
    CapabilityNotFound(CapId),
    /// Authorization failed
    AuthorizationFailed(AuthorizationError),
    /// Plugin precondition failed
    PluginPreconditionFailed(PluginPrecondition),
    /// Host call precondition failed
    HostCallPreconditionFailed(HostCallPrecondition),
    /// Kernel operation failed
    KernelOpFailed(KernelOpError),
    /// Invalid state transition
    InvalidTransition(InvalidTransitionReason),
    /// State operation failed
    StateError(StateError),
    /// Resource quota exceeded (DoS prevention)
    QuotaExceeded(u8, u64, u64, u64),
}

impl std::fmt::Display for StepError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            StepError::PluginNotFound(id) => write!(f, "plugin {id} not found"),
            StepError::ActorNotFound(id) => write!(f, "actor {id} not found"),
            StepError::AddressAlreadyFreed(addr) => write!(f, "address {addr} already freed"),
            StepError::CapabilityTargetsAddress(cap, addr) => {
                write!(f, "capability {cap} targets address {addr}")
            }
            StepError::CapabilityNotFound(id) => write!(f, "capability {id} not found"),
            StepError::AuthorizationFailed(e) => write!(f, "authorization failed: {e}"),
            StepError::PluginPreconditionFailed(reason) => {
                write!(f, "plugin precondition failed: {reason}")
            }
            StepError::HostCallPreconditionFailed(reason) => {
                write!(f, "host call precondition failed: {reason}")
            }
            StepError::KernelOpFailed(reason) => write!(f, "kernel operation failed: {reason}"),
            StepError::InvalidTransition(reason) => write!(f, "invalid transition: {reason}"),
            StepError::StateError(e) => write!(f, "state error: {e}"),
            StepError::QuotaExceeded(kind, requested, current, quota) => {
                let kind_name = match kind {
                    0 => "memory",
                    1 => "capability",
                    2 => "ipc_queue",
                    _ => "unknown",
                };
                write!(
                    f,
                    "{kind_name} quota exceeded: requested {requested}, current {current}, quota {quota}"
                )
            }
        }
    }
}

impl std::error::Error for StepError {}

impl From<AuthorizationError> for StepError {
    fn from(e: AuthorizationError) -> Self {
        StepError::AuthorizationFailed(e)
    }
}

impl From<StateError> for StepError {
    fn from(e: StateError) -> Self {
        StepError::StateError(e)
    }
}

/// Step represents a single state transition in the Lion microkernel.
#[derive(Debug, Clone)]
#[allow(clippy::large_enum_variant)]
#[must_use = "steps must be executed to apply state transitions"]
pub enum Step {
    /// Plugin-internal computation (untrusted, sandboxed)
    PluginInternal {
        /// The plugin performing computation
        pid: PluginId,
        /// The internal computation descriptor
        pi: PluginInternal,
    },

    /// Host call (trust boundary, mediated)
    HostCall {
        /// The host call request
        hc: HostCall,
        /// Authorization witness (validated at execution)
        auth: Authorized,
        /// Result of host call execution
        result: HostResult,
    },

    /// Kernel-internal operation (trusted TCB)
    KernelInternal {
        /// The kernel operation to execute
        op: KernelOp,
    },

    /// Direct memory free operation (refinement bridge)
    MemFree {
        /// The plugin requesting the free
        caller: PluginId,
        /// The address to free
        addr: MemAddr,
    },

    /// Direct capability revoke operation (refinement bridge)
    CapRevoke {
        /// The plugin requesting revocation
        caller: PluginId,
        /// The capability ID to revoke
        cap_id: CapId,
    },
}

impl Step {
    /// Create a host call step with ATOMIC authorization.
    ///
    /// The action is derived from the `HostCall` via `hc.required_action()`,
    /// binding authorization to the exact operation being performed.
    /// This prevents the vulnerability where a valid `Authorized` token
    /// for one action could be reused to execute a different `HostCall`.
    pub fn host_call_atomic(
        state: &State,
        hc: HostCall,
        cap_id: CapId,
        ctx: crate::types::PolicyContext,
        result: HostResult,
    ) -> Result<Self, StepError> {
        let cap = state
            .get_cap(cap_id)
            .cloned()
            .ok_or(StepError::CapabilityNotFound(cap_id))?;

        let action = hc.required_action()?;
        if cap.holder() != hc.caller() {
            return Err(StepError::AuthorizationFailed(
                AuthorizationError::HolderMismatch {
                    expected: hc.caller(),
                    actual: cap.holder(),
                },
            ));
        }

        let auth = Authorized::validate_atomic(state, cap, action, ctx)?;
        Ok(Step::HostCall { hc, auth, result })
    }

    /// Check if this step is effectful (crosses trust boundary).
    pub fn is_effectful(&self) -> bool {
        matches!(self, Step::HostCall { .. })
    }

    /// Get the subject (executing plugin) of the step, if any.
    pub fn subject(&self) -> Option<PluginId> {
        match self {
            Step::PluginInternal { pid, .. } => Some(*pid),
            Step::HostCall { hc, .. } => Some(hc.caller),
            Step::KernelInternal { .. } => None,
            Step::MemFree { caller, .. } | Step::CapRevoke { caller, .. } => Some(*caller),
        }
    }

    /// Get the security level of the step.
    pub fn level(&self, state: &State) -> SecurityLevel {
        match self.subject() {
            Some(pid) => state.plugin_level(pid).unwrap_or(SecurityLevel::Public),
            None => SecurityLevel::Secret,
        }
    }

    /// Check if this is a declassify operation.
    pub fn is_declassify(&self) -> bool {
        matches!(
            self,
            Step::HostCall {
                hc: HostCall {
                    function: HostFunction::Declassify,
                    ..
                },
                ..
            }
        )
    }

    /// Execute this step, returning the new state.
    pub fn execute(&self, state: &State) -> Result<State, StepError> {
        match self {
            Step::PluginInternal { pid, pi } => execute_plugin_internal(state, *pid, pi),
            Step::HostCall { hc, auth, result } => execute_host_call(state, hc, auth, result),
            Step::KernelInternal { op } => execute_kernel_internal(state, op),
            Step::MemFree { caller: _, addr } => execute_mem_free(state, *addr),
            Step::CapRevoke { caller: _, cap_id } => execute_cap_revoke(state, *cap_id),
        }
    }

    /// Mutating execution -- modifies state in place (production path).
    ///
    /// Equivalent to `execute` but avoids the full-state clone by mutating
    /// in place. The validation logic is identical.
    pub fn execute_mut(&self, state: &mut State) -> Result<(), StepError> {
        match self {
            Step::PluginInternal { pid, pi } => execute_plugin_internal_mut(state, *pid, pi),
            Step::HostCall { hc, auth, result } => execute_host_call_mut(state, hc, auth, result),
            Step::KernelInternal { op } => execute_kernel_internal_mut(state, op),
            Step::MemFree { caller: _, addr } => execute_mem_free_mut(state, *addr),
            Step::CapRevoke { caller: _, cap_id } => execute_cap_revoke_mut(state, *cap_id),
        }
    }
}

fn execute_plugin_internal(
    state: &State,
    pid: PluginId,
    pi: &PluginInternal,
) -> Result<State, StepError> {
    let plugin = state
        .get_plugin(pid)
        .ok_or(StepError::PluginNotFound(pid))?;

    pi.check_preconditions(state, pid)?;

    let mut new_state = state.clone();

    if let Some(_new_plugin) = new_state.get_plugin_mut(pid) {
        for &(addr, _size) in &pi.writes {
            if !plugin.memory().addr_in_bounds(addr, 1) {
                return Err(StepError::PluginPreconditionFailed(
                    PluginPrecondition::WriteOutOfBounds {
                        addr,
                        size: 1,
                        bounds: plugin.memory_bounds(),
                    },
                ));
            }
        }

        if pi.consume_mailbox {
            if let Some(actor) = new_state.get_actor_mut(pid) {
                let _ = actor.consume_mut();
            }
        }
    }

    Ok(new_state)
}

fn execute_host_call(
    state: &State,
    hc: &HostCall,
    auth: &Authorized,
    result: &HostResult,
) -> Result<State, StepError> {
    // Verify authorization subject matches the host call caller
    if auth.action().subject() != hc.caller() {
        return Err(StepError::AuthorizationFailed(
            AuthorizationError::HolderMismatch {
                expected: auth.action().subject(),
                actual: hc.caller(),
            },
        ));
    }

    // Verify the authorized action matches what the host call requires
    let derived = hc.required_action()?;
    if &derived != auth.action() {
        return Err(StepError::InvalidTransition(
            InvalidTransitionReason::IncompatibleStates {
                expected: "authorized host call",
                found: "mismatched host call",
            },
        ));
    }

    auth.validate(state)?;
    hc.check_preconditions(state)?;
    hc.function.execute(state, hc, result)
}

fn execute_kernel_internal(state: &State, op: &KernelOp) -> Result<State, StepError> {
    op.execute(state)
}

fn execute_mem_free(state: &State, addr: MemAddr) -> Result<State, StepError> {
    if state.ghost().is_freed(addr) {
        return Err(StepError::AddressAlreadyFreed(addr));
    }

    // ResourceId = u128, addr = u64 (MemAddr)
    if let Some(&(cap_id, _)) = state
        .kernel()
        .revocation()
        .iter()
        .find(|(_, cap)| cap.is_valid() && cap.target() == u128::from(addr))
    {
        return Err(StepError::CapabilityTargetsAddress(cap_id, addr));
    }

    state.apply_free(addr).map_err(StepError::StateError)
}

fn execute_cap_revoke(state: &State, cap_id: CapId) -> Result<State, StepError> {
    if state.kernel().revocation().get(cap_id).is_none() {
        return Err(StepError::CapabilityNotFound(cap_id));
    }

    Ok(state.apply_cap_revoke(cap_id))
}

// ============== MUTATING VARIANTS ==============
//
// These perform the same validation as their pure counterparts
// but modify `&mut State` in place instead of cloning.

fn execute_plugin_internal_mut(
    state: &mut State,
    pid: PluginId,
    pi: &PluginInternal,
) -> Result<(), StepError> {
    let plugin = state
        .get_plugin(pid)
        .ok_or(StepError::PluginNotFound(pid))?;

    pi.check_preconditions(state, pid)?;

    // Validate writes before mutating (borrows plugin immutably)
    for &(addr, _size) in &pi.writes {
        if !plugin.memory().addr_in_bounds(addr, 1) {
            return Err(StepError::PluginPreconditionFailed(
                PluginPrecondition::WriteOutOfBounds {
                    addr,
                    size: 1,
                    bounds: plugin.memory_bounds(),
                },
            ));
        }
    }

    if pi.consume_mailbox {
        if let Some(actor) = state.get_actor_mut(pid) {
            let _ = actor.consume_mut();
        }
    }

    Ok(())
}

fn execute_host_call_mut(
    state: &mut State,
    hc: &HostCall,
    auth: &Authorized,
    result: &HostResult,
) -> Result<(), StepError> {
    // Verify authorization subject matches the host call caller
    if auth.action().subject() != hc.caller() {
        return Err(StepError::AuthorizationFailed(
            AuthorizationError::HolderMismatch {
                expected: auth.action().subject(),
                actual: hc.caller(),
            },
        ));
    }

    // Verify the authorized action matches what the host call requires
    let derived = hc.required_action()?;
    if &derived != auth.action() {
        return Err(StepError::InvalidTransition(
            InvalidTransitionReason::IncompatibleStates {
                expected: "authorized host call",
                found: "mismatched host call",
            },
        ));
    }

    auth.validate(state)?;
    hc.check_preconditions(state)?;
    hc.function.execute_mut(state, hc, result)
}

fn execute_kernel_internal_mut(state: &mut State, op: &KernelOp) -> Result<(), StepError> {
    op.execute_mut(state)
}

fn execute_mem_free_mut(state: &mut State, addr: MemAddr) -> Result<(), StepError> {
    if state.ghost().is_freed(addr) {
        return Err(StepError::AddressAlreadyFreed(addr));
    }

    // ResourceId = u128, addr = u64 (MemAddr)
    if let Some(&(cap_id, _)) = state
        .kernel()
        .revocation()
        .iter()
        .find(|(_, cap)| cap.is_valid() && cap.target() == u128::from(addr))
    {
        return Err(StepError::CapabilityTargetsAddress(cap_id, addr));
    }

    state.apply_free_mut(addr).map_err(StepError::StateError)
}

fn execute_cap_revoke_mut(state: &mut State, cap_id: CapId) -> Result<(), StepError> {
    if state.kernel().revocation().get(cap_id).is_none() {
        return Err(StepError::CapabilityNotFound(cap_id));
    }

    state
        .apply_cap_revoke_mut(cap_id)
        .map_err(|_| StepError::CapabilityNotFound(cap_id))
}

/// Reachability relation -- reflexive transitive closure of Step.
pub fn reachable(start: &State, end: &State, steps: &[Step]) -> Result<bool, StepError> {
    let mut current = start.clone();
    for step in steps {
        current = step.execute(&current)?;
    }
    Ok(current.time() == end.time())
}