auth.rs

  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::{StatusCode, 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            let mut response = tide::Response::new(StatusCode::Unauthorized);
 77            response.set_body("invalid credentials");
 78            Ok(response)
 79        }
 80    }
 81}
 82
 83#[async_trait]
 84pub trait RequestExt {
 85    async fn current_user(&self) -> tide::Result<Option<User>>;
 86}
 87
 88#[async_trait]
 89impl RequestExt for Request {
 90    async fn current_user(&self) -> tide::Result<Option<User>> {
 91        if let Some(details) = self.session().get::<github::User>(CURRENT_GITHUB_USER) {
 92            let user = self.db().get_user_by_github_login(&details.login).await?;
 93            Ok(Some(User {
 94                github_login: details.login,
 95                avatar_url: details.avatar_url,
 96                is_insider: user.is_some(),
 97                is_admin: user.map_or(false, |user| user.admin),
 98            }))
 99        } else {
100            Ok(None)
101        }
102    }
103}
104
105pub fn build_client(client_id: &str, client_secret: &str) -> Client {
106    Client::new(
107        ClientId::new(client_id.to_string()),
108        Some(oauth2::ClientSecret::new(client_secret.to_string())),
109        AuthUrl::new(GITHUB_AUTH_URL.into()).unwrap(),
110        Some(TokenUrl::new(GITHUB_TOKEN_URL.into()).unwrap()),
111    )
112}
113
114pub fn add_routes(app: &mut Server<Arc<AppState>>) {
115    app.at("/sign_in").get(get_sign_in);
116    app.at("/sign_out").post(post_sign_out);
117    app.at("/auth_callback").get(get_auth_callback);
118}
119
120#[derive(Debug, Deserialize)]
121struct NativeAppSignInParams {
122    native_app_port: String,
123    native_app_public_key: String,
124}
125
126async fn get_sign_in(mut request: Request) -> tide::Result {
127    let (pkce_challenge, pkce_verifier) = PkceCodeChallenge::new_random_sha256();
128
129    request
130        .session_mut()
131        .insert("pkce_verifier", pkce_verifier)?;
132
133    let mut redirect_url = Url::parse(&format!(
134        "{}://{}/auth_callback",
135        request
136            .header("X-Forwarded-Proto")
137            .and_then(|values| values.get(0))
138            .map(|value| value.as_str())
139            .unwrap_or("http"),
140        request.host().unwrap()
141    ))?;
142
143    let app_sign_in_params: Option<NativeAppSignInParams> = request.query().ok();
144    if let Some(query) = app_sign_in_params {
145        redirect_url
146            .query_pairs_mut()
147            .clear()
148            .append_pair("native_app_port", &query.native_app_port)
149            .append_pair("native_app_public_key", &query.native_app_public_key);
150    }
151
152    let (auth_url, csrf_token) = request
153        .state()
154        .auth_client
155        .authorize_url(CsrfToken::new_random)
156        .set_redirect_uri(Cow::Owned(RedirectUrl::from_url(redirect_url)))
157        .set_pkce_challenge(pkce_challenge)
158        .url();
159
160    request
161        .session_mut()
162        .insert("auth_csrf_token", csrf_token)?;
163
164    Ok(tide::Redirect::new(auth_url).into())
165}
166
167async fn get_auth_callback(mut request: Request) -> tide::Result {
168    #[derive(Debug, Deserialize)]
169    struct Query {
170        code: String,
171        state: String,
172
173        #[serde(flatten)]
174        native_app_sign_in_params: Option<NativeAppSignInParams>,
175    }
176
177    let query: Query = request.query()?;
178
179    let pkce_verifier = request
180        .session()
181        .get("pkce_verifier")
182        .ok_or_else(|| anyhow!("could not retrieve pkce_verifier from session"))?;
183
184    let csrf_token = request
185        .session()
186        .get::<CsrfToken>("auth_csrf_token")
187        .ok_or_else(|| anyhow!("could not retrieve auth_csrf_token from session"))?;
188
189    if &query.state != csrf_token.secret() {
190        return Err(anyhow!("csrf token does not match").into());
191    }
192
193    let github_access_token = request
194        .state()
195        .auth_client
196        .exchange_code(AuthorizationCode::new(query.code))
197        .set_pkce_verifier(pkce_verifier)
198        .request_async(oauth2_surf::http_client)
199        .await
200        .context("failed to exchange oauth code")?
201        .access_token()
202        .secret()
203        .clone();
204
205    let user_details = request
206        .state()
207        .github_client
208        .user(github_access_token)
209        .details()
210        .await
211        .context("failed to fetch user")?;
212
213    let user = request
214        .db()
215        .get_user_by_github_login(&user_details.login)
216        .await?;
217
218    request
219        .session_mut()
220        .insert(CURRENT_GITHUB_USER, user_details.clone())?;
221
222    // When signing in from the native app, generate a new access token for the current user. Return
223    // a redirect so that the user's browser sends this access token to the locally-running app.
224    if let Some((user, app_sign_in_params)) = user.zip(query.native_app_sign_in_params) {
225        let access_token = create_access_token(request.db(), user.id).await?;
226        let native_app_public_key =
227            zed_auth::PublicKey::try_from(app_sign_in_params.native_app_public_key.clone())
228                .context("failed to parse app public key")?;
229        let encrypted_access_token = native_app_public_key
230            .encrypt_string(&access_token)
231            .context("failed to encrypt access token with public key")?;
232
233        return Ok(tide::Redirect::new(&format!(
234            "http://127.0.0.1:{}?user_id={}&access_token={}",
235            app_sign_in_params.native_app_port, user.id.0, encrypted_access_token,
236        ))
237        .into());
238    }
239
240    Ok(tide::Redirect::new("/").into())
241}
242
243async fn post_sign_out(mut request: Request) -> tide::Result {
244    request.session_mut().remove(CURRENT_GITHUB_USER);
245    Ok(tide::Redirect::new("/").into())
246}
247
248pub async fn create_access_token(db: &db::Db, user_id: UserId) -> tide::Result<String> {
249    let access_token = zed_auth::random_token();
250    let access_token_hash =
251        hash_access_token(&access_token).context("failed to hash access token")?;
252    db.create_access_token_hash(user_id, access_token_hash)
253        .await?;
254    Ok(access_token)
255}
256
257fn hash_access_token(token: &str) -> tide::Result<String> {
258    // Avoid slow hashing in debug mode.
259    let params = if cfg!(debug_assertions) {
260        scrypt::Params::new(1, 1, 1).unwrap()
261    } else {
262        scrypt::Params::recommended()
263    };
264
265    Ok(Scrypt
266        .hash_password(
267            token.as_bytes(),
268            None,
269            params,
270            &SaltString::generate(thread_rng()),
271        )?
272        .to_string())
273}
274
275pub fn verify_access_token(token: &str, hash: &str) -> tide::Result<bool> {
276    let hash = PasswordHash::new(hash)?;
277    Ok(Scrypt.verify_password(token.as_bytes(), &hash).is_ok())
278}