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
use crate::EntityError::IdentityApiFailed;
use crate::{
    profile::Profile, AuthenticationProof, Changes, Contact, EntityBuilder, Identity,
    IdentityRequest, IdentityResponse, Lease, MaybeContact, ProfileChangeEvent, ProfileIdentifier,
    TrustPolicy, TrustPolicyImpl, TTL,
};
use ockam_core::compat::{
    string::{String, ToString},
    vec::Vec,
};
use ockam_core::vault::{PublicKey, Secret};
use ockam_core::{async_trait, compat::boxed::Box};
use ockam_core::{Address, AsyncTryClone, Result, Route};
use ockam_node::{Context, Handle};
use IdentityRequest::*;
use IdentityResponse as Res;
#[derive(AsyncTryClone)]
pub struct Entity {
    pub(crate) handle: Handle,
    current_profile_id: Option<ProfileIdentifier>,
}

impl Entity {
    pub(crate) fn new(handle: Handle, profile_id: Option<ProfileIdentifier>) -> Self {
        Entity {
            handle,
            current_profile_id: profile_id,
        }
    }

    pub async fn create(ctx: &Context, vault_address: &Address) -> Result<Entity> {
        EntityBuilder::new(ctx, vault_address).await?.build().await
    }

    pub async fn call(&self, req: IdentityRequest) -> Result<IdentityResponse> {
        self.handle.call(req).await
    }

    pub async fn cast(&self, req: IdentityRequest) -> Result<()> {
        self.handle.cast(req).await
    }
}

impl Entity {
    pub fn id(&self) -> ProfileIdentifier {
        self.current_profile_id.as_ref().unwrap().clone()
    }
}

fn err<T>() -> Result<T> {
    Err(IdentityApiFailed.into())
}

impl Entity {
    pub async fn create_profile(&mut self, vault_address: &Address) -> Result<Profile> {
        if let Res::CreateProfile(id) = self.call(CreateProfile(vault_address.clone())).await? {
            // Set current_profile_id, if it's first profile
            if self.current_profile_id.is_none() {
                self.current_profile_id = Some(id.clone());
            }
            Ok(Profile::new(id, self.handle.async_try_clone().await?))
        } else {
            err()
        }
    }

    pub async fn remove_profile<I: Into<ProfileIdentifier>>(
        &mut self,
        profile_id: I,
    ) -> Result<()> {
        self.cast(RemoveProfile(profile_id.into())).await
    }

    pub async fn current_profile(&self) -> Result<Option<Profile>> {
        match &self.current_profile_id {
            None => Ok(None),
            Some(id) => Ok(Some(Profile::new(
                id.clone(),
                self.handle.async_try_clone().await?,
            ))),
        }
    }
}

#[async_trait]
impl Identity for Entity {
    async fn identifier(&self) -> Result<ProfileIdentifier> {
        Ok(self.current_profile_id.as_ref().unwrap().clone())
    }

    async fn create_key(&mut self, label: String) -> Result<()> {
        self.cast(CreateKey(self.id(), label)).await
    }

    async fn add_key(&mut self, label: String, secret: &Secret) -> Result<()> {
        if let Res::AddKey = self.call(AddKey(self.id(), label, secret.clone())).await? {
            Ok(())
        } else {
            err()
        }
    }

    async fn rotate_root_secret_key(&mut self) -> Result<()> {
        self.cast(RotateKey(self.id())).await
    }

    async fn get_root_secret_key(&self) -> Result<Secret> {
        if let Res::GetProfileSecretKey(secret) = self.call(GetProfileSecretKey(self.id())).await? {
            Ok(secret)
        } else {
            err()
        }
    }

    async fn get_secret_key(&self, label: String) -> Result<Secret> {
        if let Res::GetSecretKey(secret) = self.call(GetSecretKey(self.id(), label)).await? {
            Ok(secret)
        } else {
            err()
        }
    }

    async fn get_root_public_key(&self) -> Result<PublicKey> {
        if let Res::GetProfilePublicKey(public_key) =
            self.call(GetProfilePublicKey(self.id())).await?
        {
            Ok(public_key)
        } else {
            err()
        }
    }

    async fn get_public_key(&self, label: String) -> Result<PublicKey> {
        if let Res::GetPublicKey(public_key) = self.call(GetPublicKey(self.id(), label)).await? {
            Ok(public_key)
        } else {
            err()
        }
    }

    async fn create_auth_proof(&mut self, state_slice: &[u8]) -> Result<AuthenticationProof> {
        if let Res::CreateAuthenticationProof(proof) = self
            .call(CreateAuthenticationProof(
                self.id(),
                state_slice.as_ref().to_vec(),
            ))
            .await?
        {
            Ok(proof)
        } else {
            err()
        }
    }

    async fn verify_auth_proof(
        &mut self,
        state_slice: &[u8],
        peer_id: &ProfileIdentifier,
        proof_slice: &[u8],
    ) -> Result<bool> {
        if let Res::VerifyAuthenticationProof(verified) = self
            .call(VerifyAuthenticationProof(
                self.id(),
                state_slice.as_ref().to_vec(),
                peer_id.clone(),
                proof_slice.as_ref().to_vec(),
            ))
            .await?
        {
            Ok(verified)
        } else {
            err()
        }
    }

    async fn add_change(&mut self, change_event: ProfileChangeEvent) -> Result<()> {
        self.cast(AddChange(self.id(), change_event)).await
    }

    async fn get_changes(&self) -> Result<Changes> {
        if let Res::GetChanges(changes) = self.call(GetChanges(self.id())).await? {
            Ok(changes)
        } else {
            err()
        }
    }

    async fn verify_changes(&mut self) -> Result<bool> {
        if let Res::VerifyChanges(verified) = self.call(VerifyChanges(self.id())).await? {
            Ok(verified)
        } else {
            err()
        }
    }

    async fn get_contacts(&self) -> Result<Vec<Contact>> {
        if let Res::Contacts(contact) = self.call(GetContacts(self.id())).await? {
            Ok(contact)
        } else {
            err()
        }
    }

    async fn as_contact(&mut self) -> Result<Contact> {
        let mut profile = self
            .current_profile()
            .await
            .unwrap()
            .expect("no current profile");
        let contact = profile.as_contact().await?;
        Ok(contact)
    }

    async fn get_contact(&mut self, contact_id: &ProfileIdentifier) -> Result<Option<Contact>> {
        if let Res::GetContact(contact) =
            self.call(GetContact(self.id(), contact_id.clone())).await?
        {
            match contact {
                MaybeContact::None => Ok(None),
                MaybeContact::Contact(contact) => Ok(Some(contact)),
            }
        } else {
            err()
        }
    }

    async fn verify_contact(&mut self, contact: Contact) -> Result<bool> {
        if let Res::VerifyContact(contact) = self.call(VerifyContact(self.id(), contact)).await? {
            Ok(contact)
        } else {
            err()
        }
    }

    async fn verify_and_add_contact(&mut self, contact: Contact) -> Result<bool> {
        if let Res::VerifyAndAddContact(verified_and_added) =
            self.call(VerifyAndAddContact(self.id(), contact)).await?
        {
            Ok(verified_and_added)
        } else {
            err()
        }
    }

    async fn verify_and_update_contact(
        &mut self,
        profile_id: &ProfileIdentifier,
        changes: &[ProfileChangeEvent],
    ) -> Result<bool> {
        if let Res::VerifyAndUpdateContact(verified_and_updated) = self
            .call(VerifyAndUpdateContact(
                self.id(),
                profile_id.clone(),
                changes.as_ref().to_vec(),
            ))
            .await?
        {
            Ok(verified_and_updated)
        } else {
            err()
        }
    }

    async fn get_lease(
        &self,
        lease_manager_route: &Route,
        org_id: String,
        bucket: String,
        ttl: TTL,
    ) -> Result<Lease> {
        if let Res::Lease(lease) = self
            .call(GetLease(
                lease_manager_route.clone(),
                self.id(),
                org_id.to_string(),
                bucket.to_string(),
                ttl,
            ))
            .await?
        {
            Ok(lease)
        } else {
            err()
        }
    }

    async fn revoke_lease(&mut self, lease_manager_route: &Route, lease: Lease) -> Result<()> {
        self.cast(RevokeLease(lease_manager_route.clone(), self.id(), lease))
            .await
    }
}

impl Entity {
    pub async fn create_secure_channel_listener(
        &mut self,
        address: impl Into<Address>,
        trust_policy: impl TrustPolicy,
    ) -> Result<()> {
        let profile = self
            .current_profile()
            .await
            .unwrap()
            .expect("no current profile");
        let ctx = self.handle.ctx();
        let trust_policy_address = TrustPolicyImpl::create_worker(ctx, trust_policy).await?;
        if let Res::CreateSecureChannelListener = self
            .call(CreateSecureChannelListener(
                profile.identifier().await.expect("couldn't get profile id"),
                address.into(),
                trust_policy_address,
            ))
            .await?
        {
            Ok(())
        } else {
            err()
        }
    }

    pub async fn create_secure_channel(
        &mut self,
        route: impl Into<Route>,
        trust_policy: impl TrustPolicy,
    ) -> Result<Address> {
        let profile = self
            .current_profile()
            .await
            .unwrap()
            .expect("no current profile");
        let ctx = self.handle.ctx();
        let trust_policy_address = TrustPolicyImpl::create_worker(ctx, trust_policy).await?;
        if let Res::CreateSecureChannel(address) = self
            .call(CreateSecureChannel(
                profile.identifier().await.expect("couldn't get profile id"),
                route.into(),
                trust_policy_address,
            ))
            .await?
        {
            Ok(address)
        } else {
            err()
        }
    }
}