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

231 discover feature protocol #236

Merged
merged 15 commits into from
Nov 25, 2024
Merged
Show file tree
Hide file tree
Changes from 7 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
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
[package]
name = "discover-features"
version = "0.1.0"
edition = "2021"

[dependencies]
shared.workspace = true
axum.workspace = true
didcomm.workspace = true
serde = { workspace = true, features = ["derive"] }
serde_json.workspace = true
thiserror.workspace = true
tokio = { workspace = true, features = ["full", "rt"] }
uuid.workspace = true
keystore.workspace = true

[dev-dependencies]
shared = { workspace = true, features = ["test-utils"] }
keystore = { workspace = true, features = ["test-utils"] }
did-utils.workspace = true
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
pub(super) const _DISCOVER_FEATURE: &str = "https://didcomm.org/discover-features/2.0/disclose";
pub(super) const _QUERY_FEATURE: &str = "https://didcomm.org/discover-features/2.0/queries";
Christiantyemele marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
use axum::Json;
use serde_json::{json, Value};
use thiserror::Error;

#[derive(Debug, Error)]
pub enum DiscoveryError {
#[error("message body is malformed")]
MalformedBody,
#[error("Repository not set")]
RepostitoryError,
#[error("No queries field in body")]
QueryNotFound
}
impl DiscoveryError {
/// Converts the error to an axum JSON representation.
pub fn json(&self) -> Json<Value> {
Json(json!({
"error": self.to_string()
}))
}
}
Hermann-Core marked this conversation as resolved.
Show resolved Hide resolved

impl From<DiscoveryError> for Json<Value> {
fn from(error: DiscoveryError) -> Self {
error.json()
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,209 @@
use std::sync::Arc;

use axum::response::{IntoResponse, Response};
use didcomm::Message;
use serde_json::json;
use shared::state::AppState;
use uuid::Uuid;

use crate::constant::_DISCOVER_FEATURE;

use super::{
errors::DiscoveryError,
model::{Disclosures, DisclosuresContent},
};

// handle discover feature request
// https://didcomm.org/discover-features/2.0/
pub fn handle_query_request(

Check warning on line 18 in crates/web-plugins/didcomm-messaging/protocols/discover-features/src/handler.rs

View workflow job for this annotation

GitHub Actions / Build and Test

function `handle_query_request` is never used

Check warning on line 18 in crates/web-plugins/didcomm-messaging/protocols/discover-features/src/handler.rs

View workflow job for this annotation

GitHub Actions / Build and Test

function `handle_query_request` is never used
message: Message,
state: Arc<AppState>,
) -> Result<Option<Message>, Response> {
let mut disclosed_protocols: Vec<String> = Vec::new();

let body = message.body.get("queries").and_then(|val| val.as_array());
Christiantyemele marked this conversation as resolved.
Show resolved Hide resolved

if let Some(queries) = body {
for value in queries {
match value.get("feature-type") {
Some(val) => {
let val = val.as_str().unwrap();
if val.to_string() == "protocol" {
Christiantyemele marked this conversation as resolved.
Show resolved Hide resolved
match value.get("match") {
Some(id) => {
let id = id.to_string();
let parts: Vec<&str> = id.split("/").collect();
let (name, version) = (parts[3], parts[4]);
let query_protocol = format!("{}/{}", name, version);
Christiantyemele marked this conversation as resolved.
Show resolved Hide resolved

if let Some(supported_protocols) =
Christiantyemele marked this conversation as resolved.
Show resolved Hide resolved
&state.clone().supported_protocols
{
if supported_protocols
.iter()
.find(|&disclose_protocol| {
disclose_protocol == &query_protocol
})
.is_some()
{
disclosed_protocols.push(id);
}
}
Christiantyemele marked this conversation as resolved.
Show resolved Hide resolved
}
None => {
return Err(DiscoveryError::MalformedBody.json().into_response())
}
}
}
}
None => return Err(DiscoveryError::MalformedBody.json().into_response()),
}
}
Christiantyemele marked this conversation as resolved.
Show resolved Hide resolved

// build response body
let mut body = Disclosures::new();
for id in disclosed_protocols.iter() {
let content = DisclosuresContent {
feature_type: "protocol".to_string(),
id: id.to_owned(),
roles: None,
};
let content = json!(content);

body.disclosures.push(content);
}

let id = Uuid::new_v4().urn().to_string();
let msg = Message::build(id, _DISCOVER_FEATURE.to_string(), json!(body)).finalize();

Ok(Some(msg))
} else {
return Err(DiscoveryError::QueryNotFound.json().into_response());
}
}
#[cfg(test)]
mod test {

use std::{sync::Arc, vec};

use did_utils::didcore::Document;
use didcomm::Message;
use keystore::tests::MockKeyStore;
use serde_json::json;
use shared::{
repository::tests::{MockConnectionRepository, MockMessagesRepository},
state::{AppState, AppStateRepository},
};
use uuid::Uuid;

use crate::{constant::_QUERY_FEATURE, model::Queries};

use super::handle_query_request;
const TRUST: &str = "https://didcomm.org/trust-ping/2.0/ping";
pub fn setup() -> Arc<AppState> {
let public_domain = String::from("http://alice-mediator.com");

let diddoc = Document::default();

let repository = AppStateRepository {
connection_repository: Arc::new(MockConnectionRepository::from(vec![])),
message_repository: Arc::new(MockMessagesRepository::from(vec![])),
keystore: Arc::new(MockKeyStore::new(vec![])),
};

let state = Arc::new(AppState::from(
public_domain,
diddoc,
Some(vec!["trust-ping/2.0".to_string()]),
Christiantyemele marked this conversation as resolved.
Show resolved Hide resolved
Some(repository),
));

state
}

#[tokio::test]
async fn test_get_supported_protocols() {
let queries = json!({"feature-type": "protocol", "match": TRUST});

let body = Queries {
queries: vec![queries],
};
let id = Uuid::new_v4().urn().to_string();

let message = Message::build(id, _QUERY_FEATURE.to_string(), json!(body)).finalize();
let state = setup();
match handle_query_request(message, state) {
Ok(result) => {
assert!(result.clone().unwrap().body.get("disclosures").is_some());
assert!(result
.clone()
.unwrap()
.body
.get("disclosures")
.unwrap()
.is_array());
assert!(
result
.clone()
.unwrap()
.body
.get("disclosures")
.unwrap()
.as_array()
.unwrap()
.len()
== 1
);

assert_eq!(
serde_json::from_str::<String>(
result
.unwrap()
.body
.get("disclosures")
.unwrap()
.as_array()
.unwrap()[0]
.as_object()
.unwrap()
.get("id")
.unwrap()
.as_str()
.unwrap()
)
.unwrap(),
TRUST.to_string()
);
}
Err(e) => {
panic!("This should not occur {:?}", e)
}
}
}
#[tokio::test]
async fn test_unsupported_feature_type() {
let queries = json!({"feature-type": "goal-code", "match": "org.didcomm"});
let state = setup();
let body = Queries {
queries: vec![queries],
};
let id = Uuid::new_v4().urn().to_string();

let message = Message::build(id, _QUERY_FEATURE.to_string(), json!(body)).finalize();
match handle_query_request(message, state) {
Ok(result) => {
assert!(result
.unwrap()
.body
.get("disclosures")
.unwrap()
.as_array()
.unwrap()
.is_empty())
}
Err(e) => {
panic!("This should not occur: {:#?}", e)
}
}
}
}
Christiantyemele marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
mod errors;
mod constant;
mod handler;
mod model;
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
use serde::{Deserialize, Serialize};
use serde_json::Value;

#[derive(Deserialize, Serialize)]
pub struct Queries {
pub queries: Vec<Value>,
}

#[derive(Deserialize, Serialize, Debug)]
pub struct Disclosures {
pub disclosures: Vec<Value>,
}
impl Disclosures {
pub fn new() -> Self {

Check warning on line 14 in crates/web-plugins/didcomm-messaging/protocols/discover-features/src/model.rs

View workflow job for this annotation

GitHub Actions / Build and Test

associated function `new` is never used

Check warning on line 14 in crates/web-plugins/didcomm-messaging/protocols/discover-features/src/model.rs

View workflow job for this annotation

GitHub Actions / Build and Test

associated function `new` is never used
Disclosures { disclosures: vec![] }
}
}
#[derive(Deserialize, Serialize)]
pub struct DisclosuresContent {
#[serde(rename = "feature-type")]
pub feature_type: String,
pub id: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub roles: Option<Vec<String>>,
}
5 changes: 5 additions & 0 deletions crates/web-plugins/didcomm-messaging/shared/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ pub struct AppState {

// Persistence layer
pub repository: Option<AppStateRepository>,

// disclosed protocols name/version e.g 'trust-ping/2.0'
pub supported_protocols: Option<Vec<String>>
}

#[derive(Clone)]
Expand All @@ -35,6 +38,7 @@ impl AppState {
pub fn from(
public_domain: String,
diddoc: Document,
disclose_protocols: Option<Vec<String>>,
repository: Option<AppStateRepository>,
) -> Self {
let did_resolver = LocalDIDResolver::new(&diddoc);
Expand All @@ -51,6 +55,7 @@ impl AppState {
did_resolver,
secrets_resolver,
repository,
supported_protocols: disclose_protocols,
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,12 @@ pub mod tests {
keystore: Arc::new(MockKeyStore::new(vec![mediator_secret])),
};

let state = Arc::new(AppState::from(public_domain, diddoc, Some(repository)));
let state = Arc::new(AppState::from(
public_domain,
diddoc,
None,
Some(repository),
));

state
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ mod test {
message_repository: Arc::new(MockMessagesRepository::from(vec![])),
};

let state = Arc::new(AppState::from(public_domain, diddoc, Some(repository)));
let state = Arc::new(AppState::from(public_domain, diddoc, None, Some(repository)));

state
}
Expand Down
2 changes: 1 addition & 1 deletion crates/web-plugins/didcomm-messaging/src/plugin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ impl Plugin for MediatorCoordination {
};

// Compile state
let state = AppState::from(env.public_domain.clone(), diddoc, Some(repository));
let state = AppState::from(env.public_domain.clone(), diddoc,None, Some(repository));

// Build router
web::routes(Arc::new(state))
Expand Down
Loading