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
#[cfg(any(feature = "tokio", test))]
use std::sync::Arc;

use passkey_types::{
    ctap2::{
        make_credential::PublicKeyCredentialRpEntity,
        make_credential::PublicKeyCredentialUserEntity, Ctap2Error, StatusCode,
    },
    webauthn::PublicKeyCredentialDescriptor,
    Passkey,
};

/// Use this on a type that enables storage and fetching of credentials
#[async_trait::async_trait]
pub trait CredentialStore {
    /// Defines the return type of find_credentials(...)
    type PasskeyItem: TryInto<Passkey>;

    /// Find all credentials matching the given `ids` and `rp_id`.
    ///
    /// If multiple are found, it is recommended to sort the credentials using their creation date
    /// before returning as the algorithm will take the first credential from the list for assertions.
    async fn find_credentials(
        &self,
        ids: Option<&[PublicKeyCredentialDescriptor]>,
        rp_id: &str,
    ) -> Result<Vec<Self::PasskeyItem>, StatusCode>;

    /// Save the new/updated credential into your store
    async fn save_credential(
        &mut self,
        cred: Passkey,
        user: PublicKeyCredentialUserEntity,
        rp: PublicKeyCredentialRpEntity,
    ) -> Result<(), StatusCode>;
}

/// In-memory store for Passkeys
///
/// Useful for tests.
pub type MemoryStore = std::collections::HashMap<Vec<u8>, Passkey>;

#[async_trait::async_trait]
impl CredentialStore for MemoryStore {
    type PasskeyItem = Passkey;

    async fn find_credentials(
        &self,
        allow_credentials: Option<&[PublicKeyCredentialDescriptor]>,
        _rp_id: &str,
    ) -> Result<Vec<Self::PasskeyItem>, StatusCode> {
        let creds: Vec<Passkey> = allow_credentials
            .into_iter()
            .flatten()
            .filter_map(|id| self.get(&*id.id))
            .cloned()
            .collect();
        if creds.is_empty() {
            Err(Ctap2Error::NoCredentials.into())
        } else {
            Ok(creds)
        }
    }

    async fn save_credential(
        &mut self,
        cred: Passkey,
        _user: PublicKeyCredentialUserEntity,
        _rp: PublicKeyCredentialRpEntity,
    ) -> Result<(), StatusCode> {
        self.insert(cred.credential_id.clone().into(), cred);
        Ok(())
    }
}

#[async_trait::async_trait]
impl CredentialStore for Option<Passkey> {
    type PasskeyItem = Passkey;

    async fn find_credentials(
        &self,
        id: Option<&[PublicKeyCredentialDescriptor]>,
        _rp_id: &str,
    ) -> Result<Vec<Self::PasskeyItem>, StatusCode> {
        if let Some(id) = id {
            id.iter().find_map(|id| {
                // TODO: && pk.rp_id == rp_id) need rp_id on typeshared passkey
                self.clone().filter(|pk| pk.credential_id == id.id)
            })
        } else {
            self.clone() // TODO: .filter(|pk| pk.rp_id == rp_id) need rp_id on typeshared passkey
        }
        .map(|pk| vec![pk])
        .ok_or(Ctap2Error::NoCredentials.into())
    }

    async fn save_credential(
        &mut self,
        cred: Passkey,
        _user: PublicKeyCredentialUserEntity,
        _rp: PublicKeyCredentialRpEntity,
    ) -> Result<(), StatusCode> {
        self.replace(cred);
        Ok(())
    }
}

#[cfg(any(feature = "tokio", test))]
#[async_trait::async_trait]
impl<S: CredentialStore<PasskeyItem = Passkey> + Send + Sync> CredentialStore
    for Arc<tokio::sync::Mutex<S>>
{
    type PasskeyItem = Passkey;

    async fn find_credentials(
        &self,
        ids: Option<&[PublicKeyCredentialDescriptor]>,
        rp_id: &str,
    ) -> Result<Vec<Self::PasskeyItem>, StatusCode> {
        self.lock().await.find_credentials(ids, rp_id).await
    }

    async fn save_credential(
        &mut self,
        cred: Passkey,
        user: PublicKeyCredentialUserEntity,
        rp: PublicKeyCredentialRpEntity,
    ) -> Result<(), StatusCode> {
        self.lock().await.save_credential(cred, user, rp).await
    }
}

#[cfg(any(feature = "tokio", test))]
#[async_trait::async_trait]
impl<S: CredentialStore<PasskeyItem = Passkey> + Send + Sync> CredentialStore
    for Arc<tokio::sync::RwLock<S>>
{
    type PasskeyItem = Passkey;

    async fn find_credentials(
        &self,
        ids: Option<&[PublicKeyCredentialDescriptor]>,
        rp_id: &str,
    ) -> Result<Vec<Self::PasskeyItem>, StatusCode> {
        self.read().await.find_credentials(ids, rp_id).await
    }

    async fn save_credential(
        &mut self,
        cred: Passkey,
        user: PublicKeyCredentialUserEntity,
        rp: PublicKeyCredentialRpEntity,
    ) -> Result<(), StatusCode> {
        self.write().await.save_credential(cred, user, rp).await
    }
}

#[cfg(any(feature = "tokio", test))]
#[async_trait::async_trait]
impl<S: CredentialStore<PasskeyItem = Passkey> + Send + Sync> CredentialStore
    for tokio::sync::Mutex<S>
{
    type PasskeyItem = Passkey;

    async fn find_credentials(
        &self,
        ids: Option<&[PublicKeyCredentialDescriptor]>,
        rp_id: &str,
    ) -> Result<Vec<Self::PasskeyItem>, StatusCode> {
        self.lock().await.find_credentials(ids, rp_id).await
    }

    async fn save_credential(
        &mut self,
        cred: Passkey,
        user: PublicKeyCredentialUserEntity,
        rp: PublicKeyCredentialRpEntity,
    ) -> Result<(), StatusCode> {
        self.lock().await.save_credential(cred, user, rp).await
    }
}

#[cfg(any(feature = "tokio", test))]
#[async_trait::async_trait]
impl<S: CredentialStore<PasskeyItem = Passkey> + Send + Sync> CredentialStore
    for tokio::sync::RwLock<S>
{
    type PasskeyItem = Passkey;

    async fn find_credentials(
        &self,
        ids: Option<&[PublicKeyCredentialDescriptor]>,
        rp_id: &str,
    ) -> Result<Vec<Self::PasskeyItem>, StatusCode> {
        self.read().await.find_credentials(ids, rp_id).await
    }

    async fn save_credential(
        &mut self,
        cred: Passkey,
        user: PublicKeyCredentialUserEntity,
        rp: PublicKeyCredentialRpEntity,
    ) -> Result<(), StatusCode> {
        self.write().await.save_credential(cred, user, rp).await
    }
}