summaryrefslogtreecommitdiff
path: root/crates/directory/src/backend/internal/lookup.rs
blob: 7732ca5da211a14318ee5061363bc539b524d119 (plain)
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
/*
 * SPDX-FileCopyrightText: 2020 Stalwart Labs Ltd <hello@stalw.art>
 *
 * SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
 */

use mail_send::Credentials;
use store::{
    write::{DirectoryClass, ValueClass},
    IterateParams, Store, ValueKey,
};

use crate::{Principal, QueryBy, Type};

use super::{manage::ManageDirectory, PrincipalField, PrincipalInfo};

#[allow(async_fn_in_trait)]
pub trait DirectoryStore: Sync + Send {
    async fn query(
        &self,
        by: QueryBy<'_>,
        return_member_of: bool,
    ) -> trc::Result<Option<Principal>>;
    async fn email_to_ids(&self, email: &str) -> trc::Result<Vec<u32>>;

    async fn is_local_domain(&self, domain: &str) -> trc::Result<bool>;
    async fn rcpt(&self, address: &str) -> trc::Result<bool>;
    async fn vrfy(&self, address: &str) -> trc::Result<Vec<String>>;
    async fn expn(&self, address: &str) -> trc::Result<Vec<String>>;
}

impl DirectoryStore for Store {
    async fn query(
        &self,
        by: QueryBy<'_>,
        return_member_of: bool,
    ) -> trc::Result<Option<Principal>> {
        let (account_id, secret) = match by {
            QueryBy::Name(name) => (self.get_principal_id(name).await?, None),
            QueryBy::Id(account_id) => (account_id.into(), None),
            QueryBy::Credentials(credentials) => match credentials {
                Credentials::Plain { username, secret } => (
                    self.get_principal_id(username).await?,
                    secret.as_str().into(),
                ),
                Credentials::OAuthBearer { token } => {
                    (self.get_principal_id(token).await?, token.as_str().into())
                }
                Credentials::XOauth2 { username, secret } => (
                    self.get_principal_id(username).await?,
                    secret.as_str().into(),
                ),
            },
        };

        if let Some(account_id) = account_id {
            if let Some(mut principal) = self
                .get_value::<Principal>(ValueKey::from(ValueClass::Directory(
                    DirectoryClass::Principal(account_id),
                )))
                .await?
            {
                if let Some(secret) = secret {
                    if principal.verify_secret(secret).await? {
                        return Ok(None);
                    }
                }

                if return_member_of {
                    for member in self.get_member_of(principal.id).await? {
                        let field = match member.typ {
                            Type::List => PrincipalField::Lists,
                            Type::Role => PrincipalField::Roles,
                            _ => PrincipalField::MemberOf,
                        };
                        principal.append_int(field, member.principal_id);
                    }
                }
                return Ok(Some(principal));
            }
        }
        Ok(None)
    }

    async fn email_to_ids(&self, email: &str) -> trc::Result<Vec<u32>> {
        if let Some(ptype) = self
            .get_value::<PrincipalInfo>(ValueKey::from(ValueClass::Directory(
                DirectoryClass::EmailToId(email.as_bytes().to_vec()),
            )))
            .await?
        {
            if ptype.typ != Type::List {
                Ok(vec![ptype.id])
            } else {
                self.get_members(ptype.id).await
            }
        } else {
            Ok(Vec::new())
        }
    }

    async fn is_local_domain(&self, domain: &str) -> trc::Result<bool> {
        self.get_value::<PrincipalInfo>(ValueKey::from(ValueClass::Directory(
            DirectoryClass::NameToId(domain.as_bytes().to_vec()),
        )))
        .await
        .map(|p| p.map_or(false, |p| p.typ == Type::Domain))
    }

    async fn rcpt(&self, address: &str) -> trc::Result<bool> {
        self.get_value::<()>(ValueKey::from(ValueClass::Directory(
            DirectoryClass::EmailToId(address.as_bytes().to_vec()),
        )))
        .await
        .map(|ids| ids.is_some())
    }

    async fn vrfy(&self, address: &str) -> trc::Result<Vec<String>> {
        let mut results = Vec::new();
        let address = address.split('@').next().unwrap_or(address);
        if address.len() > 3 {
            self.iterate(
                IterateParams::new(
                    ValueKey::from(ValueClass::Directory(DirectoryClass::EmailToId(vec![0u8]))),
                    ValueKey::from(ValueClass::Directory(DirectoryClass::EmailToId(
                        vec![u8::MAX; 10],
                    ))),
                )
                .no_values(),
                |key, _| {
                    let key =
                        std::str::from_utf8(key.get(1..).unwrap_or_default()).unwrap_or_default();
                    if key.split('@').next().unwrap_or(key).contains(address) {
                        results.push(key.to_string());
                    }
                    Ok(true)
                },
            )
            .await?;
        }

        Ok(results)
    }

    async fn expn(&self, address: &str) -> trc::Result<Vec<String>> {
        let mut results = Vec::new();
        for account_id in self.email_to_ids(address).await? {
            if let Some(email) = self
                .get_value::<Principal>(ValueKey::from(ValueClass::Directory(
                    DirectoryClass::Principal(account_id),
                )))
                .await?
                .and_then(|mut p| p.take_str(PrincipalField::Emails))
            {
                results.push(email);
            }
        }

        Ok(results)
    }
}