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
// See `super`'s module doc comment: real throwaway CAs and certs, real TLS handshakes,
// nothing mocked at the `rustls` layer.

use crate::serve::{
    handle_connection,
    tls::{Auth, Transport, accept_tls, build_transport},
};
use indicatrix_net::{
    handshake,
    messages::{Backend, ClientMessage, PeerRole, RenderRequest, StreamEvent, Welcome},
};
use rustls::pki_types::ServerName;
use std::{
    net::{Ipv4Addr, SocketAddr, TcpListener, TcpStream},
    path::Path,
    sync::Arc,
    thread,
};

use super::{final_only, fixtures::unique_temp_dir, read_stream_until_done, tiny_scene};

fn server_config_from(pki_dir: &Path) -> Arc<rustls::ServerConfig> {
    let ca = indicatrix_net::tls::load_ca(&pki_dir.join(crate::pki::CA_CERT_FILE)).unwrap();
    let certs =
        indicatrix_net::tls::load_certs(&pki_dir.join(crate::pki::SERVER_CERT_FILE)).unwrap();
    let key =
        indicatrix_net::tls::load_private_key(&pki_dir.join(crate::pki::SERVER_KEY_FILE)).unwrap();
    indicatrix_net::tls::server_config(ca, certs, key).unwrap()
}

/// Builds a client config that trusts `trust_ca_dir`'s CA and presents the client
/// certificate bundle in `bundle_dir` -- two separate directories, so a test can trust
/// one CA while presenting a certificate signed by a different one (see
/// `client_certificate_signed_by_a_different_ca_is_rejected`).
fn client_config_from(trust_ca_dir: &Path, bundle_dir: &Path) -> Arc<rustls::ClientConfig> {
    let ca = indicatrix_net::tls::load_ca(&trust_ca_dir.join(crate::pki::CA_CERT_FILE)).unwrap();
    let certs =
        indicatrix_net::tls::load_certs(&bundle_dir.join(crate::pki::CLIENT_CERT_FILE)).unwrap();
    let key = indicatrix_net::tls::load_private_key(&bundle_dir.join(crate::pki::CLIENT_KEY_FILE))
        .unwrap();
    indicatrix_net::tls::client_config(ca, certs, key).unwrap()
}

fn loopback_server_name() -> ServerName<'static> {
    ServerName::from(std::net::IpAddr::V4(Ipv4Addr::LOCALHOST))
}

/// Signs a client certificate whose validity window is entirely in the past,
/// bypassing `crate::pki::issue_client`'s fixed lifetime -- there is no public API for
/// issuing a deliberately expired certificate, so this test-only helper builds one
/// directly with `rcgen`.
fn issue_expired_client_bundle(pki_dir: &Path, out: &Path) {
    let ca_issuer = crate::pki::load_ca(pki_dir).unwrap();
    let mut params = rcgen::CertificateParams::new(Vec::<String>::new()).unwrap();
    params
        .distinguished_name
        .push(rcgen::DnType::CommonName, "expired-client");
    params.not_before = time::OffsetDateTime::now_utc() - time::Duration::days(10);
    params.not_after = time::OffsetDateTime::now_utc() - time::Duration::days(1);
    params.extended_key_usages = vec![rcgen::ExtendedKeyUsagePurpose::ClientAuth];
    let key_pair = rcgen::KeyPair::generate().unwrap();
    let cert = params.signed_by(&key_pair, &ca_issuer).unwrap();

    std::fs::create_dir_all(out).unwrap();
    let ca_pem = std::fs::read_to_string(pki_dir.join(crate::pki::CA_CERT_FILE)).unwrap();
    std::fs::write(out.join(crate::pki::CA_CERT_FILE), ca_pem).unwrap();
    std::fs::write(out.join(crate::pki::CLIENT_CERT_FILE), cert.pem()).unwrap();
    std::fs::write(
        out.join(crate::pki::CLIENT_KEY_FILE),
        key_pair.serialize_pem(),
    )
    .unwrap();
}

/// The full path: `cert init`, `issue-server`, `issue-client`, a real TLS 1.3 handshake
/// over loopback, HELLO/WELCOME, a `RenderRequest`, and a correctly sized radiance
/// buffer back -- proving the whole stack works together, not just each piece in
/// isolation.
#[test]
fn full_round_trip_handshake_and_render_over_loopback() {
    let pki = unique_temp_dir("roundtrip-pki");
    let bundle = unique_temp_dir("roundtrip-bundle");
    crate::pki::init(&pki).unwrap();
    crate::pki::issue_server(
        &pki,
        &["localhost".to_string()],
        &["127.0.0.1".parse().unwrap()],
    )
    .unwrap();
    crate::pki::issue_client(&pki, "test-client", &bundle).unwrap();

    let server_config = server_config_from(&pki);
    let client_cfg = client_config_from(&pki, &bundle);
    let auth = Auth {
        role: PeerRole::Viewer,
        allowlist: Some(pki.join(crate::pki::VIEWER_ALLOWLIST_FILE)),
    };

    let listener = TcpListener::bind("127.0.0.1:0").unwrap();
    let addr = listener.local_addr().unwrap();

    let server = thread::spawn(move || {
        let (stream, _) = listener.accept().unwrap();
        let (tls_stream, role) = accept_tls(stream, &server_config, &auth, None)
            .expect("handshake and allowlist check should both succeed");
        assert_eq!(role, PeerRole::Viewer);
        handle_connection(tls_stream, 2, &super::test_db()).unwrap();
    });

    let tcp = TcpStream::connect(addr).unwrap();
    let conn = rustls::ClientConnection::new(client_cfg, loopback_server_name()).unwrap();
    let mut client = rustls::StreamOwned::new(conn, tcp);

    indicatrix_net::messages::write_message(&mut client, &handshake::local_hello()).unwrap();
    let welcome: Welcome = indicatrix_net::messages::read_message(&mut client).unwrap();
    assert!(matches!(
        welcome.render.as_ref().unwrap().backend,
        Backend::Cpu { .. }
    ));

    let scene = tiny_scene();
    let request = RenderRequest {
        intent: indicatrix_net::messages::RequestIntent::Batch,
        request_id: 1,
        scene: scene.clone(),
        first_sample: 0,
        samples: 3,
        stream: final_only(0),
    };
    indicatrix_net::messages::write_message(
        &mut client,
        &ClientMessage::RenderRequest(Box::new(request)),
    )
    .unwrap();
    let events = read_stream_until_done(&mut client);
    let (header, payload) = events
        .iter()
        .find_map(|(e, p)| match e {
            StreamEvent::Frame(h) => Some((h, p.as_ref().unwrap())),
            _ => None,
        })
        .unwrap();
    assert_eq!(header.samples, 3);
    assert_eq!(
        payload.len(),
        scene.width as usize * scene.height as usize * indicatrix_net::radiance::BYTES_PER_PIXEL
    );

    drop(client);
    server.join().unwrap();

    std::fs::remove_dir_all(&pki).ok();
    std::fs::remove_dir_all(&bundle).ok();
}

/// A client certificate signed by a different CA than the server trusts must be
/// rejected before `check_auth` (the allowlist) ever runs -- this test uses
/// an allowlist-free `Auth` to isolate the CA-chain failure from the allowlist check
/// exercised separately below.
#[test]
fn client_certificate_signed_by_a_different_ca_is_rejected() {
    let pki_a = unique_temp_dir("diffca-a");
    let pki_b = unique_temp_dir("diffca-b");
    let bundle_b = unique_temp_dir("diffca-bundle-b");
    crate::pki::init(&pki_a).unwrap();
    crate::pki::issue_server(&pki_a, &[], &["127.0.0.1".parse().unwrap()]).unwrap();
    crate::pki::init(&pki_b).unwrap();
    crate::pki::issue_client(&pki_b, "intruder", &bundle_b).unwrap();

    let server_config = server_config_from(&pki_a);
    // Trusts CA A (so it accepts the server's own certificate), but presents a
    // client certificate signed by CA B.
    let client_cfg = client_config_from(&pki_a, &bundle_b);

    let listener = TcpListener::bind("127.0.0.1:0").unwrap();
    let addr = listener.local_addr().unwrap();

    let server = thread::spawn(move || {
        let (stream, _) = listener.accept().unwrap();
        let any_viewer = Auth {
            role: PeerRole::Viewer,
            allowlist: None,
        };
        accept_tls(stream, &server_config, &any_viewer, None)
    });

    let mut tcp = TcpStream::connect(addr).unwrap();
    let mut conn = rustls::ClientConnection::new(client_cfg, loopback_server_name()).unwrap();
    // Not asserted on: in a TLS 1.3 handshake the client can observe its own side as
    // "complete" before the server evaluates and rejects the client's certificate.
    // The server's own verdict, asserted below, is what this test is about.
    let _ = conn.complete_io(&mut tcp);

    let server_result = server.join().unwrap();
    assert!(
        server_result.is_none(),
        "the server must refuse a client certificate signed by a CA it doesn't trust"
    );

    std::fs::remove_dir_all(&pki_a).ok();
    std::fs::remove_dir_all(&pki_b).ok();
    std::fs::remove_dir_all(&bundle_b).ok();
}

/// Same CA on both sides (so the handshake itself succeeds), but the client's
/// certificate was never added to the allowlist -- proves the allowlist check in
/// `check_auth` runs after the handshake, not as a substitute for it.
#[test]
fn client_certificate_not_on_the_allowlist_is_rejected_after_a_successful_handshake() {
    let pki = unique_temp_dir("notallowed-pki");
    let bundle = unique_temp_dir("notallowed-bundle");
    crate::pki::init(&pki).unwrap();
    crate::pki::issue_server(&pki, &[], &["127.0.0.1".parse().unwrap()]).unwrap();
    crate::pki::issue_client(&pki, "stranger", &bundle).unwrap();

    // `issue_client` already added this fingerprint to the allowlist -- overwrite it
    // with an empty one so the certificate is valid but not trusted.
    let allowlist_path = pki.join(crate::pki::VIEWER_ALLOWLIST_FILE);
    std::fs::write(&allowlist_path, "").unwrap();

    let server_config = server_config_from(&pki);
    let client_cfg = client_config_from(&pki, &bundle);

    let listener = TcpListener::bind("127.0.0.1:0").unwrap();
    let addr = listener.local_addr().unwrap();

    let server = thread::spawn(move || {
        let (stream, _) = listener.accept().unwrap();
        accept_tls(
            stream,
            &server_config,
            &Auth {
                role: PeerRole::Viewer,
                allowlist: Some(allowlist_path),
            },
            None,
        )
    });

    let mut tcp = TcpStream::connect(addr).unwrap();
    let mut conn = rustls::ClientConnection::new(client_cfg, loopback_server_name()).unwrap();
    conn.complete_io(&mut tcp)
        .expect("the TLS handshake itself must succeed -- same CA on both sides");

    let server_result = server.join().unwrap();
    assert!(
        server_result.is_none(),
        "the server must refuse a certificate that isn't on the allowlist, even though the handshake succeeded"
    );

    std::fs::remove_dir_all(&pki).ok();
    std::fs::remove_dir_all(&bundle).ok();
}

/// An expired client certificate is rejected during the handshake, and the error text
/// names expiry specifically, not a generic "handshake failed".
#[test]
fn an_expired_client_certificate_is_rejected_and_the_error_names_expiry() {
    let pki = unique_temp_dir("expired-pki");
    let bundle = unique_temp_dir("expired-bundle");
    crate::pki::init(&pki).unwrap();
    crate::pki::issue_server(&pki, &[], &["127.0.0.1".parse().unwrap()]).unwrap();
    issue_expired_client_bundle(&pki, &bundle);

    let server_config = server_config_from(&pki);
    let client_cfg = client_config_from(&pki, &bundle);

    let listener = TcpListener::bind("127.0.0.1:0").unwrap();
    let addr = listener.local_addr().unwrap();

    let server = thread::spawn(move || {
        let (stream, _) = listener.accept().unwrap();
        let conn = rustls::ServerConnection::new(server_config).unwrap();
        let mut tls_stream = rustls::StreamOwned::new(conn, stream);
        tls_stream
            .conn
            .complete_io(&mut tls_stream.sock)
            .map_err(|e| e.to_string())
    });

    let mut tcp = TcpStream::connect(addr).unwrap();
    let mut conn = rustls::ClientConnection::new(client_cfg, loopback_server_name()).unwrap();
    let _ = conn.complete_io(&mut tcp); // the client side errors too; not what this test is about

    let err = server
        .join()
        .unwrap()
        .expect_err("the server must reject an expired client certificate");
    assert!(
        err.to_lowercase().contains("expired"),
        "expected the error to name expiry specifically, got: {err}"
    );

    std::fs::remove_dir_all(&pki).ok();
    std::fs::remove_dir_all(&bundle).ok();
}

/// A certificate carrying only a DNS SAN can never validate a connection made by IP
/// address, since `rustls` ignores Common Name entirely. Pinned down so nobody "fixes"
/// the resulting failure by loosening verification instead of adding the right SAN
/// with `cert issue-server --ip`.
#[test]
fn connecting_by_ip_against_a_dns_only_san_certificate_fails() {
    let pki = unique_temp_dir("dnsonly-pki");
    let bundle = unique_temp_dir("dnsonly-bundle");
    crate::pki::init(&pki).unwrap();
    // Deliberately only a DNS SAN -- no --ip.
    crate::pki::issue_server(&pki, &["worker.lan".to_string()], &[]).unwrap();
    crate::pki::issue_client(&pki, "test-client", &bundle).unwrap();

    let server_config = server_config_from(&pki);
    let client_cfg = client_config_from(&pki, &bundle);

    let listener = TcpListener::bind("127.0.0.1:0").unwrap();
    let addr = listener.local_addr().unwrap();

    let server = thread::spawn(move || {
        let (stream, _) = listener.accept().unwrap();
        let conn = rustls::ServerConnection::new(server_config).unwrap();
        let mut tls_stream = rustls::StreamOwned::new(conn, stream);
        let _ = tls_stream.conn.complete_io(&mut tls_stream.sock);
    });

    let mut tcp = TcpStream::connect(addr).unwrap();
    // Connecting by IP -- the certificate only carries a DNS SAN, so the
    // client itself must refuse to validate it.
    let mut conn = rustls::ClientConnection::new(client_cfg, loopback_server_name()).unwrap();
    let err = conn.complete_io(&mut tcp).expect_err(
        "connecting by IP against a DNS-only-SAN certificate must fail, not silently succeed",
    );
    assert!(
        err.to_string()
            .to_lowercase()
            .contains("not valid for name"),
        "{err}"
    );

    server.join().unwrap();
    std::fs::remove_dir_all(&pki).ok();
    std::fs::remove_dir_all(&bundle).ok();
}

/// `--insecure-no-tls` is for loopback debugging only -- combined with a
/// non-loopback `--bind`, `build_transport` must refuse it outright, even if
/// `--allow-remote` is also set (that flag governs the loopback/non-loopback
/// bind check, a separate, independent gate -- see `run`'s doc comment).
#[test]
fn insecure_no_tls_with_a_non_loopback_bind_is_refused() {
    let args = crate::cli::ServeArgs {
        bind: "0.0.0.0:7878".to_string(),
        threads: 0,
        allow_remote: true,
        ca: None,
        cert: None,
        key: None,
        allowlist: None,
        trust_any_client_cert: false,
        insecure_no_tls: true,
        compute_mode: crate::cli::ComputeMode::default(),
        render: false,
        enroll_bind: None,
        no_enroll: false,
        worker_bind: None,
        worker_enroll_bind: None,
        no_workers: false,
        worker_allowlist: None,
        db: None,
        max_connections: crate::cli::DEFAULT_MAX_CONNECTIONS,
        max_preauth_per_ip: crate::cli::DEFAULT_MAX_PREAUTH_PER_IP,
        interactive_workers: 0,
        pin_interactive_worker: None,
        max_job_memory_mib: crate::cli::DEFAULT_MAX_JOB_MEMORY_MIB,
        whole_image_secs: crate::cli::DEFAULT_WHOLE_IMAGE_SECS,
        whole_image_pixel_samples: crate::cli::DEFAULT_WHOLE_IMAGE_PIXEL_SAMPLES,
        jobs_per_viewer: crate::cli::DEFAULT_JOBS_PER_VIEWER,
        payload_encoding: indicatrix_net::messages::adaptive::PayloadChoice::Auto,
    };
    let bind_addr: SocketAddr = args.bind.parse().unwrap();
    let err = build_transport(&args, bind_addr).unwrap_err();
    assert!(err.contains("--insecure-no-tls"), "{err}");
}

/// The loopback counterpart to the refusal above -- `--insecure-no-tls`
/// combined with a loopback bind must succeed and produce `Transport::Insecure`.
#[test]
fn insecure_no_tls_with_a_loopback_bind_is_accepted() {
    let args = crate::cli::ServeArgs {
        bind: "127.0.0.1:7878".to_string(),
        threads: 0,
        allow_remote: false,
        ca: None,
        cert: None,
        key: None,
        allowlist: None,
        trust_any_client_cert: false,
        insecure_no_tls: true,
        compute_mode: crate::cli::ComputeMode::default(),
        render: false,
        enroll_bind: None,
        no_enroll: false,
        worker_bind: None,
        worker_enroll_bind: None,
        no_workers: false,
        worker_allowlist: None,
        db: None,
        max_connections: crate::cli::DEFAULT_MAX_CONNECTIONS,
        max_preauth_per_ip: crate::cli::DEFAULT_MAX_PREAUTH_PER_IP,
        interactive_workers: 0,
        pin_interactive_worker: None,
        max_job_memory_mib: crate::cli::DEFAULT_MAX_JOB_MEMORY_MIB,
        whole_image_secs: crate::cli::DEFAULT_WHOLE_IMAGE_SECS,
        whole_image_pixel_samples: crate::cli::DEFAULT_WHOLE_IMAGE_PIXEL_SAMPLES,
        jobs_per_viewer: crate::cli::DEFAULT_JOBS_PER_VIEWER,
        payload_encoding: indicatrix_net::messages::adaptive::PayloadChoice::Auto,
    };
    let bind_addr: SocketAddr = args.bind.parse().unwrap();
    assert!(matches!(
        build_transport(&args, bind_addr).unwrap(),
        Transport::Insecure
    ));
}