Skip to content

Commit

Permalink
fixe() Resolving conflicts
Browse files Browse the repository at this point in the history
  • Loading branch information
ndefokou committed Dec 20, 2024
2 parents 01d5d36 + 2747ea5 commit 2a729e0
Show file tree
Hide file tree
Showing 89 changed files with 2,822 additions and 2,289 deletions.
76 changes: 40 additions & 36 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -48,49 +48,52 @@ mediator-coordination = { path = "./crates/web-plugins/didcomm-messaging/protoco
# Other common dependencies
serde = "1.0"
sha2 = "0.10"
cfg-if = "0.1"
cfg-if = "1.0"
getrandom = "0.2"
hyper-tls = "0.5.0"
json-patch = "1.0.0"
x25519-dalek = "2.0.0-rc.3"
multibase = "0.8.0"
hyper-tls = "0.6.0"
json-patch = "3.0.1"
x25519-dalek = "2.0.1"
multibase = "0.9.1"
json-canon = "0.1.3"
qrcode = "0.12.0"
image = "0.23"
reqwest = "0.11"
qrcode = "0.14.1"
image = "0.25"
reqwest = "0.12"
tempdir = "0.3.7"
headers = "0.3"
thiserror = "1.0.48"
url = "2.4.1"
num-bigint = "0.4.4"
base64 = "0.13.0"
headers = "0.4"
thiserror = "2.0.7"
url = "2.5.4"
num-bigint = "0.4.6"
base64 = "0.22.1"
hex = "0.4.3"
eyre = "0.6"
anyhow = "1"
subtle = "2.5.0"
regex = "1.10.2"
mongodb = "2.7.1"
once_cell = "1.20.0"
tower = "0.4"
nix = "0.22.0"
uuid = "1.4.1"
axum = "0.6.20"
tokio = "1.30.0"
tracing = "0.1.37"
chrono = "0.4.26"
subtle = "2.6.1"
regex = "1.11.1"
mongodb = "3.1.1"
once_cell = "1.20.2"
tower = "0.5"
nix = "0.29.0"
uuid = "1.11.0"
axum = "0.7.9"
tokio = "1.42.0"
tracing = "0.1.41"
chrono = "0.4.39"
paste = "1.0"
didcomm = "0.4.1"
hyper = "0.14.27"
lazy_static = "1.4.0"
async-trait = "0.1.73"
dotenv-flow = "0.15.0"
hyper = "1.5.2"
hyper-util = "0.1"
http-body-util = "0.1"
lazy_static = "1.5.0"
async-trait = "0.1.83"
dotenv-flow = "0.16.2"
serde_json = "1.0"
parking_lot = "0.12.0"
curve25519-dalek = "4.0.0-rc.3"
ed25519-dalek = "2.0.0-rc.3"
tracing-subscriber = "0.3.17"
tower-http = "0.4.3"
parking_lot = "0.12.3"
curve25519-dalek = "4.1.3"
ed25519-dalek = "2.1.1"
tracing-subscriber = "0.3.19"
tower-http = "0.6.2"
base64ct = { version = "1.6.0", default-features = false }
zeroize = { version = "1.6.0", default-features = false }
zeroize = { version = "1.8.1", default-features = false }


[dependencies]
Expand All @@ -104,9 +107,10 @@ tracing.workspace = true
lazy_static.workspace = true
serde_json.workspace = true
hyper.workspace = true
http-body-util.workspace = true
tokio = { workspace = true, features = ["full"] }
tracing-subscriber = { workspace = true, features = ["json"] }
tower-http = { workspace = true, features = ["catch-panic", "trace"] }
tower-http = { workspace = true, features = ["catch-panic", "trace", "cors"] }
chrono = { workspace = true, optional = true }
did-endpoint = { workspace = true, optional = true }
oob-messages = { workspace = true, optional = true }
Expand Down Expand Up @@ -135,4 +139,4 @@ mediator-coordination = ["plugin-didcomm_messaging", "didcomm-messaging/mediator


[dev-dependencies]
tower = { version = "0.4.13", features = ["util"] }
tower = { version = "0.5.2", features = ["util"] }
64 changes: 64 additions & 0 deletions crates/database/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
# Database crate

A lightweight library for managing MongoDB operations. This library provides an interface, the `Repository` trait with default implementations for interacting with MongoDB collections. It is used by the plugins in the workspace that require database access.
This crate is part of the [DIDComm mediator](https://github.com/adorsys/didcomm-mediator-rs) project.

## Usage

### Requirements

* [MongoDB](https://www.mongodb.com) server instance
* Environment variables:
* `MONGO_URI`: MongoDB connection string
* `MONGO_DBN`: Database name

### Example

* Define an entity

```rust
use database::Repository;

#[derive(Debug, Clone, Serialize, Deserialize)]
struct MyEntity {
#[serde(rename = "_id", skip_serializing_if = "Option::is_none")]
id: Option<ObjectId>,
name: String,
}

impl Identifiable for MyEntity {
fn id(&self) -> Option<ObjectId> {
self.id.clone()
}

fn set_id(&mut self, id: ObjectId) {
self.id = Some(id);
}
}
```

* Implement the `Repository` trait(the only required method is `get_collection`)

```rust
struct MyEntityRepository {
collection: Arc<RwLock<Collection<MyEntity>>>,
}

#[async_trait]
impl Repository<MyEntity> for MyEntityRepository {
fn get_collection(&self) -> Arc<RwLock<Collection<MyEntity>>> {
self.collection.clone()
}
}
```

* Use the repository

```rust
let db = get_or_init_database();
let repo = MyEntityRepository {
collection: Arc::new(RwLock::new(db.read().await.collection("my_entities"))),
};
let entity = MyEntity { id: None, name: "example".to_string() };
repo.store(entity).await?;
```
25 changes: 16 additions & 9 deletions crates/database/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,43 +68,47 @@ where
Entity: Identifiable + Unpin,
Entity: Serialize + for<'de> Deserialize<'de>,
{
/// Get a handle to a collection.
fn get_collection(&self) -> Arc<RwLock<Collection<Entity>>>;

/// Retrieve all entities from the database.
async fn find_all(&self) -> Result<Vec<Entity>, RepositoryError> {
let mut entities = Vec::new();
let collection = self.get_collection();

// Lock the Mutex and get the Collection
let mut cursor = collection.read().await.find(None, None).await?;
let mut cursor = collection.read().await.find(doc! {}).await?;
while cursor.advance().await? {
entities.push(cursor.deserialize_current()?);
}

Ok(entities)
}

/// Counts all entities by filter.
/// Gets the number of documents matching `filter`.
async fn count_by(&self, filter: BsonDocument) -> Result<usize, RepositoryError> {
let collection = self.get_collection();
// Lock the Mutex and get the Collection
let collection = collection.read().await;
Ok(collection
.count_documents(filter, None)
.count_documents(filter)
.await?
.try_into()
.map_err(|_| RepositoryError::Generic("count overflow".to_owned()))?)
}

/// Find an entity by `id`.
async fn find_one(&self, id: ObjectId) -> Result<Option<Entity>, RepositoryError> {
self.find_one_by(doc! {"_id": id}).await
}

/// Find an entity matching `filter`.
async fn find_one_by(&self, filter: BsonDocument) -> Result<Option<Entity>, RepositoryError> {
let collection = self.get_collection();

// Lock the Mutex and get the Collection
let collection = collection.read().await;
Ok(collection.find_one(filter, None).await?)
Ok(collection.find_one(filter).await?)
}

/// Stores a new entity.
Expand All @@ -115,7 +119,7 @@ where
let collection = collection.read().await;

// Insert the new entity into the database
let metadata = collection.insert_one(entity.clone(), None).await?;
let metadata = collection.insert_one(entity.clone()).await?;

// Set the ID if it was inserted and return the updated entity
if let Bson::ObjectId(oid) = metadata.inserted_id {
Expand All @@ -125,6 +129,8 @@ where
Ok(entity)
}

/// Find all entities matching `filter`.
/// If `limit` is set, only the first `limit` entities are returned.
async fn find_all_by(
&self,
filter: BsonDocument,
Expand All @@ -138,26 +144,28 @@ where
let collection = collection.read().await;

// Retrieve all entities from the database
let mut cursor = collection.find(filter, find_options).await?;
let mut cursor = collection.find(filter).with_options(find_options).await?;
while cursor.advance().await? {
entities.push(cursor.deserialize_current()?);
}

Ok(entities)
}

/// Deletes an entity by `id`.
async fn delete_one(&self, id: ObjectId) -> Result<(), RepositoryError> {
let collection = self.get_collection();

// Lock the Mutex and get the Collection
let collection = collection.read().await;

// Delete the entity from the database
collection.delete_one(doc! {"_id": id}, None).await?;
collection.delete_one(doc! {"_id": id}).await?;

Ok(())
}

/// Updates an entity.
async fn update(&self, entity: Entity) -> Result<Entity, RepositoryError> {
if entity.id().is_none() {
return Err(RepositoryError::MissingIdentifier);
Expand All @@ -171,8 +179,7 @@ where
let metadata = collection
.update_one(
doc! {"_id": entity.id().unwrap()},
doc! {"$set": bson::to_document(&entity).map_err(|_| RepositoryError::BsonConversionError)?},
None,
doc! {"$set": bson::to_document(&entity).map_err(|_| RepositoryError::BsonConversionError)?}
)
.await?;

Expand Down
2 changes: 1 addition & 1 deletion crates/filesystem/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ version = "0.1.0"
edition = "2021"

[dependencies]
nix.workspace = true
nix ={ workspace = true, features = ["fs"] }

[features]
test-utils = []
12 changes: 6 additions & 6 deletions crates/filesystem/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
use nix::fcntl::{flock, FlockArg};
use nix::fcntl::{Flock, FlockArg};
use std::{
fs::OpenOptions,
io::{Error as IoError, ErrorKind, Result as IoResult},
os::unix::io::AsRawFd,
path::Path,
};

Expand Down Expand Up @@ -54,22 +53,23 @@ impl FileSystem for StdFileSystem {
let file = OpenOptions::new()
.read(true)
.write(true)
.truncate(true)
.create(true)
.open(&path)?;
.open(path)?;

// Acquire an exclusive lock before writing to the file
flock(file.as_raw_fd(), FlockArg::LockExclusive)
let file = Flock::lock(file, FlockArg::LockExclusive)
.map_err(|_| IoError::new(ErrorKind::Other, "Error acquiring file lock"))?;

std::fs::write(path, &content).map_err(|_| {
std::fs::write(path, content).map_err(|_| {
IoError::new(
ErrorKind::Other,
"Error saving base64-encoded image to file",
)
})?;

// Release the lock after writing to the file
flock(file.as_raw_fd(), FlockArg::Unlock)
file.unlock()
.map_err(|_| IoError::new(ErrorKind::Other, "Error releasing file lock"))?;

Ok(())
Expand Down
40 changes: 40 additions & 0 deletions crates/keystore/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# Keystore Crate

The `keystore` crate is a utility library for managing cryptographic secrets. It is used in the [Didcomm Mediator](https://github.com/adorsys/didcomm-mediator-rs/) to store and retrieve cryptographic keys for DIDcomm interactions.

## Usage

This crate is internal to the [Didcomm Mediator](https://github.com/adorsys/didcomm-mediator-rs/). Below is an example of interacting with the keystore:

```rust
use keystore::{KeyStore, Secrets};
use mongodb::bson::{doc, Bson, Document};
use did_utils::jwk::Jwk;

// Initialize the keystore
let keystore = KeyStore::get();

let jwk: Jwk = serde_json::from_str(
r#"{
"kty": "OKP",
"crv": "X25519",
"x": "SHSUZ6V3x355FqCzIUfgoPzrZB0BQs0JKyag4UfMqHQ",
"d": "0A8SSFkGHg3N9gmVDRnl63ih5fcwtEvnQu9912SVplY"
}"#,
)
.unwrap();

// Store a secret
let secret = Secrets {
id: Some(ObjectId::new()),
kid: "key-1".to_string(),
secret_material: jwk,
};
keystore.store(secret).await?;

// Retrieve a secret by ID
let secret = keystore.find_one(doc! {"kid": "key-1"}).await?;

// Delete a secret by ID
keystore.delete_one(secret.id.unwrap()).await?;
```
Loading

0 comments on commit 2a729e0

Please sign in to comment.