1use crate::{
2 db::{self, AccessTokenId, Database, UserId},
3 AppState, Error, Result,
4};
5use anyhow::{anyhow, Context};
6use axum::{
7 http::{self, Request, StatusCode},
8 middleware::Next,
9 response::IntoResponse,
10};
11use lazy_static::lazy_static;
12use prometheus::{exponential_buckets, register_histogram, Histogram};
13use rand::thread_rng;
14use scrypt::{
15 password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString},
16 Scrypt,
17};
18use serde::{Deserialize, Serialize};
19use std::{sync::Arc, time::Instant};
20
21lazy_static! {
22 static ref METRIC_ACCESS_TOKEN_HASHING_TIME: Histogram = register_histogram!(
23 "access_token_hashing_time",
24 "time spent hashing access tokens",
25 exponential_buckets(10.0, 2.0, 10).unwrap(),
26 )
27 .unwrap();
28}
29
30pub async fn validate_header<B>(mut req: Request<B>, next: Next<B>) -> impl IntoResponse {
31 let mut auth_header = req
32 .headers()
33 .get(http::header::AUTHORIZATION)
34 .and_then(|header| header.to_str().ok())
35 .ok_or_else(|| {
36 Error::Http(
37 StatusCode::UNAUTHORIZED,
38 "missing authorization header".to_string(),
39 )
40 })?
41 .split_whitespace();
42
43 let user_id = UserId(auth_header.next().unwrap_or("").parse().map_err(|_| {
44 Error::Http(
45 StatusCode::BAD_REQUEST,
46 "missing user id in authorization header".to_string(),
47 )
48 })?);
49
50 let access_token = auth_header.next().ok_or_else(|| {
51 Error::Http(
52 StatusCode::BAD_REQUEST,
53 "missing access token in authorization header".to_string(),
54 )
55 })?;
56
57 let state = req.extensions().get::<Arc<AppState>>().unwrap();
58 let credentials_valid = if let Some(admin_token) = access_token.strip_prefix("ADMIN_TOKEN:") {
59 state.config.api_token == admin_token
60 } else {
61 verify_access_token(&access_token, user_id, &state.db)
62 .await
63 .unwrap_or(false)
64 };
65
66 if credentials_valid {
67 let user = state
68 .db
69 .get_user_by_id(user_id)
70 .await?
71 .ok_or_else(|| anyhow!("user {} not found", user_id))?;
72 req.extensions_mut().insert(user);
73 Ok::<_, Error>(next.run(req).await)
74 } else {
75 Err(Error::Http(
76 StatusCode::UNAUTHORIZED,
77 "invalid credentials".to_string(),
78 ))
79 }
80}
81
82const MAX_ACCESS_TOKENS_TO_STORE: usize = 8;
83
84#[derive(Serialize, Deserialize)]
85struct AccessTokenJson {
86 version: usize,
87 id: AccessTokenId,
88 token: String,
89}
90
91pub async fn create_access_token(db: &db::Database, user_id: UserId) -> Result<String> {
92 const VERSION: usize = 1;
93 let access_token = rpc::auth::random_token();
94 let access_token_hash =
95 hash_access_token(&access_token).context("failed to hash access token")?;
96 let id = db
97 .create_access_token(user_id, &access_token_hash, MAX_ACCESS_TOKENS_TO_STORE)
98 .await?;
99 Ok(serde_json::to_string(&AccessTokenJson {
100 version: VERSION,
101 id,
102 token: access_token,
103 })?)
104}
105
106fn hash_access_token(token: &str) -> Result<String> {
107 // Avoid slow hashing in debug mode.
108 let params = if cfg!(debug_assertions) {
109 scrypt::Params::new(1, 1, 1).unwrap()
110 } else {
111 scrypt::Params::new(14, 8, 1).unwrap()
112 };
113
114 Ok(Scrypt
115 .hash_password(
116 token.as_bytes(),
117 None,
118 params,
119 &SaltString::generate(thread_rng()),
120 )
121 .map_err(anyhow::Error::new)?
122 .to_string())
123}
124
125pub fn encrypt_access_token(access_token: &str, public_key: String) -> Result<String> {
126 let native_app_public_key =
127 rpc::auth::PublicKey::try_from(public_key).context("failed to parse app public key")?;
128 let encrypted_access_token = native_app_public_key
129 .encrypt_string(access_token)
130 .context("failed to encrypt access token with public key")?;
131 Ok(encrypted_access_token)
132}
133
134pub async fn verify_access_token(token: &str, user_id: UserId, db: &Arc<Database>) -> Result<bool> {
135 let token: AccessTokenJson = serde_json::from_str(&token)?;
136
137 let db_token = db.get_access_token(token.id).await?;
138 if db_token.user_id != user_id {
139 return Err(anyhow!("no such access token"))?;
140 }
141
142 let db_hash = PasswordHash::new(&db_token.hash).map_err(anyhow::Error::new)?;
143 let t0 = Instant::now();
144 let is_valid = Scrypt
145 .verify_password(token.token.as_bytes(), &db_hash)
146 .is_ok();
147 let duration = t0.elapsed();
148 log::info!("hashed access token in {:?}", duration);
149 METRIC_ACCESS_TOKEN_HASHING_TIME.observe(duration.as_millis() as f64);
150 Ok(is_valid)
151}