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
use crate::gpg::handler;
use gpgme::{Key, SignatureNotation, Subkey, UserId, UserIdSignature};
use std::fmt::{Display, Formatter, Result as FmtResult};
use std::str::FromStr;

/// Type of the key.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum KeyType {
	/// Public key.
	Public,
	/// Secret (private) key.
	Secret,
}

impl Display for KeyType {
	fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
		write!(
			f,
			"{}",
			match self {
				Self::Public => "pub",
				Self::Secret => "sec",
			}
		)
	}
}

impl FromStr for KeyType {
	type Err = ();
	fn from_str(s: &str) -> Result<Self, Self::Err> {
		for key_type in &[Self::Public, Self::Secret] {
			if key_type.to_string().matches(&s).count() >= 1 {
				return Ok(*key_type);
			}
		}
		Err(())
	}
}

/// Level of detail to show for key.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum KeyDetail {
	/// Show only the primary key and user ID.
	Minimum = 0,
	/// Show all subkeys and user IDs.
	Standard = 1,
	/// Show signatures.
	Full = 2,
}

impl Display for KeyDetail {
	fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
		write!(f, "{}", format!("{:?}", self).to_lowercase())
	}
}

impl FromStr for KeyDetail {
	type Err = ();
	fn from_str(s: &str) -> Result<Self, Self::Err> {
		match s.to_lowercase().as_str() {
			"1" | "min" | "minimum" => Ok(KeyDetail::Minimum),
			"2" | "standard" => Ok(KeyDetail::Standard),
			"3" | "full" => Ok(KeyDetail::Full),
			_ => Err(()),
		}
	}
}

impl KeyDetail {
	/// Increases the level of detail.
	pub fn increase(&mut self) {
		*self = match *self as i8 + 1 {
			1 => KeyDetail::Standard,
			2 => KeyDetail::Full,
			_ => KeyDetail::Minimum,
		}
	}
}

/// Representation of a key.
#[derive(Clone, Debug)]
pub struct GpgKey {
	/// GPGME Key type.
	inner: Key,
	/// Level of detail to show about key information.
	pub detail: KeyDetail,
}

impl From<Key> for GpgKey {
	fn from(key: Key) -> Self {
		Self {
			inner: key,
			detail: KeyDetail::Minimum,
		}
	}
}

impl GpgKey {
	/// Returns the key ID with '0x' prefix.
	pub fn get_id(&self) -> String {
		self.inner
			.id()
			.map_or(String::from("[?]"), |v| format!("0x{}", v))
	}

	/// Returns the key fingerprint.
	pub fn get_fingerprint(&self) -> String {
		self.inner
			.fingerprint()
			.map_or(String::from("[?]"), |v| v.to_string())
	}

	/// Returns the primary user of the key.
	pub fn get_user_id(&self) -> String {
		match self.inner.user_ids().next() {
			Some(user) => {
				user.id().map_or(String::from("[?]"), |v| v.to_string())
			}
			None => String::from("[?]"),
		}
	}

	/// Returns information about the subkeys.
	pub fn get_subkey_info(&self, truncate: bool) -> Vec<String> {
		let mut key_info = Vec::new();
		let subkeys = self.inner.subkeys().collect::<Vec<Subkey>>();
		for (i, subkey) in subkeys.iter().enumerate() {
			key_info.push(format!(
				"[{}] {}/{}",
				handler::get_subkey_flags(*subkey),
				subkey
					.algorithm_name()
					.unwrap_or_else(|_| { String::from("[?]") }),
				if truncate {
					subkey.id()
				} else {
					subkey.fingerprint()
				}
				.unwrap_or("[?]"),
			));
			if self.detail == KeyDetail::Minimum {
				break;
			}
			key_info.push(format!(
				"{}      └─{}",
				if i != subkeys.len() - 1 { "|" } else { " " },
				handler::get_subkey_time(
					*subkey,
					if truncate { "%Y" } else { "%F" }
				)
			));
		}
		key_info
	}

	/// Returns information about the users of the key.
	pub fn get_user_info(&self, truncate: bool) -> Vec<String> {
		let mut user_info = Vec::new();
		let user_ids = self.inner.user_ids().collect::<Vec<UserId>>();
		for (i, user) in user_ids.iter().enumerate() {
			user_info.push(format!(
				"{}[{}] {}",
				if i == 0 {
					""
				} else if i == user_ids.len() - 1 {
					" └─"
				} else {
					" ├─"
				},
				user.validity(),
				if truncate { user.email() } else { user.id() }
					.unwrap_or("[?]")
			));
			if self.detail == KeyDetail::Minimum {
				break;
			}
			if self.detail == KeyDetail::Full {
				user_info.extend(self.get_user_signatures(
					user,
					user_ids.len(),
					i,
					truncate,
				));
			}
		}
		user_info
	}

	/// Returns the signature information of an user.
	fn get_user_signatures(
		&self,
		user: &UserId,
		user_count: usize,
		user_index: usize,
		truncate: bool,
	) -> Vec<String> {
		let mut user_signatures = Vec::new();
		let signatures = user.signatures().collect::<Vec<UserIdSignature>>();
		for (i, sig) in signatures.iter().enumerate() {
			let padding = if user_count == 1 {
				" "
			} else if user_index == user_count - 1 {
				"    "
			} else if user_index == 0 {
				"│"
			} else {
				"│   "
			};
			user_signatures.push(format!(
				" {}  {}[{:x}] {} {}",
				padding,
				if i == signatures.len() - 1 {
					"└─"
				} else {
					"├─"
				},
				sig.cert_class(),
				if sig.signer_key_id() == self.inner.id() {
					String::from("selfsig")
				} else if truncate {
					sig.signer_key_id().unwrap_or("[?]").to_string()
				} else {
					let user_id = sig.signer_user_id().unwrap_or("[-]");
					format!(
						"{} {}",
						sig.signer_key_id().unwrap_or("[?]"),
						if user_id.is_empty() { "[?]" } else { user_id }
					)
				},
				handler::get_signature_time(
					*sig,
					if truncate { "%Y" } else { "%F" }
				)
			));
			let notations = sig.notations().collect::<Vec<SignatureNotation>>();
			if !notations.is_empty() {
				user_signatures.extend(self.get_signature_notations(
					notations,
					format!(" {}  ", padding),
				));
			}
		}
		user_signatures
	}

	/// Returns the notations of the given signature.
	fn get_signature_notations(
		&self,
		notations: Vec<SignatureNotation>,
		padding: String,
	) -> Vec<String> {
		notations
			.iter()
			.enumerate()
			.map(|(i, notation)| {
				format!(
					"{}   {}[{}] {}={}",
					padding,
					if i == notations.len() - 1 {
						"└─"
					} else {
						"├─"
					},
					if notation.is_critical() {
						"!"
					} else if notation.is_human_readable() {
						"h"
					} else {
						"?"
					},
					notation.name().unwrap_or("?"),
					notation.value().unwrap_or("?"),
				)
			})
			.collect()
	}
}

#[cfg(feature = "gpg-tests")]
#[cfg(test)]
mod tests {
	use super::*;
	use crate::args::Args;
	use crate::gpg::config::GpgConfig;
	use crate::gpg::context::GpgContext;
	use anyhow::Result;
	use pretty_assertions::assert_eq;
	#[test]
	fn test_gpg_key() -> Result<()> {
		let args = Args::default();
		let config = GpgConfig::new(&args)?;
		let mut context = GpgContext::new(config)?;
		let mut keys = context.get_keys(KeyType::Public, None)?;
		let key = &mut keys[0];
		key.detail.increase();
		assert_eq!(KeyDetail::Standard, key.detail);
		assert_eq!(Ok(key.detail), KeyDetail::from_str("standard"));
		key.detail.increase();
		assert_eq!(KeyDetail::Full, key.detail);
		assert_eq!("full", key.detail.to_string());
		assert!(key
			.get_subkey_info(true)
			.join("\n")
			.contains(&key.get_id().replace("0x", "")));
		assert!(key
			.get_subkey_info(false)
			.join("\n")
			.contains(&key.get_fingerprint()));
		assert!(key
			.get_user_info(false)
			.join("\n")
			.contains(&key.get_user_id()));
		Ok(())
	}
}