byteflow-actors 0.9.28

Embeddable flow runtime: M:N scheduler, Atomic Hop (Message+Cap), supervisor — use byteflow::
Documentation
//! Hop identity and capability resolution: stamping outgoing messages with
//! the sender's identity and reply capability, re-issuing host capabilities,
//! and resolving `Send` / `Ask` / relation targets through the `CapTable`.

use super::*;

/// S1 + reply grant: single choke-point before mailbox `push` on bytecode hops.
///
/// `Message.sender` / `reply_cap` are register/native data until this call.
/// The scheduler owns the executing flow’s identity and **assigns** both:
/// it does not “check equality” against forgeable fields (wrong security
/// primitive). Every future opcode that delivers a [`Message`] must call
/// this (or equivalent); do not duplicate ad-hoc stamp assignments elsewhere.
pub(super) fn authenticate_outgoing_message(
    shared: &Shared,
    sender: FlowId,
    recipient: FlowId,
    mut message: Message,
    vm: &mut crate::vm::Vm,
) -> Result<Message, CapError> {
    if message.request_id == 0 {
        message.request_id = vm.fresh_request_id();
    }
    let payload = reissue_caps_in_value(shared, sender, recipient, (*message.payload).clone(), vm)?;
    let reply = shared
        .caps
        .mint_or_reuse(recipient, sender, CapRights::SEND)
        .map_err(CapError::from)?;
    Ok(message
        .with_payload(payload)
        .authenticate(sender.as_u64(), reply))
}

/// Next host correlation id.
///
/// A fresh counter starts at 1, so the first id is 1. `0` is not an id: it
/// means the counter wrapped and is pinned there. Later calls return `None`
/// instead of issuing `1` again.
pub(crate) fn mint_host_request_id(counter: &AtomicU64) -> Option<u64> {
    loop {
        let id = counter.load(Ordering::Relaxed);
        if id == 0 {
            return None;
        }
        let next = if id == u64::MAX { 0 } else { id + 1 };
        if counter
            .compare_exchange(id, next, Ordering::Relaxed, Ordering::Relaxed)
            .is_ok()
        {
            return Some(id);
        }
    }
}

/// Host `Runtime::send`: same choke-point as bytecode hops.
///
/// The embedder is not a flow — it has no mailbox — so `reply_cap` stays
/// [`CapId::NONE`]. `sender` is always [`FlowId::HOST`]. Caps in the payload
/// are reissued with the host's trusted path (`reissue_for`), not `delegate`.
pub(crate) fn authenticate_host_outgoing_message(
    shared: &Shared,
    recipient: FlowId,
    mut message: Message,
) -> Result<Message, CapError> {
    if message.request_id == 0 {
        message.request_id = mint_host_request_id(&shared.host_next_request_id)
            .ok_or(CapError::RequestIdsExhausted)?;
    }
    let payload = reissue_caps_from_host(shared, recipient, (*message.payload).clone())?;
    Ok(message
        .with_payload(payload)
        .authenticate(FlowId::HOST.as_u64(), CapId::NONE))
}

/// Host is trusted: re-issue live Caps to `recipient` without a holder check.
///
/// A nested envelope keeps `sender` (`0` is the host). An unset `request_id`
/// is minted. A live `reply_cap` is reissued; `NONE` stays `NONE` because
/// the host has no mailbox to reply to.
pub(crate) fn reissue_caps_from_host(
    shared: &Shared,
    recipient: FlowId,
    value: Value,
) -> Result<Value, CapError> {
    if !value.within_nesting_limit() {
        return Err(CapError::TooNested);
    }
    value.map_caps(
        0,
        &CapError::TooNested,
        &mut |id| shared.caps.reissue_for(id, recipient),
        &mut |message| {
            if message.request_id == 0 {
                message.request_id = mint_host_request_id(&shared.host_next_request_id)
                    .ok_or(CapError::RequestIdsExhausted)?;
            }
            if !message.reply_cap.is_none() {
                message.reply_cap = shared.caps.reissue_for(message.reply_cap, recipient)?;
            }
            Ok(())
        },
    )
}

/// Re-issue every `Value::Cap` the sender holds so `recipient` becomes holder.
///
/// Lists and nested hops are walked. A nested envelope whose `sender` is
/// still `0` is stamped with this flow — `make_msg` cannot write any other
/// id. A non-zero nested sender was already authenticated and is kept.
/// `reply_cap` is minted when it is [`CapId::NONE`] and delegated otherwise.
/// Additive: original tokens stay valid. A cap the sender does not hold
/// fails the hop instead of copying the token.
pub(super) fn reissue_caps_in_value(
    shared: &Shared,
    sender: FlowId,
    recipient: FlowId,
    value: Value,
    vm: &mut crate::vm::Vm,
) -> Result<Value, CapError> {
    if !value.within_nesting_limit() {
        return Err(CapError::TooNested);
    }
    value.map_caps(
        0,
        &CapError::TooNested,
        &mut |id| shared.caps.delegate(id, sender, recipient),
        &mut |message| {
            if message.sender == 0 {
                message.sender = sender.as_u64();
            }
            if message.request_id == 0 {
                message.request_id = vm.fresh_request_id();
            }
            message.reply_cap = if message.reply_cap.is_none() {
                shared
                    .caps
                    .mint_or_reuse(recipient, sender, CapRights::SEND)
                    .map_err(CapError::from)?
            } else {
                shared.caps.delegate(message.reply_cap, sender, recipient)?
            };
            Ok(())
        },
    )
}

pub(super) fn receive_filter(
    match_tag: Option<u16>,
    match_request_id: Option<u64>,
    match_payload_kind: Option<u8>,
    match_payload_eq: Option<i64>,
    match_payload_value: Option<std::sync::Arc<crate::Value>>,
    match_payload_cmp: Option<(crate::bytecode::IntCmp, i64)>,
) -> WaitFilter {
    if let Some(kind) = match_payload_kind {
        return WaitFilter::PayloadKind(kind);
    }
    if let (Some(tag), Some(payload)) = (match_tag, match_payload_value) {
        return WaitFilter::TagValue { tag, payload };
    }
    if let (Some(tag), Some((cmp, bound))) = (match_tag, match_payload_cmp) {
        return WaitFilter::TagCmp { tag, cmp, bound };
    }
    if let (Some(tag), Some(payload)) = (match_tag, match_payload_eq) {
        return WaitFilter::TagPayload { tag, payload };
    }
    match (match_tag, match_request_id) {
        (Some(tag), Some(rid)) => WaitFilter::TaggedCorrelation {
            tag,
            expect_request_id: rid,
        },
        (Some(tag), None) => WaitFilter::Tag(tag),
        (None, Some(rid)) => WaitFilter::Correlation {
            expect_request_id: rid,
            expect_sender: None,
        },
        (None, None) => WaitFilter::Any,
    }
}

/// Resolve `CapId` for `holder`. Returns target [`FlowId`].
pub(super) fn resolve_cap_held(
    shared: &Shared,
    id: CapId,
    holder: FlowId,
    need: CapRights,
) -> Result<FlowId, CapError> {
    shared
        .caps
        .resolve(id, holder, need)?
        .target()
        .ok_or(CapError::WrongTarget)
}

pub(super) fn resolve_relation_cap(
    shared: &Shared,
    id: CapId,
    holder: FlowId,
    need: CapRights,
) -> Result<FlowId, String> {
    let entry = shared
        .caps
        .resolve(id, holder, need)
        .map_err(|e| e.to_string())?;
    let target = entry
        .target()
        .ok_or_else(|| CapError::WrongTarget.to_string())?;
    let cell = match shared.caps.flow_cell(target) {
        Ok(Some(c)) => c,
        Ok(None) => return Err(CapError::Unknown.to_string()),
        Err(e) => return Err(e.to_string()),
    };
    let check = if need == CapRights::LINK {
        crate::scheduler::link_admin::check_link(&entry.cap, cell.as_ref(), target.as_u64())
            .map_err(|e| e.to_string())
    } else {
        crate::scheduler::link_admin::check_monitor(&entry.cap, cell.as_ref(), target.as_u64())
            .map_err(|e| e.to_string())
    };
    check?;
    Ok(target)
}