1 // Copyright 2020, The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 //! Implements TempDir which aids in creating an cleaning up temporary directories for testing.
16
17 use std::fs::{create_dir, remove_dir_all};
18 use std::io::ErrorKind;
19 use std::path::{Path, PathBuf};
20 use std::{env::temp_dir, ops::Deref};
21
22 use android_system_keystore2::aidl::android::system::keystore2::IKeystoreService::IKeystoreService;
23 use android_security_authorization::aidl::android::security::authorization::IKeystoreAuthorization::IKeystoreAuthorization;
24
25 pub mod authorizations;
26 pub mod ffi_test_utils;
27 pub mod key_generations;
28 pub mod run_as;
29
30 static KS2_SERVICE_NAME: &str = "android.system.keystore2.IKeystoreService/default";
31 static AUTH_SERVICE_NAME: &str = "android.security.authorization";
32
33 /// Represents the lifecycle of a temporary directory for testing.
34 #[derive(Debug)]
35 pub struct TempDir {
36 path: std::path::PathBuf,
37 do_drop: bool,
38 }
39
40 impl TempDir {
41 /// Creates a temporary directory with a name of the form <prefix>_NNNNN where NNNNN is a zero
42 /// padded random number with 5 figures. The prefix must not contain file system separators.
43 /// The location of the directory cannot be chosen.
44 /// The directory with all of its content is removed from the file system when the resulting
45 /// object gets dropped.
new(prefix: &str) -> std::io::Result<Self>46 pub fn new(prefix: &str) -> std::io::Result<Self> {
47 let tmp = loop {
48 let mut tmp = temp_dir();
49 let number: u16 = rand::random();
50 tmp.push(format!("{}_{:05}", prefix, number));
51 match create_dir(&tmp) {
52 Err(e) => match e.kind() {
53 ErrorKind::AlreadyExists => continue,
54 _ => return Err(e),
55 },
56 Ok(()) => break tmp,
57 }
58 };
59 Ok(Self { path: tmp, do_drop: true })
60 }
61
62 /// Returns the absolute path of the temporary directory.
path(&self) -> &Path63 pub fn path(&self) -> &Path {
64 &self.path
65 }
66
67 /// Returns a path builder for convenient extension of the path.
68 ///
69 /// ## Example:
70 ///
71 /// ```
72 /// let tdir = TempDir::new("my_test")?;
73 /// let temp_foo_bar = tdir.build().push("foo").push("bar");
74 /// ```
75 /// `temp_foo_bar` derefs to a Path that represents "<tdir.path()>/foo/bar"
build(&self) -> PathBuilder76 pub fn build(&self) -> PathBuilder {
77 PathBuilder(self.path.clone())
78 }
79
80 /// When a test is failing you can set this to false in order to inspect
81 /// the directory structure after the test failed.
82 #[allow(dead_code)]
do_not_drop(&mut self)83 pub fn do_not_drop(&mut self) {
84 println!("Disabled automatic cleanup for: {:?}", self.path);
85 log::info!("Disabled automatic cleanup for: {:?}", self.path);
86 self.do_drop = false;
87 }
88 }
89
90 impl Drop for TempDir {
drop(&mut self)91 fn drop(&mut self) {
92 if self.do_drop {
93 remove_dir_all(&self.path).expect("Cannot delete temporary dir.");
94 }
95 }
96 }
97
98 /// Allows for convenient building of paths from a TempDir. See TempDir.build() for more details.
99 pub struct PathBuilder(PathBuf);
100
101 impl PathBuilder {
102 /// Adds another segment to the end of the path. Consumes, modifies and returns self.
push(mut self, segment: &str) -> Self103 pub fn push(mut self, segment: &str) -> Self {
104 self.0.push(segment);
105 self
106 }
107 }
108
109 impl Deref for PathBuilder {
110 type Target = Path;
111
deref(&self) -> &Self::Target112 fn deref(&self) -> &Self::Target {
113 &self.0
114 }
115 }
116
117 /// Get Keystore2 service.
get_keystore_service() -> binder::Strong<dyn IKeystoreService>118 pub fn get_keystore_service() -> binder::Strong<dyn IKeystoreService> {
119 binder::get_interface(KS2_SERVICE_NAME).unwrap()
120 }
121
122 /// Get Keystore auth service.
get_keystore_auth_service() -> binder::Strong<dyn IKeystoreAuthorization>123 pub fn get_keystore_auth_service() -> binder::Strong<dyn IKeystoreAuthorization> {
124 binder::get_interface(AUTH_SERVICE_NAME).unwrap()
125 }
126