Skip to main content

darkbio_wire/transport/
server.rs

1// wire-rs: encrypted protocol between Ark and host
2// Copyright 2025 Dark Bio AG. All rights reserved.
3//
4// Use of this source code is governed by a BSD-style
5// license that can be found in the LICENSE file.
6
7//! Server side of the transport, with the device attestation it presents and
8//! the events it reports.
9
10use crate::LogId;
11use crate::transport::DEFAULT_HANDSHAKE_TIMEOUT;
12use crate::transport::framing::FrameReader;
13use crate::transport::handshake;
14use crate::transport::io::check_deadline;
15use crate::transport::outbound::{Outbound, Side};
16use crate::transport::sealing;
17use crate::transport::sender::Sender;
18use crate::transport::{
19    CRYPTO_DOMAIN_WIRE, CRYPTO_DOMAIN_WIRE_ARK_TO_HOST, CRYPTO_DOMAIN_WIRE_HOST_TO_ARK, Closer,
20    Error, Read, Stream, Write,
21};
22use darkbio_crypto::{cbor, cose, cwt, xdsa, xhpke};
23use darkbio_trust as trust;
24use std::fmt;
25use std::sync::{Arc, Mutex};
26use std::time::{Duration, Instant};
27use tracing::{debug, info, trace, warn};
28
29/// Device attestation that a server presents during the handshake.
30///
31/// The CWT must carry hardware or emulator claims, as defined in
32/// [`trust::device`]. Construction checks that shape, and the client's
33/// [`Verifier`](crate::transport::Verifier) decides whether to trust it.
34#[derive(Clone)]
35pub struct Attestation(
36    /// Encoded CWT whose claim shape was checked at construction.
37    Vec<u8>,
38);
39
40impl Attestation {
41    /// Wraps a CWT after checking that it decodes as a device attestation.
42    pub fn new(cwt: Vec<u8>) -> Result<Self, Error> {
43        if cwt::peek::<trust::device::HardwareClaims>(&cwt).is_err()
44            && cwt::peek::<trust::device::EmulatorClaims>(&cwt).is_err()
45        {
46            return Err(Error::InvalidAttestation);
47        }
48        Ok(Self(cwt))
49    }
50
51    /// Returns the attestation's CWT bytes.
52    pub fn as_bytes(&self) -> &[u8] {
53        &self.0
54    }
55
56    /// Unwraps the attestation into its CWT bytes.
57    pub fn into_bytes(self) -> Vec<u8> {
58        self.0
59    }
60}
61
62impl fmt::Debug for Attestation {
63    /// Shows the size of the CWT, never its bytes.
64    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65        f.debug_struct("Attestation")
66            .field("len", &self.0.len())
67            .finish()
68    }
69}
70
71/// Source of the server's device attestation, asked on every handshake.
72///
73/// Asking every time lets the server pick up a new attestation after onboarding
74/// without recreating the transport.
75pub trait Attester {
76    /// Returns the device attestation to present to the client.
77    ///
78    /// It can be a root-signed CWT read from disk, or a self-signed fallback for
79    /// a device that has not been onboarded. The identity key it embeds must
80    /// match the signer passed to [`Server::new`].
81    fn attest(&mut self) -> Attestation;
82}
83
84/// A fixed attestation, presented as is on every handshake.
85impl Attester for Attestation {
86    fn attest(&mut self) -> Attestation {
87        self.clone()
88    }
89}
90
91/// Decrypted message or session transition returned by [`Server::recv`].
92///
93/// Events arrive in receive order and refer to sessions over the same byte
94/// stream. Permanent stream closure produces no event, since [`Server::recv`]
95/// returns an error for it.
96pub enum Event<W: Write> {
97    /// Completed handshake, with the sender of the encrypted session it
98    /// established.
99    ///
100    /// The sender belongs to that session and cannot send into a later
101    /// replacement. Stream closure from another thread can make it unusable
102    /// before the caller handles the event.
103    Connected(Sender<W>),
104
105    /// End of the session that the last [`Event::Connected`] opened.
106    ///
107    /// A peer reset, invalid incoming data or a failed send ends it, and a
108    /// failed send is reported once receiving progresses. After a peer reset,
109    /// the next receive call runs the handshake. A local [`Server::disconnect`]
110    /// emits no such event, and permanent stream closure is reported as an
111    /// error instead.
112    Disconnected,
113
114    /// A decrypted message from the client.
115    Message(Vec<u8>),
116}
117
118impl<W: Write> fmt::Debug for Event<W> {
119    /// Names the event, showing the sender or the message length.
120    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121        match self {
122            Self::Connected(sender) => f.debug_tuple("Connected").field(sender).finish(),
123            Self::Disconnected => f.write_str("Disconnected"),
124            Self::Message(message) => f.debug_tuple("Message").field(&message.len()).finish(),
125        }
126    }
127}
128
129/// Server side of the wire, accepting encrypted sessions over a supplied byte
130/// stream.
131///
132/// [`Server::recv`] handles client resets and handshakes. Each successful
133/// handshake returns a sender through [`Event::Connected`]. Later reads deliver
134/// decrypted messages or report that the session ended.
135/// [`Server::disconnect`] ends a session while leaving the stream available for
136/// another; [`Server::close`] permanently closes the stream.
137///
138/// On a local disconnect, a session failure, a failed handshake or data received
139/// outside a session, the server attempts an empty frame notification. A client
140/// receiving it drops its old session. Notifications are best effort and bounded
141/// by an output deadline. A failed write's own notification uses only its
142/// remaining budget and is skipped after timeout. Later incoming traffic can
143/// prompt a standalone notification.
144///
145/// An [`Attester`] supplies the device attestation. Transport forwards it to the
146/// client, whose [`Verifier`](crate::transport::Verifier) decides whether to
147/// trust it.
148pub struct Server<R: Read, W: Write, A: Attester> {
149    /// COBS frame reader for the data the client sends.
150    reader: FrameReader<R>,
151    /// Outgoing transport, which the senders reach through weak references.
152    outbound: Arc<Outbound<W>>,
153
154    /// Server's identity key, which signs the ArkHello.
155    signer: xdsa::SecretKey,
156    /// Source of the device attestation for each handshake.
157    attester: A,
158
159    /// Receive context of the current session, used only by this server.
160    receiver: Option<xhpke::Receiver>,
161    /// Send context of the current session, shared with active sends.
162    sealer: Option<Arc<Mutex<xhpke::Sender>>>,
163
164    /// Budget for each new handshake attempt.
165    handshake_timeout: Duration,
166    /// Deadline of the handshake that a received reset requested, unset while
167    /// none is pending.
168    handshake_deadline: Option<Instant>,
169    /// Label of the latest session in log lines, zero before the first one.
170    log_id: LogId,
171
172    /// Fixed ArkHello signing time for test vectors, unset to read the clock.
173    #[cfg(any(test, feature = "bench", feature = "fuzz"))]
174    timestamp: Option<i64>,
175}
176
177impl<R: Read, W: Write, A: Attester> Server<R, W, A> {
178    /// Creates a server that owns the byte stream and its shutdown operation.
179    ///
180    /// The signer is the server's identity key. It must match the key embedded
181    /// in the device attestation. Output uses the stream's configured write
182    /// timeout. The stream's [`Read`] and [`Write`] adapters must enforce
183    /// deadlines and let shutdown cancel blocked I/O.
184    pub fn new(stream: Stream<R, W>, signer: xdsa::SecretKey, attester: A) -> Self {
185        let (reader, writer, close, timeout) = stream.into_parts();
186        let outbound = Arc::new(Outbound::new(writer, Side::Server, close.clone(), timeout));
187        Self {
188            reader: FrameReader::new(reader, close),
189            outbound,
190            signer,
191            attester,
192            receiver: None,
193            sealer: None,
194            handshake_timeout: DEFAULT_HANDSHAKE_TIMEOUT,
195            handshake_deadline: None,
196            log_id: LogId::default(),
197            #[cfg(any(test, feature = "bench", feature = "fuzz"))]
198            timestamp: None,
199        }
200    }
201
202    /// Sets the budget for each later handshake, counted from the reset that
203    /// requests it.
204    ///
205    /// Defaults to [`DEFAULT_HANDSHAKE_TIMEOUT`]. Output and peer replies share
206    /// one deadline; progress and repeated resets within the attempt do not
207    /// refresh it. An already pending handshake keeps its deadline. Each
208    /// outgoing frame is also limited by the stream's write timeout. Waiting for
209    /// locks and attester callbacks can extend the call beyond the deadline.
210    /// Time between [`Server::recv`] calls also consumes the budget.
211    ///
212    /// Zero expires attempts immediately. A duration too large to add to an
213    /// [`Instant`] panics when the next handshake's deadline is constructed.
214    pub fn set_handshake_timeout(mut self, timeout: Duration) -> Self {
215        self.handshake_timeout = timeout;
216        self
217    }
218
219    /// Returns a handle that permanently closes the stream from another thread.
220    pub fn closer(&self) -> Closer {
221        self.outbound.closer()
222    }
223
224    /// Permanently closes the stream and waits for adapter shutdown.
225    ///
226    /// Senders observe closure through write failure, and buffered messages
227    /// remain readable. See [`Closer::close`].
228    pub fn close(&self) {
229        self.outbound.close();
230    }
231
232    /// Creates a server that signs every ArkHello at a fixed time, for vector
233    /// replay.
234    ///
235    /// It exists for test vectors and is not part of the normal transport API.
236    #[doc(hidden)]
237    #[inline]
238    #[cfg(any(test, feature = "bench", feature = "fuzz"))]
239    #[cfg_attr(coverage_nightly, coverage(off))]
240    pub fn new_at(
241        stream: Stream<R, W>,
242        signer: xdsa::SecretKey,
243        attester: A,
244        timestamp: i64,
245    ) -> Self {
246        let mut server = Self::new(stream, signer, attester);
247        server.timestamp = Some(timestamp);
248        server
249    }
250
251    /// Receives the next decrypted message or session transition.
252    ///
253    /// A client reset starts a handshake, whose completion returns
254    /// [`Event::Connected`] with a sender before any messages from that session
255    /// are delivered.
256    ///
257    /// A client reset or invalid incoming data ends the current session and
258    /// returns [`Event::Disconnected`]. Oversized frames count as invalid data.
259    /// A send failure also ends the session, but does not wake a blocked read.
260    /// It is reported once receiving progresses. Sessions ended by a local
261    /// disconnect are not reported again.
262    ///
263    /// The handshake after a reset runs under one configured deadline, starting
264    /// at that reset. It runs in the same call, or in the next one when the
265    /// reset ended a session. Repeated resets within the attempt do not refresh
266    /// the deadline. Expiry returns a `TimedOut` I/O error, as
267    /// [`Error::SendFailed`] while writing and as [`Error::RecvFailed`]
268    /// otherwise. A fresh reset can start another attempt.
269    ///
270    /// After decryption, message acceptance is ordered with session ending
271    /// without waiting for the writer. A concurrent send failure can cause a
272    /// decrypted message to be discarded before acceptance. An accepted message
273    /// may reach the caller after another thread ends the session. Reporting
274    /// a session's end waits for outgoing writes to finish.
275    ///
276    /// Junk outside a session and handshake protocol or authentication failures
277    /// are logged, answered with a best-effort empty frame and skipped. Handshake
278    /// write failures surface as errors; calling again waits for a new reset on
279    /// the same stream. Adapter read failures and EOF also surface as errors,
280    /// without removing the binding. The caller can retry a transient read error,
281    /// disconnect the session or close the stream. Outside a handshake, reads
282    /// wait for data or adapter shutdown without a session timeout.
283    ///
284    /// Outgoing frames and standalone empty notifications use the stream's
285    /// configured write timeout. A notification sent while handling a failed
286    /// write shares that frame's remaining budget and is skipped after timeout.
287    /// These output failures do not themselves close the byte stream.
288    ///
289    /// # Panics
290    ///
291    /// Panics if a handshake or write timeout is too large to add to an
292    /// [`Instant`], or if a handshake reads a wall time before the Unix epoch
293    /// from the stream's clock.
294    pub fn recv(&mut self) -> Result<Event<W>, Error> {
295        // Continue until a message, session transition or I/O error is ready.
296        // Empty frames request a handshake on the next pass.
297        loop {
298            // If a reset just arrived, run the handshake
299            if let Some(deadline) = self.handshake_deadline.take() {
300                match self.handshake(deadline) {
301                    // Transport errors propagate immediately
302                    Err(Error::Terminated) => return Err(Error::Terminated),
303                    Err(Error::RecvFailed(err)) => return Err(Error::RecvFailed(err)),
304                    // Outbound already attempted a notification within the failed
305                    // frame's budget, and another attempt here could block again
306                    Err(Error::SendFailed(err)) => return Err(Error::SendFailed(err)),
307
308                    // Notify the client that the handshake established no session
309                    Err(err) => {
310                        warn!("dropping wire handshake: {}", err);
311                        if let Err(err) = self.outbound.send_dropped(Some(deadline)) {
312                            warn!("failed to signal dropped handshake: {}", err);
313                        }
314                        // Do not swallow an attempt deadline exhausted during
315                        // authentication or its failure notification
316                        check_deadline(&self.outbound.clock, deadline)
317                            .map_err(Error::RecvFailed)?;
318                    }
319                    // Report the completed handshake before reading messages.
320                    // The caller can send at once, without waiting for a client
321                    // request.
322                    Ok((sender, receiver)) => {
323                        let sender = self.new_session(sender, receiver);
324                        info!("wire session {} established", self.log_id);
325                        return Ok(Event::Connected(sender));
326                    }
327                }
328                continue;
329            }
330
331            // Retrieve the next COBS encoded packet
332            let packet = match self.reader.next_packet(None) {
333                // Transport errors propagate immediately
334                Err(Error::Terminated) => return Err(Error::Terminated),
335                Err(Error::RecvFailed(err)) => return Err(Error::RecvFailed(err)),
336
337                // A reset can terminate a partial frame and cause a framing error.
338                // The frame may also have carried a sealed message. End any active
339                // session, since its encryption sequence cannot be followed past it.
340                Err(err) => {
341                    let ended = self.end_session();
342                    if ended {
343                        warn!("ending session {}: {}", self.log_id, err);
344                    } else {
345                        debug!("discarding invalid frame outside session: {}", err);
346                    }
347                    self.send_dropped();
348                    if ended {
349                        return Ok(Event::Disconnected);
350                    }
351                    continue;
352                }
353                // A reset ends any active session. Run the handshake on the next
354                // receive call if this one returns an event, or on the next pass.
355                Ok(None) => {
356                    self.handshake_deadline =
357                        Some(self.outbound.clock.now() + self.handshake_timeout);
358                    if self.end_session() {
359                        info!("wire session {} reset by host", self.log_id);
360                        return Ok(Event::Disconnected);
361                    }
362                    debug!("wire reset received, awaiting handshake");
363                    continue;
364                }
365                // Valid COBS packet
366                Ok(Some(packet)) => packet,
367            };
368
369            // Answer data outside a session with an empty frame and skip it
370            let receiver = match self.receiver.as_mut() {
371                None => {
372                    debug!("discarding data outside session");
373                    self.send_dropped();
374                    continue;
375                }
376                Some(receiver) => receiver,
377            };
378
379            // Finish after decrypting, ordering message acceptance with a send
380            // failure without ever waiting for the writer on a successful receive
381            let sealer = self
382                .sealer
383                .as_ref()
384                .expect("receiver has a sending context");
385            let opened = sealing::open(receiver, packet);
386            let undecryptable = opened.is_err();
387            let message = match self.outbound.finish_receive(sealer, opened) {
388                Err(err) => {
389                    if undecryptable {
390                        warn!("ending session {}: {}", self.log_id, err);
391                    } else {
392                        debug!(
393                            "discarding message read after session {} ended",
394                            self.log_id
395                        );
396                    }
397                    self.end_session();
398                    self.send_dropped();
399                    return Ok(Event::Disconnected);
400                }
401                Ok(message) => message,
402            };
403            trace!("received host-to-ark message ({} bytes)", packet.len());
404            return Ok(Event::Message(message));
405        }
406    }
407
408    /// Stores the negotiated contexts and returns a sender for the new session.
409    ///
410    /// The sending context's allocation identifies the session. The server owns
411    /// both contexts and shares the sending context with active sends. Idle
412    /// senders hold weak references and keep neither context nor stream alive.
413    ///
414    /// Takes the writer lock, then the binding lock. An old write that already
415    /// holds the writer lock may finish first. Once the binding is replaced,
416    /// old sends cannot write and old received messages cannot be accepted.
417    /// This method performs no handshake, crypto or stream I/O.
418    fn new_session(&mut self, sender: xhpke::Sender, receiver: xhpke::Receiver) -> Sender<W> {
419        let sealer = Arc::new(Mutex::new(sender));
420        let sender = self.outbound.bind(&sealer);
421        self.log_id = sender.log_id();
422        self.receiver = Some(receiver);
423        self.sealer = Some(sealer);
424        sender
425    }
426
427    /// Ends the current binding before releasing the server's crypto contexts.
428    ///
429    /// Waits for the writer while a session exists. After this returns, no
430    /// write or flush for that session is running or can start. A send that
431    /// gets the writer first may finish. A send still sealing after removal
432    /// cannot write its packet. This takes no encryption lock and does not wait
433    /// for crypto work.
434    ///
435    /// This does not close the stream or send a notification. An active write
436    /// may delay ending until its frame deadline. Another thread can use a
437    /// [`Closer`] to cancel I/O without taking the writer lock.
438    ///
439    /// Returns true if it removed a receive context, even if a send failure
440    /// already ended the binding. The receive loop uses this removal to emit
441    /// [`Event::Disconnected`] once. Local disconnect uses the result only for
442    /// its log line, since its caller already knows the session ended.
443    fn end_session(&mut self) -> bool {
444        if let Some(sealer) = self.sealer.as_ref() {
445            self.outbound.end(sealer);
446        }
447        self.sealer = None;
448        self.receiver.take().is_some()
449    }
450
451    /// Sends an empty frame to notify the client that it has no session,
452    /// logging any failure.
453    fn send_dropped(&self) {
454        if let Err(err) = self.outbound.send_dropped(None) {
455            warn!("failed to signal dropped session: {}", err);
456        }
457    }
458
459    /// Ends the current session, if any, and notifies the client with an empty
460    /// frame.
461    ///
462    /// The stream remains available for the client to connect again.
463    /// Notification failures are logged. This produces no
464    /// [`Event::Disconnected`], since the caller already knows the session
465    /// ended.
466    ///
467    /// Waits for the current writer and its flush, then retires the binding.
468    /// The notification gets its own frame budget. Another thread can use a
469    /// [`Closer`] to cancel output earlier.
470    pub fn disconnect(&mut self) {
471        if self.end_session() {
472            debug!("wire session {} dropped locally", self.log_id);
473        }
474        self.send_dropped();
475    }
476
477    /// Responds to the handshake after a session reset, establishing the HPKE
478    /// contexts of both directions.
479    ///
480    /// The exchange takes three messages:
481    ///
482    /// ```text
483    /// 1. Client -> Server: HostHello { host_signer, host_crypto }           (plain CBOR)
484    /// 2. Server -> Client: ArkHello  { ark_attest, ark_crypto, a2h_encap }  (cose::seal)
485    /// 3. Client -> Server: HostAck   { h2a_encap }                          (cose::seal)
486    /// ```
487    ///
488    /// Empty frames before the HostHello are skipped, and one in place of the
489    /// HostAck restarts the exchange. All steps share one deadline.
490    fn handshake(&mut self, deadline: Instant) -> Result<(xhpke::Sender, xhpke::Receiver), Error> {
491        // Wait for earlier writes and drop any binding before answering
492        self.outbound.unbind();
493        loop {
494            // Message 1: Read the HostHello (skip any trailing empty reset frames)
495            let packet = loop {
496                if let Some(packet) = self.reader.next_packet(Some(deadline))? {
497                    break packet;
498                }
499            };
500            let host_hello: handshake::HostHello = cbor::decode(packet)
501                .map_err(|err| Error::HandshakeFailed(format!("invalid client hello: {}", err)))?;
502
503            // Generate ephemeral keys and set up server-to-client encryption
504            let ark_crypto_key = xhpke::SecretKey::generate();
505            let ark_crypto_pub = ark_crypto_key.public_key();
506            let (sender, a2h_encap) = host_hello
507                .host_crypto
508                .new_sender(CRYPTO_DOMAIN_WIRE_ARK_TO_HOST)
509                .map_err(|err| {
510                    Error::HandshakeFailed(format!("server sender setup failed: {}", err))
511                })?;
512
513            // Message 2: Seal and send the ArkHello
514            let ark_hello = handshake::ArkHello {
515                ark_attest: self.attester.attest().into_bytes(),
516                ark_crypto: ark_crypto_pub.clone(),
517                a2h_encap: a2h_encap.to_vec(),
518            };
519            let auth = handshake::ArkHelloAuth {
520                host_signer: host_hello.host_signer.clone(),
521                host_crypto: host_hello.host_crypto.clone(),
522            };
523            // Sign at the clock's wall time, unless a test fixed the signing time
524            #[cfg(not(any(test, feature = "bench", feature = "fuzz")))]
525            let timestamp = handshake::timestamp(&self.outbound.clock);
526            #[cfg(any(test, feature = "bench", feature = "fuzz"))]
527            let timestamp = self
528                .timestamp
529                .unwrap_or_else(|| handshake::timestamp(&self.outbound.clock));
530            let sealed = cose::seal_at(
531                &ark_hello,
532                &auth,
533                &self.signer,
534                &host_hello.host_crypto,
535                CRYPTO_DOMAIN_WIRE,
536                timestamp,
537            );
538            let ark_hello = sealed.map_err(|err| {
539                Error::HandshakeFailed(format!("failed to seal server hello: {}", err))
540            })?;
541            self.outbound.send_packet(&ark_hello, Some(deadline))?;
542
543            // Message 3: Read and open HostAck. An empty frame is another reset;
544            // discard this attempt and wait for the next HostHello.
545            let Some(packet) = self.reader.next_packet(Some(deadline))? else {
546                debug!("wire reset received during handshake");
547                continue;
548            };
549            let host_ack: handshake::HostAck = cose::open_at(
550                packet,
551                &handshake::HostAckAuth {
552                    ark_signer: self.signer.public_key(),
553                    ark_crypto: ark_crypto_pub.clone(),
554                },
555                &ark_crypto_key,
556                &host_hello.host_signer,
557                CRYPTO_DOMAIN_WIRE,
558                None, // clock possibly unset, ephemeral keys guarantee freshness
559                0,    // unused without a drift check, so the clock is not read
560            )
561            .map_err(|err| Error::HandshakeFailed(format!("invalid client ack: {}", err)))?;
562
563            // Set up client-to-server decryption
564            let enc_h2a: [u8; xhpke::ENCAP_KEY_SIZE] = host_ack
565                .h2a_encap
566                .try_into()
567                .map_err(|_| Error::HandshakeFailed("invalid h2a_encap size".into()))?;
568            let receiver = ark_crypto_key
569                .new_receiver(&enc_h2a, CRYPTO_DOMAIN_WIRE_HOST_TO_ARK)
570                .map_err(|err| {
571                    Error::HandshakeFailed(format!("server receiver setup failed: {}", err))
572                })?;
573
574            // Hand back the contexts unless the exchange finished past its deadline
575            check_deadline(&self.outbound.clock, deadline).map_err(Error::RecvFailed)?;
576            return Ok((sender, receiver));
577        }
578    }
579}
580
581impl<R: Read, W: Write, A: Attester> Drop for Server<R, W, A> {
582    /// Closes the stream to cancel blocked I/O, then ends the binding before
583    /// releasing the contexts.
584    ///
585    /// Shutdown must come before waiting for the writer, which a blocked write
586    /// could otherwise hold until its deadline. Idle senders hold weak
587    /// references and cannot extend the stream's lifetime.
588    fn drop(&mut self) {
589        self.outbound.close();
590        self.end_session();
591    }
592}
593
594impl<R: Read, W: Write, A: Attester> fmt::Debug for Server<R, W, A> {
595    /// Shows the session label, whether a session is established and the
596    /// handshake budget, never the adapters, the keys or the encryption contexts.
597    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
598        f.debug_struct("Server")
599            .field("session", &self.log_id)
600            .field("connected", &self.sealer.is_some())
601            .field("handshake_timeout", &self.handshake_timeout)
602            .finish_non_exhaustive()
603    }
604}
605
606/// Tests of the server, its attestation and its sessions with the real client.
607#[cfg(test)]
608#[cfg_attr(coverage_nightly, coverage(off))]
609mod tests {
610    use super::*;
611    use crate::transport::mock::payload;
612    use crate::transport::testing::{Memory, test_clock};
613    use crate::transport::{Client, MAX_FRAME_SIZE, Verifier};
614    use crate::{memory, testing};
615    use darkbio_clock::Clock;
616    use darkbio_cobs as cobs;
617
618    /// Issues a self-signed attestation for a device that has not been
619    /// onboarded.
620    fn self_attestation(signer: &xdsa::SecretKey) -> Attestation {
621        use darkbio_crypto::cwt::claims::{self, eat};
622
623        let claims = darkbio_trust::device::HardwareClaims {
624            sub: claims::Subject { sub: "".into() },
625            cnf: claims::Confirm::new(signer.public_key()),
626            nbf: claims::NotBefore { nbf: 0 },
627            iat: claims::IssuedAt { iat: 0 },
628            oem: eat::Oemid::new_pen(0),
629            hwm: eat::HwModel { hw_model: vec![] },
630            hwv: eat::HwVersion::new("".into()),
631        };
632        let cwt = cwt::issue_at(
633            &claims,
634            signer,
635            darkbio_trust::CRYPTO_DOMAIN_DEVICE_ATTESTATION,
636            crate::transport::mock::TIMESTAMP,
637        )
638        .unwrap();
639        Attestation::new(cwt).unwrap()
640    }
641
642    /// COBS-encodes data and appends the frame delimiter.
643    fn cobs_frame(data: &[u8]) -> Vec<u8> {
644        let mut buf = vec![0u8; cobs::encode_buffer(data.len())];
645        let n = cobs::encode(data, &mut buf).unwrap();
646        buf.truncate(n);
647        buf.push(0x00);
648        buf
649    }
650
651    /// Tests that an oversized server hello produces one failure notification.
652    ///
653    /// The hello never reaches adapter I/O, so the handshake owns that
654    /// notification, and the writer must not emit another with its own budget.
655    /// Dummy attestation bytes isolate the framing limit, since the server
656    /// forwards them without parsing.
657    #[test]
658    fn test_oversized_hello_notifies_once() {
659        // Prepare an oversized server hello on a paused clock
660        testing::init_tracing();
661        let tester = test_clock();
662        let clock = tester.clock();
663        let hello = cbor::encode(&handshake::HostHello {
664            host_signer: xdsa::SecretKey::generate().public_key(),
665            host_crypto: xhpke::SecretKey::generate().public_key(),
666        })
667        .unwrap();
668        let mut input = vec![0, 0];
669        input.extend_from_slice(&cobs_frame(&hello));
670        let mut output = Vec::new();
671        let mut server = Server::new(
672            Stream::new(
673                Memory::new(&input[..], &clock),
674                Memory::new(&mut output, &clock),
675                || {},
676            ),
677            xdsa::SecretKey::generate(),
678            Attestation(vec![0; MAX_FRAME_SIZE]),
679        );
680
681        // Require exactly one failure notification before EOF
682        assert!(matches!(server.recv(), Err(Error::Terminated)));
683        drop(server);
684        assert_eq!(output, [0]);
685    }
686
687    /// Tests that the real client and server exchange messages, and that a fresh
688    /// handshake recovers from a dropped session.
689    #[test]
690    fn test_message_round_trip() {
691        // Connect both peers on one paused in-memory stream
692        testing::init_tracing();
693        let tester = test_clock();
694        let signer_key = xdsa::SecretKey::generate();
695        let signer_pub = signer_key.public_key();
696        let attestation = self_attestation(&signer_key);
697        let presented = attestation.clone();
698        let (host, ark) = memory::duplex(64 * 1024, &tester.clock());
699
700        // Receive two messages on the Ark side across two sessions, echoing each
701        let ark_thread = std::thread::spawn(move || {
702            let mut server = Server::new(ark, signer_key, attestation);
703            let mut sender = None;
704            let mut requests = Vec::new();
705            for _ in 0..2 {
706                let req = testing::served(&mut server, &mut sender).unwrap();
707                sender.as_ref().unwrap().send(&req).unwrap();
708                requests.push(req);
709            }
710            requests
711        });
712
713        // Open the first session, check the attestation and exchange one message
714        let mut client = Client::new(host);
715        let (sender, attest) = client.connect(&signer_pub).unwrap();
716        assert_eq!(attest.as_bytes(), presented.as_bytes());
717        sender.send(&payload(1)).unwrap();
718        assert_eq!(client.recv().unwrap(), payload(1));
719
720        // Inject a frame the server cannot decrypt. It drops the session and
721        // signals it. The client's next read reports a reset, and its old sender
722        // cannot send again.
723        client.send_packet_blob(b"interrupted transfer").unwrap();
724        let result = client.recv();
725        assert!(matches!(result, Err(Error::SessionReset)), "{result:?}");
726        let result = sender.send(&payload(2));
727        assert!(
728            matches!(result, Err(Error::EncryptionFailed(_))),
729            "{result:?}"
730        );
731
732        // Open a second session on the same stream and exchange one message
733        let (sender, _) = client.connect(&signer_pub).unwrap();
734        sender.send(&payload(2)).unwrap();
735        assert_eq!(client.recv().unwrap(), payload(2));
736
737        // Require the server to have received both messages in order
738        let requests = ark_thread.join().unwrap();
739        assert_eq!(requests, vec![payload(1), payload(2)]);
740    }
741
742    /// Tests that an untrusting verifier rejects the session on the client side.
743    #[test]
744    fn test_verifier_rejects() {
745        testing::init_tracing();
746
747        /// Verifier refusing every attestation.
748        struct Untrusting;
749
750        impl Verifier for Untrusting {
751            type Info = ();
752
753            fn verify(
754                &self,
755                _: &Attestation,
756                _: std::time::SystemTime,
757            ) -> Result<(xdsa::PublicKey, Self::Info), String> {
758                Err("attestation rejected".into())
759            }
760        }
761
762        // Connect both peers on one paused in-memory stream
763        let signer_key = xdsa::SecretKey::generate();
764        let tester = test_clock();
765        let (host, ark) = memory::duplex(64 * 1024, &tester.clock());
766
767        // Serve handshakes on the Ark side until the transport drops. The client
768        // aborts mid-handshake, so the server never delivers a message.
769        let ark_thread = std::thread::spawn(move || {
770            let attestation = self_attestation(&signer_key);
771            let mut server = Server::new(ark, signer_key, attestation);
772            let mut sender = None;
773            testing::served(&mut server, &mut sender)
774        });
775
776        // Refuse the attestation in the client's verifier
777        let mut client = Client::new(host);
778        let result = client.connect(&Untrusting);
779        assert!(result.is_err());
780
781        // Dropping the client tears down the transport, unblocking the server
782        drop(client);
783        assert!(ark_thread.join().unwrap().is_err());
784    }
785
786    /// Tests that the roots verifier accepts attestations under the trusted
787    /// roots and refuses the others.
788    #[test]
789    fn test_roots_verifier() {
790        testing::init_tracing();
791
792        use crate::transport::Roots;
793        use darkbio_crypto::cwt;
794        use darkbio_crypto::cwt::claims::{self, eat};
795        use darkbio_trust::device::{EmulatorClaims, HardwareClaims};
796        use darkbio_trust::{CRYPTO_DOMAIN_DEVICE_ATTESTATION, Realm};
797        use std::time::UNIX_EPOCH;
798
799        // Issue every attestation at the paused clock's wall time
800        let tester = test_clock();
801        let clock = tester.clock();
802        let now = clock
803            .system_time()
804            .duration_since(UNIX_EPOCH)
805            .unwrap()
806            .as_secs();
807
808        /// Runs a handshake with the given attestation and trusted roots,
809        /// returning the client's verification result.
810        fn handshake(
811            clock: &Clock,
812            signer_key: xdsa::SecretKey,
813            attestation: Attestation,
814            hardware: &[xdsa::PublicKey],
815            emulator: &[xdsa::PublicKey],
816        ) -> Result<darkbio_trust::device::Device, Error> {
817            // Serve a fresh stream on the Ark side while the client verifies
818            // the attestation through the roots
819            let (host, ark) = memory::duplex(64 * 1024, clock);
820            let ark_thread = std::thread::spawn(move || {
821                let mut server = Server::new(ark, signer_key, attestation);
822                let mut sender = None;
823                testing::served(&mut server, &mut sender)
824            });
825            let mut client = Client::new(host);
826            let result = client
827                .connect(&Roots { hardware, emulator })
828                .map(|(_, info)| info);
829
830            // Dropping the client tears down the transport, unblocking the server
831            drop(client);
832            let _ = ark_thread.join().unwrap();
833            result
834        }
835
836        // Trust one hardware root and one emulator root
837        let hardware_root = xdsa::SecretKey::generate();
838        let emulator_root = xdsa::SecretKey::generate();
839        let hardware_roots = [hardware_root.public_key()];
840        let emulator_roots = [emulator_root.public_key()];
841
842        // A hardware server attested by a hardware root is accepted with its
843        // identity
844        let signer_key = xdsa::SecretKey::generate();
845        let attestation = cwt::issue_at(
846            &HardwareClaims {
847                sub: claims::Subject {
848                    sub: "ark-1234".into(),
849                },
850                cnf: claims::Confirm::new(signer_key.public_key()),
851                nbf: claims::NotBefore { nbf: now - 10 },
852                iat: claims::IssuedAt { iat: now - 10 },
853                oem: eat::Oemid::new_pen(65145),
854                hwm: eat::HwModel {
855                    hw_model: b"Ark I".to_vec(),
856                },
857                hwv: eat::HwVersion::new("Ark I - 1.0.0".into()),
858            },
859            &hardware_root,
860            CRYPTO_DOMAIN_DEVICE_ATTESTATION,
861            now as i64,
862        )
863        .map(|cwt| Attestation::new(cwt).unwrap())
864        .unwrap();
865        let device = handshake(
866            &clock,
867            signer_key,
868            attestation.clone(),
869            &hardware_roots,
870            &[],
871        )
872        .unwrap();
873        assert_eq!(device.realm, Realm::Hardware);
874        assert_eq!(device.serial, "ark-1234");
875
876        // A hardware attestation is refused when only emulator roots are trusted
877        let signer_key = xdsa::SecretKey::generate();
878        assert!(handshake(&clock, signer_key, attestation, &[], &emulator_roots).is_err());
879
880        // An emulated server attested by an emulator root is accepted with its
881        // expiry
882        let signer_key = xdsa::SecretKey::generate();
883        let attestation = cwt::issue_at(
884            &EmulatorClaims {
885                sub: claims::Subject {
886                    sub: "emu-1234".into(),
887                },
888                cnf: claims::Confirm::new(signer_key.public_key()),
889                nbf: claims::NotBefore { nbf: now - 10 },
890                exp: claims::Expiration { exp: now + 1000 },
891                iat: claims::IssuedAt { iat: now - 10 },
892                oem: eat::Oemid::new_pen(65145),
893                hwm: eat::HwModel {
894                    hw_model: b"Ark I".to_vec(),
895                },
896                hwv: eat::HwVersion::new("Ark I - 1.0.0".into()),
897            },
898            &emulator_root,
899            CRYPTO_DOMAIN_DEVICE_ATTESTATION,
900            now as i64,
901        )
902        .map(|cwt| Attestation::new(cwt).unwrap())
903        .unwrap();
904        let device = handshake(
905            &clock,
906            signer_key,
907            attestation,
908            &hardware_roots,
909            &emulator_roots,
910        )
911        .unwrap();
912        assert_eq!(device.realm, Realm::Emulator);
913        assert_eq!(device.expiry, Some(now + 1000));
914
915        // A never onboarded server presenting a self-signed attestation is refused
916        let signer_key = xdsa::SecretKey::generate();
917        let attestation = cwt::issue_at(
918            &HardwareClaims {
919                sub: claims::Subject { sub: "".into() },
920                cnf: claims::Confirm::new(signer_key.public_key()),
921                nbf: claims::NotBefore { nbf: 0 },
922                iat: claims::IssuedAt { iat: 0 },
923                oem: eat::Oemid::new_pen(0),
924                hwm: eat::HwModel { hw_model: vec![] },
925                hwv: eat::HwVersion::new("".into()),
926            },
927            &signer_key,
928            CRYPTO_DOMAIN_DEVICE_ATTESTATION,
929            now as i64,
930        )
931        .map(|cwt| Attestation::new(cwt).unwrap())
932        .unwrap();
933        assert!(
934            handshake(
935                &clock,
936                signer_key,
937                attestation,
938                &hardware_roots,
939                &emulator_roots
940            )
941            .is_err()
942        );
943    }
944
945    /// Tests that attestation construction accepts hardware and emulator claims
946    /// and rejects junk or CWTs carrying other claim types.
947    #[test]
948    fn test_attestation_shapes() {
949        use darkbio_crypto::cwt::claims;
950        use darkbio_trust::CRYPTO_DOMAIN_DEVICE_ATTESTATION;
951
952        // Accept hardware claims through the self-signed helper
953        let signer = xdsa::SecretKey::generate();
954        let _ = self_attestation(&signer);
955
956        // Accept emulator claims
957        let emulator = darkbio_trust::device::EmulatorClaims {
958            sub: claims::Subject { sub: "".into() },
959            cnf: claims::Confirm::new(signer.public_key()),
960            nbf: claims::NotBefore { nbf: 0 },
961            exp: claims::Expiration { exp: u64::MAX },
962            iat: claims::IssuedAt { iat: 0 },
963            oem: claims::eat::Oemid::new_pen(0),
964            hwm: claims::eat::HwModel { hw_model: vec![] },
965            hwv: claims::eat::HwVersion::new("".into()),
966        };
967        let cwt = cwt::issue_at(
968            &emulator,
969            &signer,
970            CRYPTO_DOMAIN_DEVICE_ATTESTATION,
971            crate::transport::mock::TIMESTAMP,
972        )
973        .unwrap();
974        Attestation::new(cwt).expect("emulator attestation refused");
975
976        // Refuse the claims of a cloud signer and bytes that are no CWT at all
977        let cloud = darkbio_trust::cloud::SignerClaims {
978            iss: claims::Issuer { iss: "".into() },
979            sub: claims::Subject { sub: "".into() },
980            nbf: claims::NotBefore { nbf: 0 },
981            exp: claims::Expiration { exp: 1 },
982            cnf: claims::Confirm::new(signer.public_key()),
983        };
984        let cwt = cwt::issue_at(
985            &cloud,
986            &signer,
987            CRYPTO_DOMAIN_DEVICE_ATTESTATION,
988            crate::transport::mock::TIMESTAMP,
989        )
990        .unwrap();
991        let result = Attestation::new(cwt).map(|_| ());
992        assert!(
993            matches!(result, Err(Error::InvalidAttestation)),
994            "{result:?}"
995        );
996        let result = Attestation::new(b"junk".to_vec()).map(|_| ());
997        assert!(
998            matches!(result, Err(Error::InvalidAttestation)),
999            "{result:?}"
1000        );
1001    }
1002
1003    /// Tests that other threads can send while the server blocks in a read.
1004    ///
1005    /// The client must receive every message in encryption order to decrypt it.
1006    #[test]
1007    fn test_senders() {
1008        testing::init_tracing();
1009
1010        // Connect both peers on one paused in-memory stream
1011        let signer_key = xdsa::SecretKey::generate();
1012        let signer_pub = signer_key.public_key();
1013        let attestation = self_attestation(&signer_key);
1014        let tester = test_clock();
1015        let (host, ark) = memory::duplex(64 * 1024, &tester.clock());
1016
1017        // After the first request, push messages on the Ark side from a few
1018        // threads while the server waits for the second request
1019        let ark_thread = std::thread::spawn(move || {
1020            let mut server = Server::new(ark, signer_key, attestation);
1021            let mut sender = None;
1022            testing::served(&mut server, &mut sender).unwrap();
1023
1024            let pushers: Vec<_> = (0..4)
1025                .map(|thread| {
1026                    let sender = sender.as_ref().unwrap().clone();
1027                    std::thread::spawn(move || {
1028                        for i in 0..25 {
1029                            sender.send(&payload(thread * 100 + i)).unwrap();
1030                        }
1031                    })
1032                })
1033                .collect();
1034            let stop = testing::served(&mut server, &mut sender).unwrap();
1035            for pusher in pushers {
1036                pusher.join().unwrap();
1037            }
1038            stop
1039        });
1040
1041        // Request the push from the client
1042        let mut client = Client::new(host);
1043        let (sender, _) = client.connect(&signer_pub).unwrap();
1044        sender.send(&payload(1)).unwrap();
1045
1046        // Receive every pushed message, whichever thread sent it
1047        let mut pushed: Vec<Vec<u8>> = (0..100).map(|_| client.recv().unwrap()).collect();
1048        pushed.sort_unstable();
1049        let mut expected: Vec<Vec<u8>> = (0..4)
1050            .flat_map(|thread| (0..25).map(move |i| payload(thread * 100 + i)))
1051            .collect();
1052        expected.sort_unstable();
1053        assert_eq!(pushed, expected);
1054
1055        // Request the stop, which the server returns once its pushers finish
1056        sender.send(&payload(2)).unwrap();
1057        assert_eq!(ark_thread.join().unwrap(), payload(2));
1058    }
1059}