1use crate::{
2 db::{self, dev_server, AccessTokenId, Database, DevServerId, UserId},
3 rpc::Principal,
4 AppState, Error, Result,
5};
6use anyhow::{anyhow, Context};
7use axum::{
8 http::{self, Request, StatusCode},
9 middleware::Next,
10 response::IntoResponse,
11};
12use prometheus::{exponential_buckets, register_histogram, Histogram};
13pub use rpc::auth::random_token;
14use scrypt::{
15 password_hash::{PasswordHash, PasswordVerifier},
16 Scrypt,
17};
18use serde::{Deserialize, Serialize};
19use sha2::Digest;
20use std::sync::OnceLock;
21use std::{sync::Arc, time::Instant};
22use subtle::ConstantTimeEq;
23
24/// Validates the authorization header and adds an Extension<Principal> to the request.
25/// Authorization: <user-id> <token>
26/// <token> can be an access_token attached to that user, or an access token of an admin
27/// or (in development) the string ADMIN:<config.api_token>.
28/// Authorization: "dev-server-token" <token>
29pub async fn validate_header<B>(mut req: Request<B>, next: Next<B>) -> impl IntoResponse {
30 let mut auth_header = req
31 .headers()
32 .get(http::header::AUTHORIZATION)
33 .and_then(|header| header.to_str().ok())
34 .ok_or_else(|| {
35 Error::Http(
36 StatusCode::UNAUTHORIZED,
37 "missing authorization header".to_string(),
38 )
39 })?
40 .split_whitespace();
41
42 let state = req.extensions().get::<Arc<AppState>>().unwrap();
43
44 let first = auth_header.next().unwrap_or("");
45 if first == "dev-server-token" {
46 let dev_server_token = auth_header.next().ok_or_else(|| {
47 Error::Http(
48 StatusCode::BAD_REQUEST,
49 "missing dev-server-token token in authorization header".to_string(),
50 )
51 })?;
52 let dev_server = verify_dev_server_token(dev_server_token, &state.db)
53 .await
54 .map_err(|e| Error::Http(StatusCode::UNAUTHORIZED, format!("{}", e)))?;
55
56 req.extensions_mut()
57 .insert(Principal::DevServer(dev_server));
58 return Ok::<_, Error>(next.run(req).await);
59 }
60
61 let user_id = UserId(first.parse().map_err(|_| {
62 Error::Http(
63 StatusCode::BAD_REQUEST,
64 "missing user id in authorization header".to_string(),
65 )
66 })?);
67
68 let access_token = auth_header.next().ok_or_else(|| {
69 Error::Http(
70 StatusCode::BAD_REQUEST,
71 "missing access token in authorization header".to_string(),
72 )
73 })?;
74
75 // In development, allow impersonation using the admin API token.
76 // Don't allow this in production because we can't tell who is doing
77 // the impersonating.
78 let validate_result = if let (Some(admin_token), true) = (
79 access_token.strip_prefix("ADMIN_TOKEN:"),
80 state.config.is_development(),
81 ) {
82 Ok(VerifyAccessTokenResult {
83 is_valid: state.config.api_token == admin_token,
84 impersonator_id: None,
85 })
86 } else {
87 verify_access_token(&access_token, user_id, &state.db).await
88 };
89
90 if let Ok(validate_result) = validate_result {
91 if validate_result.is_valid {
92 let user = state
93 .db
94 .get_user_by_id(user_id)
95 .await?
96 .ok_or_else(|| anyhow!("user {} not found", user_id))?;
97
98 if let Some(impersonator_id) = validate_result.impersonator_id {
99 let admin = state
100 .db
101 .get_user_by_id(impersonator_id)
102 .await?
103 .ok_or_else(|| anyhow!("user {} not found", impersonator_id))?;
104 req.extensions_mut()
105 .insert(Principal::Impersonated { user, admin });
106 } else {
107 req.extensions_mut().insert(Principal::User(user));
108 };
109 return Ok::<_, Error>(next.run(req).await);
110 }
111 }
112
113 Err(Error::Http(
114 StatusCode::UNAUTHORIZED,
115 "invalid credentials".to_string(),
116 ))
117}
118
119const MAX_ACCESS_TOKENS_TO_STORE: usize = 8;
120
121#[derive(Serialize, Deserialize)]
122struct AccessTokenJson {
123 version: usize,
124 id: AccessTokenId,
125 token: String,
126}
127
128/// Creates a new access token to identify the given user. before returning it, you should
129/// encrypt it with the user's public key.
130pub async fn create_access_token(
131 db: &db::Database,
132 user_id: UserId,
133 impersonated_user_id: Option<UserId>,
134) -> Result<String> {
135 const VERSION: usize = 1;
136 let access_token = rpc::auth::random_token();
137 let access_token_hash = hash_access_token(&access_token);
138 let id = db
139 .create_access_token(
140 user_id,
141 impersonated_user_id,
142 &access_token_hash,
143 MAX_ACCESS_TOKENS_TO_STORE,
144 )
145 .await?;
146 Ok(serde_json::to_string(&AccessTokenJson {
147 version: VERSION,
148 id,
149 token: access_token,
150 })?)
151}
152
153/// Hashing prevents anyone with access to the database being able to login.
154/// As the token is randomly generated, we don't need to worry about scrypt-style
155/// protection.
156pub fn hash_access_token(token: &str) -> String {
157 let digest = sha2::Sha256::digest(token);
158 format!(
159 "$sha256${}",
160 base64::encode_config(digest, base64::URL_SAFE)
161 )
162}
163
164/// Encrypts the given access token with the given public key to avoid leaking it on the way
165/// to the client.
166pub fn encrypt_access_token(access_token: &str, public_key: String) -> Result<String> {
167 use rpc::auth::EncryptionFormat;
168
169 /// The encryption format to use for the access token.
170 ///
171 /// Currently we're using the original encryption format to avoid
172 /// breaking compatibility with older clients.
173 ///
174 /// Once enough clients are capable of decrypting the newer encryption
175 /// format we can start encrypting with `EncryptionFormat::V1`.
176 const ENCRYPTION_FORMAT: EncryptionFormat = EncryptionFormat::V0;
177
178 let native_app_public_key =
179 rpc::auth::PublicKey::try_from(public_key).context("failed to parse app public key")?;
180 let encrypted_access_token = native_app_public_key
181 .encrypt_string(access_token, ENCRYPTION_FORMAT)
182 .context("failed to encrypt access token with public key")?;
183 Ok(encrypted_access_token)
184}
185
186pub struct VerifyAccessTokenResult {
187 pub is_valid: bool,
188 pub impersonator_id: Option<UserId>,
189}
190
191/// Checks that the given access token is valid for the given user.
192pub async fn verify_access_token(
193 token: &str,
194 user_id: UserId,
195 db: &Arc<Database>,
196) -> Result<VerifyAccessTokenResult> {
197 static METRIC_ACCESS_TOKEN_HASHING_TIME: OnceLock<Histogram> = OnceLock::new();
198 let metric_access_token_hashing_time = METRIC_ACCESS_TOKEN_HASHING_TIME.get_or_init(|| {
199 register_histogram!(
200 "access_token_hashing_time",
201 "time spent hashing access tokens",
202 exponential_buckets(10.0, 2.0, 10).unwrap(),
203 )
204 .unwrap()
205 });
206
207 let token: AccessTokenJson = serde_json::from_str(&token)?;
208
209 let db_token = db.get_access_token(token.id).await?;
210 let token_user_id = db_token.impersonated_user_id.unwrap_or(db_token.user_id);
211 if token_user_id != user_id {
212 return Err(anyhow!("no such access token"))?;
213 }
214 let t0 = Instant::now();
215
216 let is_valid = if db_token.hash.starts_with("$scrypt$") {
217 let db_hash = PasswordHash::new(&db_token.hash).map_err(anyhow::Error::new)?;
218 Scrypt
219 .verify_password(token.token.as_bytes(), &db_hash)
220 .is_ok()
221 } else {
222 let token_hash = hash_access_token(&token.token);
223 db_token.hash.as_bytes().ct_eq(token_hash.as_ref()).into()
224 };
225
226 let duration = t0.elapsed();
227 log::info!("hashed access token in {:?}", duration);
228 metric_access_token_hashing_time.observe(duration.as_millis() as f64);
229
230 if is_valid && db_token.hash.starts_with("$scrypt$") {
231 let new_hash = hash_access_token(&token.token);
232 db.update_access_token_hash(db_token.id, &new_hash).await?;
233 }
234
235 Ok(VerifyAccessTokenResult {
236 is_valid,
237 impersonator_id: if db_token.impersonated_user_id.is_some() {
238 Some(db_token.user_id)
239 } else {
240 None
241 },
242 })
243}
244
245pub fn generate_dev_server_token(id: usize, access_token: String) -> String {
246 format!("{}.{}", id, access_token)
247}
248
249pub async fn verify_dev_server_token(
250 dev_server_token: &str,
251 db: &Arc<Database>,
252) -> anyhow::Result<dev_server::Model> {
253 let (id, token) = split_dev_server_token(dev_server_token)?;
254 let token_hash = hash_access_token(&token);
255 let server = db.get_dev_server(id).await?;
256
257 if server
258 .hashed_token
259 .as_bytes()
260 .ct_eq(token_hash.as_ref())
261 .into()
262 {
263 Ok(server)
264 } else {
265 Err(anyhow!("wrong token for dev server"))
266 }
267}
268
269// a dev_server_token has the format <id>.<base64>. This is to make them
270// relatively easy to copy/paste around.
271pub fn split_dev_server_token(dev_server_token: &str) -> anyhow::Result<(DevServerId, &str)> {
272 let mut parts = dev_server_token.splitn(2, '.');
273 let id = DevServerId(parts.next().unwrap_or_default().parse()?);
274 let token = parts
275 .next()
276 .ok_or_else(|| anyhow!("invalid dev server token format"))?;
277 Ok((id, token))
278}
279
280#[cfg(test)]
281mod test {
282 use rand::thread_rng;
283 use scrypt::password_hash::{PasswordHasher, SaltString};
284 use sea_orm::EntityTrait;
285
286 use super::*;
287 use crate::db::{access_token, NewUserParams};
288
289 #[gpui::test]
290 async fn test_verify_access_token(cx: &mut gpui::TestAppContext) {
291 let test_db = crate::db::TestDb::sqlite(cx.executor().clone());
292 let db = test_db.db();
293
294 let user = db
295 .create_user(
296 "example@example.com",
297 false,
298 NewUserParams {
299 github_login: "example".into(),
300 github_user_id: 1,
301 },
302 )
303 .await
304 .unwrap();
305
306 let token = create_access_token(&db, user.user_id, None).await.unwrap();
307 assert!(matches!(
308 verify_access_token(&token, user.user_id, &db)
309 .await
310 .unwrap(),
311 VerifyAccessTokenResult {
312 is_valid: true,
313 impersonator_id: None,
314 }
315 ));
316
317 let old_token = create_previous_access_token(user.user_id, None, &db)
318 .await
319 .unwrap();
320
321 let old_token_id = serde_json::from_str::<AccessTokenJson>(&old_token)
322 .unwrap()
323 .id;
324
325 let hash = db
326 .transaction(|tx| async move {
327 Ok(access_token::Entity::find_by_id(old_token_id)
328 .one(&*tx)
329 .await?)
330 })
331 .await
332 .unwrap()
333 .unwrap()
334 .hash;
335 assert!(hash.starts_with("$scrypt$"));
336
337 assert!(matches!(
338 verify_access_token(&old_token, user.user_id, &db)
339 .await
340 .unwrap(),
341 VerifyAccessTokenResult {
342 is_valid: true,
343 impersonator_id: None,
344 }
345 ));
346
347 let hash = db
348 .transaction(|tx| async move {
349 Ok(access_token::Entity::find_by_id(old_token_id)
350 .one(&*tx)
351 .await?)
352 })
353 .await
354 .unwrap()
355 .unwrap()
356 .hash;
357 assert!(hash.starts_with("$sha256$"));
358
359 assert!(matches!(
360 verify_access_token(&old_token, user.user_id, &db)
361 .await
362 .unwrap(),
363 VerifyAccessTokenResult {
364 is_valid: true,
365 impersonator_id: None,
366 }
367 ));
368
369 assert!(matches!(
370 verify_access_token(&token, user.user_id, &db)
371 .await
372 .unwrap(),
373 VerifyAccessTokenResult {
374 is_valid: true,
375 impersonator_id: None,
376 }
377 ));
378 }
379
380 async fn create_previous_access_token(
381 user_id: UserId,
382 impersonated_user_id: Option<UserId>,
383 db: &Database,
384 ) -> Result<String> {
385 let access_token = rpc::auth::random_token();
386 let access_token_hash = previous_hash_access_token(&access_token)?;
387 let id = db
388 .create_access_token(
389 user_id,
390 impersonated_user_id,
391 &access_token_hash,
392 MAX_ACCESS_TOKENS_TO_STORE,
393 )
394 .await?;
395 Ok(serde_json::to_string(&AccessTokenJson {
396 version: 1,
397 id,
398 token: access_token,
399 })?)
400 }
401
402 fn previous_hash_access_token(token: &str) -> Result<String> {
403 // Avoid slow hashing in debug mode.
404 let params = if cfg!(debug_assertions) {
405 scrypt::Params::new(1, 1, 1).unwrap()
406 } else {
407 scrypt::Params::new(14, 8, 1).unwrap()
408 };
409
410 Ok(Scrypt
411 .hash_password(
412 token.as_bytes(),
413 None,
414 params,
415 &SaltString::generate(thread_rng()),
416 )
417 .map_err(anyhow::Error::new)?
418 .to_string())
419 }
420}