adorsys / didcomm-mediator-rs

Simple mediator for DIDComm Messaging v2
Apache License 2.0
2 stars 0 forks source link

Add validation logic to PresentationMetadata #73

Closed francis-pouatcha closed 10 months ago

francis-pouatcha commented 10 months ago

To validate PresentationMetadata before it's used to create a JWT, you can add a method to the PresentationMetadata struct that checks for the presence of required fields and any other validation rules you might have.

Here's an example of how to implement and use such a validation method:

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
#[serde(rename_all = "camelCase")]
pub struct PresentationMetadata {
    // ... fields ...
}

impl PresentationMetadata {
    /// Validates the metadata to ensure all required fields are present and correct.
    pub fn validate(&self) -> Result<(), JwsError> {
        // Example validation: ensure issuer and subject are present
        if self.issuer.is_none() {
            return Err(JwsError::MissingIssuer);
        }
        if self.subject.is_none() {
            return Err(JwsError::MissingSubject);
        }

        // Add any additional validation rules here

        Ok(())
    }
}

// ... 

pub fn make_compact_jwt_presentation(
    // ... existing parameters ...
) -> Result<String, JwsError> {
    // Validate the metadata before proceeding.
    metadata.validate()?;

    // Rest of the function...
}

In this example, validate is a method on PresentationMetadata that checks if both issuer and subject are Some. If not, it returns a Result type with a JwsError indicating the specific error.

You would call this validate method inside make_compact_jwt_presentation function (or wherever else appropriate) before proceeding with the JWT creation. This way, you ensure that the metadata is valid before using it, preventing any errors further down the line.

The custom error variants like MissingIssuer and MissingSubject would need to be added to your JwsError enum:

#[derive(Debug, Error, PartialEq)]
pub enum JwsError {
    // ... other variants ...
    #[error("missing issuer in presentation metadata")]
    MissingIssuer,
    #[error("missing subject in presentation metadata")]
    MissingSubject,
    // ... other variants ...
}

By structuring your validation this way, you create a clear contract for what constitutes valid PresentationMetadata and encapsulate the validation logic within the struct itself, which is good practice for maintaining clean and modular code.

francis-pouatcha commented 10 months ago

pull request: #72

IngridPuppet commented 10 months ago

I intentionally wanted them to be optional. To make them required, I could just remove the Option type, instead of that validating logic. Isn't it?