Skip to content

Commit

Permalink
fix: add error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
nanderstabel committed Feb 11, 2025
1 parent de82caa commit b28f3ae
Show file tree
Hide file tree
Showing 10 changed files with 82 additions and 96 deletions.
14 changes: 7 additions & 7 deletions Cargo.lock

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

34 changes: 23 additions & 11 deletions agent_identity/src/document/aggregate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -212,21 +212,23 @@ impl Aggregate for Document {

let mut public_key_jwks = vec![];

let ed25519_key_id = KeyId::new(config().secret_manager.issuer_eddsa_key_id.clone());
let es256_key_id = KeyId::new(config().secret_manager.issuer_es256_key_id.clone());
let ed25519_key_id = config().secret_manager.issuer_eddsa_key_id.clone();
let es256_key_id = config().secret_manager.issuer_es256_key_id.clone();

for signing_algorithm in get_all_enabled_signing_algorithms_supported() {
match signing_algorithm {
Algorithm::EdDSA => {
let public_key_jwk: Jwk = stronghold_storage
.get_ed25519_public_key(&ed25519_key_id)
.await
.unwrap();
.map_err(|err| MissingKeyError(err.to_string()))?;
public_key_jwks.push(public_key_jwk);
}
Algorithm::ES256 => {
let public_key_jwk: Jwk =
stronghold_storage.get_es256_public_key(&es256_key_id).await.unwrap();
let public_key_jwk: Jwk = stronghold_storage
.get_es256_public_key(&es256_key_id)
.await
.map_err(|err| MissingKeyError(err.to_string()))?;
public_key_jwks.push(public_key_jwk);
}
_ => return Err(UnsupportedSigningAlgorithmError(signing_algorithm)),
Expand All @@ -246,7 +248,11 @@ impl Aggregate for Document {
// Add the new Verification Methods to the Document.
for public_key_jwk in public_key_jwks {
let fragment = public_key_jwk.kid().ok_or(MissingKidError)?;
let algorithm = public_key_jwk.alg().ok_or(MissingAlgError)?.to_string();

let algorithm = public_key_jwk
.alg()
.and_then(|alg| Algorithm::from_str(&alg).ok())
.ok_or(MissingAlgError)?;

let verification_method_id = did
.to_url()
Expand All @@ -266,7 +272,7 @@ impl Aggregate for Document {

did_methods.insert_verification_method_id(
&did_method,
Algorithm::from_str(&algorithm).expect("FIX THIS"),
algorithm,
&verification_method_id.to_string(),
);
}
Expand Down Expand Up @@ -300,9 +306,11 @@ impl Aggregate for Document {
let subject_did = document.id();

// Set the service ID.
service
.set_id(format!("{subject_did}#{service_id}").parse::<DIDUrl>().unwrap())
.unwrap();
format!("{subject_did}#{service_id}")
.parse::<DIDUrl>()
.ok()
.and_then(|service_id| service.set_id(service_id).ok())
.ok_or_else(|| InvalidDidError(service_id.to_string()))?;

// Overwrite the service if it already exists.
document.remove_service(service.id());
Expand All @@ -319,7 +327,11 @@ impl Aggregate for Document {

let service_id = format!("{subject_did}#{service_id}");

document.remove_service(&service_id.parse::<DIDUrl>().map_err(|_| InvalidDidError(service_id))?);
document.remove_service(
&service_id
.parse::<DIDUrl>()
.map_err(|err| InvalidDidError(err.to_string()))?,
);

Ok(vec![ServiceRemoved { document_id, document }])
}
Expand Down
2 changes: 2 additions & 0 deletions agent_identity/src/document/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ pub enum DocumentError {
MissingKidError,
#[error("Public Key Jwk is missing the required `alg` parameter")]
MissingAlgError,
#[error("Key not found: {0}")]
MissingKeyError(String),
#[error("Error while inserting Verification Method: {0}")]
VerificationMethodInsertionError(String),

Expand Down
4 changes: 2 additions & 2 deletions agent_identity/src/service/aggregate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ impl Aggregate for Service {
.type_("LinkedDomains")
.service_endpoint(service_endpoint)
.build()
.expect("Failed to create DID Configuration Resource");
.map_err(|err| ServiceBuilderError(err.to_string()))?;

Ok(vec![DomainLinkageServiceCreated {
service_id,
Expand Down Expand Up @@ -213,7 +213,7 @@ impl Aggregate for Service {
.type_("LinkedVerifiablePresentation")
.service_endpoint(service_endpoint)
.build()
.expect("Failed to create DID Configuration Resource");
.map_err(|err| ServiceBuilderError(err.to_string()))?;

Ok(vec![LinkedVerifiablePresentationServiceCreated {
service_id,
Expand Down
2 changes: 2 additions & 0 deletions agent_identity/src/service/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,6 @@ pub enum ServiceError {
InvalidServiceEndpointError(String),
#[error("Error producing document: {0}")]
ProduceDocumentError(String),
#[error("Error building service: {0}")]
ServiceBuilderError(String),
}
77 changes: 22 additions & 55 deletions agent_identity/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use crate::{
document::{aggregate::Document, views::DocumentView},
service::{aggregate::Service, command::ServiceCommand, views::ServiceView},
};
use agent_shared::config::{config, SupportedDidMethod, ToggleOptions};
use agent_shared::config::{config, ToggleOptions};
use agent_shared::handlers::command_handler;
use agent_shared::{application_state::CommandHandler, handlers::query_handler};
use cqrs_es::persist::ViewRepository;
Expand All @@ -19,7 +19,6 @@ use iota_sdk::client::Client;
use iota_sdk::crypto::keys::bip39;
use iota_sdk::types::block::address::Bech32Address;
use iota_sdk::types::block::address::Hrp;
use std::str::FromStr;
use std::sync::Arc;
use tracing::{info, warn};

Expand Down Expand Up @@ -114,7 +113,13 @@ pub const VERIFIABLE_PRESENTATION_SERVICE_ID: &str = "linked-verifiable-presenta
pub async fn initialize(state: &IdentityState) {
info!("Initializing ...");

let did_methods = config().did_methods.clone().into_iter().collect::<Vec<_>>();
// Only consider updateable DID methods.
let did_methods = config()
.did_methods
.clone()
.into_iter()
.filter(|(did_method, _)| did_method.is_updateable())
.collect::<Vec<_>>();

info!("DID Methods: {:?}", did_methods);

Expand Down Expand Up @@ -155,24 +160,14 @@ pub async fn initialize(state: &IdentityState) {
}
};

if command_handler(&document_id, &state.command.document, command)
.await
.is_err()
{
warn!("5: Failed to Set status `{did_method}`");
}
let _ = command_handler(&document_id, &state.command.document, command).await;

let command = DocumentCommand::SetPublicKeyJwks {
did_method: did_method.clone(),
public_key_jwks: vec![],
};

if command_handler(&document_id, &state.command.document, command)
.await
.is_err()
{
warn!("5: Failed to Set status `{did_method}`");
}
let _ = command_handler(&document_id, &state.command.document, command).await;

match query_handler(&document_id, &state.query.document).await {
Ok(Some(document)) => Ok(document),
Expand Down Expand Up @@ -211,12 +206,7 @@ pub async fn initialize(state: &IdentityState) {
documents: enabled_updateable_documents,
};

if command_handler(DOMAIN_LINKAGE_SERVICE_ID, &state.command.service, command)
.await
.is_err()
{
warn!("Failed to create domain linkage service");
}
let _ = command_handler(DOMAIN_LINKAGE_SERVICE_ID, &state.command.service, command).await;

info!("Created domain linkage service");

Expand All @@ -226,14 +216,13 @@ pub async fn initialize(state: &IdentityState) {
})) => {
info!("Found linked domains service: {service}");

try_join_all(
let _ = try_join_all(
// Loop through all DID methods.
documents
.iter()
.map(|document| async {
// Clone the variables into the async closure.
let document_id = document.document_id.clone();
let did_method = SupportedDidMethod::from_str(&document_id).unwrap();
let service = service.clone();

let command = match document.status {
Expand All @@ -246,21 +235,13 @@ pub async fn initialize(state: &IdentityState) {
},
};

if command_handler(&document_id, &state.command.document, command)
.await
.is_err()
{
warn!("7: Failed to add service to document");
}

info!("8: Added service to document for `{}`", did_method);
let _ = command_handler(&document_id, &state.command.document, command).await;

Ok::<(), ()>(())
})
.collect::<Vec<_>>(),
)
.await
.unwrap();
.await;
}
_ => {
warn!("Failed to retrieve linked domains service");
Expand All @@ -272,16 +253,11 @@ pub async fn initialize(state: &IdentityState) {
service_id: DOMAIN_LINKAGE_SERVICE_ID.to_string(),
};

if command_handler(DOMAIN_LINKAGE_SERVICE_ID, &state.command.service, command)
.await
.is_err()
{
warn!("Failed to deleted domain linkage service");
}
let _ = command_handler(DOMAIN_LINKAGE_SERVICE_ID, &state.command.service, command).await;

info!("Domain linkage service is disabled");
info!("Disabled Domain linkage service");

try_join_all(
let _ = try_join_all(
// Loop through all DID methods.
documents
.iter()
Expand All @@ -297,11 +273,10 @@ pub async fn initialize(state: &IdentityState) {
})
.collect::<Vec<_>>(),
)
.await
.expect("FIX THISS");
.await;
}

try_join_all(
let _ = try_join_all(
// Loop through all DID methods.
did_methods
.iter()
Expand All @@ -315,22 +290,14 @@ pub async fn initialize(state: &IdentityState) {
did_method: did_method.clone(),
};

info!("Publishing document for `{}`", did_method);

if command_handler(&document_id, &state.command.document, command)
.await
.is_err()
{
warn!("9: Failed to publish DID Document for `{did_method}`");
}
let _ = command_handler(&document_id, &state.command.document, command).await;
}

info!("10: Published document for `{}`", did_method);
info!("Published document for `{}`", did_method);

Ok::<(), ()>(())
})
.collect::<Vec<_>>(),
)
.await
.unwrap();
.await;
}
4 changes: 2 additions & 2 deletions agent_secret_manager/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ agent_shared = { path = "../agent_shared" }
# - All components of the `identity_stronghold_ext` module are still active.
#
# Future work: Migrate the remaining functionality into UniCore.
did_manager_consumer = { git = "https://git@github.com/impierce/did-manager.git", rev = "5a5c124", package = "consumer" }
did_manager_identity_stronghold_ext = { git = "https://git@github.com/impierce/did-manager.git", rev = "5a5c124", package = "identity_stronghold_ext" }
did_manager_consumer = { git = "https://git@github.com/impierce/did-manager.git", tag = "v1.0.0-beta.4", package = "consumer" }
did_manager_identity_stronghold_ext = { git = "https://git@github.com/impierce/did-manager.git", tag = "v1.0.0-beta.4", package = "identity_stronghold_ext" }

anyhow = "1.0"
async-trait = "0.1"
Expand Down
6 changes: 3 additions & 3 deletions agent_secret_manager/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ use log::info;
pub mod service;
pub mod subject;

// TODO: find better solution for this
pub async fn stronghold_storage() -> StrongholdExtStorage {
#[cfg(feature = "test_utils")]
iota_stronghold::engine::snapshot::try_set_encrypt_work_factor(0).unwrap();

info!("Initializing Stronghold storage");
Expand All @@ -28,8 +28,8 @@ pub async fn stronghold_storage() -> StrongholdExtStorage {

info!("Stronghold storage initialized");

let ed25519_key_id = KeyId::new(config().secret_manager.issuer_eddsa_key_id.clone());
let es256_key_id = KeyId::new(config().secret_manager.issuer_es256_key_id.clone());
let ed25519_key_id = config().secret_manager.issuer_eddsa_key_id.clone();
let es256_key_id = config().secret_manager.issuer_es256_key_id.clone();

// Generate keys if they don't exist
// TODO: currently `generate` will generate a 'static' key-ids for each keytype. In a future improvement we need to
Expand Down
Loading

0 comments on commit b28f3ae

Please sign in to comment.