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",
]
[[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]]
name = "proc-macro2"
version = "1.0.89"
@ -2614,6 +2636,7 @@ dependencies = [
"tracing",
"tracing-subscriber",
"uuid",
"validator",
]
[[package]]
@ -3187,6 +3210,36 @@ dependencies = [
"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]]
name = "valuable"
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"] }
clap = { version = "4.5.31", features = ["derive"] }
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::response::{IntoResponse, Redirect, Response};
use validator::ValidationErrors;
#[derive(Debug)]
pub struct AuthRedirectInfo {
@ -24,6 +25,12 @@ impl AppError {
pub fn auth_redirect_from_base_path(base_path: String) -> Self {
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.

View file

@ -42,14 +42,19 @@ impl Channel {
}
#[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)
}
#[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)
}
#[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 chrono::{DateTime, TimeDelta, Utc};
use diesel::{
dsl::{auto_type, AsSelect},
dsl::{auto_type, insert_into, AsSelect},
pg::Pg,
prelude::*,
sql_types::Timestamptz,
@ -28,6 +28,25 @@ pub struct 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)]
pub fn all() -> _ {
let select: AsSelect<Governor, Pg> = Governor::as_select();

View file

@ -1,5 +1,6 @@
use anyhow::Result;
use diesel::{
dsl::{auto_type, AsSelect, Eq},
dsl::{auto_type, insert_into, AsSelect, Eq},
pg::Pg,
prelude::*,
};
@ -11,6 +12,8 @@ use crate::{
teams::Team,
};
pub const DEFAULT_PROJECT_NAME: &'static str = "default";
#[derive(Associations, Clone, Debug, Identifiable, Insertable, Queryable, Selectable)]
#[diesel(table_name = projects)]
#[diesel(belongs_to(Team))]
@ -21,6 +24,34 @@ pub struct 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)]
pub fn all() -> _ {
let select: AsSelect<Project, Pg> = Project::as_select();

View file

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

View file

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

View file

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