vade-evan 0.0.5

vade plugins for working with VCs and DIDs on evan.network
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
/*
  Copyright (c) 2018-present evan GmbH.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

use async_trait::async_trait;
use chrono::{ DateTime, Utc };
use data_encoding::BASE64URL;
use regex::Regex;
use reqwest;
use secp256k1::{Message, Signature, recover, RecoveryId, SecretKey, sign};
use serde_json::Value;
use serde::{Serialize, Deserialize};
use sha2::{Digest, Sha256};
use sha3::Keccak256;
use simple_error::SimpleError;
use std::convert::TryInto;
use std::str;
use vade::traits::VcResolver;
use vade::Vade;

/// mandatory context, will be inserted automatically if not provided for
/// [create_vc](crate::plugin::rust_rust_vcresolver_evan::RustVcResolverEvan#method.create_vc)
pub const VC_W3C_MANDATORY_CONTEXT: &'static str = "https://www.w3.org/2018/credentials/v1";
/// default type, will be used if no type is provided for
/// [create_vc](crate::plugin::rust_rust_vcresolver_evan::RustVcResolverEvan#method.create_vc)
pub const VC_DEFAULT_TYPE: &'static str = "VerifiableCredential";
const JWT_REGEX: &'static str = r#"^\s*\{"iat":[^,]+,"vc":(.*),"iss":"[^"]+?"\}\s*$"#;

#[allow(non_snake_case)]
#[derive(Serialize, Deserialize, Debug)]
/// type to cover required fields in evan.network DID documents for key handling,
/// does NOT reflect a full evan.network DID document
struct EvanDid {
    pub publicKey: Vec<EvanDidPublicKey>,
}

#[allow(non_snake_case)]
#[derive(Serialize, Deserialize, Debug)]
/// type to cover required fields in evan.network DID documents for key handling,
/// does NOT reflect a full evan.network DID document
struct EvanDidPublicKey {
    pub ethereumAddress: String,
    pub id: String,
}

/// Resolver for DIDs on evan.network (currently on testnet)
pub struct RustVcResolverEvan {
    pub vade: Option<Box<Vade>>,
}

impl RustVcResolverEvan {
    /// Creates new instance of `RustVcResolverEvan`.
    pub fn new() -> RustVcResolverEvan {
        match env_logger::try_init() {
            Ok(_) | Err(_) => (),
        };
        RustVcResolverEvan {
            vade: None,
        }
    }

    /// Sets document for given vc name.
    ///
    /// # Arguments
    ///
    /// * `vc_id` - vc_id to set value for
    /// * `value` - value to set
    #[allow(dead_code)]
    async fn set_vc_document(&mut self, _vc_id: &str, _value: &str) -> std::result::Result<(), Box<dyn std::error::Error>> {
        unimplemented!();
    }

    /// Gets all keys from given DID. `self.vade` will be queried for DID, then public keys are checked for keys.
    ///
    /// # Arguments
    /// 
    /// * `key_from_did` - key reference to a DID document like "$DID#key-1"
    async fn get_key_from_did(&self, key_from_did: &str) -> Result<String, Box<dyn std::error::Error>> {
        let did = key_from_did.splitn(2, '#').next().unwrap();
        debug!("getting keys for did {:?}", &did);
        let did_document_string = self.vade.as_ref().unwrap().get_did_document(did).await.unwrap();
        let did_document: EvanDid = serde_json::from_str(&did_document_string)?;

        let key_objects: Vec<EvanDidPublicKey> = did_document.publicKey;
        let matches: Vec<String> = key_objects
            .into_iter()
            .filter(|key| key.id == key_from_did)
            .map(|key| key.ethereumAddress)
            .collect();
 
        match matches.len() {
            1 => Ok(format!("{}", matches[0])),
            0 => Err(Box::from(format!("key {} not found in DID {}", key_from_did, did))),
            _ => Err(Box::from(format!("multiple matches found for key {} in DID {}", key_from_did, did))),
        }
    }

    /// Creates a new VC document. Will automatically add manadatory fields and proof.
    /// Automatically adds the following fields if missing:
    /// - @context
    /// - type
    /// - issuer
    /// - validFrom
    /// - proof
    ///
    /// # Arguments
    ///
    /// * `vc_data` - partial or full VC
    /// * `verification_method` - issuer of VC
    /// * `private_key` - private key to create proof as 32B hex string
    pub async fn create_vc(
        &self,
        vc_data: &str,
        verification_method: &str,
        private_key: &str
    ) -> Result<String, Box<dyn std::error::Error>> {
        let mut parsed_vc: Value = serde_json::from_str(&vc_data).unwrap();

        // currently new VCs created here are offline, so id is mandatory
        if parsed_vc["id"].is_null() {
            return Err(Box::new(SimpleError::new("\"id\" is required for offline VCs")))
        } 

        // ensure proper context
        if parsed_vc["@context"].is_null() {
            parsed_vc["@context"] = Value::from(Vec::<&str>::new());
        }
        if !parsed_vc["@context"].as_array().unwrap().iter().any(|v| v == VC_W3C_MANDATORY_CONTEXT) {
            parsed_vc["@context"].as_array_mut().unwrap().push(Value::from(VC_W3C_MANDATORY_CONTEXT));
        }

        // ensure type
        if parsed_vc["type"].is_null() {
            parsed_vc["type"] = Value::from(VC_DEFAULT_TYPE);
        }

        // if not privided, fill issuer with given `verification_method`, did
        if parsed_vc["issuer"].is_null() {
            let split: Vec<&str> = verification_method.split('#').collect();
            parsed_vc["issuer"] = Value::from(split[0]);
        }

        // ensure validFrom timestamp
        let now: DateTime<Utc> = Utc::now();
        if parsed_vc["validFrom"].is_null() {
            parsed_vc["validFrom"] = Value::from(format!("{}", now.format("%Y-%m-%dT%H:%M:%S.000Z")));
        }

        // ensure proof
        if parsed_vc["proof"].is_null() {
            parsed_vc["proof"] = create_proof(&parsed_vc, &verification_method, &private_key, &now).unwrap();
        }

        // final VC document
        let vc_str = String::from(format!("{}", &parsed_vc));
        debug!("final VC document: {}", vc_str);

        Ok(vc_str)
    }
}


#[async_trait(?Send)]
impl VcResolver for RustVcResolverEvan {
    /// Checks given Vc document.
    /// A Vc document is considered as valid if returning ().
    /// Resolver may throw to indicate
    /// - that it is not responsible for this Vc
    /// - that it considers this Vc as invalid
    /// 
    /// Currently the test `vc_id` `"test"` is accepted as valid.
    ///
    /// # Arguments
    ///
    /// * `vc_id` - vc_id to check document for
    /// * `value` - value to check
    async fn check_vc(&self, vc_id: &str, value: &str) -> Result<(), Box<dyn std::error::Error>> {
        // TODO: add some pre-flight checks (key type, etc)
        let mut vc: Value = serde_json::from_str(value)?;
        if vc["proof"].is_null() {
            debug!("vcs without a proof are considered as valid");
            Ok(())
        } else {
            debug!("checking vc document");

            // separate proof and vc document (vc document will be a Map after this)
            let vc_without_proof = vc.as_object_mut().unwrap();
            let vc_proof =  vc_without_proof.remove("proof").unwrap();

            // recover address and payload text (pure jwt format)
            let (address, decoded_payload_text) = recover_address_and_data(vc_proof["jws"].as_str().unwrap())?;

            debug!("checking if document given and document from jws are equal");
            // fetch recovered vc document (without proof from jwt)
            let re = Regex::new(JWT_REGEX).unwrap();
            let caps = re.captures(&decoded_payload_text).unwrap();
            // parse recovered vc document into serde Map
            let parsed_caps1: Value = serde_json::from_str(&caps[1])?;
            let parsed_caps1_map = parsed_caps1.as_object().unwrap();
            // compare documents
            if vc_without_proof != parsed_caps1_map {
                return Err(Box::from("recovered VC document and given VC document do not match"));
            }

            debug!("checking proof of vc document");
            let address = format!("0x{}", address);
            let key_to_use = vc_proof["verificationMethod"].as_str().unwrap();
            debug!("recovered address: {}", &address);
            debug!("key to use for verification: {}", &key_to_use);
            let key_from_did = self.get_key_from_did(key_to_use).await?;
            debug!("key from did: {}", &key_from_did);
            if address != key_from_did {
                return Err(Box::from(format!("could not verify signature of \"{}\"", vc_id)));
            }

            debug!("checking if credential status is present, query it");
            if !vc["credentialStatus"].is_null()
                    && vc["credentialStatus"]["type"] == "evan:evanCredential" {
                debug!("credential status is present, query it");
                let vc_status = get_vc_status_valid(vc["credentialStatus"]["id"].as_str().unwrap()).await?;
                if !vc_status {
                  return Err(Box::from(format!("vc \"{}\" is not active", &vc_id)));
                }
            }
            
            debug!("vc document is valid");
            Ok(())
        }
    }

    /// Gets document for given vc name.
    ///
    /// # Arguments
    ///
    /// * `vc_id` - vc_id to fetch
    async fn get_vc_document(&self, vc_id: &str) -> Result<String, Box<dyn std::error::Error>> {
        let body = reqwest::get(&format!("https://testcore.evan.network/vc/{}", vc_id))
            .await?
            .text()
            .await?;
        let parsed: Value = serde_json::from_str(&body).unwrap();
        if parsed["status"] == "error" {
            Err(Box::new(SimpleError::new(format!("could not get vc document, {:?}", parsed["error"].as_str().unwrap()))))
        } else {
            Ok(serde_json::to_string(&parsed["vc"]).unwrap())
        }
    }
    
    /// Sets document for given vc name.
    ///
    /// # Arguments
    ///
    /// * `vc_name` - vc_name to set value for
    /// * `value` - value to set
    async fn set_vc_document(&mut self, _vc_name: &str, _value: &str) -> Result<(), Box<dyn std::error::Error>> {
        unimplemented!();
    }
}

/// Fetches revokation status for VCs. VCs can be active or revoked (-> true/false)
/// missing VC documents or other errors are indicated as Errors.
///
/// # Arguments
///
/// * `vc_status_id` - vc status id / url to query
async fn get_vc_status_valid(vc_status_id: &str) -> Result<bool, Box<dyn std::error::Error>> {
    let body = reqwest::get(vc_status_id)
        .await?
        .text()
        .await?;
    let parsed: Value = serde_json::from_str(&body).unwrap();
    if parsed["status"] == "error" {
        Err(Box::new(SimpleError::new(format!("vc status error, {:?}", parsed["error"].as_str().unwrap()))))
    } else {
        let is_active = match parsed["vcStatus"].as_str().unwrap() {
            "active" => true,
            _ => false,
        };
        Ok(is_active)
    }
}

/// Creates proof for VC document
///
/// # Arguments
///
/// * `vc` - vc to create proof for
/// * `verification_method` - issuer of VC
/// * `private_key` - private key to create proof as 32B hex string
/// * `now` - timestamp of issuing, may have also been used to determine `validFrom` in VC
fn create_proof(
    vc: &Value,
    verification_method: &str,
    private_key: &str,
    now: &DateTime<Utc>
) -> Result<Value, Box<dyn std::error::Error>> {
    // create to-be-signed jwt
    let header_str = r#"{"typ":"JWT","alg":"ES256K-R"}"#;
    let padded = BASE64URL.encode(header_str.as_bytes());
    let header_encoded = padded.trim_end_matches('=');
    debug!("header base64 url encdoded: {:?}", &header_encoded);

    // build data object and hash
    let mut data_json: Value = serde_json::from_str("{}").unwrap();
    let vc_clone: Value = serde_json::from_str(&format!("{}", &vc)).unwrap();
    data_json["iat"] = Value::from(now.timestamp());
    data_json["vc"] = vc_clone;
    data_json["iss"] = Value::from(vc["issuer"].as_str().unwrap());
    let padded = BASE64URL.encode(format!("{}", &data_json).as_bytes());
    let data_encoded = padded.trim_end_matches('=');
    debug!("data base64 url encdoded: {:?}", &data_encoded);

    // create hash of data (including header)
    let header_and_data = format!("{}.{}", header_encoded, data_encoded);
    let mut hasher = Sha256::new();
    hasher.input(&header_and_data);
    let hash = hasher.result();
    debug!("header_and_data hash {:?}", hash);

    // sign this hash
    let hash_arr: [u8; 32] = hash.try_into().expect("slice with incorrect length");
    let message = Message::parse(&hash_arr);
    let mut private_key_arr = [0u8; 32];
    hex::decode_to_slice(&private_key, &mut private_key_arr).expect("private key invalid");
    let secret_key = SecretKey::parse(&private_key_arr)?;
    let (sig, rec): (Signature, _) = sign(&message, &secret_key);
    // sig to bytes (len 64), append recoveryid
    let signature_arr = &sig.serialize();
    let mut sig_and_rec: [u8; 65] = [0; 65];
    for i in 0..64 {
        sig_and_rec[i] = signature_arr[i];
    }
    sig_and_rec[64] = rec.serialize();
    let padded = BASE64URL.encode(&sig_and_rec);
    let sig_base64url = padded.trim_end_matches('=');
    debug!("signature base64 url encdoded: {:?}", &sig_base64url);

    // build proof property as serde object
    let jws = format!("{}.{}", &header_and_data, sig_base64url);
    let utc_now = format!("{}", now.format("%Y-%m-%dT%H:%M:%S.000Z"));
    let proof_json_str = format!(r###"{{
        "type": "EcdsaPublicKeySecp256k1",
        "created": "{}",
        "proofPurpose": "assertionMethod",
        "verificationMethod": "{}",
        "jws": "{}"
    }}"###, &utc_now, &verification_method, &jws);
    let proof: Value = serde_json::from_str(&proof_json_str).unwrap();

    Ok(proof)
}

/// Recovers Ethereum address of signer and data part of a jwt.
///
/// # Arguments
///
/// * `jwt` - jwt as str&
fn recover_address_and_data(jwt: &str) -> Result<(String, String), Box<dyn std::error::Error>> {
    // jwt text parsing
    let split: Vec<&str> = jwt.split('.').collect();
    let (header, data, signature) = (split[0], split[1], split[2]);
    let header_and_data = format!("{}.{}", header, data);
    
    // recover data for later checks
    let data_decoded = match BASE64URL.decode(data.as_bytes()) {
        Ok(decoded) => decoded,
        Err(_) => match BASE64URL.decode(format!("{}=", data).as_bytes()) {
            Ok(decoded) => decoded,
            Err(_) => match BASE64URL.decode(format!("{}==", data).as_bytes()) {
                Ok(decoded) => decoded,
                Err(_) => BASE64URL.decode(format!("{}===", data).as_bytes()).unwrap(),
            },
        },
    };
    let data_string = String::from_utf8(data_decoded)?;

    // decode signature for validation
    let signature_decoded = match BASE64URL.decode(signature.as_bytes()) {
        Ok(decoded) => decoded,
        Err(_) => match BASE64URL.decode(format!("{}=", signature).as_bytes()) {
            Ok(decoded) => decoded,
            Err(_) => BASE64URL.decode(format!("{}==", signature).as_bytes()).unwrap(),
        },
    };
    debug!("signature_decoded {:?}", &signature_decoded);
    debug!("signature_decoded.len {:?}", signature_decoded.len());

    // create hash of data (including header)
    let mut hasher = Sha256::new();
    hasher.input(&header_and_data);
    let hash = hasher.result();
    debug!("header_and_data hash {:?}", hash);

    // prepare arguments for public key recovery
    let hash_arr: [u8; 32] = hash.try_into().expect("header_and_data hash invalid"); 
    let ctx_msg = Message::parse(&hash_arr);
    let mut signature_array = [0u8; 64];
    for i in 0..64 {
        signature_array[i] = signature_decoded[i];
    }
    // slice signature and recovery for recovery
    debug!("recovery id: {}", signature_decoded[64]);
    let ctx_sig = Signature::parse(&signature_array);
    let recovery_id = RecoveryId::parse(signature_decoded[64]).unwrap();

    // recover public key, build ethereum address from it
    let recovered_key = recover(&ctx_msg, &ctx_sig, &recovery_id).unwrap();
    let mut hasher = Keccak256::new();
    hasher.input(&recovered_key.serialize()[1..65]);
    let hash = hasher.result();
    debug!("recovered_key hash {:?}", hash);
    let address = hex::encode(&hash[12..32]);
    debug!("address 0x{}", &address);

    Ok((address, data_string))
}