api.rs

  1pub mod events;
  2pub mod extensions;
  3pub mod ips_file;
  4pub mod slack;
  5
  6use crate::{
  7    auth,
  8    db::{ContributorSelector, User, UserId},
  9    rpc, AppState, Error, Result,
 10};
 11use anyhow::anyhow;
 12use axum::{
 13    body::Body,
 14    extract::{self, Path, Query},
 15    http::{self, Request, StatusCode},
 16    middleware::{self, Next},
 17    response::IntoResponse,
 18    routing::{get, post},
 19    Extension, Json, Router,
 20};
 21use axum_extra::response::ErasedJson;
 22use chrono::SecondsFormat;
 23use serde::{Deserialize, Serialize};
 24use std::sync::Arc;
 25use tower::ServiceBuilder;
 26
 27pub use extensions::fetch_extensions_from_blob_store_periodically;
 28
 29pub fn routes(rpc_server: Option<Arc<rpc::Server>>, state: Arc<AppState>) -> Router<(), Body> {
 30    Router::new()
 31        .route("/user", get(get_authenticated_user))
 32        .route("/users/:id/access_tokens", post(create_access_token))
 33        .route("/rpc_server_snapshot", get(get_rpc_server_snapshot))
 34        .route("/contributors", get(get_contributors).post(add_contributor))
 35        .route("/contributor", get(check_is_contributor))
 36        .layer(
 37            ServiceBuilder::new()
 38                .layer(Extension(state))
 39                .layer(Extension(rpc_server))
 40                .layer(middleware::from_fn(validate_api_token)),
 41        )
 42}
 43
 44pub async fn validate_api_token<B>(req: Request<B>, next: Next<B>) -> impl IntoResponse {
 45    let token = req
 46        .headers()
 47        .get(http::header::AUTHORIZATION)
 48        .and_then(|header| header.to_str().ok())
 49        .ok_or_else(|| {
 50            Error::Http(
 51                StatusCode::BAD_REQUEST,
 52                "missing authorization header".to_string(),
 53            )
 54        })?
 55        .strip_prefix("token ")
 56        .ok_or_else(|| {
 57            Error::Http(
 58                StatusCode::BAD_REQUEST,
 59                "invalid authorization header".to_string(),
 60            )
 61        })?;
 62
 63    let state = req.extensions().get::<Arc<AppState>>().unwrap();
 64
 65    if token != state.config.api_token {
 66        Err(Error::Http(
 67            StatusCode::UNAUTHORIZED,
 68            "invalid authorization token".to_string(),
 69        ))?
 70    }
 71
 72    Ok::<_, Error>(next.run(req).await)
 73}
 74
 75#[derive(Debug, Deserialize)]
 76struct AuthenticatedUserParams {
 77    github_user_id: Option<i32>,
 78    github_login: String,
 79    github_email: Option<String>,
 80}
 81
 82#[derive(Debug, Serialize)]
 83struct AuthenticatedUserResponse {
 84    user: User,
 85    metrics_id: String,
 86}
 87
 88async fn get_authenticated_user(
 89    Query(params): Query<AuthenticatedUserParams>,
 90    Extension(app): Extension<Arc<AppState>>,
 91) -> Result<Json<AuthenticatedUserResponse>> {
 92    let initial_channel_id = app.config.auto_join_channel_id;
 93
 94    let user = app
 95        .db
 96        .get_or_create_user_by_github_account(
 97            &params.github_login,
 98            params.github_user_id,
 99            params.github_email.as_deref(),
100            initial_channel_id,
101        )
102        .await?;
103    let metrics_id = app.db.get_user_metrics_id(user.id).await?;
104    return Ok(Json(AuthenticatedUserResponse { user, metrics_id }));
105}
106
107#[derive(Deserialize, Debug)]
108struct CreateUserParams {
109    github_user_id: i32,
110    github_login: String,
111    email_address: String,
112    email_confirmation_code: Option<String>,
113    #[serde(default)]
114    admin: bool,
115    #[serde(default)]
116    invite_count: i32,
117}
118
119#[derive(Serialize, Debug)]
120struct CreateUserResponse {
121    user: User,
122    signup_device_id: Option<String>,
123    metrics_id: String,
124}
125
126async fn get_rpc_server_snapshot(
127    Extension(rpc_server): Extension<Option<Arc<rpc::Server>>>,
128) -> Result<ErasedJson> {
129    let Some(rpc_server) = rpc_server else {
130        return Err(Error::Internal(anyhow!("rpc server is not available")));
131    };
132
133    Ok(ErasedJson::pretty(rpc_server.snapshot().await))
134}
135
136async fn get_contributors(Extension(app): Extension<Arc<AppState>>) -> Result<Json<Vec<String>>> {
137    Ok(Json(app.db.get_contributors().await?))
138}
139
140#[derive(Debug, Deserialize)]
141struct CheckIsContributorParams {
142    github_user_id: Option<i32>,
143    github_login: Option<String>,
144}
145
146impl CheckIsContributorParams {
147    fn as_contributor_selector(self) -> Result<ContributorSelector> {
148        if let Some(github_user_id) = self.github_user_id {
149            return Ok(ContributorSelector::GitHubUserId { github_user_id });
150        }
151
152        if let Some(github_login) = self.github_login {
153            return Ok(ContributorSelector::GitHubLogin { github_login });
154        }
155
156        Err(anyhow!(
157            "must be one of `github_user_id` or `github_login`."
158        ))?
159    }
160}
161
162#[derive(Debug, Serialize)]
163struct CheckIsContributorResponse {
164    signed_at: Option<String>,
165}
166
167async fn check_is_contributor(
168    Extension(app): Extension<Arc<AppState>>,
169    Query(params): Query<CheckIsContributorParams>,
170) -> Result<Json<CheckIsContributorResponse>> {
171    let params = params.as_contributor_selector()?;
172    Ok(Json(CheckIsContributorResponse {
173        signed_at: app
174            .db
175            .get_contributor_sign_timestamp(&params)
176            .await?
177            .map(|ts| ts.and_utc().to_rfc3339_opts(SecondsFormat::Millis, true)),
178    }))
179}
180
181async fn add_contributor(
182    Extension(app): Extension<Arc<AppState>>,
183    extract::Json(params): extract::Json<AuthenticatedUserParams>,
184) -> Result<()> {
185    let initial_channel_id = app.config.auto_join_channel_id;
186    app.db
187        .add_contributor(
188            &params.github_login,
189            params.github_user_id,
190            params.github_email.as_deref(),
191            initial_channel_id,
192        )
193        .await
194}
195
196#[derive(Deserialize)]
197struct CreateAccessTokenQueryParams {
198    public_key: String,
199    impersonate: Option<String>,
200}
201
202#[derive(Serialize)]
203struct CreateAccessTokenResponse {
204    user_id: UserId,
205    encrypted_access_token: String,
206}
207
208async fn create_access_token(
209    Path(user_id): Path<UserId>,
210    Query(params): Query<CreateAccessTokenQueryParams>,
211    Extension(app): Extension<Arc<AppState>>,
212) -> Result<Json<CreateAccessTokenResponse>> {
213    let user = app
214        .db
215        .get_user_by_id(user_id)
216        .await?
217        .ok_or_else(|| anyhow!("user not found"))?;
218
219    let mut impersonated_user_id = None;
220    if let Some(impersonate) = params.impersonate {
221        if user.admin {
222            if let Some(impersonated_user) = app.db.get_user_by_github_login(&impersonate).await? {
223                impersonated_user_id = Some(impersonated_user.id);
224            } else {
225                return Err(Error::Http(
226                    StatusCode::UNPROCESSABLE_ENTITY,
227                    format!("user {impersonate} does not exist"),
228                ));
229            }
230        } else {
231            return Err(Error::Http(
232                StatusCode::UNAUTHORIZED,
233                "you do not have permission to impersonate other users".to_string(),
234            ));
235        }
236    }
237
238    let access_token =
239        auth::create_access_token(app.db.as_ref(), user_id, impersonated_user_id).await?;
240    let encrypted_access_token =
241        auth::encrypt_access_token(&access_token, params.public_key.clone())?;
242
243    Ok(Json(CreateAccessTokenResponse {
244        user_id: impersonated_user_id.unwrap_or(user_id),
245        encrypted_access_token,
246    }))
247}