indicatrix-worker 0.7.2

Coordinator and render worker for an indicatrix-backed design catalogue. `serve` (default build) is the coordinator: it serves indicatrix-net's read-only design-library protocol to viewers over mutual TLS and accepts joining render workers on a separate worker port. The optional `worker` feature adds render capacity -- `join` (dial a coordinator and render its requests), `serve --render` (render with the coordinator's own CPU/GPU) and `render` (a one-shot scene-to-PNG CLI).
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
use super::{
    MAX_PENDING, TOKEN_TTL_SECS, connection::handle_enroll_connection, registry::EnrollRegistry,
};
use crate::pki;
use indicatrix_net::{
    enroll::{EnrollRequest, EnrollResponse},
    token,
};
use std::{
    io::{Cursor, Read, Write},
    net::SocketAddr,
    path::PathBuf,
    time::Duration,
};
use subtle::ConstantTimeEq;
use zeroize::Zeroizing;

/// The operator secret every registry built by [`authorised_registry`] accepts.
const OPERATOR_SECRET: [u8; 32] = [7u8; 32];

/// A viewer registry that authorises `IssueAuthorized` requests carrying
/// [`OPERATOR_SECRET`].
fn authorised_registry() -> EnrollRegistry {
    EnrollRegistry::new().with_operator_secret(Zeroizing::new(OPERATOR_SECRET))
}

fn unique_temp_dir(label: &str) -> PathBuf {
    let dir = std::env::temp_dir().join(format!(
        "indicatrix-worker-enroll-test-{label}-{}-{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    ));
    std::fs::create_dir_all(&dir).unwrap();
    dir
}

fn loopback_peer() -> SocketAddr {
    "127.0.0.1:54321".parse().unwrap()
}

fn remote_peer() -> SocketAddr {
    "203.0.113.7:54321".parse().unwrap()
}

// ---- EnrollRegistry: pure in-memory, no network -----------------------------

#[test]
fn a_valid_token_claims_exactly_once() {
    let dir = unique_temp_dir("claim-once");
    pki::init(&dir).unwrap();
    let registry = EnrollRegistry::new();

    let (encoded, _ttl) = registry
        .issue_with_ttl(&dir, "laptop", Duration::from_secs(60))
        .unwrap();
    let decoded = token::decode(&encoded).unwrap();

    let first = registry.claim(&decoded.secret);
    assert!(first.is_some(), "a fresh token must claim successfully");
    assert_eq!(first.unwrap().name, "laptop");

    let second = registry.claim(&decoded.secret);
    assert!(second.is_none(), "the same secret must not claim twice");

    std::fs::remove_dir_all(&dir).ok();
}

#[test]
fn an_expired_token_fails_and_the_pending_record_is_gone() {
    let dir = unique_temp_dir("expired");
    pki::init(&dir).unwrap();
    let registry = EnrollRegistry::new();

    let (encoded, _ttl) = registry
        .issue_with_ttl(&dir, "laptop", Duration::from_millis(20))
        .unwrap();
    let decoded = token::decode(&encoded).unwrap();

    std::thread::sleep(Duration::from_millis(60));

    assert!(registry.claim(&decoded.secret).is_none());
    assert_eq!(
        registry.pending.lock().unwrap().len(),
        0,
        "the expired record must have been swept, not merely failed to match"
    );

    std::fs::remove_dir_all(&dir).ok();
}

#[test]
fn a_wrong_token_fails_and_does_not_consume_the_pending_record() {
    let dir = unique_temp_dir("wrong-token");
    pki::init(&dir).unwrap();
    let registry = EnrollRegistry::new();

    let (encoded, _ttl) = registry
        .issue_with_ttl(&dir, "laptop", Duration::from_secs(60))
        .unwrap();
    let real = token::decode(&encoded).unwrap();

    let mut wrong_secret = *real.secret;
    wrong_secret[0] ^= 0xFF;
    assert!(registry.claim(&wrong_secret).is_none());
    assert_eq!(
        registry.pending.lock().unwrap().len(),
        1,
        "a wrong secret must not consume the real pending record"
    );

    // The real secret still claims successfully afterward.
    assert!(registry.claim(&real.secret).is_some());

    std::fs::remove_dir_all(&dir).ok();
}

#[test]
fn issue_refuses_once_the_pending_cap_is_reached() {
    let dir = unique_temp_dir("cap");
    pki::init(&dir).unwrap();
    let registry = EnrollRegistry::new();

    for i in 0..MAX_PENDING {
        registry
            .issue_with_ttl(&dir, &format!("viewer-{i}"), Duration::from_secs(60))
            .unwrap();
    }
    let err = registry
        .issue_with_ttl(&dir, "one-too-many", Duration::from_secs(60))
        .unwrap_err()
        .to_string();
    assert!(err.contains("already pending"), "{err}");

    std::fs::remove_dir_all(&dir).ok();
}

/// `EnrollRegistry::issue` must sanitize `name` the same way
/// `indicatrix_net::tls::append_to_allowlist` sanitizes an allowlist label -- an
/// operator-supplied `--name`/enrollment `name` containing `\r`/`\n`/`#` must not be
/// able to inject a stray allowlist line once this enrollment is claimed.
#[test]
fn issue_sanitizes_a_name_containing_line_breaks_and_a_comment_marker() {
    let dir = unique_temp_dir("issue-sanitizes-name");
    pki::init(&dir).unwrap();
    let registry = EnrollRegistry::new();

    let evil_name =
        "laptop\r\ndeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef  # not trusted";
    let (encoded, _ttl) = registry
        .issue_with_ttl(&dir, evil_name, Duration::from_secs(60))
        .unwrap();
    let decoded = token::decode(&encoded).unwrap();

    let claimed = registry
        .claim(&decoded.secret)
        .expect("a fresh token must claim successfully");
    assert!(!claimed.name.contains('\r'));
    assert!(!claimed.name.contains('\n'));
    assert!(!claimed.name.contains('#'));
    assert_eq!(
        claimed.name,
        indicatrix_net::tls::sanitize_allowlist_label(evil_name)
    );

    std::fs::remove_dir_all(&dir).ok();
}

#[test]
fn token_comparison_uses_constant_time_equality() {
    // Timing itself isn't observable in a unit test; this just pins down that
    // `EnrollRegistry::claim`'s `ct_eq` mechanism agrees with `==` on match/mismatch.
    let a = [7u8; 32];
    let b = [7u8; 32];
    let c = {
        let mut x = [7u8; 32];
        x[31] ^= 1;
        x
    };
    assert!(bool::from(a.ct_eq(&b)));
    assert!(!bool::from(a.ct_eq(&c)));
}

// ---- allowlist ordering -------------------------------------------------------

#[test]
fn allowlist_gains_the_fingerprint_only_after_a_successful_claim() {
    let dir = unique_temp_dir("allowlist-order");
    pki::init(&dir).unwrap();
    let allowlist_path = dir.join(pki::VIEWER_ALLOWLIST_FILE);
    let registry = EnrollRegistry::new();

    let (encoded, _ttl) = registry
        .issue_with_ttl(&dir, "laptop", Duration::from_secs(60))
        .unwrap();

    // Absent beforehand: issuing never touches the allowlist.
    assert!(
        !allowlist_path.exists(),
        "issuing a token must not create/append the allowlist"
    );

    // Drive the real connection handler, not just the registry in isolation.
    let mut input = Vec::new();
    let decoded = token::decode(&encoded).unwrap();
    indicatrix_net::messages::write_message(
        &mut input,
        &EnrollRequest::Claim {
            secret: *decoded.secret,
        },
    )
    .unwrap();
    let mut duplex = DuplexHalf::new(input);
    handle_enroll_connection(
        &mut duplex,
        &registry,
        &dir,
        Some(&allowlist_path),
        Some(loopback_peer()),
    )
    .unwrap();

    let mut out = Cursor::new(duplex.out);
    let response: EnrollResponse = indicatrix_net::messages::read_message(&mut out).unwrap();
    assert!(
        matches!(response, EnrollResponse::Claimed { .. }),
        "{response:?}"
    );

    let allowlist = indicatrix_net::tls::Allowlist::load(&allowlist_path).unwrap();
    assert_eq!(
        allowlist.len(),
        1,
        "exactly the claimed certificate, appended once"
    );

    std::fs::remove_dir_all(&dir).ok();
}

#[test]
fn a_failed_claim_never_touches_the_allowlist() {
    let dir = unique_temp_dir("allowlist-no-touch");
    pki::init(&dir).unwrap();
    let allowlist_path = dir.join(pki::VIEWER_ALLOWLIST_FILE);
    let registry = EnrollRegistry::new();

    registry
        .issue_with_ttl(&dir, "laptop", Duration::from_secs(60))
        .unwrap();

    let mut input = Vec::new();
    indicatrix_net::messages::write_message(
        &mut input,
        &EnrollRequest::Claim {
            secret: [0u8; token::SECRET_LEN], // essentially certainly wrong
        },
    )
    .unwrap();
    let mut duplex = DuplexHalf::new(input);
    handle_enroll_connection(
        &mut duplex,
        &registry,
        &dir,
        Some(&allowlist_path),
        Some(loopback_peer()),
    )
    .unwrap();

    let mut out = Cursor::new(duplex.out);
    let response: EnrollResponse = indicatrix_net::messages::read_message(&mut out).unwrap();
    assert!(
        matches!(response, EnrollResponse::ClaimFailed),
        "{response:?}"
    );
    assert!(!allowlist_path.exists());

    std::fs::remove_dir_all(&dir).ok();
}

// ---- Bounded read ----------------------------------------------------------------

/// A malicious/corrupt length prefix declaring far more than
/// `connection::MAX_ENROLL_REQUEST_LEN` must be rejected from the 4-byte prefix alone,
/// before `handle_enroll_connection` ever attempts to allocate a buffer for it -- this
/// listener accepts a connection from anyone (no client certificate required), so an
/// unauthenticated peer must not be able to make it commit to a huge allocation.
#[test]
fn handle_enroll_connection_rejects_an_oversized_length_prefix_without_allocating() {
    let dir = unique_temp_dir("oversized-prefix");
    pki::init(&dir).unwrap();
    let registry = EnrollRegistry::new();

    let mut input = Vec::new();
    input.extend_from_slice(&0x1FFF_FFFFu32.to_le_bytes());
    // Deliberately no payload bytes follow: if the bound weren't enforced before
    // allocating, this would need to actually supply ~512 MiB (or the read would hang
    // waiting for bytes that never arrive) instead of failing immediately.
    let mut duplex = DuplexHalf::new(input);

    let err = handle_enroll_connection(&mut duplex, &registry, &dir, None, Some(loopback_peer()))
        .unwrap_err();
    assert!(err.contains("exceeds"), "{err}");
    assert!(
        duplex.out.is_empty(),
        "a request rejected before decoding gets no reply written"
    );

    std::fs::remove_dir_all(&dir).ok();
}

// ---- Issue is loopback-only -----------------------------------------------------

#[test]
fn issue_is_refused_from_a_non_loopback_peer() {
    let dir = unique_temp_dir("issue-remote-refused");
    pki::init(&dir).unwrap();
    let registry = authorised_registry();

    let mut input = Vec::new();
    indicatrix_net::messages::write_message(
        &mut input,
        &EnrollRequest::IssueAuthorized {
            name: "intruder".to_string(),
            operator_secret: OPERATOR_SECRET,
        },
    )
    .unwrap();
    let mut duplex = DuplexHalf::new(input);
    handle_enroll_connection(&mut duplex, &registry, &dir, None, Some(remote_peer())).unwrap();

    let mut out = Cursor::new(duplex.out);
    let response: EnrollResponse = indicatrix_net::messages::read_message(&mut out).unwrap();
    assert!(
        matches!(response, EnrollResponse::IssueRefused { .. }),
        "{response:?}"
    );
    assert_eq!(registry.pending.lock().unwrap().len(), 0);

    std::fs::remove_dir_all(&dir).ok();
}

#[test]
fn issue_succeeds_from_a_loopback_peer() {
    let dir = unique_temp_dir("issue-loopback-ok");
    pki::init(&dir).unwrap();
    let registry = authorised_registry();

    let mut input = Vec::new();
    indicatrix_net::messages::write_message(
        &mut input,
        &EnrollRequest::IssueAuthorized {
            name: "laptop".to_string(),
            operator_secret: OPERATOR_SECRET,
        },
    )
    .unwrap();
    let mut duplex = DuplexHalf::new(input);
    handle_enroll_connection(&mut duplex, &registry, &dir, None, Some(loopback_peer())).unwrap();

    let mut out = Cursor::new(duplex.out);
    let response: EnrollResponse = indicatrix_net::messages::read_message(&mut out).unwrap();
    let EnrollResponse::Issued {
        token,
        expires_in_secs,
    } = response
    else {
        panic!("expected Issued, got {response:?}");
    };
    assert!(token.starts_with(indicatrix_net::token::TOKEN_PREFIX));
    assert_eq!(expires_in_secs, TOKEN_TTL_SECS);

    std::fs::remove_dir_all(&dir).ok();
}

/// Sends one `IssueAuthorized { name }` carrying [`OPERATOR_SECRET`] from loopback
/// through `registry`'s connection handler.
fn issue_via_handler(
    registry: &EnrollRegistry,
    dir: &std::path::Path,
    name: &str,
) -> EnrollResponse {
    let mut input = Vec::new();
    indicatrix_net::messages::write_message(
        &mut input,
        &EnrollRequest::IssueAuthorized {
            name: name.to_string(),
            operator_secret: OPERATOR_SECRET,
        },
    )
    .unwrap();
    let mut duplex = DuplexHalf::new(input);
    handle_enroll_connection(&mut duplex, registry, dir, None, Some(loopback_peer())).unwrap();
    indicatrix_net::messages::read_message(&mut Cursor::new(duplex.out)).unwrap()
}

/// A worker enrollment registry mints `worker:<name>` certificates and appends them to
/// the worker allowlist; each listener refuses an `Issue` for the other role.
#[test]
fn a_worker_listener_mints_worker_certificates_and_refuses_viewer_issues() {
    use indicatrix_net::messages::PeerRole;
    let dir = unique_temp_dir("worker-role");
    pki::init(&dir).unwrap();
    let workers = EnrollRegistry::for_role(PeerRole::Worker)
        .with_operator_secret(Zeroizing::new(OPERATOR_SECRET));
    let viewers = authorised_registry();

    assert!(matches!(
        issue_via_handler(&workers, &dir, "laptop"),
        EnrollResponse::IssueRefused { reason } if reason.contains("--role worker")
    ));
    assert!(matches!(
        issue_via_handler(&viewers, &dir, "worker:box"),
        EnrollResponse::IssueRefused { reason } if reason.contains("WORKER enrollment")
    ));
    let EnrollResponse::Issued { token, .. } = issue_via_handler(&workers, &dir, "worker:box")
    else {
        panic!("a worker issue on the worker listener must succeed");
    };

    let decoded = token::decode(&token).unwrap();
    let mut input = Vec::new();
    indicatrix_net::messages::write_message(
        &mut input,
        &EnrollRequest::Claim {
            secret: *decoded.secret,
        },
    )
    .unwrap();
    let worker_allowlist = dir.join(pki::WORKER_ALLOWLIST_FILE);
    let mut duplex = DuplexHalf::new(input);
    handle_enroll_connection(
        &mut duplex,
        &workers,
        &dir,
        Some(&worker_allowlist),
        Some(loopback_peer()),
    )
    .unwrap();
    let response: EnrollResponse =
        indicatrix_net::messages::read_message(&mut Cursor::new(duplex.out)).unwrap();
    let EnrollResponse::Claimed {
        client_cert_pem, ..
    } = response
    else {
        panic!("expected Claimed, got {response:?}");
    };
    let der = rustls_pemfile_cert(&client_cert_pem);
    assert_eq!(pki::role_of_certificate(&der).unwrap(), PeerRole::Worker);
    let allowlist = indicatrix_net::tls::Allowlist::load(&worker_allowlist).unwrap();
    assert!(allowlist.contains(&indicatrix_net::tls::fingerprint(&der.into())));

    std::fs::remove_dir_all(&dir).ok();
}

/// The DER bytes of the one certificate in `pem`.
fn rustls_pemfile_cert(pem: &str) -> Vec<u8> {
    let path = unique_temp_dir("pem").join("cert.pem");
    std::fs::write(&path, pem).unwrap();
    indicatrix_net::tls::load_certs(&path).unwrap()[0].to_vec()
}

// ---- A claim connection cannot issue a render request --------------------------

// Only compilable on a `worker` build -- `RenderRequest`/`SceneState` don't exist
// without it, and a library-only build has no render protocol to reach anyway.
#[cfg(feature = "worker")]
#[test]
fn a_claim_connection_cannot_issue_a_render_request() {
    use indicatrix::{
        geometry::cuts::StandardGemCuts,
        optics::{materials::GemMaterial, raytracer::LightingPreset},
    };
    use indicatrix_net::{
        SceneState,
        messages::{ClientMessage, RenderRequest, StreamConfig, TransferMode},
    };

    let dir = unique_temp_dir("no-render-on-enroll");
    pki::init(&dir).unwrap();
    let registry = EnrollRegistry::new();

    // A real render-protocol RenderRequest -- what the render listener would accept.
    let scene = SceneState {
        width: 4,
        height: 4,
        yaw: 0.4,
        pitch: 0.3,
        distance: 3.0,
        light_yaw: 0.85,
        light_pitch: 0.95,
        exposure: 1.0,
        max_bounces: 4,
        lighting_preset: LightingPreset::Daylight,
        material: GemMaterial::diamond(),
        planes: StandardGemCuts::standard_round_brilliant(),
        girdle_frosted: false,
        backdrop: 0.0,
        environment: indicatrix_net::scene::SceneEnvironment::Studio,
        surface_glare: 1.0,
        tools: Vec::new(),
        fluorescence: indicatrix::optics::fluorescence::Fluorescence::default(),
        head_shadow_deg: 16.0,
    };
    let request = RenderRequest {
        intent: indicatrix_net::messages::RequestIntent::Batch,
        request_id: 1,
        scene,
        first_sample: 0,
        samples: 4,
        stream: StreamConfig {
            transfer_mode: TransferMode::FinalOnly,
            cadence_ms: 0,
            preview: None,
        },
    };
    let mut input = Vec::new();
    indicatrix_net::messages::write_message(
        &mut input,
        &ClientMessage::RenderRequest(Box::new(request)),
    )
    .unwrap();

    let mut duplex = DuplexHalf::new(input);
    // `handle_enroll_connection` has no reference to `stream_emit` and writes only one
    // `EnrollResponse`, so there's no code path to rendering. postcard's enum encoding
    // is a bare variant index, not self-describing, so the RenderRequest bytes might
    // decode as a garbage `EnrollRequest` variant instead of failing outright -- either
    // way, whatever gets written back must decode as an `EnrollResponse` and nothing else.
    let _ = handle_enroll_connection(&mut duplex, &registry, &dir, None, Some(loopback_peer()));
    if !duplex.out.is_empty() {
        let mut out = Cursor::new(duplex.out);
        let response: EnrollResponse = indicatrix_net::messages::read_message(&mut out)
            .expect("the only thing this listener ever writes is an EnrollResponse");
        assert!(
            matches!(
                response,
                EnrollResponse::Issued { .. }
                    | EnrollResponse::IssueRefused { .. }
                    | EnrollResponse::Claimed { .. }
                    | EnrollResponse::ClaimFailed
            ),
            "{response:?}"
        );
        assert_eq!(
            out.position(),
            out.get_ref().len() as u64,
            "nothing beyond one EnrollResponse may ever be written back on this listener"
        );
    }

    std::fs::remove_dir_all(&dir).ok();
}

/// A `Read + Write` double over two independent in-memory buffers -- reimplemented
/// rather than shared with `crate::serve::tests::DuplexHalf` (private to that module),
/// and this module needs none of its `TimeoutRead` behavior.
struct DuplexHalf {
    in_: Cursor<Vec<u8>>,
    out: Vec<u8>,
}

impl DuplexHalf {
    fn new(input: Vec<u8>) -> Self {
        Self {
            in_: Cursor::new(input),
            out: Vec::new(),
        }
    }
}

impl Read for DuplexHalf {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        self.in_.read(buf)
    }
}

impl Write for DuplexHalf {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        self.out.write(buf)
    }
    fn flush(&mut self) -> std::io::Result<()> {
        Ok(())
    }
}