Skip to content

Commit

Permalink
feat: allow sdk to work with pub endpoints only (#33)
Browse files Browse the repository at this point in the history
* feat: allow sdk wo work with pub endoints only

* fix: typos and dead code
  • Loading branch information
anton-iskryzhytskyi authored Sep 18, 2024
1 parent 0951b52 commit 95ec274
Show file tree
Hide file tree
Showing 9 changed files with 89 additions and 76 deletions.
9 changes: 3 additions & 6 deletions affinidi-messaging-sdk/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,20 +39,17 @@ cargo run --example message_pickup -- \
# send a message to the same recipient as sender
cargo run --example send_message_to_me -- \
--network-address $MEDIATOR_ENDPOINT \
--ssl-certificates $MEDIATOR_TLS_CERTIFICATES \
--mediator-did $MEDIATOR_DID
--ssl-certificates $MEDIATOR_TLS_CERTIFICATES

# send a message to another recipient Bob
cargo run --example send_message_to_bob -- \
--network-address $MEDIATOR_ENDPOINT \
--ssl-certificates $MEDIATOR_TLS_CERTIFICATES \
--mediator-did $MEDIATOR_DID
--ssl-certificates $MEDIATOR_TLS_CERTIFICATES

# pickup a message from another sender Alice
cargo run --example fetch_message_as_bob -- \
--network-address $MEDIATOR_ENDPOINT \
--ssl-certificates $MEDIATOR_TLS_CERTIFICATES \
--mediator-did $MEDIATOR_DID
--ssl-certificates $MEDIATOR_TLS_CERTIFICATES
```

## WebSocket and HTTPS support
Expand Down
25 changes: 13 additions & 12 deletions affinidi-messaging-sdk/examples/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,6 @@ struct Args {
network_address: String,
#[arg(short, long)]
ssl_certificates: String,
#[arg(short, long)]
mediator_did: String,
}

pub struct ConfigureAtmResult {
Expand Down Expand Up @@ -82,23 +80,26 @@ pub async fn configure_atm(
tracing::subscriber::set_global_default(subscriber).expect("Logging failed, exiting...");

info!("Running with address: {}", &args.network_address);
info!("Running with mediator_did: {}", &args.mediator_did);
info!("Running with ssl_certificates: {}", &args.ssl_certificates);

let atm_did = &args.mediator_did;

// TODO: in the future we likely want to pull this from the DID itself
let mut config = Config::builder()
.with_my_did(&example_configuration.did)
.with_atm_did(atm_did)
let public_config_builder = Config::builder()
.with_atm_api(&args.network_address)
.with_ssl_certificates(&mut vec![args.ssl_certificates.clone().into()])
.with_websocket_disabled();

config = config
let mut public_atm = ATM::new(public_config_builder.build()?).await?;

let atm_did = public_atm.well_known_did().await?;

let config_builder = Config::builder()
.with_atm_api(&args.network_address)
.with_ssl_certificates(&mut vec![args.ssl_certificates.into()]);
.with_ssl_certificates(&mut vec![args.ssl_certificates.into()])
.with_websocket_disabled()
.with_my_did(&example_configuration.did)
.with_atm_did(&atm_did);

// Create a new ATM Client
let mut atm = ATM::new(config.build()?).await?;
let mut atm = ATM::new(config_builder.build()?).await?;

// Add our secrets to ATM Client - stays local.
atm.add_secret(secret_from_str(
Expand Down
4 changes: 2 additions & 2 deletions affinidi-messaging-sdk/examples/ping.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,8 +82,8 @@ async fn main() -> Result<(), ATMError> {
// Ready to send a trust-ping to ATM
let start = SystemTime::now();

let well_know_res = atm.well_known_did_json().await?;
println!("did resolved: {:?}", well_know_res);
let well_know_did = atm.well_known_did().await?;
println!("did resolved: {:?}", well_know_did);

// You normally don't need to call authenticate() as it is called automatically
// We do this here so we can time the auth cycle
Expand Down
23 changes: 12 additions & 11 deletions affinidi-messaging-sdk/src/authentication/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,14 @@ impl<'c> ATM<'c> {
let _span = span!(Level::DEBUG, "authenticate",);
async move {
debug!("Retrieving authentication challenge...");

let (my_did, atm_did) = self.dids()?;
// Step 1. Get the challenge
let res = self
.client
.post(format!("{}/authenticate/challenge", self.config.atm_api))
.header("Content-Type", "application/json")
.body(format!("{{\"did\": \"{}\"}}", self.config.my_did).to_string())
.body(format!("{{\"did\": \"{}\"}}", my_did).to_string())
.send()
.await
.map_err(|e| {
Expand Down Expand Up @@ -71,15 +73,14 @@ impl<'c> ATM<'c> {
));
};

let auth_response =
self._create_auth_challenge_response(&self.config.atm_did, challenge);
let auth_response = self._create_auth_challenge_response(challenge)?;
debug!("Auth response message:\n{:#?}", auth_response);

let (auth_msg, _) = auth_response
.pack_encrypted(
&self.config.atm_did,
Some(&self.config.my_did),
Some(&self.config.my_did),
atm_did,
Some(my_did),
Some(my_did),
&self.did_resolver,
&self.secrets_resolver,
&PackEncryptedOptions::default(),
Expand Down Expand Up @@ -158,22 +159,22 @@ impl<'c> ATM<'c> {
/// - This message will expire after 60 seconds
fn _create_auth_challenge_response(
&self,
atm_did: &str,
body: &AuthenticationChallenge,
) -> Message {
) -> Result<Message, ATMError> {
let (my_did, atm_did) = self.dids()?;
let now = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap()
.as_secs();
Message::build(
Ok(Message::build(
Uuid::new_v4().into(),
"https://affinidi.com/atm/1.0/authenticate".to_owned(),
json!(body),
)
.to(atm_did.to_owned())
.from(self.config.my_did.to_owned())
.from(my_did.to_owned())
.created_time(now)
.expires_time(now + 60)
.finalize()
.finalize())
}
}
24 changes: 4 additions & 20 deletions affinidi-messaging-sdk/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,11 @@ use tracing::error;
/// ```
#[derive(Clone)]
pub struct Config<'a> {
pub(crate) my_did: String,
pub(crate) my_did: Option<String>,
pub(crate) ssl_certificates: Vec<CertificateDer<'a>>,
pub(crate) atm_api: String,
pub(crate) atm_api_ws: String,
pub(crate) atm_did: String,
pub(crate) atm_did: Option<String>,
pub(crate) ssl_only: bool,
pub(crate) ws_enabled: bool,
pub(crate) fetch_cache_limit_count: u32,
Expand Down Expand Up @@ -197,14 +197,6 @@ impl ConfigBuilder {
));
}

let my_did = if let Some(my_did) = self.my_did {
my_did
} else {
return Err(ATMError::ConfigError(
"You must provide a DID for the SDK, used for authentication!".to_owned(),
));
};

let atm_api = if let Some(atm_url) = self.atm_api {
atm_url
} else {
Expand All @@ -225,20 +217,12 @@ impl ConfigBuilder {
));
};

let atm_did = if let Some(atm_did) = self.atm_did {
atm_did
} else {
return Err(ATMError::ConfigError(
"You must provide the DID for the ATM service!".to_owned(),
));
};

Ok(Config {
ssl_certificates: certs,
my_did,
my_did: self.my_did,
atm_api,
atm_api_ws,
atm_did,
atm_did: self.atm_did,
ssl_only: self.ssl_only,
ws_enabled: self.ws_enabled,
fetch_cache_limit_count: self.fetch_cache_limit_count,
Expand Down
29 changes: 26 additions & 3 deletions affinidi-messaging-sdk/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -154,9 +154,12 @@ impl<'c> ATM<'c> {
};

// Add our own DID to the DID_RESOLVER
atm.add_did(&config.my_did).await?;
// Add our ATM DID to the DID_RESOLVER
atm.add_did(&config.atm_did).await?;
if let Some(my_did) = &config.my_did {
atm.add_did(my_did).await?;
}
if let Some(my_did) = &config.my_did {
atm.add_did(my_did).await?;
}

// Add any pre-loaded secrets
for secret in config.secrets {
Expand Down Expand Up @@ -193,4 +196,24 @@ impl<'c> ATM<'c> {
pub fn add_secret(&mut self, secret: Secret) {
self.secrets_resolver.insert(secret);
}

pub(crate) fn dids(&self) -> Result<(&String, &String), ATMError> {
let my_did = if let Some(my_did) = &self.config.my_did {
my_did
} else {
return Err(ATMError::ConfigError(
"You must provide a DID for the SDK, used for authentication!".to_owned(),
));
};

let atm_did = if let Some(atm_did) = &self.config.atm_did {
atm_did
} else {
return Err(ATMError::ConfigError(
"You must provide the DID for the ATM service!".to_owned(),
));
};

Ok((my_did, atm_did))
}
}
42 changes: 24 additions & 18 deletions affinidi-messaging-sdk/src/protocols/message_pickup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,8 @@ impl MessagePickup {
recipient_did, mediator_did, wait
);

let (my_did, atm_did) = atm.dids()?;

let mut msg = Message::build(
Uuid::new_v4().into(),
"https://didcomm.org/messagepickup/3.0/status-request".to_owned(),
Expand All @@ -97,11 +99,11 @@ impl MessagePickup {
let to_did = if let Some(mediator_did) = mediator_did {
mediator_did
} else {
atm.config.atm_did.clone()
atm_did.clone()
};
msg = msg.to(to_did.clone());

msg = msg.from(atm.config.my_did.clone());
msg = msg.from(my_did.clone());
let now = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap()
Expand All @@ -115,8 +117,8 @@ impl MessagePickup {
let (msg, _) = msg
.pack_encrypted(
&to_did,
Some(&atm.config.my_did),
Some(&atm.config.my_did),
Some(&my_did),
Some(&my_did),
&atm.did_resolver,
&atm.secrets_resolver,
&PackEncryptedOptions::default(),
Expand Down Expand Up @@ -181,6 +183,7 @@ impl MessagePickup {
) -> Result<(), ATMError> {
let _span = span!(Level::DEBUG, "toggle_live_delivery",).entered();
debug!("Setting live_delivery to ({})", live_delivery);
let (my_did, atm_did) = atm.dids()?;

let now = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
Expand All @@ -195,17 +198,17 @@ impl MessagePickup {
.header("return_route".into(), Value::String("all".into()))
.created_time(now)
.expires_time(now + 300)
.from(atm.config.my_did.clone())
.to(atm.config.atm_did.clone())
.from(my_did.clone())
.to(atm_did.clone())
.finalize();
let msg_id = msg.id.clone();

// Pack the message
let (msg, _) = msg
.pack_encrypted(
&atm.config.atm_did,
Some(&atm.config.my_did),
Some(&atm.config.my_did),
&atm_did,
Some(&my_did),
Some(&my_did),
&atm.did_resolver,
&atm.secrets_resolver,
&PackEncryptedOptions::default(),
Expand Down Expand Up @@ -381,12 +384,13 @@ impl MessagePickup {
"Delivery Request for recipient_did: {:?}, mediator_did: {:?} limit: {:?}",
recipient_did, mediator_did, limit
);
let (my_did, atm_did) = atm.dids()?;

let body = MessagePickupDeliveryRequest {
recipient_did: if let Some(recipient) = recipient_did {
recipient
} else {
atm.config.my_did.clone()
my_did.clone()
},
limit: if let Some(limit) = limit { limit } else { 10 },
};
Expand All @@ -401,11 +405,11 @@ impl MessagePickup {
let to_did = if let Some(mediator_did) = mediator_did {
mediator_did
} else {
atm.config.atm_did.clone()
atm_did.clone()
};
msg = msg.to(to_did.clone());

msg = msg.from(atm.config.my_did.clone());
msg = msg.from(my_did.clone());
let now = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap()
Expand All @@ -419,8 +423,8 @@ impl MessagePickup {
let (msg, _) = msg
.pack_encrypted(
&to_did,
Some(&atm.config.my_did),
Some(&atm.config.my_did),
Some(&my_did),
Some(&my_did),
&atm.did_resolver,
&atm.secrets_resolver,
&PackEncryptedOptions::default(),
Expand Down Expand Up @@ -554,6 +558,8 @@ impl MessagePickup {
list.len()
);

let (my_did, atm_did) = atm.dids()?;

let mut msg = Message::build(
Uuid::new_v4().into(),
"https://didcomm.org/messagepickup/3.0/delivery-request".to_owned(),
Expand All @@ -564,11 +570,11 @@ impl MessagePickup {
let to_did = if let Some(mediator_did) = mediator_did {
mediator_did
} else {
atm.config.atm_did.clone()
atm_did.clone()
};
msg = msg.to(to_did.clone());

msg = msg.from(atm.config.my_did.clone());
msg = msg.from(my_did.clone());
let now = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap()
Expand All @@ -582,8 +588,8 @@ impl MessagePickup {
let (msg, _) = msg
.pack_encrypted(
&to_did,
Some(&atm.config.my_did),
Some(&atm.config.my_did),
Some(my_did),
Some(&my_did),
&atm.did_resolver,
&atm.secrets_resolver,
&PackEncryptedOptions::default(),
Expand Down
5 changes: 3 additions & 2 deletions affinidi-messaging-sdk/src/protocols/trust_ping.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ impl TrustPing {
"Pinging {}, signed?({}) response_expected?({})",
to_did, signed, expect_response
);
let (my_did, _) = atm.dids()?;

// If an anonymous ping is being sent, we should ensure that expect_response is false
let expect_response = if !signed && expect_response {
Expand All @@ -72,8 +73,8 @@ impl TrustPing {
// Can support anonymous pings
None
} else {
msg = msg.from(atm.config.my_did.clone());
Some(atm.config.my_did.clone())
msg = msg.from(my_did.clone());
Some(my_did.clone())
};
let msg = msg.created_time(now).expires_time(now + 300).finalize();
let mut msg_info = TrustPingSent {
Expand Down
Loading

0 comments on commit 95ec274

Please sign in to comment.