-
Notifications
You must be signed in to change notification settings - Fork 82
/
Copy pathlib.rs
1137 lines (963 loc) · 32 KB
/
lib.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
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! sudo-rs test framework
#![deny(missing_docs)]
#![deny(unsafe_code)]
use std::{
collections::{BTreeMap, HashMap, HashSet},
env,
path::Path,
sync::Once,
};
use docker::{As, Container};
pub use constants::*;
pub use docker::{Child, Command, Output};
mod constants;
mod docker;
pub mod helpers;
type Error = Box<dyn std::error::Error>;
type Result<T> = core::result::Result<T, Error>;
fn base_image() -> &'static str {
if is_original_sudo() {
"sudo-test-og"
} else {
"sudo-test-rs"
}
}
/// are we testing the original sudo?
pub fn is_original_sudo() -> bool {
matches!(SudoUnderTest::from_env(), Ok(SudoUnderTest::Theirs))
}
enum SudoUnderTest {
Ours,
Theirs,
}
impl SudoUnderTest {
fn from_env() -> Result<Self> {
if let Ok(under_test) = env::var("SUDO_UNDER_TEST") {
if under_test == "ours" {
Ok(Self::Ours)
} else if under_test == "theirs" {
Ok(Self::Theirs)
} else {
Err("variable SUDO_UNDER_TEST must be set to one of: ours, theirs".into())
}
} else {
Ok(Self::Theirs)
}
}
}
type AbsolutePath = String;
type Groupname = String;
type Username = String;
/// test environment
pub struct Env {
container: Container,
users: HashSet<Username>,
}
/// creates a new test environment builder that contains the specified `/etc/sudoers` file
#[allow(non_snake_case)]
pub fn Env(sudoers: impl Into<TextFile>) -> EnvBuilder {
let mut builder = EnvBuilder::default();
builder.file(ETC_SUDOERS, sudoers);
if cfg!(target_os = "freebsd") {
// Many tests expect the users group to exist, but FreeBSD doesn't actually use it.
builder.group("users");
}
builder
}
impl Command {
/// executes the command in the specified test environment
///
/// NOTE that the trailing newline from `stdout` and `stderr` will be removed
///
/// # Panics
///
/// this method panics if the requested `as_user` does not exist in the test environment. to
/// execute a command as a non-existent user use `Command::as_user_id`
pub fn output(&self, env: &Env) -> Result<Output> {
if let Some(As::User(username)) = self.get_as() {
assert!(
env.users.contains(username),
"tried to exec as non-existent user: {username}"
);
}
env.container.output(self)
}
/// spawns the command in the specified test environment
pub fn spawn(&self, env: &Env) -> Result<Child> {
if let Some(As::User(username)) = self.get_as() {
assert!(
env.users.contains(username),
"tried to exec as non-existent user: {username}"
);
}
env.container.spawn(self)
}
}
/// test environment builder
#[derive(Default)]
pub struct EnvBuilder {
directories: BTreeMap<AbsolutePath, Directory>,
files: HashMap<AbsolutePath, TextFile>,
groups: HashMap<Groupname, Group>,
hostname: Option<String>,
users: HashMap<Username, User>,
}
impl EnvBuilder {
/// adds a `file` to the test environment at the specified `path`
///
/// # Panics
///
/// - if `path` is not an absolute path
/// - if `path` has previously been declared
pub fn file(&mut self, path: impl AsRef<str>, file: impl Into<TextFile>) -> &mut Self {
let path = path.as_ref();
assert!(Path::new(path).is_absolute(), "path must be absolute");
assert!(
!self.files.contains_key(path),
"file at {path} has already been declared"
);
self.files.insert(path.to_string(), file.into());
self
}
/// adds a `directory` to the test environment
///
/// # Panics
///
/// - if `path` is not an absolute path
/// - if `path` has previously been declared
pub fn directory(&mut self, directory: impl Into<Directory>) -> &mut Self {
let directory = directory.into();
let path = directory.get_path();
assert!(
!self.directories.contains_key(path),
"directory at {path} has already been declared"
);
self.directories.insert(path.to_string(), directory);
self
}
/// adds the specified `group` to the test environment
///
/// # Panics
///
/// - if the `group` has previously been declared
pub fn group(&mut self, group: impl Into<Group>) -> &mut Self {
let group = group.into();
let groupname = &group.name;
assert!(
!self.groups.contains_key(groupname),
"group {} has already been declared",
groupname
);
self.groups.insert(groupname.to_string(), group);
self
}
/// adds the specified `user` to the test environment
///
/// # Panics
///
/// - if the `user` has previously been declared
pub fn user(&mut self, user: impl Into<User>) -> &mut Self {
let user = user.into();
let username = &user.name;
assert!(
!self.users.contains_key(username),
"user {} has already been declared",
username
);
self.users.insert(username.to_string(), user);
self
}
/// Sets the hostname of the container to the specified string
pub fn hostname(&mut self, hostname: impl AsRef<str>) -> &mut Self {
self.hostname = Some(hostname.as_ref().to_string());
self
}
/// builds the test environment
///
/// # Panics
///
/// - if any specified `user` already exists in the base image
/// - if any specified `group` already exists in the base image
/// - if any specified `user` tries to use a user ID that already exists in the base image
/// - if any specified `group` tries to use a group ID that already exists in the base image
pub fn build(&self) -> Result<Env> {
static ONCE: Once = Once::new();
ONCE.call_once(|| {
docker::build_base_image().expect("fatal error: could not build the base Docker image")
});
let container = Container::new_with_hostname(base_image(), self.hostname.as_deref())?;
let (mut usernames, user_ids) = getent_passwd(&container)?;
for new_user in self.users.values() {
assert!(
!usernames.contains(&new_user.name),
"user {} already exists in base image",
new_user.name
);
if let Some(user_id) = new_user.id {
assert!(
!user_ids.contains(&user_id),
"user ID {user_id} already exists in base image"
);
}
}
let (groupnames, group_ids) = getent_group(&container)?;
for new_group in self.groups.values() {
assert!(
!groupnames.contains(&new_group.name),
"group {} already exists in base image",
new_group.name
);
if let Some(group_id) = new_group.id {
assert!(
!group_ids.contains(&group_id),
"group ID {group_id} already exists in base image"
);
}
}
// create groups with known IDs first to avoid collisions ..
for group in self.groups.values().filter(|group| group.id.is_some()) {
group.create(&container)?;
}
// .. with groups that get assigned IDs dynamically
for group in self.groups.values().filter(|group| group.id.is_none()) {
group.create(&container)?;
}
// create users with known IDs first to avoid collisions ..
for user in self.users.values().filter(|user| user.id.is_some()) {
user.create(&container)?;
usernames.insert(user.name.to_string());
}
// .. with users that get assigned IDs dynamically
for user in self.users.values().filter(|user| user.id.is_none()) {
user.create(&container)?;
usernames.insert(user.name.to_string());
}
for directory in self.directories.values() {
directory.create(&container)?;
}
for (path, file) in &self.files {
file.create(path, &container)?;
}
let env = Env {
container,
users: usernames,
};
if cfg!(target_os = "freebsd") {
// Podman on FreeBSD forgets the setuid bit when building an image. Manually restore it
// as necessary for the current container.
// Reported upstream as https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=282539
let _ = Command::new("chmod")
.arg("755")
.arg("/home")
.output(&env)
.unwrap();
if is_original_sudo() {
Command::new("chflags")
.arg("noschg")
.arg("/usr/bin/su")
.output(&env)
.unwrap()
.assert_success()
.unwrap();
}
Command::new("chmod")
.arg("4755")
.arg(BIN_SUDO)
.arg("/usr/bin/su")
.output(&env)
.unwrap()
.assert_success()
.unwrap();
Command::new("chmod")
.arg("755")
.arg("/usr/local/sbin")
.output(&env)
.unwrap()
.assert_success()
.unwrap();
}
Ok(env)
}
}
/// a user
pub struct User {
name: Username,
create_home_directory: bool,
groups: HashSet<Groupname>,
id: Option<u32>,
password: Option<String>,
shell: Option<String>,
}
/// creates a new user with the specified `name` and the following defaults:
///
/// - on Debian containers, primary group = `users` (GID=100)
/// - automatically assigned user ID
/// - no assigned secondary groups
/// - no assigned password
/// - home directory set to `/home/<name>` but not automatically created
#[allow(non_snake_case)]
pub fn User(name: impl AsRef<str>) -> User {
name.as_ref().into()
}
impl User {
/// assigns this user to the specified *secondary* `group`
///
/// NOTE on Debian containers, all new users will be assigned to the `users` primary group (GID=100)
pub fn secondary_group(mut self, group: impl AsRef<str>) -> Self {
let groupname = group.as_ref();
assert!(
!self.groups.contains(groupname),
"user {} has already been assigned to {groupname}",
self.name
);
self.groups.insert(groupname.to_string());
self
}
/// assigns this user to all the specified *secondary* `groups`
///
/// NOTE on Debian containers, all new users will be assigned to the `users` primary group (GID=100)
pub fn secondary_groups(mut self, groups: impl IntoIterator<Item = impl AsRef<str>>) -> Self {
for group in groups {
self = self.secondary_group(group);
}
self
}
/// assigns the specified user `id` to this user
///
/// if not specified, the user will get an automatically allocated ID
pub fn id(mut self, id: u32) -> Self {
self.id = Some(id);
self
}
/// assigns the specified `password` to this user
///
/// if not specified, the user will have no password
pub fn password(mut self, password: impl AsRef<str>) -> Self {
self.password = Some(password.as_ref().to_string());
self
}
/// creates a home directory for the user at `/home/<username>`
///
/// by default, the directory is not created
pub fn create_home_directory(mut self) -> Self {
self.create_home_directory = true;
self
}
/// sets the user's shell to the one at the specified `path`
pub fn shell(mut self, path: impl AsRef<str>) -> Self {
self.shell = Some(path.as_ref().to_string());
self
}
fn create(&self, container: &Container) -> Result<()> {
if cfg!(target_os = "freebsd") {
let mut useradd = Command::new("pw");
useradd.arg("useradd");
useradd.arg(&self.name);
if self.create_home_directory {
useradd.arg("-m");
}
if let Some(path) = &self.shell {
useradd.arg("-s").arg(path);
}
if let Some(id) = self.id {
useradd.arg("-u").arg(id.to_string());
}
if !self.groups.is_empty() {
let group_list = self.groups.iter().cloned().collect::<Vec<_>>().join(",");
useradd.arg("-G").arg(group_list);
}
container.output(&useradd)?.assert_success()?;
if let Some(password) = &self.password {
container
.output(
Command::new("pw")
.args(["usermod", "-n", &self.name, "-h", "0"])
.stdin(password),
)?
.assert_success()?;
}
} else if cfg!(target_os = "linux") {
let mut useradd = Command::new("useradd");
useradd.arg("--no-user-group");
if self.create_home_directory {
useradd.arg("--create-home");
}
if let Some(path) = &self.shell {
useradd.arg("--shell").arg(path);
}
if let Some(id) = self.id {
useradd.arg("--uid").arg(id.to_string());
}
if !self.groups.is_empty() {
let group_list = self.groups.iter().cloned().collect::<Vec<_>>().join(",");
useradd.arg("--groups").arg(group_list);
}
useradd.arg(&self.name);
container.output(&useradd)?.assert_success()?;
if let Some(password) = &self.password {
container
.output(Command::new("chpasswd").stdin(format!("{}:{password}", self.name)))?
.assert_success()?;
}
} else {
todo!();
}
Ok(())
}
}
impl From<String> for User {
fn from(name: String) -> Self {
assert!(!name.is_empty(), "user name cannot be an empty string");
Self {
create_home_directory: false,
groups: if cfg!(target_os = "freebsd") {
// Many tests expect the users group to exist, but FreeBSD doesn't actually use it.
["users".to_owned()].into_iter().collect()
} else {
HashSet::new()
},
id: None,
name,
password: None,
// Keep the shell that is used consistent across OSes
shell: Some("/bin/sh".to_owned()),
}
}
}
impl From<&'_ str> for User {
fn from(name: &'_ str) -> Self {
name.to_string().into()
}
}
/// a group
pub struct Group {
name: Groupname,
id: Option<u32>,
}
/// creates a group with the specified `name`
#[allow(non_snake_case)]
pub fn Group(name: impl AsRef<str>) -> Group {
name.as_ref().into()
}
impl Group {
/// assigns the specified group `id` to this group
///
/// if not specified, the group will get an automatically allocated ID
pub fn id(mut self, id: u32) -> Self {
self.id = Some(id);
self
}
fn create(&self, container: &Container) -> Result<()> {
if cfg!(target_os = "freebsd") {
let mut groupadd = Command::new("pw");
groupadd.arg("groupadd");
groupadd.arg(&self.name);
if let Some(id) = self.id {
groupadd.arg("-g");
groupadd.arg(id.to_string());
}
container.output(&groupadd)?.assert_success()
} else if cfg!(target_os = "linux") {
let mut groupadd = Command::new("groupadd");
if let Some(id) = self.id {
groupadd.arg("--gid");
groupadd.arg(id.to_string());
}
groupadd.arg(&self.name);
container.output(&groupadd)?.assert_success()
} else {
todo!();
}
}
}
impl From<String> for Group {
fn from(name: String) -> Self {
assert!(!name.is_empty(), "group name cannot be an empty string");
Self { name, id: None }
}
}
impl From<&'_ str> for Group {
fn from(name: &'_ str) -> Self {
name.to_string().into()
}
}
/// a text file
pub struct TextFile {
contents: String,
trailing_newline: bool,
chmod: String,
chown: String,
}
/// creates a text file with the specified `contents`
///
/// NOTE by default, a trailing newline will be appended to the contents if it doesn't contain one.
/// to omit the trailing newline use the `TextFile::no_trailing_newline` method
#[allow(non_snake_case)]
pub fn TextFile(contents: impl AsRef<str>) -> TextFile {
contents.as_ref().into()
}
impl TextFile {
const DEFAULT_CHMOD: &'static str = "000";
/// chmod string to apply to the file
///
/// if not specified, the default is "000"
pub fn chmod(mut self, chmod: impl AsRef<str>) -> Self {
self.chmod = chmod.as_ref().to_string();
self
}
/// chown string to apply to the file
///
/// if not specified, the default is "root:root"
pub fn chown(mut self, chown: impl AsRef<str>) -> Self {
self.chown = chown.as_ref().to_string();
self
}
/// strips newlines from the end of the file
pub fn no_trailing_newline(mut self) -> Self {
self.trailing_newline = false;
self
}
fn create(&self, path: &str, container: &Container) -> Result<()> {
let mut contents = self.contents.clone();
if self.trailing_newline {
if !contents.ends_with('\n') {
contents.push('\n');
}
} else if contents.ends_with('\n') {
contents.pop();
}
container.cp(path, &contents)?;
container
.output(Command::new("chown").args([&self.chown, path]))?
.assert_success()?;
container
.output(Command::new("chmod").args([&self.chmod, path]))?
.assert_success()
}
}
impl From<String> for TextFile {
fn from(contents: String) -> Self {
Self {
contents,
chmod: Self::DEFAULT_CHMOD.to_string(),
chown: format!("root:{ROOT_GROUP}"),
trailing_newline: true,
}
}
}
impl From<&'_ str> for TextFile {
fn from(contents: &'_ str) -> Self {
contents.to_string().into()
}
}
impl<S: AsRef<str>, const N: usize> From<[S; N]> for TextFile {
fn from(contents: [S; N]) -> Self {
let mut buf = String::new();
for s in contents {
buf += s.as_ref();
buf += "\n";
}
buf.into()
}
}
/// creates a directory at the specified `path`
#[allow(non_snake_case)]
pub fn Directory(path: impl AsRef<str>) -> Directory {
Directory::from(path.as_ref())
}
/// a directory
pub struct Directory {
path: String,
chmod: String,
chown: String,
}
impl Directory {
const DEFAULT_CHMOD: &'static str = "100";
/// chmod string to apply to the file
///
/// if not specified, the default is "000"
pub fn chmod(mut self, chmod: impl AsRef<str>) -> Self {
self.chmod = chmod.as_ref().to_string();
self
}
/// chown string to apply to the file
///
/// if not specified, the default is "root:root"
pub fn chown(mut self, chown: impl AsRef<str>) -> Self {
self.chown = chown.as_ref().to_string();
self
}
fn get_path(&self) -> &str {
&self.path
}
fn create(&self, container: &Container) -> Result<()> {
let path = &self.path;
container
.output(Command::new("mkdir").args([path]))?
.assert_success()?;
container
.output(Command::new("chown").args([&self.chown, path]))?
.assert_success()?;
container
.output(Command::new("chmod").args([&self.chmod, path]))?
.assert_success()
}
}
impl From<String> for Directory {
fn from(path: String) -> Self {
Self {
path,
chmod: Self::DEFAULT_CHMOD.to_string(),
chown: format!("root:{ROOT_GROUP}"),
}
}
}
impl From<&'_ str> for Directory {
fn from(path: &str) -> Self {
Directory::from(path.to_string())
}
}
fn getent_group(container: &Container) -> Result<(HashSet<Groupname>, HashSet<u32>)> {
let stdout = container
.output(Command::new("getent").arg("group"))?
.stdout()?;
let mut groupnames = HashSet::new();
let mut group_ids = HashSet::new();
for line in stdout.lines() {
let mut parts = line.split(':');
match (parts.next(), parts.next(), parts.next()) {
(Some(name), Some(_), Some(id)) => {
groupnames.insert(name.to_string());
group_ids.insert(id.parse()?);
}
_ => {
return Err(format!("invalid `getent group` syntax: {line}").into());
}
}
}
Ok((groupnames, group_ids))
}
fn getent_passwd(container: &Container) -> Result<(HashSet<Username>, HashSet<u32>)> {
let stdout = container
.output(Command::new("getent").arg("passwd"))?
.stdout()?;
let mut usernames = HashSet::new();
let mut user_ids = HashSet::new();
for line in stdout.lines() {
let mut parts = line.split(':');
match (parts.next(), parts.next(), parts.next()) {
(Some(name), Some(_), Some(id)) => {
usernames.insert(name.to_string());
user_ids.insert(id.parse()?);
}
_ => {
return Err(format!("invalid `getent passwd` syntax: {line}").into());
}
}
}
Ok((usernames, user_ids))
}
#[cfg(test)]
mod tests {
use super::*;
const USERNAME: &str = "ferris";
const GROUPNAME: &str = "rustaceans";
#[test]
fn group_creation_works() -> Result<()> {
let env = EnvBuilder::default().group(GROUPNAME).build()?;
let groupnames = getent_group(&env.container)?.0;
assert!(groupnames.contains(GROUPNAME));
Ok(())
}
#[test]
fn user_creation_works() -> Result<()> {
let env = EnvBuilder::default().user(USERNAME).build()?;
let usernames = getent_passwd(&env.container)?.0;
assert!(usernames.contains(USERNAME));
Ok(())
}
#[test]
fn no_implicit_home_creation() -> Result<()> {
let env = EnvBuilder::default().user(USERNAME).build()?;
let output = Command::new("sh")
.arg("-c")
.arg(format!("[ -d /home/{USERNAME} ]"))
.output(&env)?;
assert!(!output.status().success());
Ok(())
}
#[test]
fn no_implicit_user_group_creation() -> Result<()> {
let env = EnvBuilder::default().user(USERNAME).build()?;
let stdout = Command::new("groups")
.as_user(USERNAME)
.output(&env)?
.stdout()?;
let groups = stdout.split(' ').collect::<HashSet<_>>();
assert!(!groups.contains(USERNAME));
Ok(())
}
#[test]
fn no_password_by_default() -> Result<()> {
let env = EnvBuilder::default().user(USERNAME).build()?;
let stdout = Command::new("passwd")
.args(["--status", USERNAME])
.output(&env)?
.stdout()?;
assert!(stdout.starts_with(&format!("{USERNAME} L")));
Ok(())
}
#[test]
fn password_assignment_works() -> Result<()> {
let password = "strong-password";
let env = Env("ALL ALL=(ALL:ALL) ALL")
.user(User(USERNAME).password(password))
.build()?;
Command::new("sudo")
.args(["-S", "true"])
.as_user(USERNAME)
.stdin(password)
.output(&env)?
.assert_success()
}
#[test]
fn creating_user_part_of_existing_group_works() -> Result<()> {
let groupname = "users";
let env = EnvBuilder::default()
.user(User(USERNAME).secondary_group(groupname))
.build()?;
let stdout = Command::new("groups")
.as_user(USERNAME)
.output(&env)?
.stdout()?;
let user_groups = stdout.split(' ').collect::<HashSet<_>>();
assert!(user_groups.contains(groupname));
Ok(())
}
#[test]
fn sudoers_file_get_created_with_expected_contents() -> Result<()> {
let expected = "Hello, root!";
let env = Env(expected).build()?;
let actual = Command::new("cat")
.arg(ETC_SUDOERS)
.output(&env)?
.stdout()?;
assert_eq!(expected, actual);
Ok(())
}
#[test]
fn text_file_gets_created_with_right_perms() -> Result<()> {
let chown = format!("{USERNAME}:{GROUPNAME}");
let chmod = "600";
let expected_contents = "hello";
let path = "/root/file";
let env = EnvBuilder::default()
.user(USERNAME)
.group(GROUPNAME)
.file(path, TextFile(expected_contents).chown(chown).chmod(chmod))
.build()?;
let actual_contents = Command::new("cat").arg(path).output(&env)?.stdout()?;
assert_eq!(expected_contents, &actual_contents);
let ls_l = Command::new("ls")
.args(["-l", path])
.output(&env)?
.stdout()?;
assert!(ls_l.starts_with("-rw-------"));
assert!(ls_l.contains(&format!("{USERNAME} {GROUPNAME}")));
Ok(())
}
#[test]
#[should_panic = "user root already exists in base image"]
fn cannot_create_user_that_already_exists_in_base_image() {
EnvBuilder::default().user("root").build().unwrap();
}
#[test]
#[should_panic = "user ID 0 already exists in base image"]
fn cannot_assign_user_id_that_already_exists_in_base_image() {
EnvBuilder::default()
.user(User(USERNAME).id(0))
.build()
.unwrap();
}
#[test]
#[should_panic = "group root already exists in base image"]
fn cannot_create_group_that_already_exists_in_base_image() {
EnvBuilder::default().group("root").build().unwrap();
}
#[test]
#[should_panic = "group ID 0 already exists in base image"]
fn cannot_assign_group_id_that_already_exists_in_base_image() {
EnvBuilder::default()
.group(Group(GROUPNAME).id(0))
.build()
.unwrap();
}
#[test]
fn setting_user_id_works() -> Result<()> {
let expected = 1023;
let env = EnvBuilder::default()
.user(User(USERNAME).id(expected))
.build()?;
let actual = Command::new("id")
.args(["-u", USERNAME])
.output(&env)?
.stdout()?
.parse()?;
assert_eq!(expected, actual);
Ok(())
}
#[test]
fn setting_group_id_works() -> Result<()> {
let expected = 1023;
let env = EnvBuilder::default()
.group(Group(GROUPNAME).id(expected))
.build()?;
let stdout = Command::new("getent")
.args(["group", GROUPNAME])
.output(&env)?
.stdout()?;
let actual = stdout.split(':').nth(2);
assert_eq!(Some(expected.to_string().as_str()), actual);
Ok(())
}
#[test]
fn setting_hostname_works() -> Result<()> {
let expected = "container";
let env = EnvBuilder::default().hostname(expected).build()?;
let actual = Command::new("hostname").output(&env)?.stdout()?;
assert_eq!(expected, actual);
Ok(())
}
#[test]
fn trailing_newline_by_default() -> Result<()> {
let path_a = "/root/a";
let path_b = "/root/b";
let env = EnvBuilder::default()
.file(path_a, "hello")
.file(path_b, "hello\n")
.build()?;
let a_last_char = Command::new("tail")
.args(["-c1", path_a])
.output(&env)?
.stdout()?;
assert_eq!("", a_last_char);
let b_last_char = Command::new("tail")
.args(["-c1", path_b])
.output(&env)?
.stdout()?;
assert_eq!("", b_last_char);
Ok(())
}