-
Notifications
You must be signed in to change notification settings - Fork 61
/
did_resolve.rs
1589 lines (1526 loc) · 57.2 KB
/
did_resolve.rs
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
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use async_trait::async_trait;
use chrono::prelude::{DateTime, Utc};
#[cfg(feature = "http-did")]
use hyper::{header, Client, Request, StatusCode, Uri};
#[cfg(feature = "http-did")]
use hyper_tls::HttpsConnector;
use serde::{Deserialize, Serialize};
use serde_json;
use serde_json::Value;
use serde_urlencoded;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::convert::TryFrom;
// https://w3c-ccg.github.io/did-resolution/
use crate::did::{
DIDMethod, DIDParameters, Document, PrimaryDIDURL, Resource, ServiceEndpoint,
VerificationMethod, VerificationMethodMap, VerificationRelationship, DIDURL,
};
use crate::error::Error;
use crate::jsonld::DID_RESOLUTION_V1_CONTEXT;
use crate::one_or_many::OneOrMany;
pub const TYPE_JSON: &str = "application/json";
pub const TYPE_LD_JSON: &str = "application/ld+json";
pub const TYPE_DID_JSON: &str = "application/did+json";
pub const TYPE_DID_LD_JSON: &str = "application/did+ld+json";
pub const TYPE_URL: &str = "text/url";
pub const ERROR_INVALID_DID: &str = "invalidDid";
pub const ERROR_INVALID_DID_URL: &str = "invalidDidUrl";
pub const ERROR_UNAUTHORIZED: &str = "unauthorized";
pub const ERROR_NOT_FOUND: &str = "notFound";
pub const ERROR_METHOD_NOT_SUPPORTED: &str = "methodNotSupported";
pub const ERROR_REPRESENTATION_NOT_SUPPORTED: &str = "representationNotSupported";
pub const TYPE_DID_RESOLUTION: &str =
"application/ld+json;profile=\"https://w3id.org/did-resolution\";charset=utf-8";
// Maximum number of DID controllers to resolve at once
pub const MAX_CONTROLLERS: usize = 100;
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(untagged)]
pub enum Metadata {
String(String),
Map(HashMap<String, Metadata>),
List(Vec<Metadata>),
Boolean(bool),
Null,
}
#[derive(Debug, Serialize, Deserialize, Clone, Default)]
#[serde(rename_all = "camelCase")]
pub struct ResolutionInputMetadata {
#[serde(skip_serializing_if = "Option::is_none")]
pub accept: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub version_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub version_time: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub no_cache: Option<bool>,
#[serde(flatten)]
pub property_set: Option<HashMap<String, Metadata>>,
}
#[derive(Debug, Serialize, Deserialize, Clone, Default)]
#[serde(rename_all = "camelCase")]
/// <https://w3c.github.io/did-core/#did-resolution-metadata-properties>
pub struct ResolutionMetadata {
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub content_type: Option<String>,
#[serde(flatten)]
pub property_set: Option<HashMap<String, Metadata>>,
}
#[derive(Debug, Serialize, Deserialize, Clone, Default)]
#[serde(rename_all = "camelCase")]
pub struct DocumentMetadata {
#[serde(skip_serializing_if = "Option::is_none")]
pub created: Option<DateTime<Utc>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub updated: Option<DateTime<Utc>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub deactivated: Option<bool>,
#[serde(flatten)]
pub property_set: Option<HashMap<String, Metadata>>,
}
/// <https://w3c.github.io/did-core/#did-url-dereferencing-metadata-properties>
/// <https://w3c-ccg.github.io/did-resolution/#dereferencing-input-metadata-properties>
#[derive(Debug, Serialize, Deserialize, Clone, Default)]
#[serde(rename_all = "camelCase")]
pub struct DereferencingInputMetadata {
#[serde(skip_serializing_if = "Option::is_none")]
pub accept: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub service_type: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub follow_redirect: Option<bool>,
#[serde(flatten)]
pub property_set: Option<HashMap<String, Metadata>>,
}
#[derive(Debug, Serialize, Deserialize, Clone, Default)]
#[serde(rename_all = "camelCase")]
/// <https://w3c.github.io/did-core/#did-url-dereferencing-metadata-properties>
pub struct DereferencingMetadata {
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub content_type: Option<String>,
#[serde(flatten)]
pub property_set: Option<HashMap<String, Metadata>>,
}
#[derive(Debug, Serialize, Clone, PartialEq)]
/// A resource returned by DID URL dereferencing
#[serde(untagged)]
pub enum Content {
DIDDocument(Document),
URL(String),
Object(Resource),
Data(Vec<u8>),
Null,
}
impl Content {
pub fn into_vec(self) -> Result<Vec<u8>, Error> {
if let Content::Data(data) = self {
Ok(data)
} else {
Ok(serde_json::to_vec(&self)?)
}
}
}
impl From<Error> for DereferencingMetadata {
fn from(err: Error) -> Self {
DereferencingMetadata {
error: Some(err.to_string()),
..Default::default()
}
}
}
// needed for:
// - https://w3c-ccg.github.io/did-resolution/#dereferencing-algorithm-primary Step 2.1
// Returning a resolved DID document for DID URL dereferencing
impl From<ResolutionMetadata> for DereferencingMetadata {
fn from(res_meta: ResolutionMetadata) -> Self {
Self {
error: res_meta.error,
content_type: res_meta.content_type,
property_set: res_meta.property_set,
}
}
}
// needed for:
// - https://w3c-ccg.github.io/did-resolution/#bindings-https Step 1.10.2.1
// Producing DID resolution result after DID URL dereferencing.
impl From<DereferencingMetadata> for ResolutionMetadata {
fn from(deref_meta: DereferencingMetadata) -> Self {
Self {
error: deref_meta.error,
content_type: deref_meta.content_type,
property_set: deref_meta.property_set,
}
}
}
impl DereferencingMetadata {
pub fn from_error(err: &str) -> Self {
DereferencingMetadata {
error: Some(err.to_owned()),
..Default::default()
}
}
}
impl ResolutionMetadata {
pub fn from_error(err: &str) -> Self {
ResolutionMetadata {
error: Some(err.to_owned()),
..Default::default()
}
}
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(untagged)]
pub enum ContentMetadata {
DIDDocument(DocumentMetadata),
Other(HashMap<String, Metadata>),
}
impl Default for ContentMetadata {
fn default() -> Self {
ContentMetadata::Other(HashMap::new())
}
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
/// <https://w3c-ccg.github.io/did-resolution/#did-resolution-result>
pub struct ResolutionResult {
#[serde(rename = "@context")]
#[serde(skip_serializing_if = "Option::is_none")]
pub context: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub did_document: Option<Document>,
#[serde(skip_serializing_if = "Option::is_none")]
pub did_resolution_metadata: Option<ResolutionMetadata>,
#[serde(skip_serializing_if = "Option::is_none")]
pub did_document_metadata: Option<DocumentMetadata>,
#[serde(flatten)]
pub property_set: Option<BTreeMap<String, Value>>,
}
impl Default for ResolutionResult {
fn default() -> Self {
Self {
context: Some(Value::String(DID_RESOLUTION_V1_CONTEXT.to_string())),
did_document: None,
did_resolution_metadata: None,
did_document_metadata: None,
property_set: None,
}
}
}
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
pub trait DIDResolver: Sync {
async fn resolve(
&self,
did: &str,
input_metadata: &ResolutionInputMetadata,
) -> (
ResolutionMetadata,
Option<Document>,
Option<DocumentMetadata>,
);
async fn resolve_representation(
&self,
did: &str,
input_metadata: &ResolutionInputMetadata,
) -> (ResolutionMetadata, Vec<u8>, Option<DocumentMetadata>) {
// Implement resolveRepresentation in terms of resolve.
let (mut res_meta, doc, doc_meta) = self.resolve(did, input_metadata).await;
let doc_representation = match doc {
None => Vec::new(),
Some(doc) => match serde_json::to_vec_pretty(&doc) {
Ok(vec) => vec,
Err(err) => {
res_meta.error =
Some("Error serializing JSON: ".to_string() + &err.to_string());
Vec::new()
}
},
};
// Assume JSON-LD DID document
res_meta.content_type = Some(TYPE_DID_LD_JSON.to_string());
(res_meta, doc_representation, doc_meta)
}
/// Dereference a DID URL.
///
/// DID methods implement this function to support dereferencing DID URLs with paths and query strings.
/// Callers should use [`dereference`] instead of this function.
///
/// <https://w3c-ccg.github.io/did-resolution/#dereferencing>
async fn dereference(
&self,
_primary_did_url: &PrimaryDIDURL,
_did_url_dereferencing_input_metadata: &DereferencingInputMetadata,
) -> Option<(DereferencingMetadata, Content, ContentMetadata)> {
None
}
/// Cast the resolver as a [`DIDMethod`], if possible.
fn to_did_method(&self) -> Option<&dyn DIDMethod> {
None
}
}
/// Dereference a DID URL
///
/// <https://w3c.github.io/did-core/#did-url-dereferencing>
/// <https://w3c-ccg.github.io/did-resolution/#dereferencing-algorithm>
pub async fn dereference(
resolver: &dyn DIDResolver,
did_url_str: &str,
did_url_dereferencing_input_metadata: &DereferencingInputMetadata,
) -> (DereferencingMetadata, Content, ContentMetadata) {
let did_url = match DIDURL::try_from(did_url_str.to_string()) {
Ok(did_url) => did_url,
Err(_error) => {
return (
DereferencingMetadata::from_error(ERROR_INVALID_DID_URL),
Content::Null,
ContentMetadata::default(),
);
}
};
// 1
let did_res_input_metadata: ResolutionInputMetadata = match did_url.query.as_ref() {
Some(query) => match serde_urlencoded::from_str(query) {
Ok(meta) => meta,
Err(error) => {
return (
DereferencingMetadata::from(Error::from(error)),
Content::Null,
ContentMetadata::default(),
);
}
},
None => ResolutionInputMetadata::default(),
};
let (did_doc_res_meta, did_doc_opt, did_doc_meta_opt) = resolver
.resolve(&did_url.did, &did_res_input_metadata)
.await;
if let Some(ref error) = did_doc_res_meta.error {
return (
DereferencingMetadata::from_error(error),
Content::Null,
ContentMetadata::default(),
);
}
let (did_doc, did_doc_meta) = match (did_doc_opt, did_doc_meta_opt) {
(Some(doc), Some(meta)) => (doc, meta),
_ => {
return (
DereferencingMetadata::from_error(ERROR_NOT_FOUND),
Content::Null,
ContentMetadata::default(),
);
}
};
// 2
let (primary_did_url, fragment) = did_url.remove_fragment();
let (deref_meta, content, content_meta) = dereference_primary_resource(
resolver,
&primary_did_url,
did_url_dereferencing_input_metadata,
&did_doc_res_meta,
did_doc,
&did_doc_meta,
)
.await;
if deref_meta.error.is_some() {
return (deref_meta, content, content_meta);
}
if let Some(fragment) = fragment {
// 3
return dereference_secondary_resource(
resolver,
primary_did_url,
fragment,
did_url_dereferencing_input_metadata,
deref_meta,
content,
content_meta,
)
.await;
}
(deref_meta, content, content_meta)
}
/// <https://w3c-ccg.github.io/did-resolution/#dereferencing-algorithm-primary>
async fn dereference_primary_resource(
resolver: &dyn DIDResolver,
primary_did_url: &PrimaryDIDURL,
did_url_dereferencing_input_metadata: &DereferencingInputMetadata,
res_meta: &ResolutionMetadata,
did_doc: Document,
_did_doc_meta: &DocumentMetadata,
) -> (DereferencingMetadata, Content, ContentMetadata) {
let parameters: DIDParameters = match primary_did_url.query {
Some(ref query) => match serde_urlencoded::from_str(query) {
Ok(params) => params,
Err(err) => {
return (
DereferencingMetadata::from(Error::from(err)),
Content::Null,
ContentMetadata::default(),
);
}
},
None => Default::default(),
};
// 1
if let Some(ref service) = parameters.service {
// 1.1
let service = match did_doc.select_service(service) {
Some(service) => service,
None => {
return (
DereferencingMetadata::from_error("Service not found"),
Content::Null,
ContentMetadata::default(),
);
}
};
// 1.2, 1.2.1
// TODO: support these other cases?
let input_service_endpoint_url = match &service.service_endpoint {
None => {
return (
DereferencingMetadata::from_error("Missing service endpoint"),
Content::Null,
ContentMetadata::default(),
);
}
Some(OneOrMany::One(ServiceEndpoint::URI(uri))) => uri,
Some(OneOrMany::One(ServiceEndpoint::Map(_))) => {
return (
DereferencingMetadata::from_error("serviceEndpoint map not supported"),
Content::Null,
ContentMetadata::default(),
);
}
Some(OneOrMany::Many(_)) => {
return (
DereferencingMetadata::from_error(
"Multiple serviceEndpoint properties not supported",
),
Content::Null,
ContentMetadata::default(),
);
}
};
// 1.2.2, 1.2.3
let did_url = DIDURL::from(primary_did_url.clone());
let output_service_endpoint_url =
match construct_service_endpoint(&did_url, ¶meters, input_service_endpoint_url) {
Ok(url) => url,
Err(err) => {
return (
DereferencingMetadata::from_error(&format!(
"Unable to construct service endpoint: {}",
err
)),
Content::Null,
ContentMetadata::default(),
);
}
};
// 1.3
return (
DereferencingMetadata {
content_type: Some(TYPE_URL.to_string()),
..Default::default()
},
Content::URL(output_service_endpoint_url),
ContentMetadata::default(),
);
}
// 2
if primary_did_url.path.is_none() && primary_did_url.query.is_none() {
// 2.1
// Add back contentType, since the resolve function does not include it, but we need
// it to dereference the secondary resource.
// TODO: detect non-JSON-LD DID documents
let deref_meta = DereferencingMetadata {
content_type: Some(TYPE_DID_LD_JSON.to_string()),
..DereferencingMetadata::from(res_meta.clone())
};
return (
deref_meta,
Content::DIDDocument(did_doc),
ContentMetadata::default(),
);
}
// 3
if primary_did_url.path.is_some() || primary_did_url.query.is_some() {
// 3.1
if let Some(result) = resolver
.dereference(primary_did_url, did_url_dereferencing_input_metadata)
.await
{
return result;
}
// 3.2
// TODO: enable the client to dereference the DID URL
}
// 4
#[allow(clippy::let_and_return)]
let null_result = (
DereferencingMetadata::default(),
Content::Null,
ContentMetadata::default(),
);
// 4.1
null_result
}
/// <https://w3c-ccg.github.io/did-resolution/#dereferencing-algorithm-secondary>
async fn dereference_secondary_resource(
_resolver: &dyn DIDResolver,
primary_did_url: PrimaryDIDURL,
fragment: String,
_did_url_dereferencing_input_metadata: &DereferencingInputMetadata,
deref_meta: DereferencingMetadata,
content: Content,
content_meta: ContentMetadata,
) -> (DereferencingMetadata, Content, ContentMetadata) {
let content_type = deref_meta.content_type.as_deref();
// 1
match content {
// https://www.w3.org/TR/did-core/#application-did-json
// "Fragment identifiers used with application/did+json are treated according to the
// rules defined in § Fragment."
// https://www.w3.org/TR/did-core/#fragment
// TODO: use actual JSON-LD fragment dereferencing
// https://www.w3.org/TR/did-core/#application-did-ld-json
// Fragment identifiers used with application/did+ld+json are treated according to the
// rules associated with the JSON-LD 1.1: application/ld+json media type [JSON-LD11].
Content::DIDDocument(ref doc)
if content_type == Some(TYPE_DID_LD_JSON) || content_type == Some(TYPE_DID_JSON) =>
{
// put the fragment back in the URL
let did_url = primary_did_url.with_fragment(fragment);
// 1.1
let object = match doc.select_object(&did_url) {
Ok(object) => object,
Err(error) => {
return (
DereferencingMetadata::from_error(&format!(
"Unable to find object in DID document: {}",
error
)),
Content::Null,
ContentMetadata::default(),
);
}
};
return (
DereferencingMetadata {
content_type: Some(String::from(if content_type == Some(TYPE_DID_LD_JSON) {
TYPE_LD_JSON
} else {
TYPE_JSON
})),
..Default::default()
},
Content::Object(object),
ContentMetadata::default(),
);
}
Content::URL(mut url) => {
// 2
// 2.1
if url.contains('#') {
// https://w3c-ccg.github.io/did-resolution/#input
return (
DereferencingMetadata::from_error("DID URL and input service endpoint URL MUST NOT both have a fragment component"),
Content::Null,
ContentMetadata::default()
);
}
url.push('#');
url.push_str(&fragment);
return (deref_meta, Content::URL(url), content_meta);
}
_ => {}
}
// 3
match content_type {
None => (
DereferencingMetadata::from_error("Resource missing content type"),
Content::Null,
ContentMetadata::default(),
),
Some(content_type) => (
DereferencingMetadata::from_error(&format!(
"Unsupported content type: {}",
content_type
)),
Content::Null,
ContentMetadata::default(),
),
}
}
/// <https://w3c-ccg.github.io/did-resolution/#service-endpoint-construction>
fn construct_service_endpoint(
did_url: &DIDURL,
did_parameters: &DIDParameters,
service_endpoint_url: &str,
) -> Result<String, String> {
// https://w3c-ccg.github.io/did-resolution/#algorithm
// 1, 2, 3
let mut parts = service_endpoint_url.splitn(2, '#');
let service_endpoint_url = parts.next().unwrap();
let input_service_endpoint_fragment = parts.next();
if did_url.fragment.is_some() && input_service_endpoint_fragment.is_some() {
// https://w3c-ccg.github.io/did-resolution/#input
return Err(
"DID URL and input service endpoint URL MUST NOT both have a fragment component"
.to_string(),
);
}
parts = service_endpoint_url.splitn(2, '?');
let service_endpoint_url = parts.next().unwrap();
let input_service_endpoint_query = parts.next();
let did_url_path: String;
let did_url_query: Option<String>;
// Work around https://github.com/w3c-ccg/did-resolution/issues/61
if let Some(ref relative_ref) = did_parameters.relative_ref {
parts = relative_ref.splitn(2, '?');
did_url_path = parts.next().unwrap().to_owned();
if !did_url.path_abempty.is_empty() {
return Err("DID URL and relativeRef MUST NOT both have a path component".to_string());
}
did_url_query = parts.next().map(|q| q.to_owned());
} else {
did_url_path = did_url.path_abempty.to_owned();
did_url_query = did_url.query.to_owned();
// TODO: do something with the DID URL query that is being ignored in favor of the
// relativeRef query
}
if did_url_query.is_some() && input_service_endpoint_query.is_some() {
return Err(
"DID URL and input service endpoint URL MUST NOT both have a query component"
.to_string(),
);
}
let mut output_url = service_endpoint_url.to_owned();
// 4
output_url += &did_url_path;
// 5
if let Some(query) = input_service_endpoint_query {
output_url.push('?');
output_url.push_str(query);
}
// 6
if let Some(query) = did_url_query {
output_url.push('?');
output_url.push_str(&query);
}
// 7
if let Some(fragment) = input_service_endpoint_fragment {
output_url.push('#');
output_url.push_str(fragment);
}
// 8
if let Some(fragment) = &did_url.fragment {
output_url.push('#');
output_url.push_str(fragment);
}
Ok(output_url)
}
#[cfg(feature = "http")]
#[derive(Debug, Clone, Default)]
pub struct HTTPDIDResolver {
pub endpoint: String,
}
#[cfg(feature = "http")]
impl HTTPDIDResolver {
pub fn new(url: &str) -> Self {
Self {
endpoint: url.to_string(),
}
}
}
#[cfg(feature = "http")]
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl DIDResolver for HTTPDIDResolver {
// https://w3c-ccg.github.io/did-resolution/#bindings-https
async fn resolve(
&self,
did: &str,
input_metadata: &ResolutionInputMetadata,
) -> (
ResolutionMetadata,
Option<Document>,
Option<DocumentMetadata>,
) {
let querystring = match serde_urlencoded::to_string(input_metadata) {
Ok(qs) => qs,
Err(err) => {
return (
ResolutionMetadata {
error: Some(
"Unable to serialize input metadata into query string: ".to_string()
+ &err.to_string(),
),
content_type: None,
property_set: None,
},
None,
None,
)
}
};
let did_urlencoded =
percent_encoding::utf8_percent_encode(&did, percent_encoding::CONTROLS).to_string();
let mut url = self.endpoint.clone() + &did_urlencoded;
if !querystring.is_empty() {
url.push('?');
url.push_str(&querystring);
}
let uri: Uri = match url.parse() {
Ok(uri) => uri,
Err(_) => {
return (
ResolutionMetadata {
error: Some(ERROR_INVALID_DID.to_string()),
content_type: None,
property_set: None,
},
None,
None,
)
}
};
let https = HttpsConnector::new();
let client = Client::builder().build::<_, hyper::Body>(https);
let request = match Request::get(uri)
.header("Accept", TYPE_DID_RESOLUTION)
.header("User-Agent", crate::USER_AGENT)
.body(hyper::Body::default())
{
Ok(req) => req,
Err(err) => {
return (
ResolutionMetadata {
error: Some("Error building HTTP request: ".to_string() + &err.to_string()),
content_type: None,
property_set: None,
},
None,
None,
)
}
};
let mut resp = match client.request(request).await {
Ok(resp) => resp,
Err(err) => {
return (
ResolutionMetadata {
error: Some("HTTP Error: ".to_string() + &err.to_string()),
content_type: None,
property_set: None,
},
None,
None,
)
}
};
let res_result_representation = match hyper::body::to_bytes(resp.body_mut()).await {
Ok(vec) => vec,
Err(err) => {
return (
ResolutionMetadata {
error: Some("Error reading HTTP response: ".to_string() + &err.to_string()),
content_type: None,
property_set: None,
},
None,
None,
)
}
};
let content_type = match resp.headers().get(header::CONTENT_TYPE) {
None => None,
Some(content_type) => Some(String::from(match content_type.to_str() {
Ok(content_type) => content_type,
Err(err) => {
return (
ResolutionMetadata::from_error(&format!(
"Error reading HTTP header: {}",
err
)),
None,
None,
)
}
})),
}
.unwrap_or_else(|| "".to_string());
let mut res_meta = ResolutionMetadata::default();
let doc_opt;
let doc_meta_opt;
match &content_type[..] {
TYPE_DID_RESOLUTION => {
let result: ResolutionResult =
match serde_json::from_slice(&res_result_representation) {
Ok(result) => result,
Err(err) => {
return (
ResolutionMetadata::from_error(&format!(
"Error parsing resolution result: {}",
err
)),
None,
None,
)
}
};
if let Some(meta) = result.did_resolution_metadata {
res_meta = meta;
// https://www.w3.org/TR/did-core/#did-resolution-metadata
// contentType - "MUST NOT be present if the resolve function was called"
res_meta.content_type = None;
};
doc_opt = result.did_document;
doc_meta_opt = result.did_document_metadata;
}
_ => {
if resp.status() == StatusCode::NOT_FOUND {
res_meta.error = Some(ERROR_NOT_FOUND.to_string());
doc_opt = None;
} else {
// Assume the response is a JSON-LD DID Document by default.
let doc: Document = match serde_json::from_slice(&res_result_representation) {
Ok(doc) => doc,
Err(err) => {
return (
ResolutionMetadata::from_error(&format!(
"Error parsing DID document: {}",
err
)),
None,
None,
)
}
};
doc_opt = Some(doc);
}
doc_meta_opt = None;
}
}
(res_meta, doc_opt, doc_meta_opt)
}
// Use default resolveRepresentation implementation in terms of resolve,
// until resolveRepresentation has its own HTTP(S) binding:
// https://github.com/w3c-ccg/did-resolution/issues/57
async fn dereference(
&self,
primary_did_url: &PrimaryDIDURL,
input_metadata: &DereferencingInputMetadata,
) -> Option<(DereferencingMetadata, Content, ContentMetadata)> {
let querystring = match serde_urlencoded::to_string(input_metadata) {
Ok(qs) => qs,
Err(err) => {
return Some((
DereferencingMetadata::from_error(&format!(
"Unable to serialize input metadata into query string: {}",
err
)),
Content::Null,
ContentMetadata::default(),
))
}
};
let did_url_urlencoded = percent_encoding::utf8_percent_encode(
&primary_did_url.to_string(),
percent_encoding::CONTROLS,
)
.to_string();
let mut url = self.endpoint.clone() + &did_url_urlencoded;
if !querystring.is_empty() {
url.push('?');
url.push_str(&querystring);
}
let uri: Uri = match url.parse() {
Ok(uri) => uri,
Err(_) => {
return Some((
DereferencingMetadata::from_error(ERROR_INVALID_DID),
Content::Null,
ContentMetadata::default(),
))
}
};
let https = HttpsConnector::new();
let client = Client::builder().build::<_, hyper::Body>(https);
let request = match Request::get(uri)
.header("Accept", TYPE_DID_RESOLUTION)
.body(hyper::Body::default())
{
Ok(req) => req,
Err(err) => {
return Some((
DereferencingMetadata::from_error(&format!(
"Error building HTTP request: {}",
err
)),
Content::Null,
ContentMetadata::default(),
))
}
};
let mut resp = match client.request(request).await {
Ok(resp) => resp,
Err(err) => {
return Some((
DereferencingMetadata::from_error(&format!("HTTP Error: {}", err)),
Content::Null,
ContentMetadata::default(),
))
}
};
let mut deref_meta = DereferencingMetadata::default();
let mut content = Content::Null;
let mut content_meta = ContentMetadata::default();
deref_meta.error = match resp.status() {
StatusCode::NOT_FOUND => Some(ERROR_NOT_FOUND.to_string()),
StatusCode::BAD_REQUEST => Some(ERROR_INVALID_DID.to_string()),
StatusCode::NOT_ACCEPTABLE => Some(ERROR_REPRESENTATION_NOT_SUPPORTED.to_string()),
_ => None,
};
let deref_result_bytes = match hyper::body::to_bytes(resp.body_mut()).await {
Ok(vec) => vec,
Err(err) => {
return Some((
DereferencingMetadata::from_error(&format!(
"Error reading HTTP response: {}",
err
)),
Content::Null,
ContentMetadata::default(),
))
}
};
let content_type = match resp.headers().get(header::CONTENT_TYPE) {
None => None,
Some(content_type) => Some(String::from(match content_type.to_str() {
Ok(content_type) => content_type,
Err(err) => {
return Some((
DereferencingMetadata::from_error(&format!(
"Error reading HTTP header: {}",
err
)),
Content::Null,
ContentMetadata::default(),
))
}
})),
}
.unwrap_or_else(|| "".to_string());
match &content_type[..] {
TYPE_DID_LD_JSON | TYPE_DID_JSON => {
let doc: Document = match serde_json::from_slice(&deref_result_bytes) {
Ok(result) => result,
Err(err) => {
return Some((
DereferencingMetadata::from_error(&format!(
"Error parsing DID document: {}",
err
)),
Content::Null,
ContentMetadata::default(),
))
}
};
content = Content::DIDDocument(doc);
content_meta = ContentMetadata::DIDDocument(DocumentMetadata::default());
deref_meta.content_type = Some(TYPE_DID_LD_JSON.to_string());
}
TYPE_DID_RESOLUTION => {
let result: ResolutionResult = match serde_json::from_slice(&deref_result_bytes) {
Ok(result) => result,
Err(err) => {
return Some((
DereferencingMetadata::from_error(&format!(
"Error parsing DID resolution result: {}",
err
)),
Content::Null,
ContentMetadata::default(),
))
}
};
if let Some(res_meta) = result.did_resolution_metadata {
deref_meta = res_meta.into();
}
if let Some(doc) = result.did_document {
content = Content::DIDDocument(doc);
}
content_meta =
ContentMetadata::DIDDocument(result.did_document_metadata.unwrap_or_default());
}
TYPE_LD_JSON | TYPE_JSON => {
let object: BTreeMap<String, Value> =