1use super::{
2 db::{self, UserId},
3 errors::TideResultExt,
4};
5use crate::{github, AppState, Request, RequestExt as _};
6use anyhow::{anyhow, Context};
7use async_trait::async_trait;
8pub use oauth2::basic::BasicClient as Client;
9use oauth2::{
10 AuthUrl, AuthorizationCode, ClientId, CsrfToken, PkceCodeChallenge, RedirectUrl,
11 TokenResponse as _, TokenUrl,
12};
13use rand::thread_rng;
14use scrypt::{
15 password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString},
16 Scrypt,
17};
18use serde::{Deserialize, Serialize};
19use std::{borrow::Cow, convert::TryFrom, sync::Arc};
20use surf::Url;
21use tide::Server;
22use zrpc::auth as zed_auth;
23
24static CURRENT_GITHUB_USER: &'static str = "current_github_user";
25static GITHUB_AUTH_URL: &'static str = "https://github.com/login/oauth/authorize";
26static GITHUB_TOKEN_URL: &'static str = "https://github.com/login/oauth/access_token";
27
28#[derive(Serialize)]
29pub struct User {
30 pub github_login: String,
31 pub avatar_url: String,
32 pub is_insider: bool,
33 pub is_admin: bool,
34}
35
36pub struct VerifyToken;
37
38#[async_trait]
39impl tide::Middleware<Arc<AppState>> for VerifyToken {
40 async fn handle(
41 &self,
42 mut request: Request,
43 next: tide::Next<'_, Arc<AppState>>,
44 ) -> tide::Result {
45 let mut auth_header = request
46 .header("Authorization")
47 .ok_or_else(|| anyhow!("no authorization header"))?
48 .last()
49 .as_str()
50 .split_whitespace();
51
52 let user_id = UserId(
53 auth_header
54 .next()
55 .ok_or_else(|| anyhow!("missing user id in authorization header"))?
56 .parse()?,
57 );
58 let access_token = auth_header
59 .next()
60 .ok_or_else(|| anyhow!("missing access token in authorization header"))?;
61
62 let state = request.state().clone();
63
64 let mut credentials_valid = false;
65 for password_hash in state.db.get_access_token_hashes(user_id).await? {
66 if verify_access_token(&access_token, &password_hash)? {
67 credentials_valid = true;
68 break;
69 }
70 }
71
72 if credentials_valid {
73 request.set_ext(user_id);
74 Ok(next.run(request).await)
75 } else {
76 Err(anyhow!("invalid credentials").into())
77 }
78 }
79}
80
81#[async_trait]
82pub trait RequestExt {
83 async fn current_user(&self) -> tide::Result<Option<User>>;
84}
85
86#[async_trait]
87impl RequestExt for Request {
88 async fn current_user(&self) -> tide::Result<Option<User>> {
89 if let Some(details) = self.session().get::<github::User>(CURRENT_GITHUB_USER) {
90 let user = self.db().get_user_by_github_login(&details.login).await?;
91 Ok(Some(User {
92 github_login: details.login,
93 avatar_url: details.avatar_url,
94 is_insider: user.is_some(),
95 is_admin: user.map_or(false, |user| user.admin),
96 }))
97 } else {
98 Ok(None)
99 }
100 }
101}
102
103pub fn build_client(client_id: &str, client_secret: &str) -> Client {
104 Client::new(
105 ClientId::new(client_id.to_string()),
106 Some(oauth2::ClientSecret::new(client_secret.to_string())),
107 AuthUrl::new(GITHUB_AUTH_URL.into()).unwrap(),
108 Some(TokenUrl::new(GITHUB_TOKEN_URL.into()).unwrap()),
109 )
110}
111
112pub fn add_routes(app: &mut Server<Arc<AppState>>) {
113 app.at("/sign_in").get(get_sign_in);
114 app.at("/sign_out").post(post_sign_out);
115 app.at("/auth_callback").get(get_auth_callback);
116}
117
118#[derive(Debug, Deserialize)]
119struct NativeAppSignInParams {
120 native_app_port: String,
121 native_app_public_key: String,
122}
123
124async fn get_sign_in(mut request: Request) -> tide::Result {
125 let (pkce_challenge, pkce_verifier) = PkceCodeChallenge::new_random_sha256();
126
127 request
128 .session_mut()
129 .insert("pkce_verifier", pkce_verifier)?;
130
131 let mut redirect_url = Url::parse(&format!(
132 "{}://{}/auth_callback",
133 request
134 .header("X-Forwarded-Proto")
135 .and_then(|values| values.get(0))
136 .map(|value| value.as_str())
137 .unwrap_or("http"),
138 request.host().unwrap()
139 ))?;
140
141 let app_sign_in_params: Option<NativeAppSignInParams> = request.query().ok();
142 if let Some(query) = app_sign_in_params {
143 redirect_url
144 .query_pairs_mut()
145 .clear()
146 .append_pair("native_app_port", &query.native_app_port)
147 .append_pair("native_app_public_key", &query.native_app_public_key);
148 }
149
150 let (auth_url, csrf_token) = request
151 .state()
152 .auth_client
153 .authorize_url(CsrfToken::new_random)
154 .set_redirect_uri(Cow::Owned(RedirectUrl::from_url(redirect_url)))
155 .set_pkce_challenge(pkce_challenge)
156 .url();
157
158 request
159 .session_mut()
160 .insert("auth_csrf_token", csrf_token)?;
161
162 Ok(tide::Redirect::new(auth_url).into())
163}
164
165async fn get_auth_callback(mut request: Request) -> tide::Result {
166 #[derive(Debug, Deserialize)]
167 struct Query {
168 code: String,
169 state: String,
170
171 #[serde(flatten)]
172 native_app_sign_in_params: Option<NativeAppSignInParams>,
173 }
174
175 let query: Query = request.query()?;
176
177 let pkce_verifier = request
178 .session()
179 .get("pkce_verifier")
180 .ok_or_else(|| anyhow!("could not retrieve pkce_verifier from session"))?;
181
182 let csrf_token = request
183 .session()
184 .get::<CsrfToken>("auth_csrf_token")
185 .ok_or_else(|| anyhow!("could not retrieve auth_csrf_token from session"))?;
186
187 if &query.state != csrf_token.secret() {
188 return Err(anyhow!("csrf token does not match").into());
189 }
190
191 let github_access_token = request
192 .state()
193 .auth_client
194 .exchange_code(AuthorizationCode::new(query.code))
195 .set_pkce_verifier(pkce_verifier)
196 .request_async(oauth2_surf::http_client)
197 .await
198 .context("failed to exchange oauth code")?
199 .access_token()
200 .secret()
201 .clone();
202
203 let user_details = request
204 .state()
205 .github_client
206 .user(github_access_token)
207 .details()
208 .await
209 .context("failed to fetch user")?;
210
211 let user = request
212 .db()
213 .get_user_by_github_login(&user_details.login)
214 .await?;
215
216 request
217 .session_mut()
218 .insert(CURRENT_GITHUB_USER, user_details.clone())?;
219
220 // When signing in from the native app, generate a new access token for the current user. Return
221 // a redirect so that the user's browser sends this access token to the locally-running app.
222 if let Some((user, app_sign_in_params)) = user.zip(query.native_app_sign_in_params) {
223 let access_token = create_access_token(request.db(), user.id).await?;
224 let native_app_public_key =
225 zed_auth::PublicKey::try_from(app_sign_in_params.native_app_public_key.clone())
226 .context("failed to parse app public key")?;
227 let encrypted_access_token = native_app_public_key
228 .encrypt_string(&access_token)
229 .context("failed to encrypt access token with public key")?;
230
231 return Ok(tide::Redirect::new(&format!(
232 "http://127.0.0.1:{}?user_id={}&access_token={}",
233 app_sign_in_params.native_app_port, user.id.0, encrypted_access_token,
234 ))
235 .into());
236 }
237
238 Ok(tide::Redirect::new("/").into())
239}
240
241async fn post_sign_out(mut request: Request) -> tide::Result {
242 request.session_mut().remove(CURRENT_GITHUB_USER);
243 Ok(tide::Redirect::new("/").into())
244}
245
246pub async fn create_access_token(db: &db::Db, user_id: UserId) -> tide::Result<String> {
247 let access_token = zed_auth::random_token();
248 let access_token_hash =
249 hash_access_token(&access_token).context("failed to hash access token")?;
250 db.create_access_token_hash(user_id, access_token_hash)
251 .await?;
252 Ok(access_token)
253}
254
255fn hash_access_token(token: &str) -> tide::Result<String> {
256 // Avoid slow hashing in debug mode.
257 let params = if cfg!(debug_assertions) {
258 scrypt::Params::new(1, 1, 1).unwrap()
259 } else {
260 scrypt::Params::recommended()
261 };
262
263 Ok(Scrypt
264 .hash_password(
265 token.as_bytes(),
266 None,
267 params,
268 &SaltString::generate(thread_rng()),
269 )?
270 .to_string())
271}
272
273pub fn verify_access_token(token: &str, hash: &str) -> tide::Result<bool> {
274 let hash = PasswordHash::new(hash)?;
275 Ok(Scrypt.verify_password(token.as_bytes(), &hash).is_ok())
276}