subspace_github_auth/
lib.rs1pub 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
26pub const SIGN_IN_TIME_LIMIT: Duration = Duration::from_secs(5 * 60);
28
29#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
32pub enum AuthError {
33 #[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#[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#[derive(Debug, Clone, PartialEq, Eq)]
75pub enum Prompt {
76 Browser { url: String },
78 Device {
80 user_code: String,
81 verification_uri: String,
82 },
83}
84
85#[derive(Debug, Clone, PartialEq, Eq)]
87pub struct SignedIn {
88 pub login: String,
89 pub token: Secret,
90}
91
92pub trait Pending: Send {
94 fn finish(self: Box<Self>, cancel: &Cancel) -> Result<SignedIn, AuthError>;
97}
98
99pub struct Started {
101 pub prompt: Prompt,
102 pub pending: Box<dyn Pending>,
103}
104
105pub trait Authenticator: Send + Sync {
107 fn start(&self) -> Result<Started, AuthError>;
108 fn revoke(&self, token: &Secret);
110}
111
112#[derive(Debug, Clone)]
114pub struct GitHubOAuth {
115 client: OAuthClient,
116 endpoints: Endpoints,
117 time_limit: Duration,
118}
119
120impl GitHubOAuth {
121 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 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
159pub(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
172pub(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}