1
#[cfg(feature = "iroh")]
2
use std::collections::BTreeSet;
3
#[cfg(feature = "iroh")]
4
use std::net::SocketAddr;
5
#[cfg(tokio_unix)]
6
use std::ops::{Deref, DerefMut};
7
#[cfg(tokio_unix)]
8
use std::path::PathBuf;
9
use std::{fmt::Display, net::IpAddr};
10

            
11
use jetstream_wireformat::{JetStreamWireFormat, WireFormat};
12
#[cfg(tokio_unix)]
13
use tokio::net::{unix::UCred, UnixStream};
14
#[cfg(any(feature = "turmoil", tokio_unix, native))]
15
use tokio_util::codec::Framed;
16
#[cfg(any(feature = "iroh", feature = "x509"))]
17
use url::Url;
18

            
19
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
20
pub struct Context {
21
    remote: Option<RemoteAddr>,
22
    peer: Option<Peer>,
23
}
24

            
25
impl Display for Context {
26
56
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
27
56
        match &self.peer {
28
56
            Some(Peer::NodeId(id)) => write!(f, "{}", id.0),
29
            #[cfg(tokio_unix)]
30
            Some(Peer::Unix(cred)) => write!(
31
                f,
32
                "{}",
33
                cred.process_path()
34
                    .expect("Failed to get process path")
35
                    .to_string_lossy()
36
            ),
37
            #[cfg(feature = "x509")]
38
            Some(Peer::Tls(tls_peer)) => {
39
                if let Some(leaf) = tls_peer.leaf() {
40
                    if let Some(cn) = &leaf.common_name {
41
                        write!(f, "{}", cn)
42
                    } else {
43
                        write!(f, "{}", leaf.fingerprint)
44
                    }
45
                } else {
46
                    write!(f, "TLS(empty chain)")
47
                }
48
            }
49
            Some(Peer::WebCredentials(creds)) => {
50
                write!(
51
                    f,
52
                    "WebCredentials({})",
53
                    creds.0.to_str().unwrap_or("<invalid>")
54
                )
55
            }
56
            None => write!(f, "None"),
57
        }
58
56
    }
59
}
60

            
61
impl From<NodeId> for Context {
62
504
    fn from(value: NodeId) -> Self {
63
504
        Context {
64
504
            remote: None,
65
504
            peer: Some(Peer::NodeId(value)),
66
504
        }
67
504
    }
68
}
69

            
70
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
71
pub enum RemoteAddr {
72
    #[cfg(tokio_unix)]
73
    UnixAddr(PathBuf),
74
    #[cfg(feature = "iroh")]
75
    NodeAddr(NodeAddr),
76
    IpAddr(IpAddr),
77
}
78

            
79
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
80
pub enum Peer {
81
    #[cfg(tokio_unix)]
82
    Unix(Unix),
83
    NodeId(NodeId),
84
    #[cfg(feature = "x509")]
85
    Tls(TlsPeer),
86
    WebCredentials(WebCredentials),
87
}
88

            
89
/// Parsed TLS certificate with extracted identity information
90
#[cfg(feature = "x509")]
91
#[derive(Debug, Clone, PartialEq, Eq, Hash, JetStreamWireFormat)]
92
pub struct TlsCert {
93
    /// SHA-256 fingerprint of the certificate (hex encoded)
94
    pub fingerprint: String,
95
    /// Common Name from the certificate subject (if present)
96
    pub common_name: Option<String>,
97
    /// DNS names from SAN (e.g., "example.com")
98
    pub dns_names: Vec<String>,
99
    /// IP addresses from SAN (for P2P certs)
100
    pub ip_addresses: Vec<IpAddr>,
101
    /// Email addresses from SAN (RFC 822 names)
102
    pub emails: Vec<String>,
103
    /// URIs from SAN (e.g., "spiffe://cluster.local/ns/default/sa/myapp")
104
    pub uris: Vec<Url>,
105
}
106

            
107
#[cfg(feature = "x509")]
108
impl TlsCert {
109
    /// Parse a TLS certificate from DER-encoded bytes
110
224
    pub fn from_der(
111
224
        der: &[u8],
112
224
    ) -> Result<Self, x509_certificate::X509CertificateError> {
113
        use x509_certificate::X509Certificate;
114

            
115
224
        let cert = X509Certificate::from_der(der)?;
116

            
117
224
        let fingerprint = cert
118
224
            .sha256_fingerprint()
119
224
            .map(|d| hex::encode(d.as_ref()))
120
            .unwrap_or_default();
121

            
122
224
        let common_name = cert.subject_common_name();
123

            
124
224
        let mut dns_names = Vec::new();
125
224
        let mut ip_addresses = Vec::new();
126
224
        let mut emails = Vec::new();
127
224
        let mut uris = Vec::new();
128

            
129
        // OID for Subject Alternative Name: 2.5.29.17
130
224
        let oid_san = bcder::Oid(bytes::Bytes::from_static(&[85, 29, 17]));
131

            
132
224
        for ext in cert.iter_extensions() {
133
1344
            if ext.id == oid_san {
134
                // Parse SANs manually since x509-certificate expects constructed
135
                // tags but RFC 5280 uses IMPLICIT (primitive) tags for most types
136
224
                let value_bytes = ext.value.clone().into_bytes();
137
224
                parse_subject_alt_names(
138
224
                    &value_bytes,
139
224
                    &mut dns_names,
140
224
                    &mut ip_addresses,
141
224
                    &mut emails,
142
224
                    &mut uris,
143
224
                );
144
1120
            }
145
        }
146

            
147
224
        Ok(TlsCert {
148
224
            fingerprint,
149
224
            common_name,
150
224
            dns_names,
151
224
            ip_addresses,
152
224
            emails,
153
224
            uris,
154
224
        })
155
224
    }
156
}
157

            
158
/// Parse Subject Alternative Names from DER-encoded extension value.
159
/// RFC 5280 uses IMPLICIT tagging for GeneralName, so we parse manually.
160
#[cfg(feature = "x509")]
161
224
fn parse_subject_alt_names(
162
224
    data: &[u8],
163
224
    dns_names: &mut Vec<String>,
164
224
    ip_addresses: &mut Vec<IpAddr>,
165
224
    emails: &mut Vec<String>,
166
224
    uris: &mut Vec<Url>,
167
224
) {
168
    // SAN extension value is a SEQUENCE of GeneralName
169
    // Skip the outer SEQUENCE tag (0x30) and length
170
224
    if data.len() < 2 || data[0] != 0x30 {
171
        return;
172
224
    }
173

            
174
224
    let (seq_len, offset) = parse_der_length(&data[1..]);
175
224
    if offset == 0 {
176
        return;
177
224
    }
178
224
    let mut i = 1 + offset;
179
224
    let end = std::cmp::min(i + seq_len, data.len());
180

            
181
    // GeneralName IMPLICIT tags (context-specific, primitive):
182
    // [1] rfc822Name       - 0x81
183
    // [2] dNSName          - 0x82
184
    // [6] uniformResourceIdentifier - 0x86
185
    // [7] iPAddress        - 0x87
186
672
    while i + 2 <= end {
187
448
        let tag = data[i];
188
448
        let (content_len, len_offset) = parse_der_length(&data[i + 1..]);
189
448
        if len_offset == 0 {
190
            break;
191
448
        }
192
448
        let content_start = i + 1 + len_offset;
193
448
        let content_end = content_start + content_len;
194
448
        if content_end > end {
195
            break;
196
448
        }
197
448
        let content = &data[content_start..content_end];
198

            
199
448
        match tag {
200
            0x81 => {
201
                // rfc822Name (email)
202
224
                if let Ok(email) = std::str::from_utf8(content) {
203
224
                    emails.push(email.to_string());
204
                }
205
            }
206
            0x82 => {
207
                // dNSName
208
                if let Ok(dns) = std::str::from_utf8(content) {
209
                    dns_names.push(dns.to_string());
210
                }
211
            }
212
            0x86 => {
213
                // uniformResourceIdentifier
214
224
                if let Ok(uri_str) = std::str::from_utf8(content) {
215
224
                    if let Ok(url) = Url::parse(uri_str) {
216
224
                        uris.push(url);
217
                    }
218
                }
219
            }
220
            0x87 => {
221
                // iPAddress
222
                match content.len() {
223
                    4 => {
224
                        if let Ok(arr) = <[u8; 4]>::try_from(content) {
225
                            ip_addresses.push(IpAddr::V4(arr.into()));
226
                        }
227
                    }
228
                    16 => {
229
                        if let Ok(arr) = <[u8; 16]>::try_from(content) {
230
                            ip_addresses.push(IpAddr::V6(arr.into()));
231
                        }
232
                    }
233
                    _ => {}
234
                }
235
            }
236
            _ => {
237
                // Skip other GeneralName types (otherName, x400Address, etc.)
238
            }
239
        }
240

            
241
448
        i = content_end;
242
    }
243
224
}
244

            
245
/// Parse DER length encoding. Returns (length, bytes_consumed).
246
#[cfg(feature = "x509")]
247
672
fn parse_der_length(data: &[u8]) -> (usize, usize) {
248
672
    if data.is_empty() {
249
        return (0, 0);
250
672
    }
251
672
    let first = data[0];
252
672
    if first < 0x80 {
253
        // Short form: length is the byte itself
254
672
        (first as usize, 1)
255
    } else if first == 0x80 {
256
        // Indefinite length - not valid in DER
257
        (0, 0)
258
    } else {
259
        // Long form: first byte indicates number of length bytes
260
        let num_bytes = (first & 0x7f) as usize;
261
        if num_bytes > data.len() - 1 || num_bytes > 4 {
262
            return (0, 0);
263
        }
264
        let mut len = 0usize;
265
        for &b in &data[1..1 + num_bytes] {
266
            len = (len << 8) | (b as usize);
267
        }
268
        (len, 1 + num_bytes)
269
    }
270
672
}
271

            
272
/// TLS peer identity containing the certificate chain
273
#[cfg(feature = "x509")]
274
#[derive(Debug, Clone, PartialEq, Eq, Hash, JetStreamWireFormat)]
275
pub struct TlsPeer {
276
    /// Certificate chain (leaf cert first, then intermediates)
277
    pub chain: Vec<TlsCert>,
278
}
279

            
280
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
281
pub struct WebCredentials(pub http::HeaderValue);
282

            
283
impl WireFormat for WebCredentials {
284
    fn byte_size(&self) -> u32 {
285
        2 + self.0.as_bytes().len() as u32
286
    }
287

            
288
    fn encode<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()>
289
    where
290
        Self: Sized,
291
    {
292
        let bytes = self.0.as_bytes();
293
        writer.write_all(&(bytes.len() as u16).to_be_bytes())?;
294
        writer.write_all(bytes)
295
    }
296

            
297
    fn decode<R: std::io::Read>(reader: &mut R) -> std::io::Result<Self>
298
    where
299
        Self: Sized,
300
    {
301
        let len = u16::decode(reader)?;
302
        let mut buf = vec![0u8; len as usize];
303
        reader.read_exact(&mut buf)?;
304
        let header_value =
305
            http::HeaderValue::from_bytes(&buf).map_err(|_| {
306
                std::io::Error::new(
307
                    std::io::ErrorKind::InvalidData,
308
                    "Invalid header value",
309
                )
310
            })?;
311
        Ok(WebCredentials(header_value))
312
    }
313
}
314

            
315
#[cfg(feature = "x509")]
316
impl TlsPeer {
317
    /// Parse a certificate chain from DER-encoded bytes
318
208
    pub fn from_der_chain<T: AsRef<[u8]>>(
319
208
        certs: &[T],
320
208
    ) -> Result<Self, x509_certificate::X509CertificateError> {
321
208
        let chain = certs
322
208
            .iter()
323
208
            .map(|c| TlsCert::from_der(c.as_ref()))
324
            .collect::<Result<Vec<_>, _>>()?;
325
208
        Ok(TlsPeer { chain })
326
208
    }
327

            
328
    /// Get the leaf certificate (first in chain)
329
28
    pub fn leaf(&self) -> Option<&TlsCert> {
330
28
        self.chain.first()
331
28
    }
332
}
333

            
334
#[derive(Debug, Clone, PartialEq, Eq, Hash, JetStreamWireFormat)]
335
pub struct NodeId(String);
336

            
337
#[cfg(feature = "iroh")]
338
#[derive(Debug, Clone, PartialEq, Eq, Hash, JetStreamWireFormat)]
339
pub struct NodeAddr {
340
    id: NodeId,
341
    addrs: BTreeSet<TransportAddr>,
342
}
343

            
344
#[cfg(feature = "iroh")]
345
/// Available address types.
346
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
347
#[non_exhaustive]
348
pub enum TransportAddr {
349
    /// Relays
350
    Relay(iroh::RelayUrl),
351
    /// IP based addresses
352
    Ip(SocketAddr),
353
}
354

            
355
#[cfg(feature = "iroh")]
356
impl From<iroh::TransportAddr> for TransportAddr {
357
    fn from(addr: iroh::TransportAddr) -> Self {
358
        match addr {
359
            iroh::TransportAddr::Relay(url) => TransportAddr::Relay(url),
360
            iroh::TransportAddr::Ip(addr) => TransportAddr::Ip(addr),
361
            _ => unreachable!(),
362
        }
363
    }
364
}
365

            
366
#[cfg(feature = "iroh")]
367
impl From<&TransportAddr> for iroh::TransportAddr {
368
    fn from(addr: &TransportAddr) -> Self {
369
        match addr {
370
            TransportAddr::Relay(url) => {
371
                iroh::TransportAddr::Relay(url.clone())
372
            }
373
            TransportAddr::Ip(addr) => iroh::TransportAddr::Ip(*addr),
374
        }
375
    }
376
}
377

            
378
#[cfg(feature = "iroh")]
379
impl WireFormat for TransportAddr {
380
    fn byte_size(&self) -> u32 {
381
        1 + match self {
382
            TransportAddr::Relay(url) => url.byte_size(),
383
            TransportAddr::Ip(addr) => addr.byte_size(),
384
        }
385
    }
386

            
387
    fn encode<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()>
388
    where
389
        Self: Sized,
390
    {
391
        match self {
392
            TransportAddr::Relay(url) => {
393
                0_u8.encode(writer)?;
394
                url.encode(writer)
395
            }
396
            TransportAddr::Ip(addr) => {
397
                1_u8.encode(writer)?;
398
                addr.encode(writer)
399
            }
400
        }
401
    }
402

            
403
    fn decode<R: std::io::Read>(reader: &mut R) -> std::io::Result<Self>
404
    where
405
        Self: Sized,
406
    {
407
        match u8::decode(reader)? {
408
            0 => Ok(TransportAddr::Relay(iroh::RelayUrl::from(Url::decode(
409
                reader,
410
            )?))),
411
            1 => Ok(TransportAddr::Ip(SocketAddr::decode(reader)?)),
412
            _ => Err(std::io::Error::new(
413
                std::io::ErrorKind::InvalidData,
414
                "Invalid transport address type",
415
            )),
416
        }
417
    }
418
}
419

            
420
#[cfg(feature = "iroh")]
421
impl From<iroh::PublicKey> for NodeId {
422
224
    fn from(value: iroh::PublicKey) -> Self {
423
224
        NodeId(value.to_string())
424
224
    }
425
}
426

            
427
#[cfg(feature = "iroh")]
428
impl From<NodeAddr> for iroh::EndpointAddr {
429
    fn from(value: NodeAddr) -> Self {
430
        use std::str::FromStr;
431

            
432
        use iroh::PublicKey;
433

            
434
        iroh::EndpointAddr {
435
            id: PublicKey::from_str(&value.id.0)
436
                .expect("Failed to convert NodeId to iroh::NodeId"),
437
            addrs: value.addrs.iter().map(|addr| addr.into()).collect(),
438
        }
439
    }
440
}
441

            
442
#[cfg(feature = "iroh")]
443
impl From<iroh::EndpointAddr> for NodeAddr {
444
    fn from(value: iroh::EndpointAddr) -> Self {
445
        NodeAddr {
446
            id: NodeId(value.id.to_string()),
447
            addrs: value.addrs.into_iter().map(|addr| addr.into()).collect(),
448
        }
449
    }
450
}
451

            
452
#[derive(Debug, Clone)]
453
#[cfg(tokio_unix)]
454
pub struct Unix(UCred);
455

            
456
#[cfg(tokio_unix)]
457
impl std::hash::Hash for Unix {
458
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
459
        if let Some(pid) = self.0.pid() {
460
            H::write_i32(state, pid);
461
        }
462
        H::write_u32(state, self.0.uid());
463
        H::write_u32(state, self.0.gid());
464
    }
465
}
466

            
467
#[cfg(tokio_unix)]
468
impl PartialEq for Unix {
469
    fn eq(&self, other: &Self) -> bool {
470
        self.0.pid() == other.0.pid()
471
            && self.0.uid() == other.0.uid()
472
            && self.0.gid() == other.0.gid()
473
    }
474
}
475

            
476
#[cfg(tokio_unix)]
477
impl Eq for Unix {}
478

            
479
#[cfg(tokio_unix)]
480
impl Deref for Unix {
481
    type Target = UCred;
482

            
483
    fn deref(&self) -> &Self::Target {
484
        &self.0
485
    }
486
}
487

            
488
#[cfg(tokio_unix)]
489
impl DerefMut for Unix {
490
    fn deref_mut(&mut self) -> &mut Self::Target {
491
        &mut self.0
492
    }
493
}
494

            
495
#[cfg(tokio_unix)]
496
impl Unix {
497
    /// returns the process' path
498
    pub fn process_path(&self) -> Result<PathBuf, std::io::Error> {
499
        use std::fs::read_link;
500
        if let Some(pid) = self.pid() {
501
            read_link(format!("/proc/{}/exe", pid))
502
        } else {
503
            Err(std::io::Error::new(
504
                std::io::ErrorKind::NotFound,
505
                "PID not found",
506
            ))
507
        }
508
    }
509
}
510

            
511
pub trait Contextual {
512
    fn context(&self) -> Context;
513
}
514

            
515
#[cfg(tokio_unix)]
516
impl<U> Contextual for Framed<UnixStream, U> {
517
    fn context(&self) -> Context {
518
        let remote = if let Ok(addr) = self.get_ref().peer_addr() {
519
            addr.as_pathname()
520
                .map(|addr| RemoteAddr::UnixAddr(addr.to_path_buf()))
521
        } else {
522
            None
523
        };
524
        let peer = if let Ok(ucred) = self.get_ref().peer_cred() {
525
            Some(Peer::Unix(Unix(ucred)))
526
        } else {
527
            None
528
        };
529
        Context { remote, peer }
530
    }
531
}
532

            
533
// r[impl jetstream.session.identity]
534
// A plain TCP stream authenticates nothing, so the peer is `None` and
535
// only the remote address is reported.
536
//
537
// Gated on having a network stack rather than on unix sockets: tokio's
538
// TCP is cross-platform, and gating it with the `UnixStream` impls would
539
// leave `SingleLaneSession::service_io` unusable with TCP on Windows.
540
#[cfg(native)]
541
impl<U> Contextual for Framed<tokio::net::TcpStream, U> {
542
    fn context(&self) -> Context {
543
        let remote = self
544
            .get_ref()
545
            .peer_addr()
546
            .ok()
547
            .map(|addr| RemoteAddr::IpAddr(addr.ip()));
548
        Context { remote, peer: None }
549
    }
550
}
551

            
552
#[cfg(feature = "turmoil")]
553
impl<U> Contextual for Framed<turmoil::net::TcpStream, U> {
554
271
    fn context(&self) -> Context {
555
271
        let addr = self.get_ref().peer_addr().unwrap();
556
271
        Context {
557
271
            remote: Some(RemoteAddr::IpAddr(addr.ip())),
558
271
            peer: None,
559
271
        }
560
271
    }
561
}
562

            
563
#[cfg(cloudflare)]
564
impl Contextual for worker::Request {
565
    fn context(&self) -> Context {
566
        Context {
567
            remote: None,
568
            peer: None,
569
        }
570
    }
571
}
572

            
573
impl Context {
574
224
    pub fn new(remote: Option<RemoteAddr>, peer: Option<Peer>) -> Self {
575
224
        Context { remote, peer }
576
224
    }
577

            
578
    /// Get the remote address
579
28
    pub fn remote(&self) -> Option<&RemoteAddr> {
580
28
        self.remote.as_ref()
581
28
    }
582

            
583
    /// Get the peer identity
584
84
    pub fn peer(&self) -> Option<&Peer> {
585
84
        self.peer.as_ref()
586
84
    }
587
}