Skip to main content

Module security

Module security 

Source
Expand description

Security model: authenticated sender, FlowCap, invariants S1–S7.

§Byteflow Security Model

Capability-oriented contract: a FlowId, Message field, opcode, or register is never authority by itself. The runtime (scheduler + CapTable + quotas) is the boundary. Compact checklists: untrusted.md, sandbox/, production-embedding.md.


§1. Threat Model

§Trusted

  • Host Rust, runtime, scheduler, mailboxes, directory
  • Natives the host registered
  • Host config / admission (verify, with_attested)

Bytecode does not enforce its own policy.

§Untrusted

  • .bf bytes, instructions, registers, values, Message/Pid fields, native args, control flow

Assume hostile modules construct any value the VM type system allows.


§2. Security Boundary

VM = computation. Scheduler/runtime own identity, delivery, mailboxes, sender auth, Cap resolve, natives, quotas. A register like:

Value::Pid(42)

does not prove that the current flow is authorized to communicate with flow 42.

Likewise:

Message {
    sender: 42,
    ...
}

does not prove that flow 42 actually created the message.


§3. Atomic Hop Security

Send/Ask require Value::Message. That is typing, not authentication — bytecode can forge Message.sender. The scheduler stamps:

message.sender = current_flow.id

and ignores any sender field supplied by bytecode.


§4. Authenticated Sender

§Rule

Before a Message is delivered by Send or Ask, the runtime MUST overwrite the sender field with the identity of the flow performing the operation.

Conceptually:

message.sender = current_flow.id;

The value originally contained in Message.sender MUST NOT influence the authenticated origin of the hop.

This means the following bytecode behavior is intentionally ineffective:

make_msg_legacy_sender(
    sender = victim_flow,
    request_id = 1,
    tag = REQUEST,
    payload = 41
)

followed by Send(...). The native discards the sender operand (Message.sender = 0); the worker then stamps the real origin. The receiver MUST observe sender = actual_sender_flow and never sender = victim_flow. Current make_msg is 3-arg and never accepts a sender at all.

Host-side Runtime::send is a trusted injection path (takes a FlowId, no Cap required) but uses the same authentication choke-point as bytecode hops: sender is stamped FlowId::HOST (0), an unset request_id is minted, and payload Caps are reissued to the recipient (reissue_for). The host has no mailbox, so reply_cap is CapId::NONE.


§5. Why Sender Authentication Happens in the Worker

Sender stamping MUST happen after the VM has identified the current flow and before the message enters another flow’s mailbox.

The VM does not own mailbox state and must not become responsible for scheduler authority.

The intended execution boundary is:

bytecode
   |
   v
VM validates Message
   |
   v
VmResult::Send / VmResult::Ask
   |
   v
scheduler / worker
   |
   +--> authenticate sender
   |
   +--> resolve destination
   |
   +--> deliver mailbox message
   |
   v
target flow

The scheduler therefore becomes the single authority responsible for the identity associated with an outgoing hop.


§6. Ask Security

Ask uses request correlation.

The reply MUST NOT be accepted solely because the request_id matches.

The authenticated reply rule is:

reply.request_id == request.request_id
&&
reply.sender == target

where target is the flow to which the request was delivered.

This prevents an unrelated flow from satisfying an outstanding Ask by guessing or reusing a request_id.

The request itself is also sender-stamped before delivery.

Therefore:

  • forged request sender → overwritten by runtime
  • forged reply sender → rejected by Ask correlation

are separate security properties. Both are required.

After FlowCap (0.5.x), Ask must compare reply.sender to the resolved FlowId behind the target Cap — never to a CapId.


§7. FlowCap

Bytecode Send / Ask require Value::Cap. A CapId is an opaque 128-bit CSPRNG token — not a counter, not a FlowId. It resolves through the runtime capability table (Capability) to { holder, target, rights, native_mask, epoch }.

Resolution is always resolve(cap, current_flow, required_rights). Knowing the bits, or holding a copy in a register, is not enough: the calling flow must be the registered holder with sufficient rights.

CapId’s Display prints the high 32 bits (cap#01234567…). print and BYTEFLOW_LOG use that form. Debug still prints the full token for the host.

Value::Pid remains for identity inside authenticated messages (Message.sender / msg_sender). It is not an ambient address.

Outgoing hops attach Message.reply_cap with SEND-only rights so a receiver can answer without knowing or forging a Pid address. The token is stable per (recipient, sender) pair (mint_or_reuse); a long ping-pong must not grow the capability table. FlowId is never reused, so the reverse index cannot alias a later incarnation.

SelfPid and bytecode Spawn write a Cap (CapRights::ADDRESSING = SEND|ASK|LINK|MONITOR) into the destination register — not a raw Pid.

A Value::Cap in a hop payload is reissued to the recipient only if the sender is the current holder (CapTable::delegate). Knowing a token is not enough to pass it on.

Host Runtime::send(FlowId, …) remains a trusted host path (no Cap required) but is stamped like any other hop (sender = 0, reply_cap = NONE).

Bytecode whereis returns a freshly minted/reused SEND Cap for the caller — never a raw FlowId. register_name only publishes the calling flow and requires SEND on self-authority. Host whereis still returns the Cap stored at registration (not reissued).

Cap tables are per-runtime: a token minted in Runtime A never resolves in Runtime B.

§Untrusted constant pool (0.9)

By default, verify and decode reject Cap, Pid, and Message values in the bytecode constant pool (TrustLevel::Untrusted). Only host assemblers that intentionally embed authority-bearing constants should pass TrustLevel::Trusted.

A Value::Cap that crosses a flow boundary is reissued for the recipient, including when it sits inside a List, a Map, or another hop’s payload. Copying the token is not a grant. The sender must hold the cap; otherwise Send, Ask, and spawn fail. The same walk covers a nested hop’s reply_cap. On a local hop, NONE is replaced with the pair’s SEND cap. Spawn passes an existing reply_cap through and does not mint one that was not there.

A nested envelope whose sender is still 0 is stamped with the flow that crosses the boundary (make_msg cannot write another id). A non-zero nested sender was already stamped and is kept, so forwarding does not rewrite it. Host Runtime::send leaves nested sender == 0 alone: that id is the host. Send and Ask refuse a capability the sender does not hold before spending a send token. SendRemote does the same, and also fails when the payload still contains a live cap. encode_frame writes that hop as a .bf value. It refuses a Cap or a Pid, and it refuses an envelope whose sender is not the frame header. HostAwait completion reissues caps into the result hop and fails that flow when the grant is refused.

Untrusted verify applies the constant-pool ban inside lists and maps. A List or Map of Cap, Pid, or Message does not pass.


§8. Message Construction

The current make_msg native does not take a sender. A 4-arg legacy encoding is accepted only to ignore the first operand — it is never copied into Message.sender.

For the outer envelope of a bytecode Send or Ask:

runtime_sender = current_flow.id

always wins. The field the bytecode wrote is ignored.

A nested envelope is data, not that outer hop. sender == 0 is still unset, so the same flow id is written. Any other nested sender is a previous stamp and stays. Host delivery does not rewrite a nested 0.


§9. Native Authority

Native functions are trusted host extensions.

A native function executes with authority granted by the host’s native table.

Bytecode must not be able to manufacture native authority merely by providing a numeric native index.

Native authorization is currently host-configured and gated per flow:

A numeric native index is still not a capability by itself (S7).


§10. Mailbox Security

Mailbox operations are scheduler-owned operations.

The mailbox MUST preserve the existing anti-lost-wakeup invariant: park + push/wake must be synchronized under the same mailbox synchronization boundary.

Selective receive MUST preserve FIFO-skip semantics.

A message that does not satisfy the active waiter filter must remain in the mailbox.

Security changes MUST NOT weaken these synchronization guarantees.


§11. Fail-Closed Policy

Security failures must fail closed.

Production code MUST NOT use unwrap() / expect() / unwrap_or* for runtime security decisions.

Poisoned synchronization primitives MUST NOT be recovered through PoisonError::into_inner().

A poisoned security-relevant lock is treated as a runtime failure.

The runtime must prefer refusing an operation over continuing with potentially corrupted authority state.


§12. Panic Isolation

Untrusted bytecode must not be able to directly terminate the host process through ordinary VM execution.

Runtime boundaries should convert invalid bytecode operations into explicit VM traps or scheduler errors.

Host-native code remains trusted.

A malicious or incorrectly implemented native may still violate host-level assumptions. Native isolation is therefore outside the VM’s trust guarantees.


§13. Denial of Service

Byteflow does not provide complete resource isolation.

The following remain known limitations:

Per-flow QuotaConfig (CPU, heap, spawn/send rate) and NativeMask allowlists are enforced as of 0.9.2 (extended in 0.9.3 with sandbox presets, register heap charge, and host hop parity; tightened in 0.9.5 with release-on-overwrite and a process-wide byte ceiling). QuotaConfig::permissive is the default; QuotaConfig::sandbox is a starting point for untrusted modules (tune under load). Str / Bytes written into registers charge heap with release-on-overwrite (delta accounting). Hop payloads are still charged at Send / Ask. The process-wide ceiling is RuntimeConfig::max_runtime_bytes via MemoryBudget.

Capability security prevents unauthorized access but does not automatically prevent an authorized flow from exhausting a budget it was granted.


§14. Timing Side Channels

Byteflow does not currently claim resistance against timing side channels.

Observable differences may exist through scheduling, mailbox contention, message latency, native execution, flow starvation, and resource exhaustion.

Applications requiring side-channel resistance must implement additional isolation at the host/platform level.


§15. FFI Boundary

FFI and native code are trusted boundaries.

Values crossing the FFI boundary must be validated before being converted into runtime-owned structures.

A host must not construct invalid internal runtime state through unsafe or unchecked FFI integration.

The Byteflow runtime does not treat an FFI-provided value as trusted merely because it originated outside bytecode.


§16. Capability Model (0.9.12 — implemented)

The security architecture is object-capability based:

Value::Cap(CapId) where CapId is an opaque 128-bit CSPRNG token — not a FlowId.

A capability resolves through the per-runtime directory to { holder, target, rights, native_mask, epoch }. Resolution requires the calling flow to hold the token with sufficient rights.

LINK / MONITOR / ADMIN bits are minted as follows: addressing Caps carry LINK|MONITOR; ADMIN requires CapTarget::Scheduler and is never in the default root set.

The bytecode-visible capability MUST NOT expose the underlying FlowId.

Capability creation, delegation, attenuation, and revocation belong to the trusted runtime. Cap::attenuate is the only grant-derivation path (AND of rights and NativeMask). The runtime capability table removes every entry held by or targeting an exiting flow (revoke_flow).


§17. Security Invariants

The following invariants are normative.

§S1 — Sender authenticity

A receiver observes the sender assigned by the runtime, never the sender claimed by bytecode.

§S2 — Ask reply authenticity

An Ask completes only when the reply matches both request_id and sender == requested target.

§S3 — VM authority separation

The VM does not directly manipulate mailboxes, scheduler state, timers or threads.

§S4 — Fail closed

Invalid security state results in an error/trap rather than recovery using possibly corrupted state.

§S5 — FIFO selective receive

Selective waiting does not discard unrelated messages.

§S6 — Cap is the address; Pid is identity

Bytecode addressing for Send / Ask uses Value::Cap. Value::Pid is authenticated identity only and does not grant delivery authority.

§S7 — Native index is not inherently a capability

Native authorization is a CapRights::NATIVE bit plus a NativeMask on the flow’s self-authority. CALL_NATIVE is denied unless both pass. The index operand is untrusted input, never an ambient grant.


§18. Security Roadmap

§Phase 1 (done)

Authenticated sender stamping on bytecode Send / Ask.

§Phase 2 (done — 0.5.x → 0.9)

Flow capabilities: Value::Cap for Send/Ask; reply_cap grant; Pid = identity. 0.9 closes the model: random 128-bit ids, holder + rights resolution, untrusted constant-pool rejection, and full cap sweep on flow exit.

§Phase 3 (done — 0.9.2)

Native allowlists, per-flow quotas (CPU / memory / spawn-send rate), DELEGATE, confined SPAWN, LINK/MONITOR/ADMIN rights, and make_msg without a forgeable sender. All derivation goes through Cap::attenuate.

§Phase 3 follow-ups (done — 0.9.3)

Bytecode register_name / whereis (SEND Cap, never FlowId), heap charge for Str/Bytes in registers, QuotaConfig::sandbox, admin mem/send top-up, and host Runtime::send on the same hop auth path.

§Memory accounting + join guard (done — 0.9.5)

Register heap charge/release on overwrite (delta accounting), RuntimeConfig::max_runtime_bytes / MemoryBudget, and a machine-checked rejection of FlowHandle::join* from worker threads (JoinError::CalledFromWorker).

§Tier 1 property / fuzz (done — 0.9.5)

proptest-free stress suites for mailbox bounds, CapTable mint/resolve/revoke, and decode/verify panic-freedom (docs/properties.md).

§Phase 4 (done — 0.9.6)

Host-side bytecode integrity fingerprint: fingerprint_bf / decode_attested. Deterministic 32-byte digest over a .bf buffer so an embedder can refuse a module whose bytes do not match a known fingerprint. This is not cryptographic module attestation (no signatures, MACs, or trust roots inside Byteflow).

§Phase 5 (done — 0.9.7: relation caps + attested boot)

  • Process-wide caps on links / monitors / registry names (max_links / max_monitors / max_registry_names), enforced inside each store under the same lock as the table.
  • Every Jump / Branch is bounds-checked (Fault::BadJump). There is no config flag for that check. verify also rejects a jump that would enter another function, and a function that falls into the next one without Jump / Return / Halt / Exit / Trap.
  • Runtime::with_attested: fingerprint gate before verify/start; SpawnError::Attestation distinct from SpawnError::VerifyFailed.
  • RuntimeConfig::sandbox sets relation caps. Default stays permissive on those caps. Jump bounds are always fail-closed. Untrusted production: sandbox() + with_attested + minimal natives + Runtime::spawn_untrusted (or root_authority = Untrusted).

§19. Non-Goals

The following are explicitly outside the current security model:

  • cryptographic authentication between flows;
  • encrypted mailbox contents;
  • OS sandboxing / seccomp / process isolation;
  • constant-time scheduling;
  • protection against malicious trusted natives;
  • complete DoS resistance;
  • cryptographic module attestation (signatures / PKI — hosts may layer this on top of the Phase 4 integrity fingerprint).

These may be implemented at higher layers where appropriate.