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