Skip to main content

subspace_core/credentials/
signed_in.rs

1//! GitHub accounts signed in through Subspace (credential step 3): the
2//! logins in `github-accounts.json` beside the state file, and each
3//! account's token in the build's [`vault`]: the system keychain under
4//! `<data directory>.github`, or in a debug build the owner-only
5//! `github-tokens.json` beside the state file. Logins are not secret; a
6//! token never leaves its vault except to authorize a request.
7
8#[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
19/// The signed-in logins, beside the state file. Not secret.
20pub const LIST_FILE: &str = "github-accounts.json";
21/// Debug builds only: the owner-only token file beside the state file.
22pub const TOKEN_FILE: &str = "github-tokens.json";
23/// Serializes every read-modify-write of the list.
24static WRITES: Mutex<()> = Mutex::new(());
25
26/// One signed-in login, spelled as GitHub spells it. `expired` once GitHub
27/// rejected its token, until the account signs in again.
28#[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    "The app cannot read or save its GitHub sign-in. Unlock your system keychain and try again."
38)]
39pub struct StoreError;
40
41/// Where the list of signed-in logins is kept.
42enum 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
66/// The signed-in accounts and their tokens.
67pub 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
84/// The Keychain service of the signed-in GitHub tokens:
85/// `<directory name>.github`.
86pub fn keychain_service() -> String {
87    format!("{}.github", state::directory_name())
88}
89
90impl SignedInAccounts {
91    /// The list beside the state file, and the build's vault.
92    pub fn system() -> Self {
93        Self {
94            list: List::File(state::sibling(LIST_FILE)),
95            vault: vault::system(keychain_service(), TOKEN_FILE),
96        }
97    }
98
99    /// Kept in memory for this run only, as tests need.
100    pub fn memory() -> Self {
101        Self {
102            list: List::Memory(Mutex::default()),
103            vault: vault::memory(),
104        }
105    }
106
107    /// The list and the debug build's token file in `directory`.
108    #[cfg(test)]
109    fn in_directory(directory: &Path) -> Self {
110        Self {
111            list: List::File(Some(directory.join(LIST_FILE))),
112            vault: vault::file(directory.join(TOKEN_FILE)),
113        }
114    }
115
116    pub fn accounts(&self) -> Vec<SignedInAccount> {
117        self.list.read()
118    }
119
120    /// The signed-in account `login`, whatever its case.
121    pub fn find(&self, login: &str) -> Option<SignedInAccount> {
122        self.accounts()
123            .into_iter()
124            .find(|account| account.login.eq_ignore_ascii_case(login))
125    }
126
127    /// The token of `login` while GitHub still accepts it.
128    pub fn token(&self, login: &str) -> Result<Option<Secret>, StoreError> {
129        match self.find(login) {
130            Some(account) if !account.expired => Ok(self.vault.load(&key(login))?),
131            _ => Ok(None),
132        }
133    }
134
135    /// Keeps `token` for `login`, replacing an earlier sign-in.
136    pub fn save(&self, login: &str, token: &Secret) -> Result<(), StoreError> {
137        if !is_login(login) {
138            return Err(StoreError);
139        }
140        self.vault.save(&key(login), token)?;
141        self.update(|accounts| signed_in(accounts, login))
142    }
143
144    /// Forgets `login` and gives back its token, so it can be revoked.
145    pub fn remove(&self, login: &str) -> Result<Option<Secret>, StoreError> {
146        let token = self.vault.load(&key(login))?;
147        self.vault.delete(&key(login))?;
148        self.update(|accounts| accounts.retain(|account| !same(&account.login, login)))?;
149        Ok(token)
150    }
151
152    /// GitHub rejected `rejected`: marks `login` as needing sign-in again,
153    /// unless it has signed in again since, with another token.
154    pub fn reject(&self, login: &str, rejected: &Secret) -> Result<(), StoreError> {
155        if self.vault.load(&key(login))?.as_ref() != Some(rejected) {
156            return Ok(());
157        }
158        self.update(|accounts| expire(accounts, login))
159    }
160
161    /// `saved` when it is a usable signed-in account, else the first one.
162    pub fn preferred(&self, saved: Option<&str>) -> Option<String> {
163        preferred(&self.accounts(), saved)
164    }
165
166    fn update(&self, change: impl FnOnce(&mut Vec<SignedInAccount>)) -> Result<(), StoreError> {
167        let _writing = lock(&WRITES);
168        let mut accounts = self.list.read();
169        change(&mut accounts);
170        self.list.write(accounts)
171    }
172}
173
174fn key(login: &str) -> String {
175    login.to_ascii_lowercase()
176}
177
178fn same(left: &str, right: &str) -> bool {
179    left.eq_ignore_ascii_case(right)
180}
181
182fn signed_in(accounts: &mut Vec<SignedInAccount>, login: &str) {
183    accounts.retain(|account| !same(&account.login, login));
184    accounts.push(SignedInAccount {
185        login: login.to_owned(),
186        expired: false,
187    });
188}
189
190fn expire(accounts: &mut [SignedInAccount], login: &str) {
191    for account in accounts
192        .iter_mut()
193        .filter(|account| same(&account.login, login))
194    {
195        account.expired = true;
196    }
197}
198
199fn preferred(accounts: &[SignedInAccount], saved: Option<&str>) -> Option<String> {
200    let usable = || accounts.iter().filter(|account| !account.expired);
201    saved
202        .and_then(|saved| usable().find(|account| same(&account.login, saved)))
203        .or_else(|| usable().next())
204        .map(|account| account.login.clone())
205}
206
207#[cfg(test)]
208mod tests {
209    use super::{LIST_FILE, SignedInAccount, SignedInAccounts, StoreError, TOKEN_FILE};
210    use crate::Secret;
211
212    fn token(value: &str) -> Secret {
213        Secret::new(value)
214    }
215
216    #[test]
217    fn a_saved_account_gives_its_token_whatever_the_case() {
218        let accounts = SignedInAccounts::memory();
219        accounts.save("Octo-Dev", &token("first")).unwrap();
220        assert_eq!(accounts.token("octo-dev").unwrap(), Some(token("first")));
221        accounts.save("octo-dev", &token("second")).unwrap();
222        assert_eq!(
223            accounts.accounts(),
224            [SignedInAccount {
225                login: "octo-dev".into(),
226                expired: false
227            }]
228        );
229        assert_eq!(accounts.token("OCTO-DEV").unwrap(), Some(token("second")));
230        assert_eq!(accounts.token("someone-else").unwrap(), None);
231        assert_eq!(accounts.save("--help", &token("bad")), Err(StoreError));
232    }
233
234    #[test]
235    fn a_rejected_token_needs_sign_in_again_unless_it_was_replaced() {
236        let accounts = SignedInAccounts::memory();
237        accounts.save("octo-dev", &token("old")).unwrap();
238        accounts.save("octo-dev", &token("new")).unwrap();
239        accounts.reject("octo-dev", &token("old")).unwrap();
240        assert_eq!(accounts.token("octo-dev").unwrap(), Some(token("new")));
241        accounts.reject("octo-dev", &token("new")).unwrap();
242        assert!(accounts.find("octo-dev").unwrap().expired);
243        assert_eq!(accounts.token("octo-dev").unwrap(), None);
244        accounts.save("octo-dev", &token("again")).unwrap();
245        assert!(!accounts.find("octo-dev").unwrap().expired);
246    }
247
248    #[test]
249    fn removing_an_account_gives_back_its_token_for_revocation() {
250        let accounts = SignedInAccounts::memory();
251        accounts.save("octo-dev", &token("value")).unwrap();
252        accounts.save("mona", &token("other")).unwrap();
253        assert_eq!(accounts.remove("OCTO-dev").unwrap(), Some(token("value")));
254        assert_eq!(accounts.find("octo-dev"), None);
255        assert_eq!(accounts.remove("octo-dev").unwrap(), None);
256        assert_eq!(accounts.token("mona").unwrap(), Some(token("other")));
257    }
258
259    #[test]
260    fn the_preferred_account_is_the_saved_one_while_it_still_works() {
261        let accounts = SignedInAccounts::memory();
262        assert_eq!(accounts.preferred(Some("mona")), None);
263        accounts.save("octo-dev", &token("one")).unwrap();
264        accounts.save("mona", &token("two")).unwrap();
265        assert_eq!(accounts.preferred(Some("MONA")).as_deref(), Some("mona"));
266        assert_eq!(accounts.preferred(None).as_deref(), Some("octo-dev"));
267        accounts.reject("mona", &token("two")).unwrap();
268        assert_eq!(
269            accounts.preferred(Some("mona")).as_deref(),
270            Some("octo-dev")
271        );
272    }
273
274    #[test]
275    fn the_file_store_is_owner_only_and_keeps_tokens_out_of_the_list() {
276        let directory = tempfile::tempdir().unwrap();
277        let accounts = SignedInAccounts::in_directory(directory.path());
278        accounts.save("octo-dev", &token("fixture-value")).unwrap();
279        let reopened = SignedInAccounts::in_directory(directory.path());
280        assert_eq!(
281            reopened.token("octo-dev").unwrap(),
282            Some(token("fixture-value"))
283        );
284        for name in [LIST_FILE, TOKEN_FILE] {
285            let file = directory.path().join(name);
286            assert!(crate::private_file::is_owner_only(&file).unwrap(), "{name}");
287        }
288        let list = std::fs::read_to_string(directory.path().join(LIST_FILE)).unwrap();
289        assert!(list.contains("octo-dev") && !list.contains("fixture-value"));
290        reopened.remove("octo-dev").unwrap();
291        let tokens = std::fs::read_to_string(directory.path().join(TOKEN_FILE)).unwrap();
292        assert!(!tokens.contains("fixture-value"));
293    }
294}