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
//! [`PrivateKey`].

use std::{
	fmt::{self, Debug, Formatter},
	sync::Arc,
};

use rustls::sign::{self, SigningKey};
use serde::{Deserialize, Serializer};
use zeroize::Zeroize;

use crate::error;

/// A private key.
///
/// # Safety
/// Never give this to anybody.
#[derive(Clone, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Zeroize)]
#[zeroize(drop)]
pub struct PrivateKey(Option<Vec<u8>>);

impl Debug for PrivateKey {
	fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
		formatter
			.debug_tuple("PrivateKey")
			.field(&"[[redacted]]")
			.finish()
	}
}

impl TryFrom<Vec<u8>> for PrivateKey {
	type Error = error::PrivateKey;

	fn try_from(certificate: Vec<u8>) -> Result<Self, Self::Error> {
		Self::from_der(certificate)
	}
}

impl PrivateKey {
	/// Build [`PrivateKey`] from DER-format. This is not meant as a full
	/// validation of a [`PrivateKey`], it just offers some sane protections.
	///
	/// # Errors
	/// [`error::PrivateKey`] if the certificate couldn't be parsed.
	pub fn from_der<P: Into<Vec<u8>>>(private_key: P) -> Result<Self, error::PrivateKey> {
		let private_key = rustls::PrivateKey(private_key.into());

		if let Err(_error) = sign::any_supported_type(&private_key) {
			Err(error::PrivateKey(private_key.0))
		} else {
			Ok(Self(Some(private_key.0)))
		}
	}

	/// Build [`PrivateKey`] from DER-format. This skips the validation from
	/// [`from_der`](Self::from_der), which isn't `unsafe`, but could fail
	/// nonetheless when used on an [`Endpoint`](crate::Endpoint).
	#[must_use]
	pub fn unchecked_from_der<P: Into<Vec<u8>>>(private_key: P) -> Self {
		Self(Some(private_key.into()))
	}

	/// Convert into a rustls `PrivateKey`.
	///
	/// # Panics
	/// Panics if [`PrivateKey`] couldn't be parsed. This can't happen if
	/// [`PrivateKey`] is constructed correctly from
	/// [`from_der`](Self::from_der).
	pub(crate) fn into_rustls(self) -> rustls::PrivateKey {
		rustls::PrivateKey(Dangerous::into(self))
	}

	/// Convert into a type [`rustls`] can use for signatures.
	///
	/// # Panics
	/// Panics if [`PrivateKey`] couldn't be parsed. This can't happen if
	/// [`PrivateKey`] is constructed correctly from
	/// [`from_der`](Self::from_der).
	pub(crate) fn into_rustls_signing_key(self) -> Arc<dyn SigningKey> {
		sign::any_supported_type(&self.into_rustls())
			.expect("`PrivateKey` not compatible with `rustls`")
	}
}

/// Gives read access to the [`PrivateKey`].
///
/// # Security
/// This is only dangerous in the sense that you aren't supposed to leak the
/// [`PrivateKey`]. Make sure to use this carefully!
pub trait Dangerous {
	/// Returns a [`&[u8]`](slice) to the [`PrivateKey`].
	///
	/// # Security
	/// This is only dangerous in the sense that you aren't supposed to leak the
	/// [`PrivateKey`]. Make sure to use this carefully!
	#[must_use]
	fn as_ref(private_key: &Self) -> &[u8];

	/// Returns a [`Vec<u8>`] to the [`PrivateKey`].
	///
	/// # Security
	/// This is only dangerous in the sense that you aren't supposed to leak the
	/// [`PrivateKey`]. Make sure to use this carefully!
	#[must_use]
	fn into(private_key: Self) -> Vec<u8>;

	/// Serialize with [`serde`].
	///
	/// # Security
	/// This is only dangerous in the sense that you aren't supposed to leak the
	/// [`PrivateKey`]. Make sure to use this carefully!
	///
	/// # Errors
	/// [`S::Error`](Serializer::Error) if serialization failed.
	fn serialize<S: Serializer>(private_key: &Self, serializer: S) -> Result<S::Ok, S::Error>;
}

impl Dangerous for PrivateKey {
	fn as_ref(private_key: &Self) -> &[u8] {
		private_key.0.as_deref().expect("value already dropped")
	}

	fn into(mut private_key: Self) -> Vec<u8> {
		private_key.0.take().expect("value already dropped")
	}

	fn serialize<S: Serializer>(private_key: &Self, serializer: S) -> Result<S::Ok, S::Error> {
		serializer.serialize_newtype_struct("PrivateKey", &private_key.0)
	}
}

#[cfg(test)]
mod test {
	use anyhow::Result;
	use bincode::{config::DefaultOptions, Options, Serializer};

	use super::*;
	use crate::KeyPair;

	#[test]
	fn validate() -> Result<()> {
		let (_, private_key) = KeyPair::new_self_signed("test").into_parts();

		assert_eq!(
			private_key,
			PrivateKey::from_der(Dangerous::into(private_key.clone()))?,
		);

		Ok(())
	}

	#[test]
	fn serialize() -> Result<()> {
		let (_, private_key) = KeyPair::new_self_signed("test").into_parts();

		let mut buffer = Vec::new();

		Dangerous::serialize(
			&private_key,
			&mut Serializer::new(
				&mut buffer,
				DefaultOptions::default()
					.with_fixint_encoding()
					.allow_trailing_bytes(),
			),
		)?;

		assert_eq!(private_key, bincode::deserialize(&buffer)?);

		Ok(())
	}

	#[test]
	fn debug() {
		let (_, private_key) = KeyPair::new_self_signed("test").into_parts();
		assert_eq!("PrivateKey(\"[[redacted]]\")", format!("{private_key:?}"));
	}
}