identity_credential/presentation/
presentation_builder.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
// Copyright 2020-2023 IOTA Stiftung
// SPDX-License-Identifier: Apache-2.0

use identity_core::common::Context;
use identity_core::common::Object;
use identity_core::common::Url;
use identity_core::common::Value;

use crate::credential::Policy;
use crate::credential::RefreshService;
use crate::error::Result;

use super::Presentation;

/// A `PresentationBuilder` is used to create a customized [Presentation].
#[derive(Clone, Debug)]
pub struct PresentationBuilder<CRED, T = Object> {
  pub(crate) context: Vec<Context>,
  pub(crate) id: Option<Url>,
  pub(crate) types: Vec<String>,
  pub(crate) credentials: Vec<CRED>,
  pub(crate) holder: Url,
  pub(crate) refresh_service: Vec<RefreshService>,
  pub(crate) terms_of_use: Vec<Policy>,
  pub(crate) properties: T,
}

impl<CRED, T> PresentationBuilder<CRED, T> {
  /// Creates a new `PresentationBuilder`.
  pub fn new(holder: Url, properties: T) -> Self {
    Self {
      context: vec![Presentation::<T>::base_context().clone()],
      id: None,
      types: vec![Presentation::<T>::base_type().into()],
      credentials: Vec::new(),
      holder,
      refresh_service: Vec::new(),
      terms_of_use: Vec::new(),
      properties,
    }
  }

  /// Adds a value to the `context` set.
  #[must_use]
  pub fn context(mut self, value: impl Into<Context>) -> Self {
    self.context.push(value.into());
    self
  }

  /// Sets the unique identifier of the presentation.
  #[must_use]
  pub fn id(mut self, value: Url) -> Self {
    self.id = Some(value);
    self
  }

  /// Adds a value to the `type` set.
  #[must_use]
  pub fn type_(mut self, value: impl Into<String>) -> Self {
    self.types.push(value.into());
    self
  }

  /// Adds a value to the `verifiableCredential` set.
  #[must_use]
  pub fn credential(mut self, value: CRED) -> Self {
    self.credentials.push(value);
    self
  }

  /// Adds a value to the `refreshService` set.
  #[must_use]
  pub fn refresh_service(mut self, value: RefreshService) -> Self {
    self.refresh_service.push(value);
    self
  }

  /// Adds a value to the `termsOfUse` set.
  #[must_use]
  pub fn terms_of_use(mut self, value: Policy) -> Self {
    self.terms_of_use.push(value);
    self
  }

  /// Returns a new `Presentation` based on the `PresentationBuilder` configuration.
  pub fn build(self) -> Result<Presentation<CRED, T>> {
    Presentation::from_builder(self)
  }
}

impl PresentationBuilder<Object> {
  /// Adds a new custom property.
  #[must_use]
  pub fn property<K, V>(mut self, key: K, value: V) -> Self
  where
    K: Into<String>,
    V: Into<Value>,
  {
    self.properties.insert(key.into(), value.into());
    self
  }

  /// Adds a series of custom properties.
  #[must_use]
  pub fn properties<K, V, I>(mut self, iter: I) -> Self
  where
    I: IntoIterator<Item = (K, V)>,
    K: Into<String>,
    V: Into<Value>,
  {
    self
      .properties
      .extend(iter.into_iter().map(|(k, v)| (k.into(), v.into())));
    self
  }
}

#[cfg(test)]
mod tests {
  use serde_json::json;
  use serde_json::Value;

  use identity_core::common::Object;
  use identity_core::common::Url;
  use identity_core::convert::FromJson;

  use crate::credential::Credential;
  use crate::credential::CredentialBuilder;
  use crate::credential::Jwt;
  use crate::credential::Subject;
  use crate::presentation::Presentation;
  use crate::presentation::PresentationBuilder;

  fn subject() -> Subject {
    let json: Value = json!({
      "id": "did:example:ebfeb1f712ebc6f1c276e12ec21",
      "degree": {
        "type": "BachelorDegree",
        "name": "Bachelor of Science and Arts"
      }
    });

    Subject::from_json_value(json).unwrap()
  }

  fn issuer() -> Url {
    Url::parse("did:example:issuer").unwrap()
  }

  #[test]
  fn test_presentation_builder_valid() {
    let credential: Credential = CredentialBuilder::default()
      .type_("ExampleCredential")
      .subject(subject())
      .issuer(issuer())
      .build()
      .unwrap();

    let credential_jwt = Jwt::new(credential.serialize_jwt(None).unwrap());

    let presentation: Presentation<Jwt> = PresentationBuilder::new(Url::parse("did:test:abc1").unwrap(), Object::new())
      .type_("ExamplePresentation")
      .credential(credential_jwt)
      .build()
      .unwrap();

    assert_eq!(presentation.context.len(), 1);
    assert_eq!(
      presentation.context.get(0).unwrap(),
      Presentation::<Object>::base_context()
    );
    assert_eq!(presentation.types.len(), 2);
    assert_eq!(presentation.types.get(0).unwrap(), Presentation::<Object>::base_type());
    assert_eq!(presentation.types.get(1).unwrap(), "ExamplePresentation");
    assert_eq!(presentation.verifiable_credential.len(), 1);
  }

  #[test]
  fn test_presentation_builder_valid_without_credentials() {
    let presentation: Presentation<Jwt> = PresentationBuilder::new(Url::parse("did:test:abc1").unwrap(), Object::new())
      .type_("ExamplePresentation")
      .build()
      .unwrap();

    assert_eq!(presentation.context.len(), 1);
    assert_eq!(
      presentation.context.get(0).unwrap(),
      Presentation::<Object>::base_context()
    );
    assert_eq!(presentation.types.len(), 2);
    assert_eq!(presentation.types.get(0).unwrap(), Presentation::<Object>::base_type());
    assert_eq!(presentation.types.get(1).unwrap(), "ExamplePresentation");
    assert_eq!(presentation.verifiable_credential.len(), 0);
  }
}