Skip to content

Commit

Permalink
feat(ch-app): Removed ApiResponse, fixed warnings and hid more doc_ty…
Browse files Browse the repository at this point in the history
…pe related functions
  • Loading branch information
schoenenberg committed Oct 16, 2023
1 parent 387498c commit fc710b7
Show file tree
Hide file tree
Showing 16 changed files with 95 additions and 304 deletions.
1 change: 1 addition & 0 deletions clearing-house-app/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -64,5 +64,6 @@ serial_test = "2.0.0"
tempfile = "3.8.0"

[features]
default = []
# Enables the doc_type API
doc_type = []
8 changes: 7 additions & 1 deletion clearing-house-app/src/db/key_store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ use super::DataStoreApi;
use crate::db::init_database_client;
use crate::model::constants::{
FILE_DEFAULT_DOC_TYPE, KEYRING_DB, KEYRING_DB_CLIENT, MONGO_COLL_DOC_TYPES,
MONGO_COLL_MASTER_KEY, MONGO_ID, MONGO_PID,
MONGO_COLL_MASTER_KEY, MONGO_ID
};
#[cfg(doc_type)]
use crate::model::constants::MONGO_PID;
use crate::model::crypto::MasterKey;
use crate::model::doc_type::DocumentType;
use anyhow::anyhow;
Expand Down Expand Up @@ -179,6 +181,7 @@ impl KeyStore {
}

//TODO: Do we need to check that no documents of this type exist before we remove it from the db?
#[cfg(doc_type)]
pub async fn delete_document_type(&self, id: &String, pid: &String) -> anyhow::Result<bool> {
let coll = self
.database
Expand All @@ -194,6 +197,7 @@ impl KeyStore {
}

/// checks if the model exits
#[cfg(doc_type)]
pub async fn exists_document_type(&self, pid: &String, dt_id: &String) -> anyhow::Result<bool> {
let coll = self
.database
Expand All @@ -214,6 +218,7 @@ impl KeyStore {
}
}

#[cfg(doc_type)]
pub async fn get_all_document_types(&self) -> anyhow::Result<Vec<DocumentType>> {
let coll = self
.database
Expand Down Expand Up @@ -241,6 +246,7 @@ impl KeyStore {
}
}

#[cfg(doc_type)]
pub async fn update_document_type(
&self,
doc_type: DocumentType,
Expand Down
22 changes: 0 additions & 22 deletions clearing-house-app/src/errors.rs

This file was deleted.

4 changes: 2 additions & 2 deletions clearing-house-app/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ use std::sync::Arc;
mod config;
mod crypto;
mod db;
mod errors;
mod model;
mod ports;
mod services;
Expand All @@ -24,6 +23,7 @@ mod util;
/// Contains the application state
#[derive(Clone)]
pub(crate) struct AppState {
#[cfg_attr(not(doc_type), allow(dead_code))]
pub keyring_service: Arc<services::keyring_service::KeyringService>,
pub logging_service: Arc<services::logging_service::LoggingService>,
pub service_config: Arc<ServiceConfig>,
Expand Down Expand Up @@ -92,7 +92,7 @@ async fn main() -> Result<(), anyhow::Error> {

// Bind port and start server
let addr = SocketAddr::from(([0, 0, 0, 0], 8000));
tracing::info!("Starting server: Listening on {}", addr);
info!("Starting server: Listening on {}", addr);
Ok(axum::Server::bind(&addr)
.serve(app.into_make_service())
.with_graceful_shutdown(util::shutdown_signal())
Expand Down
59 changes: 2 additions & 57 deletions clearing-house-app/src/model/claims.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ use crate::AppState;
use anyhow::Context;
use axum::extract::FromRef;
use axum::response::IntoResponse;
use chrono::{Duration, Utc};
use num_bigint::BigUint;
use ring::signature::KeyPair;
use std::env;
Expand All @@ -27,12 +26,6 @@ impl std::fmt::Display for ChClaims {
}
}

#[derive(Debug)]
pub enum ChClaimsError {
Missing,
Invalid,
}

pub struct ExtractChClaims(pub ChClaims);

#[async_trait::async_trait]
Expand Down Expand Up @@ -72,7 +65,8 @@ where
}

pub fn get_jwks(key_path: &str) -> Option<biscuit::jwk::JWKSet<biscuit::Empty>> {
let keypair = biscuit::jws::Secret::rsa_keypair_from_file(key_path).unwrap();
let keypair = biscuit::jws::Secret::rsa_keypair_from_file(key_path)
.unwrap_or_else(|_| panic!("Failed to load keyfile from path {key_path}"));

if let biscuit::jws::Secret::RsaKeyPair(a) = keypair {
let pk_modulus = BigUint::from_bytes_be(
Expand Down Expand Up @@ -134,55 +128,6 @@ pub fn get_fingerprint(key_path: &str) -> Option<String> {
}
}

pub fn create_service_token(issuer: &str, audience: &str, client_id: &str) -> String {
let private_claims = ChClaims::new(client_id);
create_token(issuer, audience, &private_claims)
}

pub fn create_token<
T: std::fmt::Display + Clone + serde::Serialize + for<'de> serde::Deserialize<'de>,
>(
issuer: &str,
audience: &str,
private_claims: &T,
) -> String {
let signing_secret = match env::var(ENV_SHARED_SECRET) {
Ok(secret) => biscuit::jws::Secret::Bytes(secret.to_string().into_bytes()),
Err(_) => {
panic!(
"Shared Secret not configured. Please configure environment variable {}",
ENV_SHARED_SECRET
);
}
};
let expiration_date = Utc::now() + Duration::minutes(5);

let claims = biscuit::ClaimsSet::<T> {
registered: biscuit::RegisteredClaims {
issuer: Some(issuer.to_string()),
issued_at: Some(biscuit::Timestamp::from(Utc::now())),
audience: Some(biscuit::SingleOrMultiple::Single(audience.to_string())),
expiry: Some(biscuit::Timestamp::from(expiration_date)),
..Default::default()
},
private: private_claims.clone(),
};

// Construct the JWT
let jwt = biscuit::jws::Compact::new_decoded(
From::from(biscuit::jws::RegisteredHeader {
algorithm: biscuit::jwa::SignatureAlgorithm::HS256,
..Default::default()
}),
claims,
);

jwt.into_encoded(&signing_secret)
.unwrap()
.unwrap_encoded()
.to_string()
}

pub fn decode_token<T: Clone + serde::Serialize + for<'de> serde::Deserialize<'de>>(
token: &str,
audience: &str,
Expand Down
2 changes: 2 additions & 0 deletions clearing-house-app/src/model/doc_type.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ pub struct DocumentType {
}

impl DocumentType {
#[cfg(test)]
pub fn new(id: String, pid: String, parts: Vec<DocumentTypePart>) -> DocumentType {
DocumentType { id, pid, parts }
}
Expand All @@ -17,6 +18,7 @@ pub struct DocumentTypePart {
}

impl DocumentTypePart {
#[cfg(test)]
pub fn new(name: String) -> DocumentTypePart {
DocumentTypePart { name }
}
Expand Down
14 changes: 0 additions & 14 deletions clearing-house-app/src/model/document.rs
Original file line number Diff line number Diff line change
Expand Up @@ -277,20 +277,6 @@ impl EncryptedDocument {
}
}

/// companion to format_pt_for_storage
pub fn restore_pt(pt: &str) -> anyhow::Result<(String, String, String)> {
trace!("Trying to restore plain text");
let vec: Vec<&str> = pt.split(SPLIT_CT).collect();
if vec.len() != 3 {
anyhow::bail!("Could not restore plaintext");
}
Ok((
String::from(vec[0]),
String::from(vec[1]),
String::from(vec[2]),
))
}

/// companion to format_pt_for_storage_no_dt
pub fn restore_pt_no_dt(pt: &str) -> anyhow::Result<(String, String)> {
trace!("Trying to restore plain text");
Expand Down
46 changes: 0 additions & 46 deletions clearing-house-app/src/model/ids/message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,6 @@ const SENDER_AGENT: &str = "sender_agent";
const PAYLOAD: &str = "payload";
const PAYLOAD_TYPE: &str = "payload_type";

pub const RESULT_MESSAGE: &str = "ResultMessage";
pub const REJECTION_MESSAGE: &str = "RejectionMessage";
pub const MESSAGE_PROC_NOTIFICATION_MESSAGE: &str = "MessageProcessedNotificationMessage";

/// Metadata describing payload exchanged by interacting Connectors.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct IdsMessage {
Expand Down Expand Up @@ -143,48 +139,6 @@ impl Default for IdsMessage {
}

impl IdsMessage {
pub fn processed(msg: IdsMessage) -> IdsMessage {
let mut message = IdsMessage::clone(msg);
message.id = Some(autogen(MESSAGE_PROC_NOTIFICATION_MESSAGE));
message.type_message = MessageType::MessageProcessedNotificationMessage;
message
}

pub fn return_result(msg: IdsMessage) -> IdsMessage {
let mut message = IdsMessage::clone(msg);
message.id = Some(autogen(RESULT_MESSAGE));
message.type_message = MessageType::ResultMessage;
message
}

pub fn error(msg: IdsMessage) -> IdsMessage {
let mut message = IdsMessage::clone(msg);
message.id = Some(autogen(REJECTION_MESSAGE));
message.type_message = MessageType::RejectionMessage;
message
}

fn clone(msg: IdsMessage) -> IdsMessage {
IdsMessage {
context: msg.context.clone(),
type_message: msg.type_message.clone(),
id: msg.id.clone(),
pid: msg.pid.clone(),
model_version: msg.model_version.clone(),
correlation_message: msg.correlation_message.clone(),
issued: msg.issued.clone(),
issuer_connector: msg.issuer_connector.clone(),
sender_agent: msg.sender_agent.clone(),
recipient_connector: msg.recipient_connector.clone(),
recipient_agent: msg.recipient_agent.clone(),
transfer_contract: msg.transfer_contract.clone(),
security_token: msg.security_token.clone(),
authorization_token: msg.authorization_token.clone(),
payload: msg.payload.clone(),
content_version: msg.content_version.clone(),
payload_type: msg.payload.clone(),
}
}

pub fn restore() -> IdsMessage {
IdsMessage {
Expand Down
17 changes: 0 additions & 17 deletions clearing-house-app/src/model/ids/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,6 @@ impl InfoModelId {
pub fn new(id: String) -> InfoModelId {
InfoModelId::SimpleId(id)
}
pub fn complex(id: InfoModelComplexId) -> InfoModelId {
InfoModelId::ComplexId(id)
}
}

impl std::fmt::Display for InfoModelId {
Expand Down Expand Up @@ -73,9 +70,6 @@ impl InfoModelDateTime {
pub fn new() -> InfoModelDateTime {
InfoModelDateTime::Time(chrono::Local::now())
}
pub fn complex() -> InfoModelDateTime {
InfoModelDateTime::ComplexTime(InfoModelTimeStamp::default())
}
}

impl std::fmt::Display for InfoModelDateTime {
Expand Down Expand Up @@ -346,17 +340,6 @@ pub struct SecurityToken {
pub token_value: String,
}

impl SecurityToken {
pub fn new() -> SecurityToken {
SecurityToken {
type_message: MessageType::DAPSToken,
id: Some(String::new()),
token_format: None,
token_value: String::new(),
}
}
}

#[derive(Clone, serde::Serialize, serde::Deserialize, Debug)]
pub struct IdsQueryResult {
pub date_from: String,
Expand Down
15 changes: 1 addition & 14 deletions clearing-house-app/src/model/ids/request.rs
Original file line number Diff line number Diff line change
@@ -1,23 +1,10 @@
use crate::model::ids::message::IdsMessage;

/// IDS Multipart message represented as a JSON struct
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ClearingHouseMessage {
pub header: IdsMessage,
pub payload: Option<String>,
#[serde(rename = "payloadType")]
pub payload_type: Option<String>,
}

impl ClearingHouseMessage {
pub fn new(
header: IdsMessage,
payload: Option<String>,
payload_type: Option<String>,
) -> ClearingHouseMessage {
ClearingHouseMessage {
header,
payload,
payload_type,
}
}
}
6 changes: 0 additions & 6 deletions clearing-house-app/src/model/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,6 @@ pub struct OwnerList {
pub owners: Vec<String>,
}

impl OwnerList {
pub fn new(owners: Vec<String>) -> Self {
Self { owners }
}
}

#[derive(Debug, PartialEq, Clone, serde::Serialize, serde::Deserialize)]
pub struct Receipt {
pub data: biscuit::jws::Compact<DataTransaction, biscuit::Empty>,
Expand Down
Loading

0 comments on commit fc710b7

Please sign in to comment.