countersign-gateway 0.2.1

Forward proxy for user-approved client certificate authentication
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
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
use base64::{Engine, engine::general_purpose::STANDARD};
use countersign_gateway::{
    upstream::{self, SigningRelay},
    worker_sandbox::{Landlock, Layer, Layers},
};
use countersign_protocol::{
    Origin,
    wire::{GatewayActivation, SignatureScheme as Scheme, TlsVersion},
};
use nix::sys::socket::{ControlMessage, ControlMessageOwned, MsgFlags, recvmsg, sendmsg};
use rcgen::{CertificateParams, KeyPair};
use rustls::{
    RootCertStore, ServerConfig, ServerConnection, client::WebPkiServerVerifier,
    crypto::ring::default_provider,
};
use rustls_pki_types::{CertificateDer, CertificateRevocationListDer, PrivatePkcs8KeyDer};
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use std::{
    io::{IoSlice, IoSliceMut, Read, Write},
    os::{
        fd::{AsRawFd, FromRawFd, OwnedFd},
        unix::{
            net::{UnixDatagram, UnixStream},
            process::ExitStatusExt,
        },
    },
    process::{Command, ExitStatus, Stdio},
    sync::{
        Arc, Mutex,
        atomic::{AtomicUsize, Ordering},
    },
    time::Duration,
};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio_rustls::TlsAcceptor;

use super::{Result, config::WorkerSandbox, forward, invalid};

#[derive(Serialize, Deserialize)]
pub struct Start {
    pub origin: Origin,
    pub activation: GatewayActivation,
    pub roots: Vec<String>,
    pub crls: Vec<String>,
}
#[derive(Serialize, Deserialize)]
pub enum CommandMessage {
    UpstreamResponse,
    OpenStream(u64),
    CloseStream(u64),
    Csr(String),
    Sign {
        tls: TlsVersion,
        scheme: Scheme,
        input: String,
        peer_chain: Vec<String>,
    },
    Ready,
}
#[derive(Serialize, Deserialize)]
pub enum Reply {
    StreamGranted(bool),
    Certificates(Vec<String>),
    Signature(String),
    Proceed,
}
const MAX_MESSAGE: usize = 2 * 1024 * 1024;

fn encode<T: Serialize>(value: &T) -> Result<Vec<u8>> {
    let bytes = serde_json::to_vec(value)?;
    if bytes.len() > MAX_MESSAGE {
        return Err(invalid("worker IPC exceeds limit"));
    }
    let mut framed = Vec::with_capacity(bytes.len() + 4);
    framed.extend_from_slice(&(bytes.len() as u32).to_be_bytes());
    framed.extend_from_slice(&bytes);
    Ok(framed)
}
fn size(header: [u8; 4]) -> Result<usize> {
    let n = u32::from_be_bytes(header) as usize;
    if n > MAX_MESSAGE {
        return Err(invalid("worker IPC exceeds limit"));
    }
    Ok(n)
}
fn read<T: DeserializeOwned>(socket: &mut UnixStream) -> Result<T> {
    let mut header = [0u8; 4];
    socket.read_exact(&mut header)?;
    let mut buf = vec![0; size(header)?];
    socket.read_exact(&mut buf)?;
    Ok(serde_json::from_slice(&buf)?)
}
pub async fn send<T: Serialize>(socket: &mut tokio::net::UnixStream, value: &T) -> Result<()> {
    socket.write_all(&encode(value)?).await?;
    Ok(())
}
pub async fn receive<T: DeserializeOwned>(socket: &mut tokio::net::UnixStream) -> Result<T> {
    let mut header = [0; 4];
    socket.read_exact(&mut header).await?;
    let mut buf = vec![0; size(header)?];
    socket.read_exact(&mut buf).await?;
    Ok(serde_json::from_slice(&buf)?)
}

/// The command that starts a grant worker under the chosen worker sandbox.
/// Either way it gets a cleared environment, and it confines itself with the
/// base layers once it runs.
fn launch_command(sandbox: WorkerSandbox, executable: &std::path::Path) -> Command {
    match sandbox {
        WorkerSandbox::Namespaces => namespace_sandbox(executable),
        WorkerSandbox::Filter => filter_sandbox(executable),
    }
}

/// The filter sandbox: the supervisor starts the grant worker itself.
fn filter_sandbox(executable: &std::path::Path) -> Command {
    use std::os::unix::process::CommandExt;
    let mut command = Command::new(executable);
    command.env_clear();
    let supervisor = std::process::id() as nix::libc::pid_t;
    // SAFETY: the closure runs between fork and exec, and makes only system
    // calls: no allocation, no locks.
    unsafe {
        command.pre_exec(move || {
            use nix::libc;
            let check = |result: libc::c_long| match result {
                -1 => Err(std::io::Error::last_os_error()),
                _ => Ok(()),
            };
            // What bubblewrap's --die-with-parent does under the namespace
            // sandbox: a grant worker does not outlive its supervisor, whose
            // end it would not see on its control socket. The supervisor may
            // have ended before the request took effect.
            check(libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGKILL).into())?;
            if libc::getppid() != supervisor {
                return Err(std::io::Error::from_raw_os_error(libc::ESRCH));
            }
            // Only the control socket and the standard streams stay open
            // across the exec, whatever the supervisor itself inherited.
            // Marked and not closed here: the standard library reports a
            // failed exec over a descriptor of its own.
            let marked = check(libc::syscall(
                libc::SYS_close_range,
                3 as libc::c_uint,
                libc::c_uint::MAX,
                libc::CLOSE_RANGE_CLOEXEC,
            ));
            // Linux before 5.11 has no such flag, and an older container
            // profile refuses the call.
            marked.or_else(|_| mark_each_close_on_exec())
        });
    }
    command
}

/// Mark every descriptor above the standard streams close-on-exec, one at a
/// time, as listed by the kernel. It fails when it cannot list or mark them.
///
/// # Safety
/// Makes only system calls, with no allocation and no locks, so it may run
/// between fork and exec, where the process has one thread.
unsafe fn mark_each_close_on_exec() -> std::io::Result<()> {
    use nix::libc;
    let failed = std::io::Error::last_os_error;
    // SAFETY (the whole body): every pointer stays inside `entries`, which
    // the kernel filled with `read` bytes of whole directory entries, each
    // with a NUL-terminated name. `dir` is open from here to the close below.
    unsafe {
        let dir = libc::open(
            c"/proc/self/fd".as_ptr(),
            libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC,
        );
        if dir < 0 {
            return Err(failed());
        }
        // Of 64-bit words: a directory entry starts with one.
        let mut entries = [0u64; 512];
        loop {
            let read = libc::syscall(
                libc::SYS_getdents64,
                dir,
                entries.as_mut_ptr(),
                std::mem::size_of_val(&entries),
            );
            if read == 0 {
                break;
            }
            if read < 0 {
                return Err(failed());
            }
            let mut at = 0;
            while at < read as usize {
                let entry = entries
                    .as_ptr()
                    .cast::<u8>()
                    .add(at)
                    .cast::<libc::dirent64>();
                at += (*entry).d_reclen as usize;
                // The name is the descriptor's number. `.` and `..` are not one.
                let mut digit = (&raw const (*entry).d_name).cast::<u8>();
                let mut fd: libc::c_int = 0;
                while (*digit).is_ascii_digit() {
                    fd = fd * 10 + libc::c_int::from(*digit - b'0');
                    digit = digit.add(1);
                }
                if *digit != 0 || fd <= 2 {
                    continue;
                }
                if libc::fcntl(fd, libc::F_SETFD, libc::FD_CLOEXEC) < 0 {
                    return Err(failed());
                }
            }
        }
        // Itself close-on-exec, and closed on every other path by the exit
        // that follows a failed launch.
        libc::close(dir);
    }
    Ok(())
}

/// The namespace sandbox: only public runtime libraries and the executable
/// enter this grant's new mount, PID and network namespaces. Each inherited
/// stream is private IPC.
fn namespace_sandbox(executable: &std::path::Path) -> Command {
    let mut command = Command::new("/usr/bin/bwrap");
    command
        .env_clear()
        .args([
            "--unshare-all",
            "--die-with-parent",
            "--new-session",
            "--cap-drop",
            "ALL",
            "--clearenv",
            "--ro-bind",
            "/lib",
            "/lib",
            "--ro-bind-try",
            "/lib64",
            "/lib64",
            "--ro-bind",
        ])
        .arg(executable)
        .args(["/worker", "--chdir", "/", "--", "/worker"]);
    command
}

/// Why the startup probe failed: the chosen worker sandbox, the layer that
/// failed and the cause. It names no other sandbox: the operator reads the
/// trade-off before choosing one (ADR 0001, decision 4).
#[derive(Debug, thiserror::Error)]
#[error(
    "worker sandbox \"{sandbox}\" failed: {layer}: {cause}\nSee \"Choose a worker sandbox\" in the operator guide: https://zeroae.github.io/countersign/operate/#choose-a-worker-sandbox"
)]
pub struct SandboxError {
    sandbox: WorkerSandbox,
    layer: String,
    cause: String,
}

/// The exit status of a grant worker that could not apply a base layer. It
/// carries the layer to the startup probe, through bubblewrap too, which
/// exits with the status of the grant worker it ran. The cause is on the
/// standard error stream.
pub const fn failed_layer_exit(layer: Layer) -> i32 {
    match layer {
        Layer::NonDumpable => 64,
        Layer::Landlock => 65,
        Layer::AllowList => 66,
    }
}
fn failed_layer(status: ExitStatus) -> Option<Layer> {
    [Layer::NonDumpable, Layer::Landlock, Layer::AllowList]
        .into_iter()
        .find(|layer| status.code() == Some(failed_layer_exit(*layer)))
}

/// Resolves with a grant worker's exit status when it ends on its own, and
/// with an error when the supervisor stopped it.
pub type Exit = tokio::sync::oneshot::Receiver<ExitStatus>;

/// Whether the seccomp allow-list killed this grant worker. bubblewrap, which
/// the supervisor waits on under the namespace sandbox, reports its child's
/// fatal signal as an exit code of 128 plus the signal (measured with
/// bubblewrap 0.9.0 on 2026-11-19: `bwrap ... sh -c 'kill -SYS $$'` exits 159).
pub fn killed_by_filter(status: ExitStatus) -> bool {
    let sigsys = nix::libc::SIGSYS;
    status.signal() == Some(sigsys) || status.code() == Some(128 + sigsys)
}

/// The startup probe's report of a grant worker's layers, in one byte: the
/// Landlock ABI, or 0 for none.
fn report(layers: Layers) -> [u8; 1] {
    match layers.landlock {
        Landlock::Unavailable => [0],
        Landlock::Abi(abi) => [abi],
    }
}
fn reported(report: [u8; 1]) -> Layers {
    Layers {
        landlock: match report {
            [0] => Landlock::Unavailable,
            [abi] => Landlock::Abi(abi),
        },
    }
}

pub struct ChildHandle {
    control: UnixDatagram,
    /// Dropping this stops the grant worker.
    _stop: tokio::sync::oneshot::Sender<()>,
}
impl ChildHandle {
    fn start(
        sandbox: WorkerSandbox,
        stderr: Stdio,
    ) -> Result<(tokio::process::Child, UnixDatagram)> {
        let (control, child_control) = UnixDatagram::pair()?;
        control.set_nonblocking(true)?;
        let process =
            tokio::process::Command::from(launch_command(sandbox, &std::env::current_exe()?))
                .kill_on_drop(true)
                .arg("grant-worker")
                .stdin(Stdio::from(OwnedFd::from(child_control)))
                .stdout(Stdio::null())
                .stderr(stderr)
                .spawn()?;
        Ok((process, control))
    }

    pub fn launch(sandbox: WorkerSandbox) -> Result<(Self, Exit)> {
        let (mut process, control) = Self::start(sandbox, Stdio::null())?;
        let (stop, mut stopped) = tokio::sync::oneshot::channel::<()>();
        let (report, exit) = tokio::sync::oneshot::channel();
        tokio::spawn(async move {
            tokio::select! {
                status = process.wait() => {
                    if let Ok(status) = status {
                        let _ = report.send(status);
                    }
                }
                _ = &mut stopped => {
                    let _ = process.kill().await;
                }
            }
        });
        Ok((
            Self {
                control,
                _stop: stop,
            },
            exit,
        ))
    }

    /// Check the chosen worker sandbox, the executable and the control socket
    /// at startup. This short-lived worker receives no grant, credentials or
    /// traffic. It confines itself as every grant worker does and reports its
    /// layers.
    pub async fn verify_environment(
        sandbox: WorkerSandbox,
    ) -> std::result::Result<Layers, SandboxError> {
        Self::probe(sandbox)
            .await
            .map_err(|(layer, cause)| SandboxError {
                sandbox,
                layer: match layer {
                    Some(base) => base.to_string(),
                    // Not a base layer's failure, so the supervisor's: the
                    // layer it adds, or under the filter sandbox, which adds
                    // none, the launch itself.
                    None => sandbox.outer_layer().unwrap_or("launch").to_owned(),
                },
                cause,
            })
    }

    /// The probe's layers, or the base layer that failed, when it was one,
    /// and the cause.
    async fn probe(sandbox: WorkerSandbox) -> std::result::Result<Layers, (Option<Layer>, String)> {
        let supervisor = |error: &dyn std::fmt::Display| (None, error.to_string());
        let (process, control) =
            Self::start(sandbox, Stdio::piped()).map_err(|error| supervisor(&error))?;
        control.send(&[0]).map_err(|error| supervisor(&error))?;
        let output = tokio::time::timeout(Duration::from_secs(5), process.wait_with_output())
            .await
            .map_err(|_| supervisor(&"the probe grant worker did not finish in 5 seconds"))?
            .map_err(|error| supervisor(&error))?;
        if killed_by_filter(output.status) {
            return Err((
                Some(Layer::AllowList),
                "the allow-list killed the probe grant worker (SIGSYS)".to_owned(),
            ));
        }
        if !output.status.success() {
            let hint: String = String::from_utf8_lossy(&output.stderr)
                .split_whitespace()
                .collect::<Vec<_>>()
                .join(" ")
                .chars()
                .take(512)
                .collect();
            return Err((
                failed_layer(output.status),
                if hint.is_empty() {
                    format!("the probe grant worker ended with {}", output.status)
                } else {
                    hint
                },
            ));
        }
        // The report was queued before the probe exited.
        let mut message = [0u8; 2];
        match control.recv(&mut message) {
            Ok(1) => Ok(reported([message[0]])),
            _ => Err(supervisor(&"the probe grant worker reported no layers")),
        }
    }

    pub fn attach(&mut self) -> Result<[tokio::net::UnixStream; 3]> {
        let (a, b) = UnixStream::pair()?;
        let (c, d) = UnixStream::pair()?;
        let (e, f) = UnixStream::pair()?;
        let fds = [b.as_raw_fd(), d.as_raw_fd(), f.as_raw_fd()];
        sendmsg::<()>(
            self.control.as_raw_fd(),
            &[IoSlice::new(&[1])],
            &[ControlMessage::ScmRights(&fds)],
            MsgFlags::MSG_NOSIGNAL,
            None,
        )?;
        let stream = |s: UnixStream| -> Result<tokio::net::UnixStream> {
            s.set_nonblocking(true)?;
            Ok(tokio::net::UnixStream::from_std(s)?)
        };
        Ok([stream(a)?, stream(c)?, stream(e)?])
    }
}

pub fn serve(layers: Layers) -> Result<()> {
    // No secrets or network sockets are inherited. The authenticated parent
    // delivers three fresh, connected local stream endpoints per connection.
    let active = Arc::new(AtomicUsize::new(0));
    loop {
        let mut byte = [0u8; 1];
        let mut iov = [IoSliceMut::new(&mut byte)];
        let mut space = nix::cmsg_space!([i32; 3]);
        let msg = recvmsg::<()>(0, &mut iov, Some(&mut space), MsgFlags::MSG_CMSG_CLOEXEC)?;
        let mut received = Vec::new();
        for control in msg.cmsgs()? {
            if let ControlMessageOwned::ScmRights(fds) = control {
                for fd in fds {
                    // SAFETY: each SCM_RIGHTS descriptor is freshly allocated to this
                    // process by recvmsg and transferred exactly once here.
                    received.push(unsafe { UnixStream::from_raw_fd(fd) });
                }
            }
        }
        if msg.bytes != 1
            || msg
                .flags
                .intersects(MsgFlags::MSG_TRUNC | MsgFlags::MSG_CTRUNC)
        {
            return Err(invalid("invalid worker dispatch"));
        }
        if byte == [0] && received.is_empty() {
            // The startup probe. It reports this grant worker's layers from
            // where a connection is served, a thread with an async runtime, so
            // a host that the allow-list cannot serve on fails at startup.
            return std::thread::spawn(move || -> Result<()> {
                tokio::runtime::Builder::new_current_thread()
                    .enable_all()
                    .build()?;
                nix::unistd::write(std::io::stdin(), &report(layers))?;
                Ok(())
            })
            .join()
            .map_err(|_| invalid("worker sandbox probe panicked"))?;
        }
        if byte != [1] {
            return Err(invalid("invalid worker control command"));
        }
        let [down, up, control]: [UnixStream; 3] = received
            .try_into()
            .map_err(|_| invalid("invalid worker streams"))?;
        if active.load(Ordering::Acquire) >= 32 {
            continue;
        }
        active.fetch_add(1, Ordering::AcqRel);
        let active = active.clone();
        // Unnamed: naming a thread is one more system call to allow.
        std::thread::Builder::new().spawn(move || {
            let _ = run(down, up, control);
            active.fetch_sub(1, Ordering::AcqRel);
        })?;
    }
}

struct Relay {
    control: Mutex<UnixStream>,
}
impl SigningRelay for Relay {
    fn sign(
        &self,
        v: rustls::ProtocolVersion,
        s: rustls::SignatureScheme,
        peer_chain: &[CertificateDer<'static>],
        data: &[u8],
    ) -> std::result::Result<Vec<u8>, rustls::Error> {
        use rustls::SignatureScheme::*;
        let deny = || rustls::Error::General("scoped signing unavailable".into());
        let tls = match v {
            rustls::ProtocolVersion::TLSv1_3 => TlsVersion::Tls13,
            rustls::ProtocolVersion::TLSv1_2 => TlsVersion::Tls12,
            _ => return Err(deny()),
        };
        let scheme = match s {
            ECDSA_NISTP256_SHA256 => Scheme::EcdsaNistp256Sha256,
            ECDSA_NISTP384_SHA384 => Scheme::EcdsaNistp384Sha384,
            RSA_PSS_SHA256 => Scheme::RsaPssSha256,
            RSA_PSS_SHA384 => Scheme::RsaPssSha384,
            RSA_PSS_SHA512 => Scheme::RsaPssSha512,
            RSA_PKCS1_SHA256 => Scheme::RsaPkcs1Sha256,
            RSA_PKCS1_SHA384 => Scheme::RsaPkcs1Sha384,
            RSA_PKCS1_SHA512 => Scheme::RsaPkcs1Sha512,
            _ => return Err(deny()),
        };
        let mut control = self.control.lock().map_err(|_| deny())?;
        let bytes = encode(&CommandMessage::Sign {
            tls,
            scheme,
            input: STANDARD.encode(data),
            peer_chain: peer_chain
                .iter()
                .map(|cert| STANDARD.encode(cert))
                .collect(),
        })
        .map_err(|_| deny())?;
        control.write_all(&bytes).map_err(|_| deny())?;
        match read(&mut control).map_err(|_| deny())? {
            Reply::Signature(text) => STANDARD.decode(text).map_err(|_| deny()),
            _ => Err(deny()),
        }
    }
}
fn run(down: UnixStream, up: UnixStream, mut control: UnixStream) -> Result<()> {
    control.set_read_timeout(Some(Duration::from_secs(120)))?;
    control.set_write_timeout(Some(Duration::from_secs(5)))?;
    let start: Start = read(&mut control)?;
    let key = KeyPair::generate()?;
    let csr =
        CertificateParams::new(vec![start.origin.host().to_owned()])?.serialize_request(&key)?;
    control.write_all(&encode(&CommandMessage::Csr(STANDARD.encode(csr.der())))?)?;
    let Reply::Certificates(certs) = read(&mut control)? else {
        return Err(invalid("invalid issuer response"));
    };
    let certs = certs
        .iter()
        .map(|b| STANDARD.decode(b).map(CertificateDer::from))
        .collect::<std::result::Result<Vec<_>, _>>()?;
    let provider = Arc::new(default_provider());
    let mut server = ServerConfig::builder_with_provider(provider.clone())
        .with_safe_default_protocol_versions()?
        .with_no_client_auth()
        .with_single_cert(certs, PrivatePkcs8KeyDer::from(key.serialize_der()).into())?;
    server.session_storage = Arc::new(rustls::server::NoServerSessionStorage {});
    server.send_tls13_tickets = 0;
    server.max_early_data_size = 0;
    server.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()];
    let mut roots = RootCertStore::empty();
    for root in start.roots {
        roots.add(CertificateDer::from(STANDARD.decode(root)?))?;
    }
    let mut verifier = WebPkiServerVerifier::builder_with_provider(Arc::new(roots), provider);
    if !start.crls.is_empty() {
        let crls = start
            .crls
            .iter()
            .map(|c| STANDARD.decode(c).map(CertificateRevocationListDer::from))
            .collect::<std::result::Result<Vec<_>, _>>()?;
        verifier = verifier.with_crls(crls).enforce_revocation_expiration();
    }
    let verifier = verifier.build()?;
    let chain = start
        .activation
        .chain
        .as_slice()
        .iter()
        .map(|b| CertificateDer::from(b.as_slice().to_vec()))
        .collect();
    let fp = start
        .activation
        .activation
        .grant
        .cert_sha256
        .as_slice()
        .try_into()?;
    // The current-thread executor belongs to this connection only. A native
    // signing wait cannot starve another connection or the parent lease timers.
    tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()?
        .block_on(async {
            down.set_nonblocking(true)?;
            up.set_nonblocking(true)?;
            let down = tokio::net::UnixStream::from_std(down)?;
            let up = tokio::net::UnixStream::from_std(up)?;
            let down = TlsAcceptor::from(Arc::new(server)).accept(down).await?;
            let tls: &ServerConnection = down.get_ref().1;
            let name = tls
                .server_name()
                .ok_or_else(|| invalid("missing downstream SNI"))?;
            if name != start.origin.host() {
                return Err(invalid("downstream SNI mismatch"));
            }
            let down_h2 = tls.alpn_protocol() == Some(b"h2");
            let relay = Arc::new(Relay {
                control: Mutex::new(control.try_clone()?),
            });
            let up = upstream::connect(up, &start.origin, verifier, chain, fp, relay).await?;
            let up_h2 = up.get_ref().1.alpn_protocol() == Some(b"h2");
            control.write_all(&encode(&CommandMessage::Ready)?)?;
            let Reply::Proceed = read(&mut control)? else {
                return Err(invalid("connection admission refused"));
            };
            let limits = Arc::new(StreamLimits {
                control: Mutex::new(control),
                next: std::sync::atomic::AtomicU64::new(1),
                upstream_response: std::sync::atomic::AtomicBool::new(false),
            });
            forward::http(down, down_h2, up, up_h2, start.origin, limits).await
        })
}

/// These short IPC exchanges execute on the thread dedicated to this TLS pair.
/// The supervisor owns request quotas across concurrent HTTP/2 connections.
pub struct StreamLimits {
    control: Mutex<UnixStream>,
    next: std::sync::atomic::AtomicU64,
    upstream_response: std::sync::atomic::AtomicBool,
}
pub struct StreamPermit {
    limits: Arc<StreamLimits>,
    id: u64,
}
impl StreamLimits {
    pub fn observed_response(&self) {
        if !self.upstream_response.swap(true, Ordering::Relaxed)
            && let Ok(mut control) = self.control.lock()
            && let Ok(frame) = encode(&CommandMessage::UpstreamResponse)
        {
            let _ = control.write_all(&frame);
        }
    }
    pub fn acquire(self: &Arc<Self>) -> Result<Option<StreamPermit>> {
        let id = self.next.fetch_add(1, Ordering::Relaxed);
        if id == 0 {
            return Err(invalid("request counter exhausted"));
        }
        let mut control = self
            .control
            .lock()
            .map_err(|_| invalid("worker control unavailable"))?;
        control.write_all(&encode(&CommandMessage::OpenStream(id))?)?;
        match read(&mut control)? {
            Reply::StreamGranted(true) => Ok(Some(StreamPermit {
                limits: self.clone(),
                id,
            })),
            Reply::StreamGranted(false) => Ok(None),
            _ => Err(invalid("unexpected request admission response")),
        }
    }
}
impl Drop for StreamPermit {
    fn drop(&mut self) {
        if let (Ok(mut control), Ok(request)) = (
            self.limits.control.lock(),
            encode(&CommandMessage::CloseStream(self.id)),
        ) {
            let _ = control.write_all(&request);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::{fs, net::TcpListener, path::Path};
    #[test]
    fn filter_sandbox_launch_passes_on_no_descriptor_and_no_environment() {
        // A descriptor the supervisor inherited open across exec, as `dup`
        // leaves one.
        let file = fs::File::open("/dev/null").unwrap();
        // SAFETY: `dup` takes a descriptor number and returns a new one, closed below.
        let inherited = unsafe { nix::libc::dup(std::os::fd::AsRawFd::as_raw_fd(&file)) };
        assert!(inherited > 2);
        // sh and env stand in for the grant worker, started as the supervisor starts one.
        let descriptors = filter_sandbox(Path::new("/bin/sh"))
            .args(["-c", r#"test ! -e /proc/self/fd/"$1""#, "probe"])
            .arg(inherited.to_string())
            .stdin(Stdio::null())
            .output()
            .unwrap();
        // SAFETY: closes the descriptor `dup` returned above, once.
        unsafe { nix::libc::close(inherited) };
        assert!(descriptors.status.success(), "{descriptors:?}");
        assert!(std::env::vars_os().next().is_some());
        let environment = filter_sandbox(Path::new("/usr/bin/env")).output().unwrap();
        assert!(
            environment.status.success() && environment.stdout.is_empty(),
            "{environment:?}"
        );
    }
    #[test]
    fn worker_namespace_excludes_parent_files_and_parent_network() {
        let marker =
            std::env::temp_dir().join(format!("countersign-isolation-{}", uuid::Uuid::new_v4()));
        fs::write(&marker, b"private sentinel").unwrap();
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let port = listener.local_addr().unwrap().port().to_string();
        // Use bash only as the test executable, under the same namespace
        // and mount configuration as a production grant worker.
        let result=namespace_sandbox(Path::new("/bin/bash"))
            .args(["-c", r#"test ! -e "$1" && test ! -e /proc/1/mem && ! (echo probe > /dev/tcp/127.0.0.1/"$2")"#,"probe"])
            .arg(&marker).arg(port).output();
        fs::remove_file(marker).unwrap();
        let result = result.unwrap();
        assert!(
            result.status.success(),
            "{}",
            String::from_utf8_lossy(&result.stderr)
        );
        listener.set_nonblocking(true).unwrap();
        assert_eq!(
            listener.accept().unwrap_err().kind(),
            std::io::ErrorKind::WouldBlock
        );
    }
}