Skip to main content

heika_wallet/
keystore_file.rs

1//! キーストアのファイル。置き場所を決め、どこで落ちても壊れないように書く。
2//!
3//! CLI と GUI が同じファイルを同じやり方で読み書きするように、ここにまとめる。
4
5use 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
16/// キーストアのファイルの名前
17pub const FILE_NAME: &str = "keystore.age";
18
19/// キーストアを置く場所。OS ごとに、ユーザーのデータを置くところの下の heika。
20///
21/// Linux では `$XDG_DATA_HOME/heika/keystore.age`(なければ `~/.local/share` の下)、
22/// macOS では `~/Library/Application Support/heika/keystore.age`、
23/// Windows では `%LOCALAPPDATA%\heika\keystore.age`。
24pub 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
44/// 書き換える前の中身を残すファイル
45pub fn backup_path(path: &Path) -> PathBuf {
46    with_suffix(path, ".bak")
47}
48
49/// 書き換える前の中身を残したファイルを消して、消したことをフォルダーに書き込む
50pub 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
56/// キーストアを書く。どこで落ちても、古いファイルか新しいファイルのどちらかが完全な形で残るようにする。
57///
58/// ハーベストの秘密がない秘密には、先に作って入れる([`Keystore::fill_harvest_secrets`])。
59/// 同じフォルダーの一時ファイルに書いて同期し、読み戻して同じパスフレーズで開けることを確かめてから、
60/// 前のファイルを [`backup_path`] に写し、一時ファイルを本来の名前に置き換えて、フォルダーも同期する。
61pub 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    // 前に落ちたときの一時ファイルが残っていれば消す。本来のファイルではないので、消しても失うものはない
74    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
104/// キーストアを置くフォルダー。ファイルの名前だけなら、今のフォルダー
105fn 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
117/// キーストアのフォルダーを作る。Unix では自分だけが入れるようにする。
118fn 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
128/// 秘密を書くファイルを新しく作る。すでにあれば上書きしない。Unix では自分だけが読み書きできるようにする。
129fn 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
139/// 置き換えたことをフォルダーに書き込む。Windows ではフォルダーを開いて同期できないので、何もしない
140fn 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    /// ユーザーのデータを置くところを決める環境変数がない
153    NoDataDirectory { variable: &'static str },
154    /// ファイルかフォルダーを扱えなかった。`action` は「作れ」「書け」のような、「ませんでした」の前に来る言葉
155    Io {
156        action: &'static str,
157        path: PathBuf,
158        source: io::Error,
159    },
160    /// 書いたキーストアを開き直せない
161    Reopen(KeystoreError),
162    /// 書いたキーストアの中身が、書こうとしたものと違う
163    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        // 前に落ちたときの一時ファイルが残っていても書ける
245        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        // 書くときにハーベストの秘密を入れていて、読み戻しても同じ
252        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}