Compare commits

..

3 commits

9 changed files with 235 additions and 80 deletions

53
Cargo.lock generated
View file

@ -2083,6 +2083,28 @@ dependencies = [
"vcpkg", "vcpkg",
] ]
[[package]]
name = "proc-macro-error-attr2"
version = "2.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "96de42df36bb9bba5542fe9f1a054b8cc87e172759a1868aa05c1f3acc89dfc5"
dependencies = [
"proc-macro2",
"quote",
]
[[package]]
name = "proc-macro-error2"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "11ec05c52be0a07b08061f7dd003e7d7092e0472bc731b4af7bb1ef876109802"
dependencies = [
"proc-macro-error-attr2",
"proc-macro2",
"quote",
"syn",
]
[[package]] [[package]]
name = "proc-macro2" name = "proc-macro2"
version = "1.0.89" version = "1.0.89"
@ -2614,6 +2636,7 @@ dependencies = [
"tracing", "tracing",
"tracing-subscriber", "tracing-subscriber",
"uuid", "uuid",
"validator",
] ]
[[package]] [[package]]
@ -3187,6 +3210,36 @@ dependencies = [
"wasm-bindgen", "wasm-bindgen",
] ]
[[package]]
name = "validator"
version = "0.20.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "43fb22e1a008ece370ce08a3e9e4447a910e92621bb49b85d6e48a45397e7cfa"
dependencies = [
"idna 1.0.3",
"once_cell",
"regex",
"serde",
"serde_derive",
"serde_json",
"url",
"validator_derive",
]
[[package]]
name = "validator_derive"
version = "0.20.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7df16e474ef958526d1205f6dda359fdfab79d9aa6d54bafcb92dcd07673dca"
dependencies = [
"darling",
"once_cell",
"proc-macro-error2",
"proc-macro2",
"quote",
"syn",
]
[[package]] [[package]]
name = "valuable" name = "valuable"
version = "0.1.0" version = "0.1.0"

View file

@ -34,3 +34,4 @@ regex = "1.11.1"
lettre = { version = "0.11.12", features = ["tokio1", "serde", "tracing", "tokio1-native-tls"] } lettre = { version = "0.11.12", features = ["tokio1", "serde", "tracing", "tokio1-native-tls"] }
clap = { version = "4.5.31", features = ["derive"] } clap = { version = "4.5.31", features = ["derive"] }
diesel_migrations = { version = "2.2.0", features = ["postgres"] } diesel_migrations = { version = "2.2.0", features = ["postgres"] }
validator = { version = "0.20.0", features = ["derive"] }

View file

@ -2,6 +2,7 @@ use std::fmt::{self, Display};
use axum::http::StatusCode; use axum::http::StatusCode;
use axum::response::{IntoResponse, Redirect, Response}; use axum::response::{IntoResponse, Redirect, Response};
use validator::ValidationErrors;
#[derive(Debug)] #[derive(Debug)]
pub struct AuthRedirectInfo { pub struct AuthRedirectInfo {
@ -24,6 +25,12 @@ impl AppError {
pub fn auth_redirect_from_base_path(base_path: String) -> Self { pub fn auth_redirect_from_base_path(base_path: String) -> Self {
Self::AuthRedirect(AuthRedirectInfo { base_path }) Self::AuthRedirect(AuthRedirectInfo { base_path })
} }
pub fn from_validation_errors(errs: ValidationErrors) -> Self {
Self::BadRequestError(
serde_json::to_string(&errs).unwrap_or("validation error".to_string()),
)
}
} }
// Tell axum how to convert `AppError` into a response. // Tell axum how to convert `AppError` into a response.

View file

@ -42,14 +42,19 @@ impl Channel {
} }
#[auto_type(no_type_alias)] #[auto_type(no_type_alias)]
pub fn with_id(channel_id: Uuid) -> _ { pub fn with_id<'a>(channel_id: &'a Uuid) -> _ {
channels::id.eq(channel_id) channels::id.eq(channel_id)
} }
#[auto_type(no_type_alias)] #[auto_type(no_type_alias)]
pub fn with_team(team_id: Uuid) -> _ { pub fn with_team<'a>(team_id: &'a Uuid) -> _ {
channels::team_id.eq(team_id) channels::team_id.eq(team_id)
} }
#[auto_type(no_type_alias)]
pub fn where_enabled_by_default() -> _ {
channels::enable_by_default.eq(true)
}
} }
/** /**

View file

@ -3,7 +3,7 @@
use anyhow::Result; use anyhow::Result;
use chrono::{DateTime, TimeDelta, Utc}; use chrono::{DateTime, TimeDelta, Utc};
use diesel::{ use diesel::{
dsl::{auto_type, AsSelect}, dsl::{auto_type, insert_into, AsSelect},
pg::Pg, pg::Pg,
prelude::*, prelude::*,
sql_types::Timestamptz, sql_types::Timestamptz,
@ -28,6 +28,25 @@ pub struct Governor {
} }
impl Governor { impl Governor {
pub fn insert_new<'a>(
db_conn: &mut diesel::PgConnection,
team_id: &'a Uuid,
project_id: Option<&'a Uuid>,
window_size: &'a TimeDelta,
max_count: i32,
) -> Result<Self> {
let id: Uuid = Uuid::now_v7();
Ok(insert_into(governors::table)
.values((
governors::team_id.eq(team_id),
governors::id.eq(id),
governors::project_id.eq(project_id),
governors::window_size.eq(window_size),
governors::max_count.eq(max_count),
))
.get_result(db_conn)?)
}
#[auto_type(no_type_alias)] #[auto_type(no_type_alias)]
pub fn all() -> _ { pub fn all() -> _ {
let select: AsSelect<Governor, Pg> = Governor::as_select(); let select: AsSelect<Governor, Pg> = Governor::as_select();

View file

@ -1,5 +1,6 @@
use anyhow::Result;
use diesel::{ use diesel::{
dsl::{auto_type, AsSelect, Eq}, dsl::{auto_type, insert_into, AsSelect, Eq},
pg::Pg, pg::Pg,
prelude::*, prelude::*,
}; };
@ -11,6 +12,8 @@ use crate::{
teams::Team, teams::Team,
}; };
pub const DEFAULT_PROJECT_NAME: &'static str = "default";
#[derive(Associations, Clone, Debug, Identifiable, Insertable, Queryable, Selectable)] #[derive(Associations, Clone, Debug, Identifiable, Insertable, Queryable, Selectable)]
#[diesel(table_name = projects)] #[diesel(table_name = projects)]
#[diesel(belongs_to(Team))] #[diesel(belongs_to(Team))]
@ -21,6 +24,34 @@ pub struct Project {
} }
impl Project { impl Project {
pub fn insert_new<'a>(
db_conn: &mut diesel::PgConnection,
team_id: &'a Uuid,
name: &'a str,
) -> Result<Self> {
let default_channels = Channel::all()
.filter(Channel::with_team(team_id))
.filter(Channel::where_enabled_by_default())
.load(db_conn)?;
let id: Uuid = Uuid::now_v7();
let project: Self = insert_into(projects::table)
.values((
projects::id.eq(id),
projects::team_id.eq(team_id),
projects::name.eq(name),
))
.get_result(db_conn)?;
for channel in default_channels {
insert_into(channel_selections::table)
.values((
channel_selections::project_id.eq(&project.id),
channel_selections::channel_id.eq(&channel.id),
))
.execute(db_conn)?;
}
Ok(project)
}
#[auto_type(no_type_alias)] #[auto_type(no_type_alias)]
pub fn all() -> _ { pub fn all() -> _ {
let select: AsSelect<Project, Pg> = Project::as_select(); let select: AsSelect<Project, Pg> = Project::as_select();

View file

@ -27,7 +27,7 @@ use crate::{
email::{MailSender as _, Mailer}, email::{MailSender as _, Mailer},
guards, guards,
nav_state::{Breadcrumb, NavState}, nav_state::{Breadcrumb, NavState},
projects::Project, projects::{Project, DEFAULT_PROJECT_NAME},
schema::{self, channel_selections, channels}, schema::{self, channel_selections, channels},
settings::Settings, settings::Settings,
team_memberships::TeamMembership, team_memberships::TeamMembership,
@ -213,15 +213,16 @@ async fn post_new_team(
user_id: current_user.id, user_id: current_user.id,
}; };
db_conn db_conn
.interact(move |conn| { .interact::<_, Result<(), AppError>>(move |conn| {
conn.transaction(move |conn| { conn.transaction::<(), AppError, _>(move |conn| {
insert_into(schema::teams::table) insert_into(schema::teams::table)
.values(team) .values(&team)
.execute(conn)?; .execute(conn)?;
insert_into(schema::team_memberships::table) insert_into(schema::team_memberships::table)
.values(team_membership) .values(&team_membership)
.execute(conn)?; .execute(conn)?;
diesel::QueryResult::Ok(()) Project::insert_new(conn, &team.id, DEFAULT_PROJECT_NAME)?;
Ok(())
}) })
}) })
.await .await
@ -286,12 +287,18 @@ async fn channels_page(
) -> Result<impl IntoResponse, AppError> { ) -> Result<impl IntoResponse, AppError> {
let team = guards::require_team_membership(&current_user, &team_id, &db_conn).await?; let team = guards::require_team_membership(&current_user, &team_id, &db_conn).await?;
let team_filter = Channel::with_team(team_id); let channels = {
let channels = db_conn let team_id = team_id.clone();
.interact(move |conn| Channel::all().filter(team_filter).load(conn)) db_conn
.await .interact(move |conn| {
.unwrap() Channel::all()
.context("Failed to load channels list.")?; .filter(Channel::with_team(&team_id))
.load(conn)
})
.await
.unwrap()
.context("Failed to load channels list.")?
};
let csrf_token = generate_csrf_token(&db_conn, Some(current_user.id.clone())).await?; let csrf_token = generate_csrf_token(&db_conn, Some(current_user.id.clone())).await?;
let nav_state = NavState::new() let nav_state = NavState::new()
@ -379,25 +386,27 @@ async fn channel_page(
) -> Result<impl IntoResponse, AppError> { ) -> Result<impl IntoResponse, AppError> {
let team = guards::require_team_membership(&current_user, &team_id, &db_conn).await?; let team = guards::require_team_membership(&current_user, &team_id, &db_conn).await?;
let id_filter = Channel::with_id(channel_id); let channel = {
let team_filter = Channel::with_team(team_id.clone()); let channel_id = channel_id.clone();
let channel = match db_conn let team_id = team_id.clone();
.interact(move |conn| { match db_conn
Channel::all() .interact(move |conn| {
.filter(id_filter) Channel::all()
.filter(team_filter) .filter(Channel::with_id(&channel_id))
.first(conn) .filter(Channel::with_team(&team_id))
.optional() .first(conn)
}) .optional()
.await })
.unwrap()? .await
{ .unwrap()?
None => { {
return Err(AppError::NotFoundError( None => {
"Channel with that team and ID not found".to_string(), return Err(AppError::NotFoundError(
)); "Channel with that team and ID not found".to_string(),
));
}
Some(channel) => channel,
} }
Some(channel) => channel,
}; };
let csrf_token = generate_csrf_token(&db_conn, Some(current_user.id.clone())).await?; let csrf_token = generate_csrf_token(&db_conn, Some(current_user.id.clone())).await?;
@ -457,21 +466,27 @@ async fn update_channel(
guards::require_valid_csrf_token(&form_body.csrf_token, &current_user, &db_conn).await?; guards::require_valid_csrf_token(&form_body.csrf_token, &current_user, &db_conn).await?;
guards::require_team_membership(&current_user, &team_id, &db_conn).await?; guards::require_team_membership(&current_user, &team_id, &db_conn).await?;
let id_filter = Channel::with_id(channel_id.clone()); let updated_rows = {
let team_filter = Channel::with_team(team_id.clone()); let channel_id = channel_id.clone();
let updated_rows = db_conn let team_id = team_id.clone();
.interact(move |conn| { db_conn
update(channels::table.filter(id_filter).filter(team_filter)) .interact(move |conn| {
update(
channels::table
.filter(Channel::with_id(&channel_id))
.filter(Channel::with_team(&team_id)),
)
.set(( .set((
channels::name.eq(form_body.name), channels::name.eq(form_body.name),
channels::enable_by_default channels::enable_by_default
.eq(form_body.enable_by_default.unwrap_or("false".to_string()) == "true"), .eq(form_body.enable_by_default.unwrap_or("false".to_string()) == "true"),
)) ))
.execute(conn) .execute(conn)
}) })
.await .await
.unwrap() .unwrap()
.context("Failed to load Channel while updating.")?; .context("Failed to load Channel while updating.")?
};
if updated_rows != 1 { if updated_rows != 1 {
return Err(AppError::NotFoundError( return Err(AppError::NotFoundError(
"Channel with that team and ID not found".to_string(), "Channel with that team and ID not found".to_string(),
@ -490,10 +505,10 @@ async fn update_channel(
* Helper function to query a channel from the database by ID and team, and * Helper function to query a channel from the database by ID and team, and
* return an appropriate error if no such channel exists. * return an appropriate error if no such channel exists.
*/ */
fn get_channel_by_params( fn get_channel_by_params<'a>(
conn: &mut PgConnection, conn: &mut PgConnection,
team_id: Uuid, team_id: &'a Uuid,
channel_id: Uuid, channel_id: &'a Uuid,
) -> Result<Channel, AppError> { ) -> Result<Channel, AppError> {
match Channel::all() match Channel::all()
.filter(Channel::with_id(channel_id)) .filter(Channel::with_id(channel_id))
@ -551,14 +566,14 @@ async fn update_channel_email_recipient(
.interact(move |conn| { .interact(move |conn| {
// TODO: transaction retries // TODO: transaction retries
conn.transaction::<_, AppError, _>(move |conn| { conn.transaction::<_, AppError, _>(move |conn| {
let channel = get_channel_by_params(conn, team_id, channel_id)?; let channel = get_channel_by_params(conn, &team_id, &channel_id)?;
let new_config = BackendConfig::Email(EmailBackendConfig { let new_config = BackendConfig::Email(EmailBackendConfig {
recipient, recipient,
verification_code, verification_code,
verification_code_guesses: 0, verification_code_guesses: 0,
..channel.backend_config.try_into()? ..channel.backend_config.try_into()?
}); });
let num_rows = update(channels::table.filter(Channel::with_id(channel.id))) let num_rows = update(channels::table.filter(Channel::with_id(&channel.id)))
.set(channels::backend_config.eq(new_config)) .set(channels::backend_config.eq(new_config))
.execute(conn)?; .execute(conn)?;
if num_rows != 1 { if num_rows != 1 {
@ -641,7 +656,7 @@ async fn verify_email(
db_conn db_conn
.interact(move |conn| { .interact(move |conn| {
conn.transaction::<(), AppError, _>(move |conn| { conn.transaction::<(), AppError, _>(move |conn| {
let channel = get_channel_by_params(conn, team_id, channel_id)?; let channel = get_channel_by_params(conn, &team_id, &channel_id)?;
let config: EmailBackendConfig = channel.backend_config.try_into()?; let config: EmailBackendConfig = channel.backend_config.try_into()?;
if config.verified { if config.verified {
return Err(AppError::BadRequestError( return Err(AppError::BadRequestError(
@ -666,7 +681,7 @@ async fn verify_email(
..config ..config
} }
}; };
update(channels::table.filter(Channel::with_id(channel_id))) update(channels::table.filter(Channel::with_id(&channel_id)))
.set(channels::backend_config.eq(Into::<BackendConfig>::into(new_config))) .set(channels::backend_config.eq(Into::<BackendConfig>::into(new_config)))
.execute(conn)?; .execute(conn)?;
Ok(()) Ok(())
@ -722,12 +737,18 @@ async fn project_page(
.map(|channel| channel.id) .map(|channel| channel.id)
.collect(); .collect();
let team_filter = Channel::with_team(team.id.clone()); let team_channels = {
let team_channels = db_conn let team_id = team.id.clone();
.interact(move |conn| Channel::all().filter(team_filter).load(conn)) db_conn
.await .interact(move |conn| {
.unwrap() Channel::all()
.context("failed to load team channels")?; .filter(Channel::with_team(&team_id))
.load(conn)
})
.await
.unwrap()
.context("failed to load team channels")?
};
let csrf_token = generate_csrf_token(&db_conn, Some(current_user.id)).await?; let csrf_token = generate_csrf_token(&db_conn, Some(current_user.id)).await?;
let nav_state = NavState::new() let nav_state = NavState::new()

View file

@ -1,6 +1,6 @@
use anyhow::{Context as _, Result}; use anyhow::{Context as _, Result};
use axum::extract::FromRef; use axum::extract::FromRef;
use config::{Config, ConfigError, Environment}; use config::{Config, Environment};
use dotenvy::dotenv; use dotenvy::dotenv;
use serde::Deserialize; use serde::Deserialize;

View file

@ -1,3 +1,5 @@
use std::sync::LazyLock;
use anyhow::Context; use anyhow::Context;
use axum::{ use axum::{
extract::Query, extract::Query,
@ -7,9 +9,11 @@ use axum::{
}; };
use chrono::TimeDelta; use chrono::TimeDelta;
use diesel::{dsl::insert_into, prelude::*, update}; use diesel::{dsl::insert_into, prelude::*, update};
use regex::Regex;
use serde::Deserialize; use serde::Deserialize;
use serde_json::json; use serde_json::json;
use uuid::Uuid; use uuid::Uuid;
use validator::Validate;
use crate::{ use crate::{
api_keys::ApiKey, api_keys::ApiKey,
@ -17,29 +21,51 @@ use crate::{
app_state::{AppState, DbConn}, app_state::{AppState, DbConn},
channels::Channel, channels::Channel,
governors::Governor, governors::Governor,
projects::Project, projects::{Project, DEFAULT_PROJECT_NAME},
schema::{api_keys, governors, messages, projects}, schema::{api_keys, messages},
}; };
const TEAM_GOVERNOR_DEFAULT_WINDOW_SIZE_SEC: i64 = 300; const TEAM_GOVERNOR_DEFAULT_WINDOW_SIZE_SEC: i64 = 300;
const TEAM_GOVERNOR_DEFAULT_MAX_COUNT: i32 = 50; const TEAM_GOVERNOR_DEFAULT_MAX_COUNT: i32 = 50;
static RE_PROJECT_NAME: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"^[a-z0-9_-]{1,100}$").unwrap());
pub fn new_router(state: AppState) -> Router<AppState> { pub fn new_router(state: AppState) -> Router<AppState> {
Router::new().route("/say", get(say_get)).with_state(state) Router::new().route("/say", get(say_get)).with_state(state)
} }
#[derive(Deserialize)] #[derive(Deserialize, Validate)]
struct SayQuery { struct SayQuery {
#[serde(alias = "k")]
key: Uuid, key: Uuid,
#[serde(alias = "p")]
#[serde(default = "default_project")]
#[validate(regex(
path = *RE_PROJECT_NAME,
message = "may be no more than 100 characters and contain only alphanumerics, -, and _",
))]
project: String, project: String,
#[serde(alias = "m")]
#[validate(length(
min = 1,
max = 2048,
message = "message must be non-empty and no larger than 2KiB"
))]
message: String, message: String,
} }
fn default_project() -> String {
DEFAULT_PROJECT_NAME.to_string()
}
async fn say_get( async fn say_get(
DbConn(db_conn): DbConn, DbConn(db_conn): DbConn,
Query(query): Query<SayQuery>, Query(mut query): Query<SayQuery>,
) -> Result<impl IntoResponse, AppError> { ) -> Result<impl IntoResponse, AppError> {
// TODO: do some validation of message contents query.project = query.project.to_lowercase().replace(" ", "_");
query.validate().map_err(AppError::from_validation_errors)?;
let api_key = { let api_key = {
let query_key = query.key.clone(); let query_key = query.key.clone();
db_conn db_conn
@ -57,7 +83,7 @@ async fn say_get(
}; };
let project = { let project = {
let project_name = query.project.to_lowercase(); let project_name = query.project.clone();
db_conn db_conn
.interact::<_, Result<Project, AppError>>(move |conn| { .interact::<_, Result<Project, AppError>>(move |conn| {
conn.transaction(move |conn| { conn.transaction(move |conn| {
@ -70,13 +96,7 @@ async fn say_get(
.context("failed to load project")? .context("failed to load project")?
{ {
Some(project) => project, Some(project) => project,
None => insert_into(projects::table) None => Project::insert_new(conn, &api_key.team_id, &project_name)
.values((
projects::id.eq(Uuid::now_v7()),
projects::team_id.eq(api_key.team_id),
projects::name.eq(project_name),
))
.get_result(conn)
.context("failed to insert project")?, .context("failed to insert project")?,
}, },
) )
@ -100,16 +120,14 @@ async fn say_get(
diesel::QueryResult::Ok(governor) => Ok(governor), diesel::QueryResult::Ok(governor) => Ok(governor),
diesel::QueryResult::Err(diesel::result::Error::NotFound) => { diesel::QueryResult::Err(diesel::result::Error::NotFound) => {
// Lazily initialize governor // Lazily initialize governor
Ok(diesel::insert_into(governors::table) Governor::insert_new(
.values(( conn,
governors::team_id.eq(team_id), &team_id,
governors::id.eq(Uuid::now_v7()), None,
governors::project_id.eq(None as Option<Uuid>), &TimeDelta::seconds(TEAM_GOVERNOR_DEFAULT_WINDOW_SIZE_SEC),
governors::window_size TEAM_GOVERNOR_DEFAULT_MAX_COUNT,
.eq(TimeDelta::seconds(TEAM_GOVERNOR_DEFAULT_WINDOW_SIZE_SEC)), )
governors::max_count.eq(TEAM_GOVERNOR_DEFAULT_MAX_COUNT), .map_err(Into::into)
))
.get_result(conn)?)
} }
diesel::QueryResult::Err(err) => Err(err.into()), diesel::QueryResult::Err(err) => Err(err.into()),
} }