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
pub mod crypto;
pub(crate) mod git;
pub mod store;
pub mod sync;
pub mod types;
use std::fmt;
use std::fs;
use std::path::{Path, PathBuf};
use anyhow::Result;
use gpgme::Context;
use thiserror::Error;
use crate::store::Store;
pub const STORE_DEFAULT_ROOT: &str = "~/.password-store";
const STORE_GPG_IDS_FILE: &str = ".gpg-id";
const STORE_PUB_KEY_DIR: &str = ".public-keys/";
pub struct Recipients {
keys: Vec<Key>,
}
impl Recipients {
pub fn from(keys: Vec<Key>) -> Self {
Self { keys }
}
pub fn find(fingerprints: Vec<String>) -> Result<Recipients> {
let keys = if fingerprints.is_empty() {
vec![]
} else {
crypto::context()?
.find_keys(fingerprints)?
.filter_map(|x| x.ok())
.filter(|k| k.can_encrypt())
.map(|k| k.into())
.collect()
};
Ok(Recipients::from(keys))
}
pub fn find_from_file<P: AsRef<Path>>(path: P) -> Result<Recipients> {
Self::find(read_fingerprints_file(path)?)
}
pub fn keys(&self) -> &[Key] {
&self.keys
}
fn has_fingerprint(&self, fingerprint: &str) -> bool {
let fp = fingerprint.trim().to_uppercase();
self.keys.iter().any(|k| k.fingerprint(false) == fp)
}
pub fn add(&mut self, key: Key) {
if !self.keys.contains(&key) {
self.keys.push(key);
}
}
pub fn remove(&mut self, key: &Key) {
self.keys.retain(|k| k != key);
}
pub fn remove_many(&mut self, keys: &[Key]) {
self.keys.retain(|k| !keys.contains(k));
}
pub fn load(store: &Store) -> Result<Self> {
let path = store_gpg_ids_file(&store);
if !path.is_file() {
return Ok(Recipients::from(vec![]));
}
Recipients::find_from_file(path)
}
pub fn save(&self, store: &Store) -> Result<()> {
self.write_to_file(store_gpg_ids_file(store))?;
self.sync_public_key_files(store)
}
pub fn import_missing_keys_from_store(store: &Store) -> Result<()> {
let dir = store_public_keys_dir(store);
if !dir.is_dir() {
return Ok(());
}
let files: Vec<(PathBuf, String)> = dir
.read_dir()
.map_err(Err::SyncKeyFiles)?
.filter_map(|e| e.ok())
.filter(|e| e.file_type().map(|f| f.is_file()).unwrap_or(false))
.filter_map(|e| {
e.file_name()
.to_str()
.map(|fp| (e.path(), format_fingerprint(fp)))
})
.collect();
let all = all(true)?;
let missing: Vec<_> = files
.into_iter()
.filter(|(_, fp)| !all.has_fingerprint(fp))
.collect();
if missing.is_empty() {
return Ok(());
}
let mut context = crypto::context()?;
for (path, _) in missing {
import_key_file(&mut context, &path)?;
}
Ok(())
}
pub fn sync_public_key_files(&self, store: &Store) -> Result<()> {
let dir = store_public_keys_dir(store);
fs::create_dir_all(&dir).map_err(Err::SyncKeyFiles)?;
let files: Vec<(PathBuf, String)> = dir
.read_dir()
.map_err(Err::SyncKeyFiles)?
.filter_map(|e| e.ok())
.filter(|e| e.file_type().map(|f| f.is_file()).unwrap_or(false))
.filter_map(|e| {
e.file_name()
.to_str()
.map(|fp| (e.path(), format_fingerprint(fp)))
})
.collect();
for (path, _) in files.iter().filter(|(_, fp)| !self.has_fingerprint(fp)) {
fs::remove_file(path).map_err(Err::SyncKeyFiles)?;
}
let mut context: Option<_> = None;
for (key, fp) in self
.keys
.iter()
.map(|k| (k, k.fingerprint(false)))
.filter(|(_, fp)| !files.iter().any(|(_, other)| fp == other))
{
if context.is_none() {
context = Some(crypto::context()?);
}
let path = dir.join(&fp);
export_key_file(context.as_mut().unwrap(), key, &path)?;
}
Ok(())
}
fn write_to_file<P: AsRef<Path>>(&self, path: P) -> Result<()> {
fs::write(
path,
self.keys
.iter()
.map(|k| k.fingerprint(false))
.collect::<Vec<_>>()
.join("\n"),
)
.map_err(|err| Err::WriteFile(err).into())
}
}
pub fn contains_own_secret_key(recipients: &Recipients) -> Result<bool> {
let secrets = all(true)?;
Ok(recipients
.keys()
.iter()
.any(|k| secrets.has_fingerprint(&k.fingerprint(false))))
}
pub fn read_fingerprints_file<P: AsRef<Path>>(path: P) -> Result<Vec<String>> {
Ok(fs::read_to_string(path)
.map_err(Err::ReadFile)?
.lines()
.filter(|fp| !fp.trim().is_empty())
.map(|fp| fp.into())
.collect())
}
pub fn filter_imported_fingerprints(fingerprints: Vec<String>) -> Result<Vec<String>> {
let mut context = crypto::context()?;
Ok(fingerprints
.into_iter()
.filter(|fp| context.get_key(fp).is_err())
.collect())
}
pub fn store_gpg_ids_file(store: &Store) -> PathBuf {
store.root.join(STORE_GPG_IDS_FILE)
}
pub fn store_public_keys_dir(store: &Store) -> PathBuf {
store.root.join(STORE_PUB_KEY_DIR)
}
pub fn import_key(context: &mut Context, key: &[u8]) -> Result<(), gpgme::Error> {
let key_str = std::str::from_utf8(&key).expect("exported key is invalid UTF-8");
assert!(
!key_str.contains("PRIVATE KEY"),
"imported key contains PRIVATE KEY, blocked to prevent accidentally leaked secret key"
);
assert!(
key_str.contains("PUBLIC KEY"),
"imported key must contain PUBLIC KEY, blocked to prevent accidentally leaked secret key"
);
context.import(key).map(|_| ())
}
pub fn import_key_file(context: &mut Context, path: &Path) -> Result<()> {
import_key(context, &fs::read(path).map_err(Err::ReadKey)?)
.map_err(|err| Err::Import(err).into())
}
pub fn export_key(context: &mut Context, key: &Key) -> Result<Vec<u8>, gpgme::Error> {
let mut data: Vec<u8> = vec![];
let armor = context.armor();
context.set_armor(true);
context.export_keys(&[key.0.clone()], gpgme::ExportMode::empty(), &mut data)?;
context.set_armor(armor);
let data_str = std::str::from_utf8(&data).expect("exported key is invalid UTF-8");
assert!(
!data_str.contains("PRIVATE KEY"),
"exported key contains PRIVATE KEY, blocked to prevent accidentally leaking secret key"
);
assert!(
data_str.contains("PUBLIC KEY"),
"exported key must contain PUBLIC KEY, blocked to prevent accidentally leaking secret key"
);
Ok(data)
}
pub fn export_key_file(context: &mut Context, key: &Key, path: &Path) -> Result<()> {
fs::write(path, export_key(context, key).map_err(Err::Export)?)
.map_err(|err| Err::WriteKey(err).into())
}
#[derive(Clone)]
pub struct Key(pub gpgme::Key);
impl Key {
pub fn fingerprint(&self, short: bool) -> String {
let fp = self.0.fingerprint().expect("key does not have fingerprint");
if short {
return format_fingerprint(&fp[fp.len() - 16..]);
}
format_fingerprint(fp)
}
pub fn user_display(&self) -> String {
self.0
.user_ids()
.map(|user| {
let mut parts = vec![];
if let Ok(name) = user.name() {
if !name.trim().is_empty() {
parts.push(name.into());
}
}
if let Ok(comment) = user.comment() {
if !comment.trim().is_empty() {
parts.push(format!("({})", comment));
}
}
if let Ok(email) = user.email() {
if !email.trim().is_empty() {
parts.push(format!("<{}>", email));
}
}
parts.join(" ")
})
.collect::<Vec<_>>()
.join("; ")
}
}
impl PartialEq for Key {
fn eq(&self, other: &Self) -> bool {
self.0.id_raw() == other.0.id_raw() && self.0.fingerprint_raw() == other.0.fingerprint_raw()
}
}
impl fmt::Display for Key {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"[GPG] {} - {}",
self.fingerprint(true),
self.user_display()
)
}
}
impl From<gpgme::Key> for Key {
fn from(key: gpgme::Key) -> Self {
Self(key)
}
}
pub fn all(secret: bool) -> Result<Recipients> {
let mut context = crypto::context()?;
let keys = if !secret {
context.keys()?
} else {
context.secret_keys()?
};
Ok(Recipients::from(
keys.into_iter()
.filter_map(|k| k.ok())
.filter(|k| k.can_encrypt())
.map(|k| k.into())
.collect(),
))
}
fn format_fingerprint<S: AsRef<str>>(fingerprint: S) -> String {
fingerprint.as_ref().trim().to_uppercase()
}
#[derive(Debug, Error)]
pub enum Err {
#[error("failed to read file")]
ReadFile(#[source] std::io::Error),
#[error("failed to write file")]
WriteFile(#[source] std::io::Error),
#[error("failed to sync public key files")]
SyncKeyFiles(#[source] std::io::Error),
#[error("failed to read public key")]
ReadKey(#[source] std::io::Error),
#[error("failed to write public key")]
WriteKey(#[source] std::io::Error),
#[error("failed to import key")]
Import(#[source] gpgme::Error),
#[error("failed to export key")]
Export(#[source] gpgme::Error),
}