Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(fingerprint): add fingerprint table and corresponding db interface #75

Merged
merged 15 commits into from
Feb 7, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
10 changes: 10 additions & 0 deletions Cargo.lock

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

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,8 @@ moka = { version = "0.12.1", features = ["future"], optional = true }

argh = "0.1.12"

nanoid = "0.4.0"

[dev-dependencies]
rand = "0.8.5"
criterion = "0.5.1"
Expand Down
3 changes: 3 additions & 0 deletions migrations/2024-02-06-064347_add-fingerprint-table/down.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
-- This file should undo anything in `up.sql`

DROP TABLE fingerprint;
8 changes: 8 additions & 0 deletions migrations/2024-02-06-064347_add-fingerprint-table/up.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
-- Your SQL goes here

CREATE TABLE fingerprint (
id SERIAL,
card_hash BYTEA UNIQUE NOT NULL,
card_fingerprint VARCHAR(64) NOT NULL,
PRIMARY KEY (card_hash)
);
14 changes: 14 additions & 0 deletions src/error/custom_error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,20 @@ pub enum HashDBError {
UnknownError,
}

#[derive(Debug, thiserror::Error)]
pub enum FingerprintDBError {
#[error("Error while connecting to database")]
DBError,
#[error("Error while finding element in the database")]
DBFilterError,
#[error("Error while inserting element in the database")]
DBInsertError,
#[error("Unpredictable error occurred")]
UnknownError,
#[error("Error while encoding data")]
EncodingError,
}

pub trait NotFoundError {
fn is_not_found(&self) -> bool;
}
Expand Down
33 changes: 33 additions & 0 deletions src/error/transforms.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,39 @@ impl<'a> From<&'a super::StorageError> for super::HashDBError {
}
}

error_transform!(super::StorageError => super::FingerprintDBError);
impl<'a> From<&'a super::StorageError> for super::FingerprintDBError {
fn from(value: &'a super::StorageError) -> Self {
match value {
super::StorageError::DBPoolError | super::StorageError::PoolClientFailure => {
Self::DBError
}
super::StorageError::FindError | super::StorageError::NotFoundError => {
Self::DBFilterError
}
super::StorageError::DecryptionError
| super::StorageError::EncryptionError
| super::StorageError::DeleteError => Self::UnknownError,
super::StorageError::InsertError => Self::DBInsertError,
}
}
}

error_transform!(super::CryptoError => super::FingerprintDBError);
impl<'a> From<&'a super::CryptoError> for super::FingerprintDBError {
fn from(value: &'a super::CryptoError) -> Self {
match value {
super::CryptoError::SerdeJsonError(_)
| super::CryptoError::JWError(_)
| super::CryptoError::InvalidData(_)
| super::CryptoError::NotImplemented
| super::CryptoError::EncryptionError
| super::CryptoError::DecryptionError => Self::UnknownError,
super::CryptoError::EncodingError(_) => Self::EncodingError,
}
}
}

error_transform!(super::CryptoError => super::HashDBError);
impl<'a> From<&'a super::CryptoError> for super::HashDBError {
fn from(value: &'a super::CryptoError) -> Self {
Expand Down
22 changes: 22 additions & 0 deletions src/storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,11 @@ use masking::{PeekInterface, Secret};
#[cfg(feature = "caching")]
pub mod caching;

pub mod consts;
pub mod db;
pub mod schema;
pub mod types;
pub mod utils;

pub trait State {}

Expand Down Expand Up @@ -183,3 +185,23 @@ pub trait HashInterface {
data_hash: Vec<u8>,
) -> Result<types::HashTable, ContainerError<Self::Error>>;
}

///
/// Fingerprint:
///
/// Interface providing functions to interface with the fingerprint table in database
#[async_trait::async_trait]
pub trait FingerprintInterface {
type Error;

async fn find_by_card_hash(
&self,
card_hash: Secret<&[u8]>,
) -> Result<Option<types::Fingerprint>, ContainerError<Self::Error>>;

async fn insert_fingerprint(
&self,
card: types::CardNumber,
hash_key: Secret<String>,
) -> Result<types::Fingerprint, ContainerError<Self::Error>>;
}
10 changes: 10 additions & 0 deletions src/storage/consts.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/// Characters to use for generating NanoID
pub(crate) const ALPHABETS: [char; 62] = [
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B',
'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
'V', 'W', 'X', 'Y', 'Z',
];

/// Number of characters in a generated ID
pub const ID_LENGTH: usize = 20;
57 changes: 56 additions & 1 deletion src/storage/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@ use masking::ExposeInterface;
use masking::Secret;

use crate::crypto::aes::{generate_aes256_key, GcmAes256};
use crate::crypto::sha::HmacSha512;
use crate::crypto::Encode;
use crate::error::{self, ContainerError, ResultContainerExt};

use super::types::StorageDecryption;
use super::types::StorageEncryption;
use super::{schema, types, LockerInterface, MerchantInterface, Storage};
use super::{consts, schema, types, utils, LockerInterface, MerchantInterface, Storage};

#[async_trait::async_trait]
impl MerchantInterface for Storage {
Expand Down Expand Up @@ -259,3 +261,56 @@ impl super::HashInterface for Storage {
}
}
}

#[async_trait::async_trait]
impl super::FingerprintInterface for Storage {
type Error = error::FingerprintDBError;

async fn find_by_card_hash(
&self,
card_hash: Secret<&[u8]>,
) -> Result<Option<types::Fingerprint>, ContainerError<Self::Error>> {
let mut conn = self.get_conn().await?;

let output: Result<_, diesel::result::Error> = types::Fingerprint::table()
.filter(schema::fingerprint::card_hash.eq(card_hash))
.get_result(&mut conn)
.await;

match output {
Ok(inner) => Ok(Some(inner)),
Err(inner_err) => match inner_err {
diesel::result::Error::NotFound => Ok(None),
error => Err(error).change_error(error::StorageError::FindError)?,
},
}
}
async fn insert_fingerprint(
&self,
card: types::CardNumber,
hash_key: Secret<String>,
) -> Result<types::Fingerprint, ContainerError<Self::Error>> {
let algo = HmacSha512::<1>::new(hash_key.expose().into_bytes().into());

let card_hash = algo.encode(card.into_bytes())?;

let output = self.find_by_card_hash(Secret::new(&card_hash)).await?;
match output {
Some(inner) => Ok(inner),
None => {
let mut conn = self.get_conn().await?;
let query = diesel::insert_into(types::Fingerprint::table()).values(
types::FingerprintTableNew {
card_hash: card_hash.into(),
card_fingerprint: utils::generate_id(consts::ID_LENGTH).into(),
},
);

Ok(query
.get_result(&mut conn)
.await
.change_error(error::StorageError::InsertError)?)
}
}
}
}
11 changes: 10 additions & 1 deletion src/storage/schema.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
// @generated automatically by Diesel CLI.

diesel::table! {
fingerprint (card_hash) {
id -> Int4,
card_hash -> Bytea,
#[max_length = 64]
card_fingerprint -> Varchar,
}
}

diesel::table! {
hash_table (hash_id) {
id -> Int4,
Expand Down Expand Up @@ -40,4 +49,4 @@ diesel::table! {
}
}

diesel::allow_tables_to_appear_in_same_query!(hash_table, locker, merchant,);
diesel::allow_tables_to_appear_in_same_query!(fingerprint, hash_table, locker, merchant,);
26 changes: 25 additions & 1 deletion src/storage/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use diesel::{
serialize::ToSql,
sql_types, AsExpression, Identifiable, Insertable, Queryable,
};
use masking::{ExposeInterface, Secret};
use masking::{ExposeInterface, PeekInterface, Secret};

use crate::crypto::{self, Encryption};

Expand Down Expand Up @@ -97,6 +97,30 @@ pub struct HashTable {
pub created_at: time::PrimitiveDateTime,
}

#[derive(Debug, Clone, Identifiable, Queryable)]
#[diesel(table_name = schema::fingerprint)]
pub struct Fingerprint {
pub id: i32,
pub card_hash: Secret<Vec<u8>>,
pub card_fingerprint: Secret<String>,
}

#[derive(Debug, serde::Deserialize)]
pub struct CardNumber(masking::StrongSecret<String>);
NishantJoshi00 marked this conversation as resolved.
Show resolved Hide resolved

impl CardNumber {
pub fn into_bytes(self) -> Vec<u8> {
self.0.peek().clone().into_bytes()
}
}

#[derive(Debug, Insertable)]
#[diesel(table_name = schema::fingerprint)]
pub(super) struct FingerprintTableNew {
pub card_hash: Secret<Vec<u8>>,
pub card_fingerprint: Secret<String>,
}

#[derive(Debug, Insertable)]
#[diesel(table_name = schema::hash_table)]
pub(super) struct HashTableNew {
Expand Down
5 changes: 5 additions & 0 deletions src/storage/utils.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
use crate::storage::consts;

pub fn generate_id(id_length: usize) -> String {
nanoid::nanoid!(id_length, &consts::ALPHABETS)
}
Loading