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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
//! Various error types for response verification failure scenarios

use ic_cbor::CborError;
use ic_certificate_verification::CertificateVerificationError;
#[cfg(all(target_arch = "wasm32", feature = "js"))]
use wasm_bindgen::prelude::*;

use crate::cel;

/// Convenience type that represents the Result of performing response verification
pub type ResponseVerificationResult<T = ()> = Result<T, ResponseVerificationError>;

/// The primary container for response verification errors
#[derive(thiserror::Error, Debug)]
pub enum ResponseVerificationError {
    /// Error converting UTF-8 string
    #[error(r#"IO error: "{0}""#)]
    IoError(#[from] std::io::Error),

    /// An unsupported verification version was requested
    #[error(r#"The requested verification version {requested_version:?} is not supported, the current supported range is {min_supported_version:?}-{max_supported_version:?}"#)]
    UnsupportedVerificationVersion {
        /// The minimum supported verification version
        min_supported_version: u8,
        /// The maximum supported verification version
        max_supported_version: u8,
        /// The actual requested verification version
        requested_version: u8,
    },

    /// Mismatch between the minimum requested version and the actual requested version
    #[error(r#"The requested verification version {requested_version:?} is lower than the minimum requested version {min_requested_verification_version:?}"#)]
    RequestedVerificationVersionMismatch {
        /// The minimum version that will be requested
        min_requested_verification_version: u8,
        /// The actual requested version
        requested_version: u8,
    },

    /// Error parsing CEL expression
    #[error("Cel parser error")]
    CelError(#[from] cel::CelParserError),

    /// Error decoding base64
    #[error("Base64 decoding error")]
    Base64DecodingError(#[from] base64::DecodeError),

    /// Error parsing int
    #[error("Error parsing int")]
    ParseIntError(#[from] std::num::ParseIntError),

    /// The tree has different root hash from the expected value in the certified variables
    #[error("Invalid tree root hash")]
    InvalidTree,

    /// The CEL expression path is invalid
    #[error("Invalid expression path")]
    InvalidExpressionPath,

    /// The response body was a mismatch from the expected values in the tree
    #[error("Invalid response body")]
    InvalidResponseBody,

    /// The response hashes were a mismatch from the expected values in the tree
    #[error("Invalid response hashes")]
    InvalidResponseHashes,

    /// The certificate was missing from the certification header
    #[error("Certificate not found")]
    MissingCertificate,

    /// The tree was missing from the certification header
    #[error("Tree not found")]
    MissingTree,

    /// The certificate expression path was missing from the certification header
    #[error("Certificate expression path not found")]
    MissingCertificateExpressionPath,

    /// The certificate expression was missing from the response headers
    #[error("Certificate expression not found")]
    MissingCertificateExpression,

    /// The certification values could not be found in the response headers
    #[error("Certification values not found")]
    MissingCertification,

    /// Failed to decode CBOR
    #[error("CBOR decoding failed")]
    CborDecodingFailed(#[from] CborError),

    /// Failed to verify certificate
    #[error("Certificate verification failed")]
    CertificateVerificationFailed(#[from] CertificateVerificationError),

    /// HTTP Certification error
    #[error(r#"HTTP Certification error: "{0}""#)]
    HttpCertificationError(#[from] ic_http_certification::HttpCertificationError),
}

/// JS Representation of the ResponseVerificationError code
#[cfg(all(target_arch = "wasm32", feature = "js"))]
#[wasm_bindgen(js_name = ResponseVerificationErrorCode)]
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum ResponseVerificationJsErrorCode {
    /// Error converting UTF-8 string
    IoError,
    /// An unsupported verification version was requested
    UnsupportedVerificationVersion,
    /// Mismatch between the minimum requested version and the actual requested version
    RequestedVerificationVersionMismatch,
    /// Error parsing CEL expression
    CelError,
    /// Error decoding base64
    Base64DecodingError,
    /// Error parsing int
    ParseIntError,
    /// The tree has different root hash from the expected value in the certified variables
    InvalidTree,
    /// The CEL expression path is invalid
    InvalidExpressionPath,
    /// The response body was a mismatch from the expected values in the tree
    InvalidResponseBody,
    /// The response hashes were a mismatch from the expected values in the tree
    InvalidResponseHashes,
    /// The certificate was missing from the certification header
    MissingCertificate,
    /// The tree was missing from the certification header
    MissingTree,
    /// The certificate expression path was missing from the certification header
    MissingCertificateExpressionPath,
    /// The certificate expression was missing from the response headers
    MissingCertificateExpression,
    /// The certification values could not be found in the response headers
    MissingCertification,
    /// Failed to decode CBOR
    CborDecodingFailed,
    /// Failed to verify certificate
    CertificateVerificationFailed,
    /// HTTP Certification error
    HttpCertificationError,
}

/// JS Representation of the ResponseVerificationError
#[cfg(all(target_arch = "wasm32", feature = "js"))]
#[wasm_bindgen(inspectable, js_name = ResponseVerificationError)]
#[derive(Debug, Eq, PartialEq)]
pub struct ResponseVerificationJsError {
    /// Error code as an enum
    #[wasm_bindgen(readonly)]
    pub code: ResponseVerificationJsErrorCode,

    /// Stringified error message
    #[wasm_bindgen(getter_with_clone, readonly)]
    pub message: String,
}

#[cfg(all(target_arch = "wasm32", feature = "js"))]
impl From<ResponseVerificationError> for ResponseVerificationJsError {
    fn from(error: ResponseVerificationError) -> ResponseVerificationJsError {
        let code = match error {
            ResponseVerificationError::IoError(_) => ResponseVerificationJsErrorCode::IoError,
            ResponseVerificationError::UnsupportedVerificationVersion { .. } => {
                ResponseVerificationJsErrorCode::UnsupportedVerificationVersion
            }
            ResponseVerificationError::RequestedVerificationVersionMismatch { .. } => {
                ResponseVerificationJsErrorCode::RequestedVerificationVersionMismatch
            }
            ResponseVerificationError::CelError(_) => ResponseVerificationJsErrorCode::CelError,
            ResponseVerificationError::Base64DecodingError(_) => {
                ResponseVerificationJsErrorCode::Base64DecodingError
            }
            ResponseVerificationError::ParseIntError(_) => {
                ResponseVerificationJsErrorCode::ParseIntError
            }
            ResponseVerificationError::InvalidTree => ResponseVerificationJsErrorCode::InvalidTree,
            ResponseVerificationError::InvalidExpressionPath => {
                ResponseVerificationJsErrorCode::InvalidExpressionPath
            }
            ResponseVerificationError::InvalidResponseBody => {
                ResponseVerificationJsErrorCode::InvalidResponseBody
            }
            ResponseVerificationError::InvalidResponseHashes => {
                ResponseVerificationJsErrorCode::InvalidResponseHashes
            }
            ResponseVerificationError::MissingCertificate => {
                ResponseVerificationJsErrorCode::MissingCertificate
            }
            ResponseVerificationError::MissingTree => ResponseVerificationJsErrorCode::MissingTree,
            ResponseVerificationError::MissingCertificateExpressionPath => {
                ResponseVerificationJsErrorCode::MissingCertificateExpressionPath
            }
            ResponseVerificationError::MissingCertificateExpression => {
                ResponseVerificationJsErrorCode::MissingCertificateExpression
            }
            ResponseVerificationError::MissingCertification => {
                ResponseVerificationJsErrorCode::MissingCertification
            }
            ResponseVerificationError::CborDecodingFailed(_) => {
                ResponseVerificationJsErrorCode::CborDecodingFailed
            }
            ResponseVerificationError::CertificateVerificationFailed(_) => {
                ResponseVerificationJsErrorCode::CertificateVerificationFailed
            }
            ResponseVerificationError::HttpCertificationError(_) => {
                ResponseVerificationJsErrorCode::HttpCertificationError
            }
        };
        let message = error.to_string();

        ResponseVerificationJsError {
            code: code.into(),
            message,
        }
    }
}

#[cfg(all(target_arch = "wasm32", feature = "js", test))]
mod tests {
    use super::*;
    use crate::cel::CelParserError;
    use base64::{engine::general_purpose, Engine as _};
    use ic_http_certification::HttpCertificationError;
    use ic_response_verification_test_utils::hex_decode;
    use wasm_bindgen_test::wasm_bindgen_test;

    #[wasm_bindgen_test]
    fn error_into_http_certification_error() {
        let error = ResponseVerificationError::HttpCertificationError(
            HttpCertificationError::MalformedUrl("https://internetcomputer.org".into()),
        );
        let result = ResponseVerificationJsError::from(error);

        assert_eq!(
            result,
            ResponseVerificationJsError {
                code: ResponseVerificationJsErrorCode::HttpCertificationError,
                message: r#"HTTP Certification error: "Failed to parse url: "https://internetcomputer.org"""#.into(),
            }
        )
    }

    #[wasm_bindgen_test]
    fn error_into_io_error() {
        let inner_error = std::fs::File::open("foo.txt").expect_err("Expected error");
        let error_msg = inner_error.to_string();

        let error = ResponseVerificationError::IoError(inner_error);

        let result = ResponseVerificationJsError::from(error);

        assert_eq!(
            result,
            ResponseVerificationJsError {
                code: ResponseVerificationJsErrorCode::IoError,
                message: format!(r#"IO error: "{}""#, error_msg),
            }
        )
    }

    #[wasm_bindgen_test]
    fn error_into_utf8_conversion_error() {
        let invalid_utf_bytes = hex_decode("fca1a1a1a1a1");
        let inner_error = String::from_utf8(invalid_utf_bytes).expect_err("Expected error");

        let error = ResponseVerificationError::HttpCertificationError(
            HttpCertificationError::Utf8ConversionError(inner_error.clone()),
        );

        let result = ResponseVerificationJsError::from(error);

        assert_eq!(
            result,
            ResponseVerificationJsError {
                code: ResponseVerificationJsErrorCode::HttpCertificationError,
                message: format!(
                    r#"HTTP Certification error: "Error converting UTF8 string bytes: "{0}"""#,
                    inner_error.to_string()
                ),
            }
        )
    }

    #[wasm_bindgen_test]
    fn error_into_unsupported_verification_version() {
        let error = ResponseVerificationError::UnsupportedVerificationVersion {
            min_supported_version: 1,
            max_supported_version: 2,
            requested_version: 42,
        };

        let result = ResponseVerificationJsError::from(error);

        assert_eq!(
            result,
            ResponseVerificationJsError {
                code: ResponseVerificationJsErrorCode::UnsupportedVerificationVersion,
                message: r#"The requested verification version 42 is not supported, the current supported range is 1-2"#.into(),
            }
        )
    }

    #[wasm_bindgen_test]
    fn error_into_verification_version_mismatch() {
        let error = ResponseVerificationError::RequestedVerificationVersionMismatch {
            min_requested_verification_version: 2,
            requested_version: 1,
        };

        let result = ResponseVerificationJsError::from(error);

        assert_eq!(
            result,
            ResponseVerificationJsError {
                code: ResponseVerificationJsErrorCode::RequestedVerificationVersionMismatch,
                message: r#"The requested verification version 1 is lower than the minimum requested version 2"#.into(),
            }
        )
    }

    #[wasm_bindgen_test]
    fn error_into_cel_error() {
        let inner_error = CelParserError::CelSyntaxException(
            "Garbage is not allowed in the CEL expression!".into(),
        );
        let error = ResponseVerificationError::from(inner_error);

        let result = ResponseVerificationJsError::from(error);

        assert_eq!(
            result,
            ResponseVerificationJsError {
                code: ResponseVerificationJsErrorCode::CelError,
                message: r#"Cel parser error"#.into(),
            }
        )
    }

    #[wasm_bindgen_test]
    fn error_into_base64_decoding_error() {
        let invalid_base64 = hex_decode("fca1a1a1a1a1");
        let inner_error = general_purpose::STANDARD
            .decode(invalid_base64)
            .expect_err("Expected error");

        let error = ResponseVerificationError::Base64DecodingError(inner_error);

        let result = ResponseVerificationJsError::from(error);

        assert_eq!(
            result,
            ResponseVerificationJsError {
                code: ResponseVerificationJsErrorCode::Base64DecodingError,
                message: format!(r#"Base64 decoding error"#),
            }
        )
    }

    #[wasm_bindgen_test]
    fn error_into_parse_int_error() {
        let invalid_int = "fortytwo";
        let inner_error = invalid_int.parse::<u8>().expect_err("Expected error");

        let error = ResponseVerificationError::ParseIntError(inner_error);

        let result = ResponseVerificationJsError::from(error);

        assert_eq!(
            result,
            ResponseVerificationJsError {
                code: ResponseVerificationJsErrorCode::ParseIntError,
                message: format!(r#"Error parsing int"#),
            }
        )
    }

    #[wasm_bindgen_test]
    fn error_into_invalid_tree_error() {
        let error = ResponseVerificationError::InvalidTree;
        let result = ResponseVerificationJsError::from(error);

        assert_eq!(
            result,
            ResponseVerificationJsError {
                code: ResponseVerificationJsErrorCode::InvalidTree,
                message: format!(r#"Invalid tree root hash"#),
            }
        )
    }

    #[wasm_bindgen_test]
    fn error_into_invalid_expression_path_error() {
        let error = ResponseVerificationError::InvalidExpressionPath;
        let result = ResponseVerificationJsError::from(error);

        assert_eq!(
            result,
            ResponseVerificationJsError {
                code: ResponseVerificationJsErrorCode::InvalidExpressionPath,
                message: format!(r#"Invalid expression path"#),
            }
        )
    }

    #[wasm_bindgen_test]
    fn error_into_invalid_response_body_error() {
        let error = ResponseVerificationError::InvalidResponseBody;
        let result = ResponseVerificationJsError::from(error);

        assert_eq!(
            result,
            ResponseVerificationJsError {
                code: ResponseVerificationJsErrorCode::InvalidResponseBody,
                message: format!(r#"Invalid response body"#),
            }
        )
    }

    #[wasm_bindgen_test]
    fn error_into_invalid_response_hashes_error() {
        let error = ResponseVerificationError::InvalidResponseHashes;
        let result = ResponseVerificationJsError::from(error);

        assert_eq!(
            result,
            ResponseVerificationJsError {
                code: ResponseVerificationJsErrorCode::InvalidResponseHashes,
                message: format!(r#"Invalid response hashes"#),
            }
        )
    }

    #[wasm_bindgen_test]
    fn error_into_invalid_missing_certificate_error() {
        let error = ResponseVerificationError::MissingCertificate;
        let result = ResponseVerificationJsError::from(error);

        assert_eq!(
            result,
            ResponseVerificationJsError {
                code: ResponseVerificationJsErrorCode::MissingCertificate,
                message: format!(r#"Certificate not found"#),
            }
        )
    }

    #[wasm_bindgen_test]
    fn error_into_invalid_missing_tree_error() {
        let error = ResponseVerificationError::MissingTree;
        let result = ResponseVerificationJsError::from(error);

        assert_eq!(
            result,
            ResponseVerificationJsError {
                code: ResponseVerificationJsErrorCode::MissingTree,
                message: format!(r#"Tree not found"#),
            }
        )
    }

    #[wasm_bindgen_test]
    fn error_into_invalid_missing_certificate_expr_path_error() {
        let error = ResponseVerificationError::MissingCertificateExpressionPath;
        let result = ResponseVerificationJsError::from(error);

        assert_eq!(
            result,
            ResponseVerificationJsError {
                code: ResponseVerificationJsErrorCode::MissingCertificateExpressionPath,
                message: format!(r#"Certificate expression path not found"#),
            }
        )
    }

    #[wasm_bindgen_test]
    fn error_into_invalid_missing_certificate_expr_error() {
        let error = ResponseVerificationError::MissingCertificateExpression;
        let result = ResponseVerificationJsError::from(error);

        assert_eq!(
            result,
            ResponseVerificationJsError {
                code: ResponseVerificationJsErrorCode::MissingCertificateExpression,
                message: format!(r#"Certificate expression not found"#),
            }
        )
    }

    #[wasm_bindgen_test]
    fn error_into_invalid_missing_certification_error() {
        let error = ResponseVerificationError::MissingCertification;
        let result = ResponseVerificationJsError::from(error);

        assert_eq!(
            result,
            ResponseVerificationJsError {
                code: ResponseVerificationJsErrorCode::MissingCertification,
                message: format!(r#"Certification values not found"#),
            }
        )
    }

    #[wasm_bindgen_test]
    fn error_into_cbor_decoding_failed_error() {
        let error = ResponseVerificationError::CborDecodingFailed(CborError::MalformedCbor(
            "HashTree CBOR is malformed".into(),
        ));
        let result = ResponseVerificationJsError::from(error);

        assert_eq!(
            result,
            ResponseVerificationJsError {
                code: ResponseVerificationJsErrorCode::CborDecodingFailed,
                message: format!(r#"CBOR decoding failed"#),
            }
        )
    }

    #[wasm_bindgen_test]
    fn error_into_certificate_verification_failed_error() {
        let error = ResponseVerificationError::CertificateVerificationFailed(
            CertificateVerificationError::MissingTimePathInTree {
                path: vec![b"time".to_vec()],
            },
        );
        let result = ResponseVerificationJsError::from(error);

        assert_eq!(
            result,
            ResponseVerificationJsError {
                code: ResponseVerificationJsErrorCode::CertificateVerificationFailed,
                message: format!(r#"Certificate verification failed"#),
            }
        )
    }
}