gload 0.5.1

A command line client for the Gemini protocol.
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
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
//! This software is licensed as described in the file LICENSE, which
//! you should have received as part of this distribution.
//!
//! You may opt to use, copy, modify, merge, publish, distribute and/or sell
//! copies of the Software, and permit persons to whom the Software is
//! furnished to do so, under the terms of the LICENSE file.
//!
//! This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
//! KIND, either express or implied.
//!
//! SPDX-License-Identifier: BSD-3-Clause

use core::{net::SocketAddr, time::Duration};
use rustls::{
	ClientConfig, Error as Terror, RootCertStore, SignatureScheme,
	client::{
		danger::{ServerCertVerified, ServerCertVerifier},
		verify_server_cert_signed_by_trust_anchor, verify_server_name,
	},
	crypto::{CryptoProvider, verify_tls12_signature, verify_tls13_signature},
	pki_types::ServerName,
	server::ParsedCertificate,
};
use std::{io::ErrorKind, sync::Arc, time::Instant};
use tokio::{
	io::{AsyncReadExt, AsyncWriteExt},
	net::TcpStream,
};
use tokio_rustls::TlsConnector;
use x509_parser::oid_registry::OID_X509_COMMON_NAME;

macro_rules! debug {
	($($arg:tt)+) => {{
		#[cfg(feature = "logging")]
		::log::debug!(target: "gload::tls", $($arg)+)
	}}
}

macro_rules! warn {
	($($arg:tt)+) => {{
		#[cfg(feature = "logging")]
		::log::warn!(target: "gload::tls", $($arg)+)
	}}
}

// Spec: "Client and server implementations MUST support TLS SNI (Server Name Indication) and clients MUST include hostname information when making requests for URLs where the authority section is a hostname. If requesting a URL where the authority section is an IP address (contrary to recommendation 5. in the overview), clients SHOULD omit SNI information rather than setting it to an empty value."

pub(crate) type Stream = tokio_rustls::client::TlsStream<TcpStream>;

/// Attempts to open a TCP stream with the host at the given server.
pub(crate) async fn open_stream(
	addr: &SocketAddr,
	authority: ServerName<'static>,
) -> Result<Stream, TlsError> {
	// Custom cert verifier
	let verifier = Arc::new(Verifier::new());

	// Spec: "TLS 1.2 is the minimum required version"
	let versions = [&rustls::version::TLS12, &rustls::version::TLS13];
	let cfg = ClientConfig::builder_with_protocol_versions(&versions)
		.dangerous()
		.with_custom_certificate_verifier(verifier)
		.with_no_client_auth();

	// Start TLS connection (handshake?)
	debug!("* ALPN: gload offers none"); // we don't bother about ALPN with Gemini
	let connector = TlsConnector::from(Arc::new(cfg));

	// Open a stream
	let timeout = Duration::from_secs(15);
	let start = Instant::now();
	let stream = match tokio::time::timeout(timeout, TcpStream::connect(addr)).await {
		Err(_) => {
			return Err(TlsError::TimedOut(authority, addr.port(), start.elapsed()));
		}
		Ok(Err(err)) if err.kind() == ErrorKind::TimedOut => {
			return Err(TlsError::TimedOut(authority, addr.port(), start.elapsed()));
		}
		Ok(Err(err)) => return Err(TlsError::Open(err)),
		Ok(Ok(s)) => s,
	};

	let stream = match connector.connect(authority.clone(), stream).await {
		Err(err) => match err.downcast::<Terror>() {
			Ok(Terror::InvalidCertificate(err)) => {
				return Err(TlsError::ServerCertificate(err));
			}
			Ok(Terror::InappropriateHandshakeMessage { .. }) => {
				return Err(TlsError::InappropriateHandshakeMessage);
			}
			Ok(err) => panic!("something went wrong: {err}"), // TODO: Handle these other errors with a proper exit code
			Err(err) => return Err(TlsError::InitialConnect(err, authority, addr.port())),
		},
		Ok(c) => c,
	};

	Ok(stream)
}

/// Attempts to send data to the given TCP stream. An `Ok` result is guaranteed to be nonempty.
pub(crate) async fn send(
	addr: &SocketAddr,
	authority: &ServerName<'static>,
	mut tcp_stream: Stream,
	payload: Vec<u8>,
	allow_truncation: bool,
) -> Result<Vec<u8>, TlsError> {
	debug!(
		"* Connected to {} ({}) port {}",
		authority.to_str(),
		addr.ip(),
		addr.port()
	);
	debug!("* using Gemini/0.24.x");
	let start = Instant::now();
	match tcp_stream.write_all(&payload).await {
		Err(err) if err.kind() == ErrorKind::TimedOut => {
			return Err(TlsError::TimedOut(
				authority.to_owned(),
				addr.port(),
				start.elapsed(),
			));
		}
		Err(err) => match err.downcast::<Terror>() {
			Ok(Terror::InvalidCertificate(err)) => {
				return Err(TlsError::ServerCertificate(err));
			}
			Ok(Terror::InappropriateHandshakeMessage { .. }) => {
				return Err(TlsError::InappropriateHandshakeMessage);
			}
			Ok(err) => panic!("something went wrong: {err}"), // TODO: Handle these other errors with a proper exit code
			Err(err) => return Err(TlsError::Send(err)),
		},
		Ok(()) => {
			debug!(
				"> {}",
				str::from_utf8(&payload)
					.expect("the payload came from a utf-8 string")
					.replace('\r', "")
					.replace('\n', "\n> ") // start each line with a '>'
			);
		}
	}
	debug!("* Request completely sent off");

	let mut buffer: Vec<u8> = Vec::with_capacity(512);
	let timeout = Duration::from_secs(15);
	let start = Instant::now();
	match tokio::time::timeout(timeout, tcp_stream.read_to_end(&mut buffer)).await {
		Err(_) => {
			return Err(TlsError::TimedOut(
				authority.clone(),
				addr.port(),
				start.elapsed(),
			));
		}
		Ok(Err(e)) if e.kind() == ErrorKind::UnexpectedEof => {
			// Spec: "Both clients and servers SHOULD handle the case when the TLS close_notify mechanism is not used (such as a low level socket error that closes the socket without properly terminating the TLS connection). A client SHOULD notify the user of such a case; the server MAY log such a case."
			warn!("* rustls: server closed abruptly (missing close_notify)");
			if allow_truncation {
				// proceed
			} else {
				return Err(TlsError::ClosedWithoutNotify);
			}
		}
		Ok(Err(e)) => return Err(TlsError::Receive(e)),
		Ok(Ok(_)) => {} // proceed
	}

	// Spec: "Clients SHOULD NOT close a connection by default" but we're ignoring that
	// because it's good manners to inform the server that we're finished writing.
	//
	// In TLS 1.2, sending close_notify after writes would also close reads, and we'd fail.
	// Instead, we send close_notify after reads.
	tcp_stream.get_mut().1.send_close_notify();
	let timeout = Duration::from_secs(3);
	let start = Instant::now();
	match tokio::time::timeout(timeout, tcp_stream.write(&[])).await {
		Err(_) => {
			return Err(TlsError::TimedOut(
				authority.clone(),
				addr.port(),
				start.elapsed(),
			));
		}
		Ok(Err(err)) => {
			return Err(TlsError::ShutdownFailed(err));
		}
		Ok(Ok(_)) => {} // proceed
	}

	// The server MUST send *something*, or there's a problem.
	if buffer.is_empty() {
		return Err(TlsError::NoResponse);
	}

	Ok(buffer)
}

#[derive(Debug)]
struct Verifier(CryptoProvider);

impl Verifier {
	fn new() -> Self {
		let provider = rustls::crypto::aws_lc_rs::default_provider();
		Self(provider)
	}
}

impl ServerCertVerifier for Verifier {
	fn verify_server_cert(
		&self,
		end_entity: &rustls::pki_types::CertificateDer<'_>,
		intermediates: &[rustls::pki_types::CertificateDer<'_>],
		server_name: &rustls::pki_types::ServerName<'_>,
		_ocsp_response: &[u8],
		now: rustls::pki_types::UnixTime,
	) -> Result<rustls::client::danger::ServerCertVerified, Terror> {
		use rustls::{CertificateError, OtherError};

		// Parse DER a different way, since rustls offers only minimal information from its public parser :(
		let cert = match x509_parser::parse_x509_certificate(end_entity) {
			Err(_) => return Err(Terror::InvalidCertificate(CertificateError::BadEncoding)),
			Ok((_, cert)) => cert,
		};

		// Check cert expiration
		match u64::try_from(cert.validity.not_before.timestamp()) {
			Err(_) => {} // if i64 doesn't fit in u64 then it must be negative, meaning this cert was valid before 1970; pass
			Ok(not_before) => {
				if now.as_secs() < not_before {
					return Err(Terror::InvalidCertificate(CertificateError::NotValidYet));
				}
			}
		}

		match u64::try_from(cert.validity.not_after.timestamp()) {
			Err(_) => return Err(Terror::InvalidCertificate(CertificateError::Expired)), // if i64 doesn't fit in u64 then it must be negative, meaning this cert expired before 1970; fail
			Ok(not_after) => {
				if now.as_secs() > not_after {
					return Err(Terror::InvalidCertificate(CertificateError::Expired));
				}
			}
		}

		// TODO: TOFU mode. Complain if the certificate has changed since last TOFU-mode visit

		debug!("* Server certificate:");
		debug!("*  subject: {}", cert.subject);
		debug!("*  start date: {}", cert.validity.not_before);
		debug!("*  expire date: {}", cert.validity.not_after);

		// Verify server name (first against subjectAltName, then against subject)
		let parsed_cert = ParsedCertificate::try_from(end_entity)?;
		let subject_alternative_names = match cert.subject_alternative_name() {
			Err(err) => {
				return Err(Terror::InvalidCertificate(CertificateError::Other(
					OtherError(Arc::new(err)),
				)));
			}
			Ok(None) => None,
			Ok(Some(name)) => Some(name.value.general_names.to_owned()),
		};
		if let Some(names) = subject_alternative_names {
			// Verify cert's subjectAltName against our expected server_name.
			// rustls's own verifier is preferred, but fails (probably correctly)
			// to check common_name, which is sometimes used as a Gemini capsule's
			// cert's only name!
			match verify_server_name(&parsed_cert, server_name) {
				Err(err) => return Err(err),
				Ok(()) => {
					debug!(
						r#"*  subjectAltName: host "{}" matched cert's "{}""#,
						server_name.to_str(),
						names
							.iter()
							.map(|n| n.to_string())
							.map(|n| n.strip_prefix("DNSName(").unwrap_or(&n).to_owned())
							.map(|n| n.strip_suffix(")").unwrap_or(&n).to_owned())
							.collect::<Vec<_>>()
							.join(",")
					);
				}
			}

			// No subjectAltName; verify cert's Common Name instead
		} else if let Some(attr) = cert
			.subject
			.iter()
			.flat_map(|n| n.iter())
			.find(|a| a.attr_type() == &OID_X509_COMMON_NAME)
			&& let Ok(common_name) = attr.as_str()
			&& common_name == server_name.to_str()
		{
			debug!("*  subjectAltName: (none)");
		} else {
			// No name presented!
			return Err(Terror::InvalidCertificate(
				CertificateError::NotValidForName,
			));
		}

		debug!("*  issuer: {}", cert.issuer);

		// Spec: "Clients are strongly RECOMMENDED to [...] not reject self-signed certificates as invalid"
		if cert.subject == cert.issuer {
			// Self-signed, no need to check authority
			debug!("* Cert is self-signed");
		} else {
			// Possibly authority-signed, so we should check its CA chain
			let system_ca = rustls_native_certs::load_native_certs().certs; // TODO: Handle errors, and exit with code 77 if something dire went wrong
			let mut roots = RootCertStore {
				roots: if system_ca.is_empty() {
					webpki_roots::TLS_SERVER_ROOTS.to_vec()
				} else {
					Vec::with_capacity(system_ca.len())
				},
			};
			if !system_ca.is_empty() {
				for ca in system_ca {
					roots.add(ca).unwrap();
				}
			}

			let supported_algs = self.0.signature_verification_algorithms.all;
			let is_verified_by_ca = verify_server_cert_signed_by_trust_anchor(
				&parsed_cert,
				&roots,
				intermediates,
				now,
				supported_algs,
			)
			.is_ok();

			if is_verified_by_ca {
				debug!("* Cert is signed by a trusted central authority");
			} else {
				return Err(Terror::InvalidCertificate(CertificateError::UnknownIssuer));
			}
		}

		// TODO: OCSP

		Ok(ServerCertVerified::assertion())
	}

	fn verify_tls12_signature(
		&self,
		message: &[u8],
		cert: &rustls::pki_types::CertificateDer<'_>,
		dss: &rustls::DigitallySignedStruct,
	) -> Result<rustls::client::danger::HandshakeSignatureValid, Terror> {
		let supported_schemes = self.0.signature_verification_algorithms;
		match verify_tls12_signature(message, cert, dss, &supported_schemes) {
			Ok(valid) => {
				debug!("* Valid TLSv1.2 signature");
				Ok(valid)
			}
			Err(err) => {
				debug!("* Invalid TLSv1.2 signature!");
				Err(err)
			}
		}
	}

	fn verify_tls13_signature(
		&self,
		message: &[u8],
		cert: &rustls::pki_types::CertificateDer<'_>,
		dss: &rustls::DigitallySignedStruct,
	) -> Result<rustls::client::danger::HandshakeSignatureValid, Terror> {
		let supported_schemes = self.0.signature_verification_algorithms;
		match verify_tls13_signature(message, cert, dss, &supported_schemes) {
			Ok(valid) => {
				debug!("* Valid TLSv1.3 signature");
				Ok(valid)
			}
			Err(err) => {
				debug!("* Invalid TLSv1.3 signature!");
				Err(err)
			}
		}
	}

	fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
		self.0.signature_verification_algorithms.supported_schemes()
	}
}

#[derive(Debug)]
#[non_exhaustive]
pub enum TlsError {
	/// The server closed the connection before sending `close_notify`.
	/// This could mean an attacker caused a premature closure and the
	/// message was truncated, or the remote server simply forgot to
	/// send the alert. [[RFC 8446 § 6.1]]
	///
	/// Erroring out when `close_notify` is missing is comparable to
	/// cURL's behavior with HTTP/1.1 over TLS. Like HTTP/1.1, the
	/// Gemini network protocol does not have any way of indicating
	/// beforehand how much data the client should expect, so
	/// `close_notify` is its only mechanism for informing the client
	/// that transmission is complete and that data was not truncated,
	/// before closing the socket. [[curl#4427]], [[curl#11586]], [[curl/TODO]]
	///
	/// [RFC 8446 § 6.1]: https://datatracker.ietf.org/doc/html/rfc8446#section-6.1
	/// [curl#4427]: https://github.com/curl/curl/issues/4427#issuecomment-536122844
	/// [curl#11586]: https://github.com/curl/curl/discussions/11586#discussioncomment-6634966
	/// [curl/TODO]: https://github.com/curl/curl/blob/7f78150e87aa1ccf57467b8f40423b7c318e682c/docs/TODO#L941
	ClosedWithoutNotify,

	/// Received an inappropriate handshake message from the server.
	InappropriateHandshakeMessage,

	/// Failed to connect to the remote.
	InitialConnect(std::io::Error, ServerName<'static>, u16),

	/// The server replied with nothing, or didn't reply at all.
	NoResponse,

	/// Failed to open a TCP socket.
	Open(std::io::Error),

	/// Failed to read data from the server.
	Receive(std::io::Error),

	/// Failed to send data to the server.
	Send(std::io::Error),

	/// Could not read or validate the certificate.
	ServerCertificate(rustls::CertificateError),

	/// Failed to shut down the TCP connection.
	ShutdownFailed(std::io::Error),

	/// Timed out while opening a socket or awaiting a response.
	TimedOut(ServerName<'static>, u16, Duration),
}

impl core::fmt::Display for TlsError {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		match self {
			Self::ClosedWithoutNotify => write!(
				f,
				"the server closed the TLS connection without sending close_notify; the response may have been truncated"
			),
			Self::InappropriateHandshakeMessage => write!(
				f,
				"received an inappropriate handshake message from the server"
			),
			Self::InitialConnect(err, server_name, port) => {
				write!(
					f,
					"failed to connect to {} on port {port}: {err}",
					server_name.to_str()
				)
			}
			Self::NoResponse => write!(
				f,
				"the server replied with nothing, or did not reply at all"
			),
			Self::Open(err) => write!(f, "failed to open a TCP socket: {err}"),
			Self::Receive(err) => write!(f, "failed to read data from the server: {err}"),
			Self::Send(err) => write!(f, "failed to send data to the server: {err}"),
			Self::ServerCertificate(err) => write!(
				f,
				"could not read or validate the server certificate: {err}"
			),
			Self::ShutdownFailed(err) => write!(f, "failed to shut down the TCP connection: {err}"),
			Self::TimedOut(server_name, port, duration) => write!(
				f,
				"timed out after {} ms while opening a socket or awaiting a response from {} on port {port}",
				duration.as_millis(),
				server_name.to_str(),
			),
		}
	}
}

impl core::error::Error for TlsError {}

// MARK: - Tests

#[cfg(test)]
mod tests {
	use super::*;
	use crate::{
		request::Request,
		test_server::{
			FRIENDLY, new_simple_runtime, start_friendly_server,
			start_unfriendly_server_no_close_notify,
		},
	};
	use rustls::pki_types::DnsName;

	#[test]
	fn test_fails_when_close_notify_is_missing() {
		let server = start_unfriendly_server_no_close_notify();
		let addr = server.addr();

		let runtime = new_simple_runtime("test-client-runtime-worker");
		let authority = ServerName::DnsName(DnsName::try_from_str("localhost").unwrap());
		let stream = runtime
			.block_on(open_stream(&addr, authority.clone()))
			.unwrap();
		let req = Request::from_uri_string("gemini://localhost").unwrap();

		let err = runtime
			.block_on(send(&addr, &authority, stream, req.as_bytes(), false))
			.err()
			.unwrap();
		assert!(matches!(err, TlsError::ClosedWithoutNotify), "{err:?}");
		assert_eq!(server.request_count(), 1);
	}

	// TODO: Test that we send close_notify when we're done talking

	#[test]
	fn test_validates_cert_with_subject_alt_name() {
		// Generate a cert real quick..
		let authority = ServerName::DnsName(DnsName::try_from_str("localhost").unwrap());
		let key = rcgen::generate_simple_self_signed([authority.to_str().into()]).unwrap();
		let server = start_friendly_server(key);
		let addr = server.addr();

		let runtime = new_simple_runtime("test-client-runtime-worker");
		let stream = runtime
			.block_on(open_stream(&addr, authority.clone()))
			.unwrap();
		let req = Request::from_uri_string("gemini://localhost").unwrap();

		let expected = FRIENDLY;
		let result = runtime
			.block_on(send(&addr, &authority, stream, req.as_bytes(), false))
			.unwrap();
		assert_eq!(result, expected, "{}", String::from_utf8_lossy(&result));
		assert_eq!(server.request_count(), 1);
	}

	#[test]
	fn test_validates_cert_with_subject_alt_name_with_different_common_name() {
		let mut cert_params = rcgen::CertificateParams::new(["localhost".into()]).unwrap();
		cert_params
			.distinguished_name
			.push(rcgen::DnType::CommonName, "localhost.local");
		let signing_key = rcgen::KeyPair::generate().unwrap();
		let cert = cert_params.self_signed(&signing_key).unwrap();
		let key = rcgen::CertifiedKey { cert, signing_key };
		let server = start_friendly_server(key);
		let authority = ServerName::DnsName(DnsName::try_from_str("localhost").unwrap());
		let addr = server.addr();

		let runtime = new_simple_runtime("test-client-runtime-worker");
		let stream = runtime
			.block_on(open_stream(&addr, authority.clone()))
			.unwrap();
		let req = Request::from_uri_string("gemini://localhost").unwrap();

		let expected = FRIENDLY;
		let result = runtime
			.block_on(send(&addr, &authority, stream, req.as_bytes(), false))
			.unwrap();
		assert_eq!(result, expected, "{}", String::from_utf8_lossy(&result));
		assert_eq!(server.request_count(), 1);
	}

	#[test]
	fn test_rejects_cert_with_different_subject_alt_name() {
		let key = rcgen::generate_simple_self_signed(["localhost.local".into()]).unwrap();
		let server = start_friendly_server(key);
		let addr = server.addr();

		let runtime = new_simple_runtime("test-client-runtime-worker");
		let authority = ServerName::DnsName(DnsName::try_from_str("localhost").unwrap());
		let err = runtime
			.block_on(open_stream(&addr, authority.clone()))
			.err()
			.unwrap();
		assert!(
			matches!(
				err,
				TlsError::ServerCertificate(
					rustls::CertificateError::NotValidForNameContext {
					ref expected,
					ref presented,
				}) if expected == &authority && presented == &vec![r#"DnsName("localhost.local")"#]),
			"{err:?}"
		);
	}

	#[test]
	fn test_rejects_cert_with_different_subject_alt_name_and_matching_common_name() {
		let mut cert_params = rcgen::CertificateParams::new(["localhost.local".into()]).unwrap();
		cert_params
			.distinguished_name
			.push(rcgen::DnType::CommonName, "localhost");
		let signing_key = rcgen::KeyPair::generate().unwrap();
		let cert = cert_params.self_signed(&signing_key).unwrap();
		let key = rcgen::CertifiedKey { cert, signing_key };
		let server = start_friendly_server(key);
		let addr = server.addr();

		let runtime = new_simple_runtime("test-client-runtime-worker");
		let authority = ServerName::DnsName(DnsName::try_from_str("localhost").unwrap());
		let err = runtime
			.block_on(open_stream(&addr, authority.clone()))
			.err()
			.unwrap();
		assert!(
			matches!(
				err,
				TlsError::ServerCertificate(
					rustls::CertificateError::NotValidForNameContext {
					ref expected,
					ref presented,
				}) if expected == &authority && presented == &vec![r#"DnsName("localhost.local")"#]),
			"{err:?}"
		);
	}

	#[test]
	fn test_rejects_cert_with_no_subject_alt_name_and_different_common_name() {
		let mut cert_params = rcgen::CertificateParams::new(Vec::new()).unwrap();
		cert_params
			.distinguished_name
			.push(rcgen::DnType::CommonName, "localhost.local");
		let signing_key = rcgen::KeyPair::generate().unwrap();
		let cert = cert_params.self_signed(&signing_key).unwrap();
		let key = rcgen::CertifiedKey { cert, signing_key };

		let server = start_friendly_server(key);
		let addr = server.addr();

		let runtime = new_simple_runtime("test-client-runtime-worker");
		let authority = ServerName::DnsName(DnsName::try_from_str("localhost").unwrap());
		let err = runtime
			.block_on(open_stream(&addr, authority.clone()))
			.err()
			.unwrap();
		assert!(
			matches!(
				err,
				TlsError::ServerCertificate(rustls::CertificateError::NotValidForName)
			),
			"{err:?}"
		);
	}

	#[test]
	fn test_validates_cert_with_only_common_name() {
		let mut cert_params = rcgen::CertificateParams::new(Vec::new()).unwrap();
		cert_params
			.distinguished_name
			.push(rcgen::DnType::CommonName, "localhost");
		let signing_key = rcgen::KeyPair::generate().unwrap();
		let cert = cert_params.self_signed(&signing_key).unwrap();
		let key = rcgen::CertifiedKey { cert, signing_key };

		let server = start_friendly_server(key);
		let addr = server.addr();

		let runtime = new_simple_runtime("test-client-runtime-worker");
		let authority = ServerName::DnsName(DnsName::try_from_str("localhost").unwrap());
		let stream = runtime
			.block_on(open_stream(&addr, authority.clone()))
			.unwrap();
		let req = Request::from_uri_string("gemini://localhost").unwrap();

		let expected = FRIENDLY;
		let result = runtime
			.block_on(send(&addr, &authority, stream, req.as_bytes(), false))
			.unwrap();
		assert_eq!(result, expected, "{}", String::from_utf8_lossy(&result));
		assert_eq!(server.request_count(), 1);
	}

	#[test]
	fn test_validates_cert_with_only_common_name_with_other_details() {
		let mut cert_params = rcgen::CertificateParams::new(Vec::new()).unwrap();
		cert_params
			.distinguished_name
			.push(rcgen::DnType::OrganizationName, "yeahhhhhh");
		cert_params
			.distinguished_name
			.push(rcgen::DnType::CommonName, "localhost");
		let signing_key = rcgen::KeyPair::generate().unwrap();
		let cert = cert_params.self_signed(&signing_key).unwrap();
		let key = rcgen::CertifiedKey { cert, signing_key };

		let server = start_friendly_server(key);
		let addr = server.addr();

		let runtime = new_simple_runtime("test-client-runtime-worker");
		let authority = ServerName::DnsName(DnsName::try_from_str("localhost").unwrap());
		let stream = runtime
			.block_on(open_stream(&addr, authority.clone()))
			.unwrap();
		let req = Request::from_uri_string("gemini://localhost").unwrap();

		let expected = FRIENDLY;
		let result = runtime
			.block_on(send(&addr, &authority, stream, req.as_bytes(), false))
			.unwrap();
		assert_eq!(result, expected, "{}", String::from_utf8_lossy(&result));
		assert_eq!(server.request_count(), 1);
	}

	#[test]
	fn test_rejects_cert_with_no_name() {
		let cert_params = rcgen::CertificateParams::new(Vec::new()).unwrap();
		let signing_key = rcgen::KeyPair::generate().unwrap();
		let cert = cert_params.self_signed(&signing_key).unwrap();
		let key = rcgen::CertifiedKey { cert, signing_key };

		let server = start_friendly_server(key);
		let addr = server.addr();

		let runtime = new_simple_runtime("test-client-runtime-worker");
		let authority = ServerName::DnsName(DnsName::try_from_str("localhost").unwrap());
		let err = runtime
			.block_on(open_stream(&addr, authority.clone()))
			.err()
			.unwrap();
		assert!(
			matches!(
				err,
				TlsError::ServerCertificate(rustls::CertificateError::NotValidForName)
			),
			"{err:?}"
		);
	}

	#[test]
	fn test_rejects_future_cert() {
		let mut params = rcgen::CertificateParams::new(["localhost".into()]).unwrap();
		params.not_before = time::OffsetDateTime::now_utc().saturating_add(time::Duration::days(5)); // hasn't happened yet
		params.not_after = params.not_before.saturating_add(time::Duration::days(1));
		let signing_key = rcgen::KeyPair::generate().unwrap();
		let cert = params.self_signed(&signing_key).unwrap();
		let key = rcgen::CertifiedKey { cert, signing_key };

		let server = start_friendly_server(key);
		let addr = server.addr();

		let runtime = new_simple_runtime("test-client-runtime-worker");
		let authority = ServerName::DnsName(DnsName::try_from_str("localhost").unwrap());
		let err = runtime
			.block_on(open_stream(&addr, authority.clone()))
			.err()
			.unwrap();
		assert!(
			matches!(
				err,
				TlsError::ServerCertificate(rustls::CertificateError::NotValidYet)
			),
			"{err:?}"
		);
	}

	#[test]
	fn test_rejects_expired_cert() {
		let mut params = rcgen::CertificateParams::new(["localhost".into()]).unwrap();
		params.not_before = time::OffsetDateTime::now_utc().saturating_sub(time::Duration::days(2));
		params.not_after = params.not_before.saturating_add(time::Duration::days(1)); // yesterday was so long ago 😔
		let signing_key = rcgen::KeyPair::generate().unwrap();
		let cert = params.self_signed(&signing_key).unwrap();
		let key = rcgen::CertifiedKey { cert, signing_key };

		let server = start_friendly_server(key);
		let addr = server.addr();

		let runtime = new_simple_runtime("test-client-runtime-worker");
		let authority = ServerName::DnsName(DnsName::try_from_str("localhost").unwrap());
		let err = runtime
			.block_on(open_stream(&addr, authority.clone()))
			.err()
			.unwrap();
		assert!(
			matches!(
				err,
				TlsError::ServerCertificate(rustls::CertificateError::Expired)
			),
			"{err:?}"
		);
	}

	#[test]
	fn test_validates_old_cert_still_valid() {
		let mut params = rcgen::CertificateParams::new(["localhost".into()]).unwrap();
		params.not_before =
			time::OffsetDateTime::UNIX_EPOCH.saturating_sub(time::Duration::days(100)); // well before unix epoch
		params.not_after = time::OffsetDateTime::now_utc().saturating_add(time::Duration::days(1));
		let signing_key = rcgen::KeyPair::generate().unwrap();
		let cert = params.self_signed(&signing_key).unwrap();
		let key = rcgen::CertifiedKey { cert, signing_key };

		let server = start_friendly_server(key);
		let addr = server.addr();

		let runtime = new_simple_runtime("test-client-runtime-worker");
		let authority = ServerName::DnsName(DnsName::try_from_str("localhost").unwrap());
		let stream = runtime
			.block_on(open_stream(&addr, authority.clone()))
			.unwrap();
		let req = Request::from_uri_string("gemini://localhost").unwrap();

		let expected = FRIENDLY;
		let result = runtime
			.block_on(send(&addr, &authority, stream, req.as_bytes(), false))
			.unwrap();
		assert_eq!(result, expected, "{}", String::from_utf8_lossy(&result));
		assert_eq!(server.request_count(), 1);
	}

	#[test]
	fn test_rejects_ancient_cert() {
		let mut params = rcgen::CertificateParams::new(["localhost".into()]).unwrap();
		params.not_before =
			time::OffsetDateTime::UNIX_EPOCH.saturating_sub(time::Duration::days(100));
		params.not_after = params.not_before.saturating_add(time::Duration::days(1)); // well before unix epoch
		let signing_key = rcgen::KeyPair::generate().unwrap();
		let cert = params.self_signed(&signing_key).unwrap();
		let key = rcgen::CertifiedKey { cert, signing_key };

		let server = start_friendly_server(key);
		let addr = server.addr();

		let runtime = new_simple_runtime("test-client-runtime-worker");
		let authority = ServerName::DnsName(DnsName::try_from_str("localhost").unwrap());
		let err = runtime
			.block_on(open_stream(&addr, authority.clone()))
			.err()
			.unwrap();
		assert!(
			matches!(
				err,
				TlsError::ServerCertificate(rustls::CertificateError::Expired)
			),
			"{err:?}"
		);
	}
}