# Byteflow Security Model
## Status
This document defines the security contract of the Byteflow runtime.
The security model is intentionally capability-oriented. Byteflow does not
consider a numeric FlowId, Message field, opcode, or register value to be an
authority by itself.
The runtime is the security boundary.
---
## 1. Threat Model
Byteflow executes bytecode that may be supplied by an untrusted module.
The following distinction is fundamental:
### Trusted components
The following components are trusted:
- host Rust code;
- the Byteflow runtime;
- the scheduler;
- the mailbox implementation;
- the flow directory;
- native functions explicitly registered by the host;
- the host supervisor responsible for configuring the runtime;
- verified bytecode admission performed by the host.
Trusted components are responsible for enforcing all authority boundaries.
Bytecode must never be trusted to enforce its own security policy.
### Untrusted components
The following are considered untrusted:
- `.bf` bytecode;
- bytecode instructions;
- register contents;
- values constructed by bytecode;
- Message fields supplied by bytecode;
- Pid values supplied by bytecode;
- native arguments supplied by bytecode;
- control flow generated by bytecode.
A malformed or malicious bytecode module must therefore be assumed capable of
deliberately constructing invalid values whenever the VM permits such values.
---
## 2. Security Boundary
The VM is a computation engine, not the authority manager.
The VM may validate structural invariants required by an instruction, but it
must not grant authority merely because a bytecode value claims to possess it.
The scheduler and runtime own:
- flow identity;
- message delivery;
- mailbox ownership;
- sender authentication;
- capability resolution;
- native authority;
- resource quotas.
This distinction is critical.
A register containing:
```text
Value::Pid(42)
```
does not prove that the current flow is authorized to communicate with flow 42.
Likewise:
```text
Message {
sender: 42,
...
}
```
does not prove that flow 42 actually created the message.
---
## 3. Atomic Hop Security
Byteflow's Atomic Hop model establishes that Send and Ask operate on
`Value::Message`.
This provides an important structural invariant:
```text
Send/Ask -> Message -> mailbox
```
However, structural typing is not authentication.
A Message constructed by bytecode may contain arbitrary application data,
including a forged sender field.
Therefore the runtime MUST authenticate the sender at the scheduler boundary.
The authoritative sender is:
```text
current_flow.id
```
and never:
```text
Message.sender
```
provided 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:
```text
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:
```text
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`](../src/scheduler/runtime.rs) remains a **trusted**
injection path: the host may choose `sender` (including `0` for non-flow
origins). Only bytecode-driven `Send` / `Ask` are re-stamped.
---
## 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:
```text
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:
```text
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 — Current Version (0.9.2)
Bytecode `Send` / `Ask` require [`Value::Cap`](crate::Value::Cap). A [`CapId`](crate::CapId)
is an opaque **128-bit CSPRNG token** — not a counter, not a [`FlowId`](crate::FlowId).
It resolves through the runtime capability table ([`Capability`](crate::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.
[`Value::Pid`](crate::Value::Pid) remains for **identity** inside authenticated messages
(`Message.sender` / `msg_sender`). It is **not** an ambient address.
Outgoing hops mint `Message.reply_cap` with **SEND**-only rights so a
receiver can answer without knowing or forging a Pid address.
`SelfPid` and bytecode `Spawn` write a Cap (`SEND|ASK`) into the destination
register — not a raw Pid.
Host `Runtime::send(FlowId, …)` remains a trusted host path (no Cap required).
Cap tables are **per-runtime**: a token minted in Runtime A never resolves in
Runtime B.
### Untrusted constant pool (0.9)
By default, [`verify`](crate::verify) and [`decode`](crate::decode) reject
`Cap`, `Pid`, and `Message` values in the bytecode constant pool
([`TrustLevel::Untrusted`](crate::TrustLevel::Untrusted)). Only host assemblers that intentionally embed
authority-bearing constants should pass [`TrustLevel::Trusted`](crate::TrustLevel::Trusted).
---
## 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 outgoing Send and Ask operations:
```text
runtime_sender = current_flow.id
```
always wins.
---
## 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:
- host `Runtime::spawn` mints a root Cap with [`CapRights::NATIVE`](crate::CapRights::NATIVE) plus a
full [`NativeMask`](crate::NativeMask) over the attached [`NativeTable`](crate::NativeTable);
- bytecode `Spawn` attenuates that mask through [`Cap::attenuate`](crate::Cap::attenuate) (the only
derivation path);
- `CALL_NATIVE` runs [`check_native_call`](crate::check_native_call) **before**
indexing the function-pointer table.
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:
- mailbox growth is bounded per inbox (`MailboxConfig`: hop count + byte budget);
there is no runtime-wide byte cap across all flows;
- flow creation is capped only when [`RuntimeConfig::max_flows`](../src/scheduler/runtime.rs) is set (`0` = unlimited);
- outstanding `Ask` waits are released if the target exits (`TAG_SYS_EXIT`);
they are not otherwise quota-limited;
- native functions that consume arbitrary host resources.
Per-flow [`QuotaConfig`](crate::QuotaConfig) (CPU, heap, spawn/send rate)
and [`NativeMask`](crate::NativeMask) allowlists are enforced as of 0.9.2.
Defaults are generous so existing samples keep passing; sandboxed modules
must tighten `RuntimeConfig::quota` and spawn rights. There is still no
runtime-wide byte cap across all flows.
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.2 — implemented)
The security architecture is object-capability based:
`Value::Cap(CapId)` where [`CapId`](crate::CapId) is an opaque 128-bit CSPRNG
token — **not** a [`FlowId`](crate::FlowId).
A capability resolves through the per-runtime directory to
`{ holder, target, rights, 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`](crate::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`](crate::Cap::attenuate) is the **only**
grant-derivation path (AND of rights and [`NativeMask`](crate::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`](crate::CapRights::NATIVE) bit plus a [`NativeMask`](crate::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`](crate::Cap::attenuate).
### Phase 4
Optional host-side bytecode attestation.
---
## 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.
These may be implemented at higher layers where appropriate.