Repository navigation
Expand file tree
/
Copy pathlib.rs
More file actions
380 lines (354 loc) · 12.5 KB
/
Copy pathlib.rs
File metadata and controls
380 lines (354 loc) · 12.5 KB
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
#[macro_use]
extern crate log;
pub mod cli;
pub mod error;
pub mod cmd {
mod check;
mod decrypt;
mod edit;
mod encrypt;
mod env;
mod keygen;
mod pubkey;
pub use check::check;
pub use decrypt::decrypt;
pub use edit::edit;
pub use encrypt::encrypt;
pub use env::env;
pub use keygen::keygen;
pub use pubkey::pubkey;
}
use std::fs::{File, OpenOptions};
use std::io::{stdin, stdout, BufRead, BufReader, Read, Write};
#[cfg(unix)]
use std::os::unix::fs::OpenOptionsExt;
use std::path::Path;
use std::path::PathBuf;
use std::str::FromStr;
use age::x25519;
use base64::prelude::*;
use serde_yaml as sy;
use strum::{Display, EnumIs, EnumIter, EnumString};
use substring::Substring;
use crate::error::{IOResultExt, Result, YageError};
pub fn stdout_or_file(path: &Path) -> Result<Box<dyn Write>> {
Ok(if path == Path::new("-") {
Box::new(stdout())
} else {
Box::new(File::create(path).path_ctx(path)?)
})
}
pub fn stdout_or_private_file(path: &Path) -> Result<Box<dyn Write>> {
Ok(if path == Path::new("-") {
Box::new(stdout())
} else {
Box::new(create_private_file(path)?)
})
}
pub fn create_private_file(path: &Path) -> Result<File> {
let mut file_opts = OpenOptions::new();
file_opts.write(true).create_new(true);
#[cfg(unix)]
file_opts.mode(0o600);
file_opts.open(path).path_ctx(path)
}
pub fn stdin_or_file(path: &Path) -> Result<BufReader<Box<dyn Read>>> {
Ok(if path == Path::new("-") {
BufReader::new(Box::new(stdin()))
} else {
BufReader::new(Box::new(File::open(path).path_ctx(path)?))
})
}
pub fn stdin_or_private_file(path: &Path) -> Result<BufReader<Box<dyn Read>>> {
Ok(if path == Path::new("-") {
BufReader::new(Box::new(stdin()))
} else {
let br: BufReader<Box<dyn Read>> =
BufReader::new(Box::new(File::open(path).path_ctx(path)?));
if let Err(e) = fs_mistrust::Mistrust::new()
.verifier()
.require_file()
.check(path)
{
warn!("file {path:?} is not private: {e}");
}
br
})
}
pub fn decrypt_yaml(value: &sy::Value, identities: &[x25519::Identity]) -> Result<sy::Value> {
match value {
sy::Value::Mapping(mapping) => {
let mut output = sy::Mapping::new();
for (key, value) in mapping {
let key = key.clone();
let value = decrypt_yaml(value, identities)?;
output.insert(key, value);
}
Ok(sy::Value::Mapping(output))
}
sy::Value::Sequence(sequence) => {
let mut output = Vec::new();
for value in sequence {
let value = decrypt_yaml(value, identities)?;
output.push(value);
}
Ok(sy::Value::Sequence(output))
}
sy::Value::String(encrypted) => {
let decrypted = decrypt_value(encrypted, identities)?;
Ok(decrypted)
}
_ => Ok(value.clone()),
}
}
pub fn decrypt_value(s: &str, identities: &[x25519::Identity]) -> Result<sy::Value> {
match YageEncodedValue::from_str(s) {
Ok(yev) => {
let encrypted = BASE64_STANDARD.decode(yev.data)?;
let decryptor = match age::Decryptor::new(&encrypted[..])? {
age::Decryptor::Recipients(d) => Ok(d),
_ => Err(YageError::PassphraseUnsupported),
}?;
let mut decrypted = vec![];
let mut reader =
decryptor.decrypt(identities.iter().map(|i| i as &dyn age::Identity))?;
reader.read_to_end(&mut decrypted)?;
let value: sy::Value = sy::from_slice(&decrypted)?;
Ok(value)
}
Err(_) => Ok(sy::Value::String(s.to_owned())),
}
}
pub fn load_identities(keys: &[String], key_files: &[PathBuf]) -> Result<Vec<x25519::Identity>> {
let mut identities: Vec<x25519::Identity> = Vec::new();
for key in keys.iter() {
debug!("loading key: {key}");
let key = x25519::Identity::from_str(key)
.map_err(|e| YageError::KeyParse { message: e.into() })?;
identities.push(key);
}
for key_file in key_files.iter() {
debug!("loading key file: {key_file:?}");
let input = stdin_or_private_file(key_file)?;
let keys = age::IdentityFile::from_buffer(input).path_ctx(key_file)?;
for key in keys.into_identities() {
let age::IdentityFileEntry::Native(key) = key;
identities.push(key);
}
}
Ok(identities)
}
pub fn encrypt_yaml(value: &sy::Value, recipients: &[x25519::Recipient]) -> Result<sy::Value> {
match value {
sy::Value::Mapping(mapping) => {
let mut output = sy::Mapping::new();
for (key, value) in mapping {
let key = key.clone();
let value = encrypt_yaml(value, recipients)?;
output.insert(key, value);
}
Ok(sy::Value::Mapping(output))
}
sy::Value::Sequence(sequence) => {
let mut output = Vec::new();
for value in sequence {
let value = encrypt_yaml(value, recipients)?;
output.push(value);
}
Ok(sy::Value::Sequence(output))
}
sy::Value::String(s) => {
let output = if YageEncodedValue::from_str(s).is_ok() {
// keep the already encrypted value
s.to_owned()
} else {
encrypt_value(value, recipients)?
};
Ok(sy::Value::String(output))
}
sy::Value::Number(_) => {
let output = encrypt_value(value, recipients)?;
Ok(sy::Value::String(output))
}
_ => Ok(value.clone()),
}
}
pub fn encrypt_value(value: &sy::Value, recipients: &[x25519::Recipient]) -> Result<String> {
type Recipients = Vec<Box<dyn age::Recipient + Send + 'static>>;
let data = sy::to_string(value)?;
let recipients_dyn = recipients
.iter()
.map(|r| Box::new(r.clone()) as Box<dyn age::Recipient + Send + 'static>)
.collect::<Recipients>();
let mut encrypted = vec![];
let encryptor =
age::Encryptor::with_recipients(recipients_dyn).ok_or(YageError::NoRecipients)?;
// let mut armored = ArmoredWriter::wrap_output(&mut encrypted, Format::AsciiArmor)?;
let mut writer = encryptor.wrap_output(&mut encrypted)?;
writer.write_all(data.as_bytes())?;
writer.finish()?;
let mut recipients: Vec<_> = recipients.iter().map(|r| r.to_string()).collect();
recipients.sort();
recipients.dedup();
let yev = YageEncodedValue {
data: BASE64_STANDARD.encode(&encrypted),
recipients,
};
Ok(yev.to_string())
}
pub fn load_recipients(
recipients: &[String],
recipients_paths: &[PathBuf],
) -> Result<Vec<x25519::Recipient>> {
let mut res: Vec<x25519::Recipient> = Vec::new();
// read the recipient from the command line
for recipient in recipients.iter() {
debug!("loading recipient: {recipient}");
let recipient =
x25519::Recipient::from_str(recipient).map_err(|e| YageError::RecipientParse {
recipient: recipient.to_owned(),
message: e.into(),
})?;
res.push(recipient);
}
// read the recipient from the files
for path in recipients_paths.iter() {
debug!("loading recipient file: {path:?}");
let input = stdin_or_file(path)?;
for recipient in input.lines() {
let recipient = recipient.path_ctx(path)?;
let recipient =
x25519::Recipient::from_str(&recipient).map_err(|e| YageError::RecipientParse {
recipient: recipient.to_owned(),
message: e.into(),
})?;
res.push(recipient);
}
}
res.sort_by_cached_key(|r| r.to_string());
res.dedup();
Ok(res)
}
#[derive(Debug, Clone, Copy, PartialEq, Display, EnumString, EnumIs, EnumIter)]
pub enum EncryptionStatus {
Encrypted,
NotEncrypted,
Mixed,
NoValue,
}
pub fn check_encrypted(value: &sy::Value) -> EncryptionStatus {
match value {
sy::Value::Mapping(mapping) => check_encrypted_iter(mapping.iter().map(|(_, v)| v)),
sy::Value::Sequence(sequence) => check_encrypted_iter(sequence.iter()),
sy::Value::String(s) => {
if YageEncodedValue::from_str(s).is_ok() {
EncryptionStatus::Encrypted
} else {
EncryptionStatus::NotEncrypted
}
}
sy::Value::Null => EncryptionStatus::NoValue,
_ => EncryptionStatus::NotEncrypted,
}
}
fn check_encrypted_iter<'a>(iter: impl Iterator<Item = &'a sy::Value>) -> EncryptionStatus {
let mut status = EncryptionStatus::NoValue;
for value in iter {
match check_encrypted(value) {
EncryptionStatus::Encrypted => {
status = match status {
EncryptionStatus::Encrypted => EncryptionStatus::Encrypted,
EncryptionStatus::NotEncrypted => EncryptionStatus::Mixed,
EncryptionStatus::Mixed => EncryptionStatus::Mixed,
EncryptionStatus::NoValue => EncryptionStatus::Encrypted,
}
}
EncryptionStatus::NotEncrypted => {
status = match status {
EncryptionStatus::Encrypted => EncryptionStatus::Mixed,
EncryptionStatus::NotEncrypted => EncryptionStatus::NotEncrypted,
EncryptionStatus::Mixed => EncryptionStatus::Mixed,
EncryptionStatus::NoValue => EncryptionStatus::NotEncrypted,
}
}
EncryptionStatus::Mixed => {
status = EncryptionStatus::Mixed;
}
EncryptionStatus::NoValue => (),
}
}
status
}
pub fn flatten_yage_encrypted_values(value: &sy::Value) -> Vec<YageEncodedValue> {
match value {
sy::Value::Mapping(mapping) => mapping
.iter()
.flat_map(|(_, v)| flatten_yage_encrypted_values(v))
.collect(),
sy::Value::Sequence(sequence) => sequence
.iter()
.flat_map(flatten_yage_encrypted_values)
.collect(),
sy::Value::String(s) => match YageEncodedValue::from_str(s) {
Ok(yev) => vec![yev],
Err(_) => vec![],
},
_ => vec![],
}
}
pub fn check_recipients(value: &sy::Value) -> bool {
flatten_yage_encrypted_values(value)
.iter()
.filter(|v| !v.recipients.is_empty())
.map(|v| &v.recipients)
.collect::<Vec<_>>()
.windows(2)
.all(|w| w[0] == w[1])
}
#[derive(Debug, Clone)]
pub struct YageEncodedValue {
pub data: String,
pub recipients: Vec<String>,
}
impl FromStr for YageEncodedValue {
type Err = YageError;
fn from_str(s: &str) -> Result<Self> {
if !s.starts_with("yage[") || !s.ends_with(']') {
return Err(YageError::InvalidValueEncoding);
}
// remove the yage[…] prefix and suffix
let payload = s.substring(5, s.len() - 1);
let components: Vec<_> = payload.split('|').collect();
if components.len() != 2 {
return Err(YageError::InvalidValueEncoding);
}
let data = components[0].to_owned();
if !components[1].starts_with("r:") {
return Err(YageError::InvalidValueEncoding);
}
let recipients = components[1].substring(2, components[1].len());
let recipients: Vec<String> = recipients.split(',').map(|r| r.to_owned()).collect();
Ok(YageEncodedValue { data, recipients })
}
}
impl std::fmt::Display for YageEncodedValue {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let recipients = self.recipients.join(",");
write!(f, "yage[{}|r:{}]", self.data, recipients)
}
}
pub fn get_yaml_recipients(value: &sy::Value) -> Result<Vec<x25519::Recipient>> {
let yevs = flatten_yage_encrypted_values(value);
let mut recipients: Vec<_> = yevs.iter().flat_map(|yev| &yev.recipients).collect();
recipients.sort();
recipients.dedup();
let mut output: Vec<x25519::Recipient> = Vec::with_capacity(recipients.len());
for s in recipients {
let r = x25519::Recipient::from_str(s).map_err(|msg| YageError::RecipientParse {
recipient: s.to_owned(),
message: msg.to_owned(),
})?;
output.push(r);
}
Ok(output)
}