1use std::env;
6use std::fmt;
7use std::fs::{self, File, OpenOptions};
8use std::io::{self, Write};
9use std::path::{Path, PathBuf};
10
11use rand_core::CryptoRng;
12
13use crate::age;
14use crate::keystore::{Keystore, KeystoreError};
15
16pub const FILE_NAME: &str = "keystore.age";
18
19pub fn default_path() -> Result<PathBuf, KeystoreFileError> {
25 let var = |name: &'static str| {
26 env::var_os(name)
27 .filter(|value| !value.is_empty())
28 .map(PathBuf::from)
29 .ok_or(KeystoreFileError::NoDataDirectory { variable: name })
30 };
31 let directory = if cfg!(windows) {
32 var("LOCALAPPDATA")?
33 } else if cfg!(target_os = "macos") {
34 var("HOME")?.join("Library/Application Support")
35 } else {
36 match var("XDG_DATA_HOME") {
37 Ok(directory) => directory,
38 Err(_) => var("HOME")?.join(".local/share"),
39 }
40 };
41 Ok(directory.join("heika").join(FILE_NAME))
42}
43
44pub fn backup_path(path: &Path) -> PathBuf {
46 with_suffix(path, ".bak")
47}
48
49pub fn remove_backup(path: &Path) -> Result<(), KeystoreFileError> {
51 let backup = backup_path(path);
52 fs::remove_file(&backup).map_err(|error| KeystoreFileError::io("消せ", &backup, error))?;
53 sync_directory(directory_of(path))
54}
55
56pub fn save<R: CryptoRng + ?Sized>(
62 rng: &mut R,
63 path: &Path,
64 keystore: &mut Keystore,
65 passphrase: &str,
66) -> Result<(), KeystoreFileError> {
67 let directory = directory_of(path);
68 create_private_directory(directory)?;
69 keystore.fill_harvest_secrets(rng);
70 let sealed = keystore.seal(rng, passphrase.as_bytes(), age::DEFAULT_WORK_FACTOR);
71
72 let temporary = with_suffix(path, ".tmp");
73 match fs::remove_file(&temporary) {
75 Ok(()) => {}
76 Err(error) if error.kind() == io::ErrorKind::NotFound => {}
77 Err(error) => return Err(KeystoreFileError::io("消せ", &temporary, error)),
78 }
79 let mut file = create_secret_file(&temporary)?;
80 file.write_all(&sealed)
81 .and_then(|()| file.sync_all())
82 .map_err(|error| KeystoreFileError::io("書け", &temporary, error))?;
83 drop(file);
84
85 let written = fs::read(&temporary)
86 .map_err(|error| KeystoreFileError::io("読み戻せ", &temporary, error))?;
87 let reopened =
88 Keystore::open(passphrase.as_bytes(), &written).map_err(KeystoreFileError::Reopen)?;
89 if *reopened.to_text() != *keystore.to_text() {
90 return Err(KeystoreFileError::Mismatch);
91 }
92
93 if path.exists() {
94 let backup = backup_path(path);
95 fs::copy(path, &backup)
96 .and_then(|_| OpenOptions::new().write(true).open(&backup)?.sync_all())
97 .map_err(|error| KeystoreFileError::io("作れ", &backup, error))?;
98 }
99 fs::rename(&temporary, path)
100 .map_err(|error| KeystoreFileError::io("置き換えられ", path, error))?;
101 sync_directory(directory)
102}
103
104fn directory_of(path: &Path) -> &Path {
106 path.parent()
107 .filter(|directory| !directory.as_os_str().is_empty())
108 .unwrap_or(Path::new("."))
109}
110
111fn with_suffix(path: &Path, suffix: &str) -> PathBuf {
112 let mut name = path.as_os_str().to_owned();
113 name.push(suffix);
114 PathBuf::from(name)
115}
116
117fn create_private_directory(directory: &Path) -> Result<(), KeystoreFileError> {
119 let mut builder = fs::DirBuilder::new();
120 builder.recursive(true);
121 #[cfg(unix)]
122 std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700);
123 builder
124 .create(directory)
125 .map_err(|error| KeystoreFileError::io("作れ", directory, error))
126}
127
128fn create_secret_file(path: &Path) -> Result<File, KeystoreFileError> {
130 let mut options = OpenOptions::new();
131 options.write(true).create_new(true);
132 #[cfg(unix)]
133 std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
134 options
135 .open(path)
136 .map_err(|error| KeystoreFileError::io("作れ", path, error))
137}
138
139fn sync_directory(directory: &Path) -> Result<(), KeystoreFileError> {
141 #[cfg(unix)]
142 File::open(directory)
143 .and_then(|directory| directory.sync_all())
144 .map_err(|error| KeystoreFileError::io("同期でき", directory, error))?;
145 #[cfg(not(unix))]
146 let _ = directory;
147 Ok(())
148}
149
150#[derive(Debug)]
151pub enum KeystoreFileError {
152 NoDataDirectory { variable: &'static str },
154 Io {
156 action: &'static str,
157 path: PathBuf,
158 source: io::Error,
159 },
160 Reopen(KeystoreError),
162 Mismatch,
164}
165
166impl KeystoreFileError {
167 fn io(action: &'static str, path: &Path, source: io::Error) -> Self {
168 Self::Io {
169 action,
170 path: path.to_owned(),
171 source,
172 }
173 }
174}
175
176impl fmt::Display for KeystoreFileError {
177 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
178 match self {
179 Self::NoDataDirectory { variable } => {
180 write!(
181 f,
182 "{variable} がないので、キーストアを置く場所を決められません"
183 )
184 }
185 Self::Io {
186 action,
187 path,
188 source,
189 } => write!(f, "{} を{action}ませんでした: {source}", path.display()),
190 Self::Reopen(error) => write!(f, "書いたキーストアを開き直せませんでした: {error}"),
191 Self::Mismatch => f.write_str("書いたキーストアの中身が、書こうとしたものと違います"),
192 }
193 }
194}
195
196impl std::error::Error for KeystoreFileError {
197 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
198 match self {
199 Self::Io { source, .. } => Some(source),
200 Self::Reopen(error) => Some(error),
201 _ => None,
202 }
203 }
204}
205
206#[cfg(test)]
207mod tests {
208 use heika_core::key::PrivateKey;
209 use heika_core::network::NetworkIdentifier;
210
211 use super::*;
212 use crate::keystore::{Account, Entry, Secret};
213 use crate::testing::Replay;
214
215 #[test]
216 fn writes_crash_safely_and_keeps_a_backup() {
217 let directory = env::temp_dir().join(format!("heika-wallet-test-{}", std::process::id()));
218 let path = directory.join("nested").join(FILE_NAME);
219 save(&mut Replay(&[1; 64]), &path, &mut Keystore::new(), "first").unwrap();
220 let first = fs::read(&path).unwrap();
221 assert!(Keystore::open(b"first", &first).is_ok());
222 assert!(!backup_path(&path).exists());
223 assert!(!with_suffix(&path, ".tmp").exists());
224 #[cfg(unix)]
225 {
226 use std::os::unix::fs::PermissionsExt;
227 let mode = |path: &Path| fs::metadata(path).unwrap().permissions().mode() & 0o777;
228 assert_eq!(mode(&path), 0o600);
229 assert_eq!(mode(path.parent().unwrap()), 0o700);
230 }
231
232 let mut keystore = Keystore::new();
233 keystore
234 .add(Entry {
235 secret: Secret::PrivateKey(PrivateKey::from_bytes(&[1; 32])),
236 harvest_secret: None,
237 accounts: vec![Account {
238 network: NetworkIdentifier::TESTNET,
239 index: None,
240 label: "a".to_owned(),
241 }],
242 })
243 .unwrap();
244 fs::write(with_suffix(&path, ".tmp"), b"broken").unwrap();
246 save(&mut Replay(&[2; 96]), &path, &mut keystore, "second").unwrap();
247 let backup = fs::read(backup_path(&path)).unwrap();
248 assert_eq!(backup, first);
249 let second = Keystore::open(b"second", &fs::read(&path).unwrap()).unwrap();
250 assert_eq!(second.accounts().count(), 1);
251 assert!(keystore.entries()[0].harvest_secret.is_some());
253 assert_eq!(*second.to_text(), *keystore.to_text());
254 fs::remove_dir_all(&directory).unwrap();
255 }
256}