Skip to content
Open
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions cot/src/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -685,6 +685,50 @@ impl ToDbValue for PasswordHash {
}
}

#[cfg(feature = "db")]
impl FromDbValue for Option<PasswordHash> {
#[cfg(feature = "sqlite")]
fn from_sqlite(value: crate::db::impl_sqlite::SqliteValueRef<'_>) -> cot::db::Result<Self> {
value
.get::<Option<String>>()
.map(|op_str| op_str.map(PasswordHash::new))?
.transpose()
.map_err(cot::db::DatabaseError::value_decode)
}

#[cfg(feature = "postgres")]
fn from_postgres(
value: crate::db::impl_postgres::PostgresValueRef<'_>,
) -> cot::db::Result<Self> {
value
.get::<Option<String>>()
.map(|op_str| op_str.map(PasswordHash::new))?
.transpose()
.map_err(cot::db::DatabaseError::value_decode)
}

#[cfg(feature = "mysql")]
fn from_mysql(value: crate::db::impl_mysql::MySqlValueRef<'_>) -> crate::db::Result<Self>
where
Self: Sized,
{
value
.get::<Option<String>>()
.map(|op_str| op_str.map(PasswordHash::new))?
.transpose()
.map_err(cot::db::DatabaseError::value_decode)
}
}

impl ToDbValue for Option<PasswordHash> {
fn to_db_value(&self) -> DbValue {
match self {
Some(hash) => hash.to_db_value(),
None => <Option<String>>::None.to_db_value(),
}
}
}

/// Authentication helper structure.
///
/// This is an object that provides methods to sign users in and out, by using
Expand Down
84 changes: 84 additions & 0 deletions cot/src/common_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -393,6 +393,47 @@ impl FromDbValue for Url {
}
}

impl FromDbValue for Option<Url> {
fn from_sqlite(value: SqliteValueRef<'_>) -> cot::db::Result<Self>
where
Self: Sized,
{
value
.get::<Option<String>>()
.map(|opt_str| opt_str.map(Url::new))?
.transpose()
.map_err(cot::db::DatabaseError::value_decode)
}

fn from_postgres(value: PostgresValueRef<'_>) -> cot::db::Result<Self>
where
Self: Sized,
{
value
.get::<Option<String>>()
.map(|opt_str| opt_str.map(Url::new))?
.transpose()
.map_err(cot::db::DatabaseError::value_decode)
}

fn from_mysql(value: MySqlValueRef<'_>) -> cot::db::Result<Self>
where
Self: Sized,
{
value
.get::<Option<String>>()
.map(|opt_str| opt_str.map(Url::new))?
.transpose()
.map_err(cot::db::DatabaseError::value_decode)
}
}

impl ToDbValue for Option<Url> {
fn to_db_value(&self) -> DbValue {
self.clone().map(|url| url.into_string()).into()
}
}

#[cfg(feature = "db")]
impl DatabaseField for Url {
const TYPE: ColumnType = ColumnType::Text;
Expand Down Expand Up @@ -683,6 +724,49 @@ impl FromDbValue for Email {
}
}

#[cfg(feature = "db")]
impl ToDbValue for Option<Email> {
fn to_db_value(&self) -> DbValue {
self.clone().map(|email| email.email()).into()
}
}

#[cfg(feature = "db")]
impl FromDbValue for Option<Email> {
fn from_sqlite(value: SqliteValueRef<'_>) -> cot::db::Result<Self>
where
Self: Sized,
{
value
.get::<Option<String>>()
.map(|opt_str| opt_str.map(Email::new))?
.transpose()
.map_err(cot::db::DatabaseError::value_decode)
}

fn from_postgres(value: PostgresValueRef<'_>) -> cot::db::Result<Self>
where
Self: Sized,
{
value
.get::<Option<String>>()
.map(|opt_str| opt_str.map(Email::new))?
.transpose()
.map_err(cot::db::DatabaseError::value_decode)
}

fn from_mysql(value: MySqlValueRef<'_>) -> cot::db::Result<Self>
where
Self: Sized,
{
value
.get::<Option<String>>()
.map(|opt_str| opt_str.map(Email::new))?
.transpose()
.map_err(cot::db::DatabaseError::value_decode)
}
}

/// Defines the database field type for `Email`.
///
/// Emails are stored as strings with a maximum length of 254 characters,
Expand Down
29 changes: 29 additions & 0 deletions cot/src/db/fields.rs
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,35 @@ impl<const LIMIT: u32> ToDbValue for Option<LimitedString<LIMIT>> {
}
}

impl<const LIMIT: u32> FromDbValue for Option<LimitedString<LIMIT>> {
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's very arguable that duplication of impl code can be abstracted into the impl_db_field macro. I'm still accessing this. My main concern is prioritizing code readability and reducing the number of special cases when improving the macro to support most cases.

#[cfg(feature = "sqlite")]
fn from_sqlite(value: SqliteValueRef<'_>) -> Result<Self> {
value
.get::<Option<String>>()
.map(|opt_str| opt_str.map(LimitedString::new))?
.transpose()
.map_err(DatabaseError::value_decode)
}

#[cfg(feature = "postgres")]
fn from_postgres(value: PostgresValueRef<'_>) -> Result<Self> {
value
.get::<Option<String>>()
.map(|opt_str| opt_str.map(LimitedString::new))?
.transpose()
.map_err(DatabaseError::value_decode)
}

#[cfg(feature = "mysql")]
fn from_mysql(value: MySqlValueRef<'_>) -> Result<Self> {
value
.get::<Option<String>>()
.map(|opt_str| opt_str.map(LimitedString::new))?
.transpose()
.map_err(DatabaseError::value_decode)
}
}

impl<T: Model + Send + Sync> DatabaseField for ForeignKey<T> {
const NULLABLE: bool = T::PrimaryKey::NULLABLE;
const TYPE: ColumnType = T::PrimaryKey::TYPE;
Expand Down
85 changes: 85 additions & 0 deletions cot/tests/db.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
#![cfg(feature = "fake")]
#![cfg_attr(miri, ignore)]

use cot::auth::PasswordHash;
use cot::common_types::{Email, Password, Url};
use cot::db::migrations::{Field, Operation};
use cot::db::query::ExprEq;
use cot::db::{
Expand Down Expand Up @@ -39,6 +41,31 @@
}
}

struct EmailFaker;

impl Dummy<EmailFaker> for Email {
fn dummy_with_rng<R: fake::rand::Rng + ?Sized>(_: &EmailFaker, rng: &mut R) -> Self {
let username: String = (0..10)
.map(|_| (0x61u8 + (rng.next_u32() % 26) as u8) as char)
.collect();
let domain: String = (0..10)
.map(|_| (0x61u8 + (rng.next_u32() % 26) as u8) as char)
.collect();
Email::new(format!("{}@{}.com", username, domain)).expect("Generated email should be valid")
}
}

struct UrlFaker;

impl Dummy<UrlFaker> for Url {
fn dummy_with_rng<R: RngExt + ?Sized>(config: &UrlFaker, rng: &mut R) -> Self {
let domain: String = (0..10)
.map(|_| (0x61u8 + (rng.next_u32() % 26) as u8) as char)
.collect();
Url::new(format!("https://{}.com", domain)).expect("Generated URL should be valid")
}
}

#[derive(Debug, PartialEq)]
#[model]
struct TestModel {
Expand Down Expand Up @@ -221,8 +248,17 @@
field_blob: Vec<u8>,
field_option: Option<String>,
field_limited_string: LimitedString<10>,
field_option_limited_string: Option<LimitedString<10>>,
#[dummy(faker = "WeekdaySetFaker")]
field_weekday_set: chrono::WeekdaySet,
#[dummy(faker = "EmailFaker")]
field_email: Email,
#[dummy(faker = "EmailFaker")]
field_option_email: Option<Email>,
#[dummy(faker = "UrlFaker")]
field_url: Url,
#[dummy(faker = "UrlFaker")]
field_option_url: Option<Url>,
}

async fn migrate_all_fields_model(db: &Database) {
Expand Down Expand Up @@ -254,7 +290,13 @@
all_fields_migration_field!(blob, Vec<u8>),
all_fields_migration_field!(option, Option<String>),
all_fields_migration_field!(limited_string, LimitedString<10>),
all_fields_migration_field!(option_limited_string, Option<LimitedString<10>>),
all_fields_migration_field!(weekday_set, chrono::WeekdaySet),
all_fields_migration_field!(email, Email),
all_fields_migration_field!(option_email, Option<Email>),
all_fields_migration_field!(url, Url),
all_fields_migration_field!(option_url, Option<Url>),
all_fields_migration_field!(option_password_hash, Option<PasswordHash>),
])
.build();

Expand Down Expand Up @@ -315,6 +357,49 @@
};
}

#[cot_macros::dbtest]
async fn password_hash_field(db: &TestDatabase) {
#[derive(Debug, Clone)]
#[model]
struct OptionPasswordHashModel {
#[model(primary_key)]
id: Auto<i32>,
password: Option<PasswordHash>,
}

const CREATE_OPTIONAL_PASSWORD_HASH_MODEL: Operation = Operation::create_model()
.table_name(Identifier::new("cot__option_password_hash_model"))
.fields(&[
Field::new(Identifier::new("id"), <Auto<i32> as DatabaseField>::TYPE)
.primary_key()
.auto(),
Field::new(
Identifier::new("password"),
<Option<PasswordHash> as DatabaseField>::TYPE,
)
.set_null(<Option<PasswordHash> as DatabaseField>::NULLABLE),
])
.build();

run_migrations!(db, CREATE_OPTIONAL_PASSWORD_HASH_MODEL);

let mut with_password = OptionPasswordHashModel {
id: Auto::auto(),
password: Some(PasswordHash::from_password(&Password::new("password123"))),

Check failure

Code scanning / CodeQL

Hard-coded cryptographic value Critical test

This hard-coded value is used as
a password
.
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
};
with_password.save(&**db).await.unwrap();

let mut without_password = OptionPasswordHashModel {
id: Auto::auto(),
password: None,
};
without_password.save(&**db).await.unwrap();

let models = OptionPasswordHashModel::objects().all(&**db).await.unwrap();

assert_eq!(models.len(), 2);
}

#[cot_macros::dbtest]
async fn foreign_keys(db: &mut TestDatabase) {
#[derive(Debug, Clone, PartialEq)]
Expand Down
Loading