mosaik 0.3.13

A Rust runtime for building self-organizing, leaderless distributed systems.
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
# Intel TDX

Intel **Trust Domain Extensions (TDX)** is a hardware-based TEE technology that
provides confidential computing at the virtual machine level. Mosaik's TDX
support lets nodes running inside a TDX Trust Domain generate attestation
tickets and lets other nodes validate them against expected measurements.

Enable TDX support with the `tdx` feature flag:

```toml
[dependencies]
mosaik = { version = "0.3", features = ["tdx"] }
```

## Network Extension

The `tdx` feature adds a `.tdx()` method to `Network` via the `NetworkTdxExt`
trait:

```rust,ignore
use mosaik::{Network, tdx::NetworkTdxExt};

let network = Network::new("my-network".into()).await?;

// Check if TDX hardware is available
if network.tdx().available() {
    // Generate and install an attestation ticket
    network.tdx().install_own_ticket()?;
}
```

### Available Methods

| Method                                        | Description                                                  |
| --------------------------------------------- | ------------------------------------------------------------ |
| `available()`                                 | Returns `true` if TDX hardware is present and functional     |
| `ticket()`                                    | Generates a non-expiring TDX attestation ticket              |
| `ticket_with_expiration(exp)`                 | Generates a ticket with a specific expiration                |
| `install_own_ticket()`                        | Generates a ticket and adds it to the node's discovery entry |
| `measurements()`                              | Returns all TDX measurements (MR_TD, RTMRs)                  |
| `mrtd()`                                      | Returns the MR_TD measurement                                |
| `rtmr0()` / `rtmr1()` / `rtmr2()` / `rtmr3()` | Returns individual RTMR measurements                         |

## TDX Tickets

A `TdxTicket` wraps a hardware-generated TDX Quote together with mosaik-specific
extra data. The ticket structure:

```text
TdxTicket
├── quote_bytes     Raw TDX Quote (hardware-signed attestation)
└── extra
    ├── peer_id     The mosaik PeerId of the attesting node
    ├── network_id  The NetworkId the node belongs to
    ├── started_at  When the node process started
    ├── quoted_at   When the quote was generated
    └── expiration  Ticket expiration policy
```

The TDX Quote's `report_data` field contains a hash of the extra data, creating
a cryptographic binding between the hardware attestation and the mosaik peer
identity.

### Converting between ticket types

`TdxTicket` converts to and from mosaik's generic `Ticket` type:

```rust,ignore
// Generate a TDX-specific ticket
let generic_ticket: Ticket = network.tdx().ticket()?;

// Parse a generic ticket back into a TdxTicket
let tdx_ticket: TdxTicket = generic_ticket.try_into()?;

// Access TDX-specific fields
println!("Peer: {}", tdx_ticket.peer_id());
println!("MR_TD: {}", tdx_ticket.measurements().mrtd());
println!("Quote verified: {}", tdx_ticket.quote().verify().is_ok());
```

Tickets are compressed with zstd before serialization to reduce gossip overhead.

## Measurements

TDX measurements are 48-byte register values that identify the software running
inside a Trust Domain:

| Register | Description                                                 |
| -------- | ----------------------------------------------------------- |
| `MR_TD`  | Measurement of the TD build-time configuration and firmware |
| `RTMR0`  | Runtime measurement register 0                              |
| `RTMR1`  | Runtime measurement register 1                              |
| `RTMR2`  | Runtime measurement register 2                              |
| `RTMR3`  | Runtime measurement register 3                              |

### Creating measurements

```rust,ignore
use mosaik::tdx::Measurement;

// From a hex string (96 characters = 48 bytes)
let m = Measurement::hex("91eb2b44d141d4ece09f0c75c2c53d247a3c68edd7fafe8a3520c942a604a407de03ae6dc5f87f27428b2538873118b7");

// From a byte array
let m = Measurement::new([0u8; 48]);

// Parse from string at runtime
let m: Measurement = "91eb2b44...".parse()?;
```

### Reading local measurements

When running inside a TDX guest, you can read the local machine's measurements
directly without needing a `Network` instance:

```rust,ignore
use mosaik::tdx::Measurements;

let local = Measurements::local()?;
println!("MR_TD: {}", local.mrtd());
println!("RTMR0: {}", local.rtmr0());
println!("RTMR1: {}", local.rtmr1());
println!("RTMR2: {}", local.rtmr2());
println!("RTMR3: {}", local.rtmr3());
```

This is also available through `network.tdx().measurements()`, which delegates
to the same underlying call.

## Tdx

`Tdx` implements the `TicketValidator` trait for TDX attestation. It
validates that a peer's TDX Quote carries valid hardware signatures and that
the measurements match specified criteria.

### Basic usage

```rust,ignore
use mosaik::tdx::Tdx;

// Accept any valid TDX attestation (signatures must verify)
let validator = Tdx::new();

// Require a specific MR_TD value
let validator = Tdx::new()
    .require_mrtd("91eb2b44d141d4ece09f0c75c2c53d247a3c68edd7fafe8a3520c942a604a407de03ae6dc5f87f27428b2538873118b7");

// Require specific RTMRs
let validator = Tdx::new()
    .require_mrtd("...")
    .require_rtmr0("...")
    .require_rtmr2("...");
```

### Builder methods

| Method                       | Description                                         |
| ---------------------------- | --------------------------------------------------- |
| `new()` / `empty()`          | Accept any valid TDX attestation                    |
| `baseline(criteria)`         | Start from a `MeasurementsCriteria` baseline        |
| `from_local()`               | Require all measurements to match the local machine |
| `require_mrtd(measurement)`  | Require a specific MR_TD value                      |
| `require_rtmr0(measurement)` | Require a specific RTMR0 value                      |
| `require_rtmr1(measurement)` | Require a specific RTMR1 value                      |
| `require_rtmr2(measurement)` | Require a specific RTMR2 value                      |
| `require_rtmr3(measurement)` | Require a specific RTMR3 value                      |
| `require_own_mrtd()`         | Require the same MR_TD as the local machine         |
| `require_own_rtmr0()`        | Require the same RTMR0 as the local machine         |
| `require_own_rtmr1()`        | Require the same RTMR1 as the local machine         |
| `require_own_rtmr2()`        | Require the same RTMR2 as the local machine         |
| `require_own_rtmr3()`        | Require the same RTMR3 as the local machine         |
| `allow_variant(criteria)`    | Allow an alternative set of measurement criteria    |

The `from_local()` and `require_own_*` methods read measurements from TDX
hardware and return `Result`, so they require `?` or `.expect()` in the builder
chain.

### Validation checks

When validating a peer's ticket, `Tdx` performs these checks in order:

1. Deserializes the ticket data into a `TdxTicket`
2. Parses and verifies the TDX Quote's hardware signature
3. Verifies the quote's `report_data` matches the hash of the extra data
4. Checks the baseline measurement criteria against the quote's measurements
5. If variant criteria are configured, checks that at least one matches
6. Verifies the ticket's peer ID matches the peer entry's ID
7. Verifies the ticket's network ID matches the peer entry's network ID
8. Checks that the ticket has not expired

### Multiple measurement profiles

The `allow_variant` method lets you accept nodes with different software
configurations. The baseline criteria must always be satisfied, and at least one
variant must also match (if any are configured):

```rust,ignore
use mosaik::tdx::{Tdx, MeasurementsCriteria};

let validator = Tdx::new()
    // All nodes must have this MR_TD
    .require_mrtd("aabb...")
    // Accept nodes running firmware version A
    .allow_variant(
        MeasurementsCriteria::new().require_rtmr0("1111...")
    )
    // OR firmware version B
    .allow_variant(
        MeasurementsCriteria::new().require_rtmr0("2222...")
    );
```

### Matching local measurements

When every node in a group runs the same binary on the same TDX image, you can
require peers to present measurements identical to the local machine's — without
hardcoding hex strings. The values are read from TDX hardware at construction
time and become part of the validator's signature, so all nodes with the same
measurements will derive the same group identity.

```rust,ignore
use mosaik::tdx::Tdx;

// Require all measurements to match (MR_TD + all RTMRs)
let validator = Tdx::from_local()?;

// Require only specific registers to match
let validator = Tdx::new()
    .require_own_mrtd()?
    .require_own_rtmr2()?;

// Mix local and explicit measurements
let local = Measurements::local()?;
let validator = Tdx::new()
    .require_mrtd(local.mrtd())
    .require_rtmr1("abcd...");
```

This is particularly useful for collections and groups where the validator's
signature is part of the group identity — every peer with the same TDX image
will derive matching signatures automatically.

## Using TDX with Streams

```rust,ignore
use mosaik::*;
use mosaik::tdx::Tdx;

// Via the stream! macro
declare::stream!(
    pub SecureFeed = PriceUpdate, "secure.prices",
    consumer require_ticket: Tdx::new()
        .require_mrtd("..."),
);

// Via the builder API
let producer = network.streams()
    .producer::<PriceUpdate>()
    .require_ticket(Tdx::new().require_mrtd("..."))
    .build()?;

let consumer = network.streams()
    .consumer::<PriceUpdate>()
    .require_ticket(Tdx::new().require_mrtd("..."))
    .build();
```

## Using TDX with Groups

```rust,ignore
use mosaik::tdx::Tdx;
use mosaik::groups::GroupKey;

let validator = Tdx::new().require_mrtd("...");

let group = network.groups()
    .with_key(GroupKey::from(&validator))
    .with_state_machine(MyStateMachine::default())
    .require_ticket(validator)
    .join();
```

## Using TDX with Collections

```rust,ignore
use mosaik::*;
use mosaik::tdx::Tdx;

// Via the collection! macro with a hardcoded measurement
declare::collection!(
    pub SecureStore = mosaik::collections::Map<String, String>,
    "secure.store",
    require_ticket: Tdx::new().require_mrtd("..."),
);

// Via the collection! macro with local measurement matching
declare::collection!(
    pub SecureStore = mosaik::collections::Map<String, String>,
    "secure.store",
    require_ticket: Tdx::new()
        .require_own_mrtd()
        .expect("TDX must be available")
        .require_own_rtmr2()
        .expect("TDX must be available"),
);

// Via CollectionConfig
let config = CollectionConfig::default()
    .require_ticket(Tdx::from_local()?);

let writer = mosaik::collections::Map::<String, String>::writer_with_config(
    &network, store_id, config,
);
```

## TDX Image Builder

Mosaik includes a build-time tool for creating TDX guest images from Rust
crates. Two builder variants are available:

| Builder    | Target                      | Root Filesystem           | Binary Linking  | Feature Flag         |
| ---------- | --------------------------- | ------------------------- | --------------- | -------------------- |
| **Alpine** | `x86_64-unknown-linux-musl` | Alpine minirootfs (~5 MB) | Static (musl)   | `tdx-builder-alpine` |
| **Ubuntu** | `x86_64-unknown-linux-gnu`  | Ubuntu base (~25 MB)      | Dynamic (glibc) | `tdx-builder-ubuntu` |

Both builders cross-compile your binary, package it with a kernel and OVMF
firmware into a CPIO initramfs, pre-compute TDX measurements, and generate a
self-extracting QEMU launch script. Use `tdx-builder-all` to enable both.

### When to use which

- **Alpine** — smaller images, faster boot, ideal for lightweight services
  that don't need glibc or the Ubuntu package ecosystem.
- **Ubuntu** — full glibc environment with standard Ubuntu packages
  (`kmod`, `iproute2`, etc.) pre-installed. Better compatibility with
  libraries that require glibc or dynamically linked C dependencies.

### Enable in build-dependencies

```toml
[build-dependencies]
# Alpine only
mosaik = { version = "0.3", features = ["tdx-builder-alpine"] }

# Ubuntu only
mosaik = { version = "0.3", features = ["tdx-builder-ubuntu"] }

# Both
mosaik = { version = "0.3", features = ["tdx-builder-all"] }
```

### Usage in build.rs

```rust,ignore
fn main() {
    // Alpine builder
    let output = mosaik::tdx::build::alpine().build();

    // Ubuntu builder
    let output = mosaik::tdx::build::ubuntu().build();
}
```

You can also select the builder at build time via an environment variable:

```rust,ignore
fn main() {
    let output = match std::env::var("BUILD_TYPE").as_deref() {
        Err(_) | Ok("alpine") => {
            mosaik::tee::tdx::build::alpine().build()
        }
        Ok("ubuntu") => {
            mosaik::tee::tdx::build::ubuntu().build()
        }
        _ => panic!("Unknown BUILD_TYPE"),
    };
}
```

```bash
# Build with Alpine (default)
cargo build -p my-crate

# Build with Ubuntu
BUILD_TYPE=ubuntu cargo build -p my-crate
```

### Build steps

Both builders follow the same pipeline:

1. Cross-compile the current crate for the target triple
2. Download the base root filesystem (Alpine minirootfs or Ubuntu base)
3. Download a TDX-enabled kernel and OVMF firmware
4. Bundle everything into a gzipped CPIO initramfs
5. Pre-compute `MR_TD`, `RTMR[1]`, and `RTMR[2]` measurements
6. Generate a self-extracting QEMU launch script

The pre-computed `MR_TD` can be used directly in `Tdx::require_mrtd()`
for compile-time attestation binding — the binary that builds the image knows
exactly what measurement to expect from the resulting TDX guest.

### Builder options

Both `AlpineBuilder` and `UbuntuBuilder` share a common fluent API:

| Method                           | Description                                         |
| -------------------------------- | --------------------------------------------------- |
| `with_custom_vmlinuz(bytes)`     | Provide a kernel binary in-memory (skips download)  |
| `with_custom_ovmf(bytes)`        | Provide OVMF firmware in-memory (skips download)    |
| `with_ssh_key(pubkey)`           | Add an SSH public key for guest access              |
| `with_ssh_forward(host, guest)`  | Configure SSH port forwarding                       |
| `with_default_cpu_count(n)`      | Set default vCPU count (default: 4)                 |
| `with_default_memory_size(size)` | Set default memory size (default: `"4G"`)           |
| `with_bundle_runner()`           | Include the mosaik bundle runner (default)          |
| `without_bundle_runner()`        | Exclude the mosaik bundle runner                    |
| `with_extra_file(host, guest)`   | Bundle additional files into the image              |
| `with_kernel_module(path)`       | Include a `.ko` kernel module file                  |
| `with_kernel_modules_dir(path)`  | Auto-discover TDX kernel modules from a directory   |
| `with_kernel_version(v)`         | Set kernel version for download (e.g. `"6.8.0-55"`) |
| `with_kernel_abi(abi)`           | Set kernel ABI for download (e.g. `"57"`)           |
| `with_ovmf_version(v)`           | Set OVMF version for download                       |
| `with_artifacts_output_path(p)`  | Custom output directory for build artifacts         |
| `with_arg(arg)`                  | Append a command-line argument to the guest binary  |
| `with_args(args)`                | Append multiple command-line arguments at once      |
| `with_env(key, value)`           | Set an environment variable for the guest binary    |

**Alpine-specific:**

| Method                          | Description                                 |
| ------------------------------- | ------------------------------------------- |
| `with_major_version(v)`         | Alpine major version (default: `"3.21"`)    |
| `with_minor_version(v)`         | Alpine patch release (default: `"0"`)       |
| `with_custom_minirootfs(bytes)` | Provide Alpine minirootfs tarball in-memory |

**Ubuntu-specific:**

| Method                      | Description                                  |
| --------------------------- | -------------------------------------------- |
| `with_ubuntu_version(v)`    | Ubuntu version (default: `"24.04.4"`)        |
| `with_custom_rootfs(bytes)` | Provide Ubuntu base rootfs tarball in-memory |

### Environment variable overrides

Both builders respect environment variables for CI or scripted builds:

| Variable                       | Description                             |
| ------------------------------ | --------------------------------------- |
| `TDX_IMAGE_SKIP=1`             | Skip the entire TDX image build         |
| `TDX_IMAGE_ALPINE_VERSION`     | Alpine major version (Alpine builder)   |
| `TDX_IMAGE_ALPINE_MINOR`       | Alpine patch release (Alpine builder)   |
| `TDX_IMAGE_UBUNTU_VERSION`     | Ubuntu version (Ubuntu builder)         |
| `TDX_IMAGE_KERNEL`             | Path to a custom kernel binary          |
| `TDX_IMAGE_KERNEL_VERSION`     | Ubuntu kernel version for download      |
| `TDX_IMAGE_KERNEL_ABI`         | Ubuntu kernel ABI for download          |
| `TDX_IMAGE_OVMF`               | Path to a custom OVMF firmware file     |
| `TDX_IMAGE_OVMF_VERSION`       | OVMF version for download               |
| `TDX_IMAGE_EXTRA_FILES`        | Colon-separated `host:guest` file pairs |
| `TDX_IMAGE_KERNEL_MODULES`     | Colon-separated `.ko` module paths      |
| `TDX_IMAGE_KERNEL_MODULES_DIR` | Kernel modules auto-discovery directory |

### Build artifacts

Both builders produce the same set of artifacts under
`<target_dir>/<profile>/tdx-artifacts/<crate_name>/<distro>/`:

| File                        | Description                        |
| --------------------------- | ---------------------------------- |
| `<crate>-initramfs.cpio.gz` | Gzipped initramfs                  |
| `<crate>-vmlinuz`           | Kernel binary                      |
| `<crate>-ovmf.fd`           | OVMF firmware                      |
| `<crate>-run-qemu.sh`       | Self-extracting QEMU launch script |
| `<crate>-launch-tdx.sh`     | Simple launch wrapper              |
| `<crate>-mrtd.hex`          | Pre-computed MR_TD measurement     |
| `<crate>-rtmr1.hex`         | Pre-computed RTMR[1] measurement   |
| `<crate>-rtmr2.hex`         | Pre-computed RTMR[2] measurement   |