api.rs

  1pub mod contributors;
  2pub mod events;
  3pub mod extensions;
  4pub mod ips_file;
  5pub mod slack;
  6
  7use crate::db::Database;
  8use crate::{
  9    AppState, Error, Result, auth,
 10    db::{User, UserId},
 11    rpc,
 12};
 13use anyhow::Context as _;
 14use axum::{
 15    Extension, Json, Router,
 16    body::Body,
 17    extract::{Path, Query},
 18    headers::Header,
 19    http::{self, HeaderName, Request, StatusCode},
 20    middleware::{self, Next},
 21    response::IntoResponse,
 22    routing::{get, post},
 23};
 24use axum_extra::response::ErasedJson;
 25use serde::{Deserialize, Serialize};
 26use std::sync::{Arc, OnceLock};
 27use tower::ServiceBuilder;
 28
 29pub use extensions::fetch_extensions_from_blob_store_periodically;
 30
 31pub struct CloudflareIpCountryHeader(String);
 32
 33impl Header for CloudflareIpCountryHeader {
 34    fn name() -> &'static HeaderName {
 35        static CLOUDFLARE_IP_COUNTRY_HEADER: OnceLock<HeaderName> = OnceLock::new();
 36        CLOUDFLARE_IP_COUNTRY_HEADER.get_or_init(|| HeaderName::from_static("cf-ipcountry"))
 37    }
 38
 39    fn decode<'i, I>(values: &mut I) -> Result<Self, axum::headers::Error>
 40    where
 41        Self: Sized,
 42        I: Iterator<Item = &'i axum::http::HeaderValue>,
 43    {
 44        let country_code = values
 45            .next()
 46            .ok_or_else(axum::headers::Error::invalid)?
 47            .to_str()
 48            .map_err(|_| axum::headers::Error::invalid())?;
 49
 50        Ok(Self(country_code.to_string()))
 51    }
 52
 53    fn encode<E: Extend<axum::http::HeaderValue>>(&self, _values: &mut E) {
 54        unimplemented!()
 55    }
 56}
 57
 58impl std::fmt::Display for CloudflareIpCountryHeader {
 59    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 60        write!(f, "{}", self.0)
 61    }
 62}
 63
 64pub struct SystemIdHeader(String);
 65
 66impl Header for SystemIdHeader {
 67    fn name() -> &'static HeaderName {
 68        static SYSTEM_ID_HEADER: OnceLock<HeaderName> = OnceLock::new();
 69        SYSTEM_ID_HEADER.get_or_init(|| HeaderName::from_static("x-zed-system-id"))
 70    }
 71
 72    fn decode<'i, I>(values: &mut I) -> Result<Self, axum::headers::Error>
 73    where
 74        Self: Sized,
 75        I: Iterator<Item = &'i axum::http::HeaderValue>,
 76    {
 77        let system_id = values
 78            .next()
 79            .ok_or_else(axum::headers::Error::invalid)?
 80            .to_str()
 81            .map_err(|_| axum::headers::Error::invalid())?;
 82
 83        Ok(Self(system_id.to_string()))
 84    }
 85
 86    fn encode<E: Extend<axum::http::HeaderValue>>(&self, _values: &mut E) {
 87        unimplemented!()
 88    }
 89}
 90
 91impl std::fmt::Display for SystemIdHeader {
 92    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 93        write!(f, "{}", self.0)
 94    }
 95}
 96
 97pub fn routes(rpc_server: Arc<rpc::Server>) -> Router<(), Body> {
 98    Router::new()
 99        .route("/users/look_up", get(look_up_user))
100        .route("/users/:id/access_tokens", post(create_access_token))
101        .route("/rpc_server_snapshot", get(get_rpc_server_snapshot))
102        .merge(contributors::router())
103        .layer(
104            ServiceBuilder::new()
105                .layer(Extension(rpc_server))
106                .layer(middleware::from_fn(validate_api_token)),
107        )
108}
109
110pub async fn validate_api_token<B>(req: Request<B>, next: Next<B>) -> impl IntoResponse {
111    let token = req
112        .headers()
113        .get(http::header::AUTHORIZATION)
114        .and_then(|header| header.to_str().ok())
115        .ok_or_else(|| {
116            Error::http(
117                StatusCode::BAD_REQUEST,
118                "missing authorization header".to_string(),
119            )
120        })?
121        .strip_prefix("token ")
122        .ok_or_else(|| {
123            Error::http(
124                StatusCode::BAD_REQUEST,
125                "invalid authorization header".to_string(),
126            )
127        })?;
128
129    let state = req.extensions().get::<Arc<AppState>>().unwrap();
130
131    if token != state.config.api_token {
132        Err(Error::http(
133            StatusCode::UNAUTHORIZED,
134            "invalid authorization token".to_string(),
135        ))?
136    }
137
138    Ok::<_, Error>(next.run(req).await)
139}
140
141#[derive(Debug, Deserialize)]
142struct LookUpUserParams {
143    identifier: String,
144}
145
146#[derive(Debug, Serialize)]
147struct LookUpUserResponse {
148    user: Option<User>,
149}
150
151async fn look_up_user(
152    Query(params): Query<LookUpUserParams>,
153    Extension(app): Extension<Arc<AppState>>,
154) -> Result<Json<LookUpUserResponse>> {
155    let user = resolve_identifier_to_user(&app.db, &params.identifier).await?;
156    let user = if let Some(user) = user {
157        match user {
158            UserOrId::User(user) => Some(user),
159            UserOrId::Id(id) => app.db.get_user_by_id(id).await?,
160        }
161    } else {
162        None
163    };
164
165    Ok(Json(LookUpUserResponse { user }))
166}
167
168enum UserOrId {
169    User(User),
170    Id(UserId),
171}
172
173async fn resolve_identifier_to_user(
174    db: &Arc<Database>,
175    identifier: &str,
176) -> Result<Option<UserOrId>> {
177    if let Some(identifier) = identifier.parse::<i32>().ok() {
178        let user = db.get_user_by_id(UserId(identifier)).await?;
179
180        return Ok(user.map(UserOrId::User));
181    }
182
183    if identifier.starts_with("cus_") {
184        let billing_customer = db
185            .get_billing_customer_by_stripe_customer_id(&identifier)
186            .await?;
187
188        return Ok(billing_customer.map(|billing_customer| UserOrId::Id(billing_customer.user_id)));
189    }
190
191    if identifier.starts_with("sub_") {
192        let billing_subscription = db
193            .get_billing_subscription_by_stripe_subscription_id(&identifier)
194            .await?;
195
196        if let Some(billing_subscription) = billing_subscription {
197            let billing_customer = db
198                .get_billing_customer_by_id(billing_subscription.billing_customer_id)
199                .await?;
200
201            return Ok(
202                billing_customer.map(|billing_customer| UserOrId::Id(billing_customer.user_id))
203            );
204        } else {
205            return Ok(None);
206        }
207    }
208
209    if identifier.contains('@') {
210        let user = db.get_user_by_email(identifier).await?;
211
212        return Ok(user.map(UserOrId::User));
213    }
214
215    if let Some(user) = db.get_user_by_github_login(identifier).await? {
216        return Ok(Some(UserOrId::User(user)));
217    }
218
219    Ok(None)
220}
221
222#[derive(Deserialize, Debug)]
223struct CreateUserParams {
224    github_user_id: i32,
225    github_login: String,
226    email_address: String,
227    email_confirmation_code: Option<String>,
228    #[serde(default)]
229    admin: bool,
230    #[serde(default)]
231    invite_count: i32,
232}
233
234async fn get_rpc_server_snapshot(
235    Extension(rpc_server): Extension<Arc<rpc::Server>>,
236) -> Result<ErasedJson> {
237    Ok(ErasedJson::pretty(rpc_server.snapshot().await))
238}
239
240#[derive(Deserialize)]
241struct CreateAccessTokenQueryParams {
242    public_key: String,
243    impersonate: Option<String>,
244}
245
246#[derive(Serialize)]
247struct CreateAccessTokenResponse {
248    user_id: UserId,
249    encrypted_access_token: String,
250}
251
252async fn create_access_token(
253    Path(user_id): Path<UserId>,
254    Query(params): Query<CreateAccessTokenQueryParams>,
255    Extension(app): Extension<Arc<AppState>>,
256) -> Result<Json<CreateAccessTokenResponse>> {
257    let user = app
258        .db
259        .get_user_by_id(user_id)
260        .await?
261        .context("user not found")?;
262
263    let mut impersonated_user_id = None;
264    if let Some(impersonate) = params.impersonate {
265        if user.admin {
266            if let Some(impersonated_user) = app.db.get_user_by_github_login(&impersonate).await? {
267                impersonated_user_id = Some(impersonated_user.id);
268            } else {
269                return Err(Error::http(
270                    StatusCode::UNPROCESSABLE_ENTITY,
271                    format!("user {impersonate} does not exist"),
272                ));
273            }
274        } else {
275            return Err(Error::http(
276                StatusCode::UNAUTHORIZED,
277                "you do not have permission to impersonate other users".to_string(),
278            ));
279        }
280    }
281
282    let access_token =
283        auth::create_access_token(app.db.as_ref(), user_id, impersonated_user_id).await?;
284    let encrypted_access_token =
285        auth::encrypt_access_token(&access_token, params.public_key.clone())?;
286
287    Ok(Json(CreateAccessTokenResponse {
288        user_id: impersonated_user_id.unwrap_or(user_id),
289        encrypted_access_token,
290    }))
291}