Skip to main content

subspace_github_auth/
lib.rs

1//! Sign in with GitHub through the app's OAuth App, without GPUI.
2//!
3//! The app supplies its OAuth App ([`OAuthClient`]); the Framework has none.
4//! With the client secret, sign-in uses the browser: an authorization
5//! code with PKCE (RFC 7636) and a random `state`, returned to a one-shot
6//! listener on `127.0.0.1` ([`browser`]). Without it, sign-in uses the device
7//! flow (RFC 8628, [`device`]). Either way the token's owner comes from
8//! `GET /user`. Tokens, codes and the secret are [`Secret`]s or stay inside
9//! this crate; no log line or error carries one.
10
11pub mod browser;
12pub mod config;
13pub mod device;
14pub mod pkce;
15pub mod token;
16mod user;
17
18use std::sync::Arc;
19use std::sync::atomic::{AtomicBool, Ordering};
20use std::time::Duration;
21
22use subspace_core::Secret;
23
24pub use config::{Endpoints, OAuthClient};
25
26/// How long a sign-in waits for the browser or the code before giving up.
27pub const SIGN_IN_TIME_LIMIT: Duration = Duration::from_secs(5 * 60);
28
29/// Why a sign-in did not finish. Every message is plain words for the user
30/// and carries no token, code or secret.
31#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
32pub enum AuthError {
33    /// The user cancelled in Subspace.
34    #[error("Sign-in was cancelled.")]
35    Cancelled,
36    #[error("GitHub sign-in took too long. Try again.")]
37    TimedOut,
38    #[error("The browser's reply did not belong to this sign-in. Try again.")]
39    StateMismatch,
40    #[error("GitHub sign-in was declined in the browser.")]
41    Denied,
42    #[error("The code expired before it was entered on GitHub. Try again.")]
43    Expired,
44    #[error(
45        "GitHub does not allow sign-in with a code for this app yet. Use a release build of \
46         the app, or run `gh auth login`."
47    )]
48    DeviceFlowDisabled,
49    #[error("GitHub did not grant {0}. Sign in again and approve every permission.")]
50    MissingScopes(String),
51    #[error("Subspace cannot wait for the browser: {0}.")]
52    Listener(String),
53    #[error("GitHub could not complete the sign-in: {0}")]
54    Service(String),
55    #[error("GitHub could not be reached: {0}")]
56    Network(String),
57}
58
59/// A sign-in's cancel switch, shared with the thread that waits.
60#[derive(Debug, Clone, Default)]
61pub struct Cancel(Arc<AtomicBool>);
62
63impl Cancel {
64    pub fn cancel(&self) {
65        self.0.store(true, Ordering::Relaxed);
66    }
67
68    pub fn is_cancelled(&self) -> bool {
69        self.0.load(Ordering::Relaxed)
70    }
71}
72
73/// What the user does next.
74#[derive(Debug, Clone, PartialEq, Eq)]
75pub enum Prompt {
76    /// Continue on GitHub in the browser, opened at `url`.
77    Browser { url: String },
78    /// Enter `user_code` at `verification_uri`.
79    Device {
80        user_code: String,
81        verification_uri: String,
82    },
83}
84
85/// A finished sign-in: the account and its token.
86#[derive(Debug, Clone, PartialEq, Eq)]
87pub struct SignedIn {
88    pub login: String,
89    pub token: Secret,
90}
91
92/// The rest of a started sign-in, run off the UI thread.
93pub trait Pending: Send {
94    /// Waits for the browser or the code, then exchanges and checks the
95    /// token. Returns [`AuthError::Cancelled`] soon after `cancel`.
96    fn finish(self: Box<Self>, cancel: &Cancel) -> Result<SignedIn, AuthError>;
97}
98
99/// A started sign-in: what to show, and what to wait for.
100pub struct Started {
101    pub prompt: Prompt,
102    pub pending: Box<dyn Pending>,
103}
104
105/// Starts sign-ins and revokes signed-out tokens; injectable for tests.
106pub trait Authenticator: Send + Sync {
107    fn start(&self) -> Result<Started, AuthError>;
108    /// Best effort: asks GitHub to forget the app's grant for `token`.
109    fn revoke(&self, token: &Secret);
110}
111
112/// Sign-in through the app's GitHub OAuth App.
113#[derive(Debug, Clone)]
114pub struct GitHubOAuth {
115    client: OAuthClient,
116    endpoints: Endpoints,
117    time_limit: Duration,
118}
119
120impl GitHubOAuth {
121    /// `client`, with the build's endpoints.
122    pub fn for_client(client: OAuthClient) -> Self {
123        Self::new(client, Endpoints::from_build())
124    }
125
126    pub fn new(client: OAuthClient, endpoints: Endpoints) -> Self {
127        Self {
128            client,
129            endpoints,
130            time_limit: SIGN_IN_TIME_LIMIT,
131        }
132    }
133
134    /// A shorter wait, for tests.
135    // qual:api
136    pub fn with_time_limit(mut self, time_limit: Duration) -> Self {
137        self.time_limit = time_limit;
138        self
139    }
140}
141
142impl Authenticator for GitHubOAuth {
143    fn start(&self) -> Result<Started, AuthError> {
144        match &self.client.secret {
145            Some(secret) => {
146                browser::start(&self.client.id, secret, &self.endpoints, self.time_limit)
147            }
148            None => device::start(&self.client.id, &self.endpoints, self.time_limit),
149        }
150    }
151
152    fn revoke(&self, token: &Secret) {
153        if let Some(secret) = &self.client.secret {
154            user::revoke(&self.endpoints, (&self.client.id, secret), token);
155        }
156    }
157}
158
159/// The account a token belongs to, once its scopes are known to be enough.
160pub(crate) fn signed_in(
161    endpoints: &Endpoints,
162    granted: token::Granted,
163) -> Result<SignedIn, AuthError> {
164    token::check_scopes(&granted.scopes)?;
165    let login = user::login(endpoints, &granted.token)?;
166    Ok(SignedIn {
167        login,
168        token: granted.token,
169    })
170}
171
172/// Blocks for `duration` in short steps, returning early on `cancel`.
173pub(crate) fn sleep(duration: Duration, cancel: &Cancel) -> Result<(), AuthError> {
174    const STEP: Duration = Duration::from_millis(100);
175    let mut left = duration;
176    while !left.is_zero() {
177        if cancel.is_cancelled() {
178            return Err(AuthError::Cancelled);
179        }
180        let step = left.min(STEP);
181        std::thread::sleep(step);
182        left -= step;
183    }
184    Ok(())
185}