Skip to content

Commit

Permalink
custom serdelizers to ensure minstring works
Browse files Browse the repository at this point in the history
  • Loading branch information
DougAnderson444 committed Sep 17, 2024
1 parent 55dc647 commit 8ec995d
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 4 deletions.
6 changes: 4 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions crates/seed-keeper-core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,8 @@ rand = "0.8.5"
thiserror = "1.0.51"
serde = { version = "1.0", features = ["derive"], optional = true }

[dev-dependencies]
serde_json = "1.0.128"

[features]
default = ["serde", "argon2/std"]
52 changes: 50 additions & 2 deletions crates/seed-keeper-core/src/credentials.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::{marker::PhantomData, ops::Deref};

use serde::{Deserialize, Serialize};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};

use crate::{
Expand Down Expand Up @@ -32,13 +32,31 @@ impl Credentials {
}
}

#[derive(Serialize, Deserialize, Default, Debug, Zeroize, ZeroizeOnDrop)]
#[derive(Default, Debug, Zeroize, ZeroizeOnDrop)]
pub struct MinString<const N: usize> {
#[zeroize]
value: String,
_marker: PhantomData<()>,
}

impl<const N: usize> Serialize for MinString<N> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&self.value)
}
}
impl<'de, const N: usize> Deserialize<'de> for MinString<N> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let value = String::deserialize(deserializer)?;
MinString::new(&value).map_err(serde::de::Error::custom)
}
}

impl<const N: usize> MinString<N> {
pub fn new(value: &str) -> Result<Self, error::Error> {
if value.len() >= N {
Expand Down Expand Up @@ -149,4 +167,34 @@ mod tests {

Ok(())
}

#[test]
fn test_json_credentials_roundtrip() -> Result<(), error::Error> {
let credentials = Credentials {
username: MinString::new("username")?,
password: MinString::new("password")?,
encrypted_seed: None,
};

let json = serde_json::to_string(&credentials).map_err(|e| e.to_string())?;

let credentials: Credentials = serde_json::from_str(&json).map_err(|e| e.to_string())?;

assert_eq!(credentials.username.value(), "username");
assert_eq!(credentials.password.value(), "password");

Ok(())
}

#[test]
fn it_fails_too_short() -> Result<(), String> {
let json = r#"{"username":"user","password":"pass","encrypted_seed":null}"#;

// it should deserialize the json
let credentialss: Result<Credentials, _> = serde_json::from_str(json);

assert!(credentialss.is_err());

Ok(())
}
}

0 comments on commit 8ec995d

Please sign in to comment.