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
use core::fmt::{Debug, Formatter};
use ockam_core::access_control::IncomingAccessControl;
use ockam_core::compat::{boxed::Box, sync::Arc, vec::Vec};
use ockam_core::Result;
use ockam_core::{async_trait, RelayMessage};

use crate::secure_channel::local_info::IdentitySecureChannelLocalInfo;
use crate::IdentityAttributesRepository;

/// Access control checking that message senders have a specific set of attributes
#[derive(Clone)]
pub struct CredentialAccessControl {
    required_attributes: Vec<(Vec<u8>, Vec<u8>)>,
    identity_attributes_repository: Arc<dyn IdentityAttributesRepository>,
}

impl CredentialAccessControl {
    /// Create a new credential access control
    pub fn new(
        required_attributes: &[(Vec<u8>, Vec<u8>)],
        identity_attributes_repository: Arc<dyn IdentityAttributesRepository>,
    ) -> Self {
        Self {
            required_attributes: required_attributes.to_vec(),
            identity_attributes_repository,
        }
    }
}

impl Debug for CredentialAccessControl {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        let attributes = format!("{:?}", self.required_attributes.iter().map(|x| &x.0));

        f.debug_struct("Credential Access Control")
            .field("Required attributes", &attributes)
            .finish()
    }
}

#[async_trait]
impl IncomingAccessControl for CredentialAccessControl {
    async fn is_authorized(&self, relay_message: &RelayMessage) -> Result<bool> {
        if let Ok(msg_identity_id) =
            IdentitySecureChannelLocalInfo::find_info(relay_message.local_message())
        {
            let attributes = match self
                .identity_attributes_repository
                .get_attributes(&msg_identity_id.their_identity_id())
                .await?
            {
                Some(a) => a,
                None => return Ok(false), // No attributes for that Identity
            };

            for required_attribute in self.required_attributes.iter() {
                let attr_val = match attributes.attrs().get(&required_attribute.0) {
                    Some(v) => v,
                    None => return Ok(false), // No required key
                };

                if &required_attribute.1 != attr_val {
                    return Ok(false); // Value doesn't match
                }
            }

            Ok(true)
        } else {
            Ok(false)
        }
    }
}