subspace_core/credentials/
signed_in.rs1#[cfg(test)]
9use std::path::Path;
10use std::path::PathBuf;
11use std::sync::Mutex;
12
13use serde::{Deserialize, Serialize};
14
15use super::hosts_yml::is_login;
16use crate::vault::{self, Vault, VaultError, lock, read_json, write_json};
17use crate::{Secret, state};
18
19pub const LIST_FILE: &str = "github-accounts.json";
21pub const TOKEN_FILE: &str = "github-tokens.json";
23static WRITES: Mutex<()> = Mutex::new(());
25
26#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
29pub struct SignedInAccount {
30 pub login: String,
31 #[serde(default)]
32 pub expired: bool,
33}
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
36#[error(
37 "Subspace cannot read or save its GitHub sign-in. Unlock your system keychain and try again."
38)]
39pub struct StoreError;
40
41enum List {
43 File(Option<PathBuf>),
44 Memory(Mutex<Vec<SignedInAccount>>),
45}
46
47impl List {
48 fn read(&self) -> Vec<SignedInAccount> {
49 match self {
50 Self::File(file) => read_json(file.as_deref()),
51 Self::Memory(accounts) => lock(accounts).clone(),
52 }
53 }
54
55 fn write(&self, accounts: Vec<SignedInAccount>) -> Result<(), StoreError> {
56 match self {
57 Self::File(file) => Ok(write_json(file.as_deref(), &accounts)?),
58 Self::Memory(saved) => {
59 *lock(saved) = accounts;
60 Ok(())
61 }
62 }
63 }
64}
65
66pub struct SignedInAccounts {
68 list: List,
69 vault: Box<dyn Vault>,
70}
71
72impl From<VaultError> for StoreError {
73 fn from(_: VaultError) -> Self {
74 StoreError
75 }
76}
77
78impl Default for SignedInAccounts {
79 fn default() -> Self {
80 Self::memory()
81 }
82}
83
84impl SignedInAccounts {
85 pub fn system() -> Self {
87 Self {
88 list: List::File(state::sibling(LIST_FILE)),
89 vault: vault::system(format!("{}.github", state::directory_name()), TOKEN_FILE),
90 }
91 }
92
93 pub fn memory() -> Self {
95 Self {
96 list: List::Memory(Mutex::default()),
97 vault: vault::memory(),
98 }
99 }
100
101 #[cfg(test)]
103 fn in_directory(directory: &Path) -> Self {
104 Self {
105 list: List::File(Some(directory.join(LIST_FILE))),
106 vault: vault::file(directory.join(TOKEN_FILE)),
107 }
108 }
109
110 pub fn accounts(&self) -> Vec<SignedInAccount> {
111 self.list.read()
112 }
113
114 pub fn find(&self, login: &str) -> Option<SignedInAccount> {
116 self.accounts()
117 .into_iter()
118 .find(|account| account.login.eq_ignore_ascii_case(login))
119 }
120
121 pub fn token(&self, login: &str) -> Result<Option<Secret>, StoreError> {
123 match self.find(login) {
124 Some(account) if !account.expired => Ok(self.vault.load(&key(login))?),
125 _ => Ok(None),
126 }
127 }
128
129 pub fn save(&self, login: &str, token: &Secret) -> Result<(), StoreError> {
131 if !is_login(login) {
132 return Err(StoreError);
133 }
134 self.vault.save(&key(login), token)?;
135 self.update(|accounts| signed_in(accounts, login))
136 }
137
138 pub fn remove(&self, login: &str) -> Result<Option<Secret>, StoreError> {
140 let token = self.vault.load(&key(login))?;
141 self.vault.delete(&key(login))?;
142 self.update(|accounts| accounts.retain(|account| !same(&account.login, login)))?;
143 Ok(token)
144 }
145
146 pub fn reject(&self, login: &str, rejected: &Secret) -> Result<(), StoreError> {
149 if self.vault.load(&key(login))?.as_ref() != Some(rejected) {
150 return Ok(());
151 }
152 self.update(|accounts| expire(accounts, login))
153 }
154
155 pub fn preferred(&self, saved: Option<&str>) -> Option<String> {
157 preferred(&self.accounts(), saved)
158 }
159
160 fn update(&self, change: impl FnOnce(&mut Vec<SignedInAccount>)) -> Result<(), StoreError> {
161 let _writing = lock(&WRITES);
162 let mut accounts = self.list.read();
163 change(&mut accounts);
164 self.list.write(accounts)
165 }
166}
167
168fn key(login: &str) -> String {
169 login.to_ascii_lowercase()
170}
171
172fn same(left: &str, right: &str) -> bool {
173 left.eq_ignore_ascii_case(right)
174}
175
176fn signed_in(accounts: &mut Vec<SignedInAccount>, login: &str) {
177 accounts.retain(|account| !same(&account.login, login));
178 accounts.push(SignedInAccount {
179 login: login.to_owned(),
180 expired: false,
181 });
182}
183
184fn expire(accounts: &mut [SignedInAccount], login: &str) {
185 for account in accounts
186 .iter_mut()
187 .filter(|account| same(&account.login, login))
188 {
189 account.expired = true;
190 }
191}
192
193fn preferred(accounts: &[SignedInAccount], saved: Option<&str>) -> Option<String> {
194 let usable = || accounts.iter().filter(|account| !account.expired);
195 saved
196 .and_then(|saved| usable().find(|account| same(&account.login, saved)))
197 .or_else(|| usable().next())
198 .map(|account| account.login.clone())
199}
200
201#[cfg(test)]
202mod tests {
203 use super::{LIST_FILE, SignedInAccount, SignedInAccounts, StoreError, TOKEN_FILE};
204 use crate::Secret;
205
206 fn token(value: &str) -> Secret {
207 Secret::new(value)
208 }
209
210 #[test]
211 fn a_saved_account_gives_its_token_whatever_the_case() {
212 let accounts = SignedInAccounts::memory();
213 accounts.save("Octo-Dev", &token("first")).unwrap();
214 assert_eq!(accounts.token("octo-dev").unwrap(), Some(token("first")));
215 accounts.save("octo-dev", &token("second")).unwrap();
216 assert_eq!(
217 accounts.accounts(),
218 [SignedInAccount {
219 login: "octo-dev".into(),
220 expired: false
221 }]
222 );
223 assert_eq!(accounts.token("OCTO-DEV").unwrap(), Some(token("second")));
224 assert_eq!(accounts.token("someone-else").unwrap(), None);
225 assert_eq!(accounts.save("--help", &token("bad")), Err(StoreError));
226 }
227
228 #[test]
229 fn a_rejected_token_needs_sign_in_again_unless_it_was_replaced() {
230 let accounts = SignedInAccounts::memory();
231 accounts.save("octo-dev", &token("old")).unwrap();
232 accounts.save("octo-dev", &token("new")).unwrap();
233 accounts.reject("octo-dev", &token("old")).unwrap();
234 assert_eq!(accounts.token("octo-dev").unwrap(), Some(token("new")));
235 accounts.reject("octo-dev", &token("new")).unwrap();
236 assert!(accounts.find("octo-dev").unwrap().expired);
237 assert_eq!(accounts.token("octo-dev").unwrap(), None);
238 accounts.save("octo-dev", &token("again")).unwrap();
239 assert!(!accounts.find("octo-dev").unwrap().expired);
240 }
241
242 #[test]
243 fn removing_an_account_gives_back_its_token_for_revocation() {
244 let accounts = SignedInAccounts::memory();
245 accounts.save("octo-dev", &token("value")).unwrap();
246 accounts.save("mona", &token("other")).unwrap();
247 assert_eq!(accounts.remove("OCTO-dev").unwrap(), Some(token("value")));
248 assert_eq!(accounts.find("octo-dev"), None);
249 assert_eq!(accounts.remove("octo-dev").unwrap(), None);
250 assert_eq!(accounts.token("mona").unwrap(), Some(token("other")));
251 }
252
253 #[test]
254 fn the_preferred_account_is_the_saved_one_while_it_still_works() {
255 let accounts = SignedInAccounts::memory();
256 assert_eq!(accounts.preferred(Some("mona")), None);
257 accounts.save("octo-dev", &token("one")).unwrap();
258 accounts.save("mona", &token("two")).unwrap();
259 assert_eq!(accounts.preferred(Some("MONA")).as_deref(), Some("mona"));
260 assert_eq!(accounts.preferred(None).as_deref(), Some("octo-dev"));
261 accounts.reject("mona", &token("two")).unwrap();
262 assert_eq!(
263 accounts.preferred(Some("mona")).as_deref(),
264 Some("octo-dev")
265 );
266 }
267
268 #[test]
269 fn the_file_store_is_owner_only_and_keeps_tokens_out_of_the_list() {
270 let directory = tempfile::tempdir().unwrap();
271 let accounts = SignedInAccounts::in_directory(directory.path());
272 accounts.save("octo-dev", &token("fixture-value")).unwrap();
273 let reopened = SignedInAccounts::in_directory(directory.path());
274 assert_eq!(
275 reopened.token("octo-dev").unwrap(),
276 Some(token("fixture-value"))
277 );
278 for name in [LIST_FILE, TOKEN_FILE] {
279 let file = directory.path().join(name);
280 assert!(crate::private_file::is_owner_only(&file).unwrap(), "{name}");
281 }
282 let list = std::fs::read_to_string(directory.path().join(LIST_FILE)).unwrap();
283 assert!(list.contains("octo-dev") && !list.contains("fixture-value"));
284 reopened.remove("octo-dev").unwrap();
285 let tokens = std::fs::read_to_string(directory.path().join(TOKEN_FILE)).unwrap();
286 assert!(!tokens.contains("fixture-value"));
287 }
288}