/
create_or_insert_into_file.rs
643 lines (566 loc) · 21.3 KB
/
create_or_insert_into_file.rs
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
use nix::unistd::{chown, Group, User};
use crate::action::{
Action, ActionDescription, ActionError, ActionErrorKind, ActionTag, StatefulAction,
};
use rand::Rng;
use std::{
io::SeekFrom,
os::{unix::fs::MetadataExt, unix::prelude::PermissionsExt},
path::{Path, PathBuf},
};
use tokio::{
fs::{remove_file, File, OpenOptions},
io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt},
};
use tracing::{span, Span};
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, PartialEq, Eq)]
pub enum Position {
Beginning,
End,
Before {
index: usize,
expected_content: String,
},
}
/** Create a file at the given location with the provided `buf` as
contents, optionally with an owning user, group, and mode.
If the file exists, the provided `buf` will be inserted at its
beginning or end, depending on the position field.
*/
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
pub struct CreateOrInsertIntoFile {
path: PathBuf,
user: Option<String>,
group: Option<String>,
mode: Option<u32>,
buf: String,
position: Position,
}
impl CreateOrInsertIntoFile {
#[tracing::instrument(level = "debug", skip_all)]
pub async fn plan(
path: impl AsRef<Path>,
user: impl Into<Option<String>>,
group: impl Into<Option<String>>,
mode: impl Into<Option<u32>>,
buf: String,
position: Position,
) -> Result<StatefulAction<Self>, ActionError> {
let path = path.as_ref().to_path_buf();
let mode = mode.into();
let user = user.into();
let group = group.into();
let this = Self {
path,
user,
group,
mode,
buf,
position,
};
if this.path.exists() {
// If the path exists, perhaps we can just skip this
let mut file = File::open(&this.path)
.await
.map_err(|e| ActionErrorKind::Open(this.path.clone(), e))
.map_err(Self::error)?;
let metadata = file
.metadata()
.await
.map_err(|e| ActionErrorKind::GettingMetadata(this.path.clone(), e))
.map_err(Self::error)?;
if !metadata.is_file() {
return Err(Self::error(ActionErrorKind::PathWasNotFile(this.path)));
}
if let Some(mode) = mode {
// Does the file have the right permissions?
let discovered_mode = metadata.permissions().mode();
// We only care about user-group-other permissions
let discovered_mode = discovered_mode & 0o777;
if discovered_mode != mode {
tracing::debug!(
"`{}` has mode `{}`, a mode of `{}` was expected",
this.path.display(),
discovered_mode,
mode,
);
}
}
// Does it have the right user/group?
if let Some(user) = &this.user {
// If the file exists, the user must also exist to be correct.
let expected_uid = User::from_name(user.as_str())
.map_err(|e| ActionErrorKind::GettingUserId(user.clone(), e))
.map_err(Self::error)?
.ok_or_else(|| ActionErrorKind::NoUser(user.clone()))
.map_err(Self::error)?
.uid;
let found_uid = metadata.uid();
if found_uid != expected_uid.as_raw() {
return Err(Self::error(ActionErrorKind::PathUserMismatch(
this.path.clone(),
found_uid,
expected_uid.as_raw(),
)));
}
}
if let Some(group) = &this.group {
// If the file exists, the group must also exist to be correct.
let expected_gid = Group::from_name(group.as_str())
.map_err(|e| ActionErrorKind::GettingGroupId(group.clone(), e))
.map_err(Self::error)?
.ok_or_else(|| ActionErrorKind::NoUser(group.clone()))
.map_err(Self::error)?
.gid;
let found_gid = metadata.gid();
if found_gid != expected_gid.as_raw() {
return Err(Self::error(ActionErrorKind::PathGroupMismatch(
this.path.clone(),
found_gid,
expected_gid.as_raw(),
)));
}
}
// Does it have the right content?
let mut discovered_buf = String::new();
file.read_to_string(&mut discovered_buf)
.await
.map_err(|e| ActionErrorKind::Read(this.path.clone(), e))
.map_err(Self::error)?;
if discovered_buf.contains(&this.buf) {
tracing::debug!("Inserting into `{}` already complete", this.path.display(),);
return Ok(StatefulAction::completed(this));
}
if let Position::Before {
index,
expected_content,
} = &this.position
{
if discovered_buf.lines().nth(*index) != Some(expected_content.as_str()) {
return Err(ActionErrorKind::DifferentLineContent(
this.path.clone(),
this.position.clone(),
))
.map_err(Self::error);
}
}
// If not, we can't skip this, so we still do it
}
Ok(StatefulAction::uncompleted(this))
}
}
#[async_trait::async_trait]
#[typetag::serde(name = "create_or_insert_into_file")]
impl Action for CreateOrInsertIntoFile {
fn action_tag() -> ActionTag {
ActionTag("create_or_insert_into_file")
}
fn tracing_synopsis(&self) -> String {
format!("Create or insert file `{}`", self.path.display())
}
fn tracing_span(&self) -> Span {
let span = span!(
tracing::Level::DEBUG,
"create_or_insert_file",
path = tracing::field::display(self.path.display()),
user = self.user,
group = self.group,
mode = self
.mode
.map(|v| tracing::field::display(format!("{:#o}", v))),
buf = tracing::field::Empty,
);
if tracing::enabled!(tracing::Level::TRACE) {
span.record("buf", &self.buf);
}
span
}
fn execute_description(&self) -> Vec<ActionDescription> {
vec![ActionDescription::new(self.tracing_synopsis(), vec![])]
}
#[tracing::instrument(level = "debug", skip_all)]
async fn execute(&mut self) -> Result<(), ActionError> {
let Self {
path,
user,
group,
mode,
buf,
position,
} = self;
let mut orig_file = match OpenOptions::new().read(true).open(&path).await {
Ok(f) => Some(f),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
Err(e) => return Err(Self::error(ActionErrorKind::Open(path.to_owned(), e))),
};
// Create a temporary file in the same directory as the one
// that the final file goes in, so that we can rename it
// atomically
let parent_dir = path.parent().expect("File must be in a directory");
let mut temp_file_path = parent_dir.to_owned();
{
let mut rng = rand::thread_rng();
temp_file_path.push(format!("nix-installer-tmp.{}", rng.gen::<u32>()));
}
let mut temp_file = OpenOptions::new()
.create(true)
.write(true)
// If the file is created, ensure that it has harmless
// permissions regardless of whether the mode will be
// changed later (if we ever create setuid executables,
// they should only become setuid once they are owned by
// the appropriate user)
.mode(0o600)
.open(&temp_file_path)
.await
.map_err(|e| {
ActionErrorKind::Open(temp_file_path.clone(), e)
}).map_err(Self::error)?;
match position {
Position::End => {
if let Some(ref mut orig_file) = orig_file {
tokio::io::copy(orig_file, &mut temp_file)
.await
.map_err(|e| {
ActionErrorKind::Copy(path.to_owned(), temp_file_path.to_owned(), e)
})
.map_err(Self::error)?;
}
temp_file
.write_all(buf.as_bytes())
.await
.map_err(|e| ActionErrorKind::Write(temp_file_path.clone(), e))
.map_err(Self::error)?;
},
Position::Beginning => {
temp_file
.write_all(buf.as_bytes())
.await
.map_err(|e| ActionErrorKind::Write(temp_file_path.clone(), e))
.map_err(Self::error)?;
if let Some(ref mut orig_file) = orig_file {
tokio::io::copy(orig_file, &mut temp_file)
.await
.map_err(|e| {
ActionErrorKind::Copy(path.to_owned(), temp_file_path.to_owned(), e)
})
.map_err(Self::error)?;
}
},
Position::Before {
index,
expected_content,
} => {
let mut original_content_buf = Vec::new();
if let Some(ref mut orig_file) = orig_file {
tokio::io::copy(orig_file, &mut original_content_buf)
.await
.map_err(|e| {
ActionErrorKind::Copy(path.to_owned(), temp_file_path.to_owned(), e)
})
.map_err(Self::error)?;
}
let original_content = String::from_utf8(original_content_buf)
.map_err(ActionErrorKind::FromUtf8)
.map_err(Self::error)?;
let mut original_content_lines = original_content.lines().collect::<Vec<_>>();
// The last line should match expected
if original_content_lines.get(*index).copied() != Some(expected_content.as_str()) {
return Err(ActionErrorKind::DifferentLineContent(
path.clone(),
position.clone(),
))
.map_err(Self::error);
}
original_content_lines.insert(*index, buf);
let new_content = original_content_lines.join("\n");
temp_file
.write_all(new_content.as_bytes())
.await
.map_err(|e| ActionErrorKind::Write(temp_file_path.clone(), e))
.map_err(Self::error)?;
},
};
let gid = if let Some(group) = group {
Some(
Group::from_name(group.as_str())
.map_err(|e| ActionErrorKind::GettingGroupId(group.clone(), e))
.map_err(Self::error)?
.ok_or(ActionErrorKind::NoGroup(group.clone()))
.map_err(Self::error)?
.gid,
)
} else {
None
};
let uid = if let Some(user) = user {
Some(
User::from_name(user.as_str())
.map_err(|e| ActionErrorKind::GettingUserId(user.clone(), e))
.map_err(Self::error)?
.ok_or(ActionErrorKind::NoUser(user.clone()))
.map_err(Self::error)?
.uid,
)
} else {
None
};
// Change ownership _before_ applying mode, to ensure that if
// a file needs to be setuid it will never be setuid for the
// wrong user
chown(&temp_file_path, uid, gid)
.map_err(|e| ActionErrorKind::Chown(path.clone(), e))
.map_err(Self::error)?;
if let Some(mode) = mode {
tokio::fs::set_permissions(&temp_file_path, PermissionsExt::from_mode(*mode))
.await
.map_err(|e| ActionErrorKind::SetPermissions(*mode, path.to_owned(), e))
.map_err(Self::error)?;
} else if let Some(original_file) = orig_file {
let original_file_mode = original_file
.metadata()
.await
.map_err(|e| ActionErrorKind::GettingMetadata(path.to_path_buf(), e))
.map_err(Self::error)?
.permissions()
.mode();
tokio::fs::set_permissions(
&temp_file_path,
PermissionsExt::from_mode(original_file_mode),
)
.await
.map_err(|e| ActionErrorKind::SetPermissions(original_file_mode, path.to_owned(), e))
.map_err(Self::error)?;
}
tokio::fs::rename(&temp_file_path, &path)
.await
.map_err(|e| ActionErrorKind::Rename(path.to_owned(), temp_file_path.to_owned(), e))
.map_err(Self::error)?;
Ok(())
}
fn revert_description(&self) -> Vec<ActionDescription> {
let Self {
path,
user: _,
group: _,
mode: _,
buf,
position: _,
} = &self;
vec![ActionDescription::new(
format!("Delete Nix related fragment from file `{}`", path.display()),
vec![format!(
"Delete Nix related fragment from file `{}`. Fragment: `{buf}`",
path.display()
)],
)]
}
#[tracing::instrument(level = "debug", skip_all)]
async fn revert(&mut self) -> Result<(), ActionError> {
let Self {
path,
user: _,
group: _,
mode: _,
buf,
position: _,
} = self;
let mut file = OpenOptions::new()
.create(false)
.write(true)
.read(true)
.open(&path)
.await
.map_err(|e| ActionErrorKind::Open(path.to_owned(), e))
.map_err(Self::error)?;
let mut file_contents = String::default();
file.read_to_string(&mut file_contents)
.await
.map_err(|e| ActionErrorKind::Read(path.to_owned(), e))
.map_err(Self::error)?;
if let Some(start) = file_contents.rfind(buf.as_str()) {
let end = start + buf.len();
file_contents.replace_range(start..end, "")
}
if file_contents.is_empty() {
remove_file(&path)
.await
.map_err(|e| ActionErrorKind::Remove(path.to_owned(), e))
.map_err(Self::error)?;
} else {
file.seek(SeekFrom::Start(0))
.await
.map_err(|e| ActionErrorKind::Seek(path.to_owned(), e))
.map_err(Self::error)?;
file.set_len(0)
.await
.map_err(|e| ActionErrorKind::Truncate(path.to_owned(), e))
.map_err(Self::error)?;
file.write_all(file_contents.as_bytes())
.await
.map_err(|e| ActionErrorKind::Write(path.to_owned(), e))
.map_err(Self::error)?;
file.flush()
.await
.map_err(|e| ActionErrorKind::Flush(path.to_owned(), e))
.map_err(Self::error)?;
}
Ok(())
}
}
#[cfg(test)]
mod test {
use super::*;
use color_eyre::eyre::eyre;
use tokio::fs::{read_to_string, write};
#[tokio::test]
async fn creates_and_deletes_file() -> eyre::Result<()> {
let temp_dir = tempfile::tempdir()?;
let test_file = temp_dir.path().join("creates_and_deletes_file");
let mut action = CreateOrInsertIntoFile::plan(
test_file.clone(),
None,
None,
None,
"Test".into(),
Position::Beginning,
)
.await?;
action.try_execute().await?;
action.try_revert().await?;
assert!(!test_file.exists(), "File should have been deleted");
Ok(())
}
#[tokio::test]
async fn edits_and_reverts_file() -> eyre::Result<()> {
let temp_dir = tempfile::tempdir()?;
let test_file = temp_dir.path().join("edits_and_reverts_file");
let test_content = "Some other content";
tokio::fs::write(&test_file, test_content)
.await
.expect("Could not write to test temp file");
let mut action = CreateOrInsertIntoFile::plan(
test_file.clone(),
None,
None,
None,
"Test".into(),
Position::Beginning,
)
.await?;
action.try_execute().await?;
action.try_revert().await?;
assert!(test_file.exists(), "File should have not been deleted");
let read_content = tokio::fs::read_to_string(test_file)
.await
.expect("Could not read test temp file");
assert_eq!(test_content, read_content);
Ok(())
}
#[tokio::test]
async fn recognizes_existing_containing_exact_contents_and_reverts_it() -> eyre::Result<()> {
let temp_dir = tempfile::tempdir()?;
let test_file = temp_dir
.path()
.join("recognizes_existing_containing_exact_contents_and_reverts_it");
let expected_content = "Some expected content";
write(test_file.as_path(), expected_content).await?;
let added_content = "\nSome more expected content";
write(test_file.as_path(), added_content).await?;
// We test all `Position` options
let positions = [Position::Beginning, Position::End];
for position in positions {
let mut action = CreateOrInsertIntoFile::plan(
test_file.clone(),
None,
None,
None,
expected_content.into(),
position,
)
.await?;
action.try_execute().await?;
action.try_revert().await?;
assert!(test_file.exists(), "File should have not been deleted");
let after_revert_content = read_to_string(&test_file).await?;
assert_eq!(after_revert_content, added_content);
}
Ok(())
}
#[tokio::test]
async fn recognizes_wrong_mode_and_does_not_error() -> eyre::Result<()> {
let temp_dir = tempfile::tempdir()?;
let test_file = temp_dir
.path()
.join("recognizes_wrong_mode_and_does_not_error");
let initial_mode = 0o777;
let expected_mode = 0o666;
write(test_file.as_path(), "Some content").await?;
tokio::fs::set_permissions(test_file.as_path(), PermissionsExt::from_mode(initial_mode))
.await?;
let mut action = CreateOrInsertIntoFile::plan(
test_file.clone(),
None,
None,
Some(expected_mode),
"Some different content".into(),
Position::End,
)
.await?;
action.try_execute().await?;
action.try_revert().await?;
assert!(test_file.exists(), "File should have not been deleted");
Ok(())
}
#[tokio::test]
async fn recognizes_correct_mode() -> eyre::Result<()> {
let temp_dir = tempfile::tempdir()?;
let test_file = temp_dir.path().join("recognizes_correct_mode");
let initial_mode = 0o777;
write(test_file.as_path(), "Some content").await?;
tokio::fs::set_permissions(test_file.as_path(), PermissionsExt::from_mode(initial_mode))
.await?;
let mut action = CreateOrInsertIntoFile::plan(
test_file.clone(),
None,
None,
Some(initial_mode),
"Some content".into(),
Position::End,
)
.await?;
action.try_execute().await?;
action.try_revert().await?;
assert!(!test_file.exists(), "File should have been deleted");
Ok(())
}
#[tokio::test]
async fn errors_on_dir() -> eyre::Result<()> {
let temp_dir = tempfile::tempdir()?;
match CreateOrInsertIntoFile::plan(
temp_dir.path(),
None,
None,
None,
"Some different content".into(),
Position::End,
)
.await
{
Err(err) => match err.kind() {
ActionErrorKind::PathWasNotFile(path) => assert_eq!(path, temp_dir.path()),
_ => {
return Err(eyre!(
"Should have returned an ActionErrorKind::PathWasNotFile error"
))
},
},
_ => {
return Err(eyre!(
"Should have returned an ActionErrorKind::PathWasNotFile error"
))
},
}
Ok(())
}
}