Compare commits

..

No commits in common. "b3870cd48a6c4c901ceedc2940204ea7effebfa7" and "35a4d00e77736c009d5c6b7bb8dafa5d111ef7b7" have entirely different histories.

9 changed files with 80 additions and 235 deletions

53
Cargo.lock generated
View file

@ -2083,28 +2083,6 @@ 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"
@ -2636,7 +2614,6 @@ dependencies = [
"tracing", "tracing",
"tracing-subscriber", "tracing-subscriber",
"uuid", "uuid",
"validator",
] ]
[[package]] [[package]]
@ -3210,36 +3187,6 @@ 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,4 +34,3 @@ 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,7 +2,6 @@ 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 {
@ -25,12 +24,6 @@ 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,19 +42,14 @@ impl Channel {
} }
#[auto_type(no_type_alias)] #[auto_type(no_type_alias)]
pub fn with_id<'a>(channel_id: &'a Uuid) -> _ { pub fn with_id(channel_id: 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<'a>(team_id: &'a Uuid) -> _ { pub fn with_team(team_id: 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, insert_into, AsSelect}, dsl::{auto_type, AsSelect},
pg::Pg, pg::Pg,
prelude::*, prelude::*,
sql_types::Timestamptz, sql_types::Timestamptz,
@ -28,25 +28,6 @@ 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,6 +1,5 @@
use anyhow::Result;
use diesel::{ use diesel::{
dsl::{auto_type, insert_into, AsSelect, Eq}, dsl::{auto_type, AsSelect, Eq},
pg::Pg, pg::Pg,
prelude::*, prelude::*,
}; };
@ -12,8 +11,6 @@ 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))]
@ -24,34 +21,6 @@ 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, DEFAULT_PROJECT_NAME}, projects::Project,
schema::{self, channel_selections, channels}, schema::{self, channel_selections, channels},
settings::Settings, settings::Settings,
team_memberships::TeamMembership, team_memberships::TeamMembership,
@ -213,16 +213,15 @@ async fn post_new_team(
user_id: current_user.id, user_id: current_user.id,
}; };
db_conn db_conn
.interact::<_, Result<(), AppError>>(move |conn| { .interact(move |conn| {
conn.transaction::<(), AppError, _>(move |conn| { conn.transaction(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)?;
Project::insert_new(conn, &team.id, DEFAULT_PROJECT_NAME)?; diesel::QueryResult::Ok(())
Ok(())
}) })
}) })
.await .await
@ -287,18 +286,12 @@ 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 channels = { let team_filter = Channel::with_team(team_id);
let team_id = team_id.clone(); let channels = db_conn
db_conn .interact(move |conn| Channel::all().filter(team_filter).load(conn))
.interact(move |conn| { .await
Channel::all() .unwrap()
.filter(Channel::with_team(&team_id)) .context("Failed to load channels list.")?;
.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()
@ -386,27 +379,25 @@ 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 channel = { let id_filter = Channel::with_id(channel_id);
let channel_id = channel_id.clone(); let team_filter = Channel::with_team(team_id.clone());
let team_id = team_id.clone(); let channel = match db_conn
match db_conn .interact(move |conn| {
.interact(move |conn| { Channel::all()
Channel::all() .filter(id_filter)
.filter(Channel::with_id(&channel_id)) .filter(team_filter)
.filter(Channel::with_team(&team_id)) .first(conn)
.first(conn) .optional()
.optional() })
}) .await
.await .unwrap()?
.unwrap()? {
{ None => {
None => { 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(), ));
));
}
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?;
@ -466,27 +457,21 @@ 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 updated_rows = { let id_filter = Channel::with_id(channel_id.clone());
let channel_id = channel_id.clone(); let team_filter = Channel::with_team(team_id.clone());
let team_id = team_id.clone(); let updated_rows = db_conn
db_conn .interact(move |conn| {
.interact(move |conn| { update(channels::table.filter(id_filter).filter(team_filter))
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(),
@ -505,10 +490,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<'a>( fn get_channel_by_params(
conn: &mut PgConnection, conn: &mut PgConnection,
team_id: &'a Uuid, team_id: Uuid,
channel_id: &'a Uuid, channel_id: 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))
@ -566,14 +551,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 {
@ -656,7 +641,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(
@ -681,7 +666,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(())
@ -737,18 +722,12 @@ async fn project_page(
.map(|channel| channel.id) .map(|channel| channel.id)
.collect(); .collect();
let team_channels = { let team_filter = Channel::with_team(team.id.clone());
let team_id = team.id.clone(); let team_channels = db_conn
db_conn .interact(move |conn| Channel::all().filter(team_filter).load(conn))
.interact(move |conn| { .await
Channel::all() .unwrap()
.filter(Channel::with_team(&team_id)) .context("failed to load team channels")?;
.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, Environment}; use config::{Config, ConfigError, Environment};
use dotenvy::dotenv; use dotenvy::dotenv;
use serde::Deserialize; use serde::Deserialize;

View file

@ -1,5 +1,3 @@
use std::sync::LazyLock;
use anyhow::Context; use anyhow::Context;
use axum::{ use axum::{
extract::Query, extract::Query,
@ -9,11 +7,9 @@ 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,
@ -21,51 +17,29 @@ use crate::{
app_state::{AppState, DbConn}, app_state::{AppState, DbConn},
channels::Channel, channels::Channel,
governors::Governor, governors::Governor,
projects::{Project, DEFAULT_PROJECT_NAME}, projects::Project,
schema::{api_keys, messages}, schema::{api_keys, governors, messages, projects},
}; };
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, Validate)] #[derive(Deserialize)]
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(mut query): Query<SayQuery>, Query(query): Query<SayQuery>,
) -> Result<impl IntoResponse, AppError> { ) -> Result<impl IntoResponse, AppError> {
query.project = query.project.to_lowercase().replace(" ", "_"); // TODO: do some validation of message contents
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
@ -83,7 +57,7 @@ async fn say_get(
}; };
let project = { let project = {
let project_name = query.project.clone(); let project_name = query.project.to_lowercase();
db_conn db_conn
.interact::<_, Result<Project, AppError>>(move |conn| { .interact::<_, Result<Project, AppError>>(move |conn| {
conn.transaction(move |conn| { conn.transaction(move |conn| {
@ -96,7 +70,13 @@ async fn say_get(
.context("failed to load project")? .context("failed to load project")?
{ {
Some(project) => project, Some(project) => project,
None => Project::insert_new(conn, &api_key.team_id, &project_name) 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)
.context("failed to insert project")?, .context("failed to insert project")?,
}, },
) )
@ -120,14 +100,16 @@ 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
Governor::insert_new( Ok(diesel::insert_into(governors::table)
conn, .values((
&team_id, governors::team_id.eq(team_id),
None, governors::id.eq(Uuid::now_v7()),
&TimeDelta::seconds(TEAM_GOVERNOR_DEFAULT_WINDOW_SIZE_SEC), governors::project_id.eq(None as Option<Uuid>),
TEAM_GOVERNOR_DEFAULT_MAX_COUNT, governors::window_size
) .eq(TimeDelta::seconds(TEAM_GOVERNOR_DEFAULT_WINDOW_SIZE_SEC)),
.map_err(Into::into) governors::max_count.eq(TEAM_GOVERNOR_DEFAULT_MAX_COUNT),
))
.get_result(conn)?)
} }
diesel::QueryResult::Err(err) => Err(err.into()), diesel::QueryResult::Err(err) => Err(err.into()),
} }