aboutsummaryrefslogtreecommitdiff
path: root/crates/secd/src/auth/n.rs
blob: 1f32fd65c62a4b2a8f4e968bf05c6278f6e85468 (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
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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
use crate::{
    client::{
        email::{
            parse_email_template, EmailValidationMessage, Sendable, DEFAULT_SIGNIN_EMAIL,
            DEFAULT_SIGNUP_EMAIL,
        },
        store::{
            AddressLens, AddressValidationLens, CredentialLens, IdentityLens, SessionLens,
            Storable, StoreError,
        },
    },
    util, Address, AddressType, AddressValidation, AddressValidationId, AddressValidationMethod,
    Credential, CredentialType, Identity, IdentityId, Secd, SecdError, Session, SessionToken,
    ADDRESSS_VALIDATION_CODE_SIZE, ADDRESS_VALIDATION_ALLOWS_ATTEMPTS,
    ADDRESS_VALIDATION_IDENTITY_SURJECTION, EMAIL_VALIDATION_DURATION,
};
use email_address::EmailAddress;
use log::warn;
use rand::Rng;
use std::str::FromStr;
use time::{Duration, OffsetDateTime};
use uuid::Uuid;

impl Secd {
    pub async fn validate_email(
        &self,
        email_address: &str,
        identity_id: Option<IdentityId>,
    ) -> Result<AddressValidation, SecdError> {
        let email_address = EmailAddress::from_str(email_address)?;
        let mut email_template = self
            .cfg
            .email_signup_message
            .clone()
            .unwrap_or(DEFAULT_SIGNUP_EMAIL.into());

        let mut address = Address {
            id: Uuid::new_v4(),
            t: AddressType::Email {
                email_address: Some(email_address.clone()),
            },
            created_at: OffsetDateTime::now_utc(),
        };

        if let Err(StoreError::IdempotentCheckAlreadyExists) =
            address.write(self.store.clone()).await
        {
            address = Address::find(
                self.store.clone(),
                &AddressLens {
                    id: None,
                    t: Some(&AddressType::Email {
                        email_address: Some(email_address.clone()),
                    }),
                },
            )
            .await?
            .into_iter()
            .next()
            .ok_or(SecdError::AddressValidationFailed)?;

            email_template = self
                .cfg
                .email_signin_message
                .clone()
                .unwrap_or(DEFAULT_SIGNIN_EMAIL.into());
        }

        let secret = hex::encode(rand::thread_rng().gen::<[u8; 32]>());
        let code: String = vec![0; ADDRESSS_VALIDATION_CODE_SIZE as usize]
            .into_iter()
            .map(|_| char::from_digit(rand::thread_rng().gen_range(0..=9), 10).unwrap())
            .collect();

        let mut validation = AddressValidation {
            id: Uuid::new_v4(),
            identity_id,
            address,
            method: AddressValidationMethod::Email,
            created_at: OffsetDateTime::now_utc(),
            expires_at: OffsetDateTime::now_utc()
                .checked_add(Duration::new(EMAIL_VALIDATION_DURATION, 0))
                .ok_or(SecdError::Todo)?,
            revoked_at: None,
            validated_at: None,
            attempts: 0,
            hashed_token: util::hash(&secret.as_bytes()),
            hashed_code: util::hash(&code.as_bytes()),
        };

        validation.write(self.store.clone()).await?;

        let msg = EmailValidationMessage {
            from_address: self
                .cfg
                .email_address_from
                .clone()
                .unwrap_or("SecD <noreply@secd.com>".parse().unwrap()),
            replyto_address: self
                .cfg
                .email_address_replyto
                .clone()
                .unwrap_or("SecD <noreply@secd.com>".parse().unwrap()),
            recipient: email_address.clone(),
            subject: "Login Request".into(),
            body: parse_email_template(&email_template, validation.id, Some(secret), Some(code))?,
        };

        match msg.send(self.email_messenger.clone()).await {
            Ok(_) => { /* TODO: Write down the message*/ }
            Err(e) => {
                validation.revoked_at = Some(OffsetDateTime::now_utc());
                validation.write(self.store.clone()).await?;
                return Err(SecdError::EmailMessengerError(e));
            }
        }

        Ok(validation)
    }
    pub async fn validate_sms(
        &self,
        // phone_number: &PhoneNumber,
    ) -> Result<AddressValidation, SecdError> {
        todo!()
    }

    pub async fn complete_address_validation(
        &self,
        validation_id: &AddressValidationId,
        plaintext_token: Option<String>,
        plaintext_code: Option<String>,
    ) -> Result<Session, SecdError> {
        let mut validation = AddressValidation::find(
            self.store.clone(),
            &AddressValidationLens {
                id: Some(validation_id),
            },
        )
        .await?
        .into_iter()
        .next()
        .ok_or(SecdError::AddressValidationFailed)?;

        if validation.validated_at.is_some() {
            return Err(SecdError::AddressValidationExpiredOrConsumed);
        }

        validation.attempts += 1;
        if validation.attempts > ADDRESS_VALIDATION_ALLOWS_ATTEMPTS as i32 {
            warn!(
                "validation failed: Too many validation attempts were tried for validation {:?}",
                validation.id
            );
            validation.write(self.store.clone()).await?;
            return Err(SecdError::AddressValidationExpiredOrConsumed);
        }

        let hashed_token = plaintext_token.map(|s| util::hash(s.as_bytes()));
        let hashed_code = plaintext_code.map(|c| util::hash(c.as_bytes()));

        let mut warn_msg = None;
        match (hashed_token, hashed_code) {
            (None, None) => {
                warn_msg = Some("neither token nor hash was provided during the address validation session exchange");
            }
            (Some(t), None) => {
                if validation.hashed_token != t {
                    warn_msg =
                        Some("the provided token does not match the address validation token");
                }
            }
            (None, Some(c)) => {
                if validation.hashed_code != c {
                    warn_msg = Some("the provided code does not match the address validation code");
                }
            }
            (Some(t), Some(c)) => {
                if validation.hashed_token != t || validation.hashed_code != c {
                    warn_msg = Some("the provided token and code must both match the address validation token and code");
                }
            }
        };

        if let Some(msg) = warn_msg {
            warn!("validation failed: {}", msg);
            validation.write(self.store.clone()).await?;
            return Err(SecdError::AddressValidationSessionExchangeFailed);
        }

        let identity = Identity::find(
            self.store.clone(),
            &IdentityLens {
                id: None,
                address_type: Some(&validation.address.t),
                validated_address: Some(true),
                session_token_hash: None,
            },
        )
        .await?;

        if !ADDRESS_VALIDATION_IDENTITY_SURJECTION && identity.len() > 1 {
            warn!("validation failed: identity validation surjection disallowed");
            validation.write(self.store.clone()).await?;
            return Err(SecdError::TooManyIdentities);
        }

        let mut identity = identity.into_iter().next();
        if identity.is_none() {
            let i = Identity {
                id: Uuid::new_v4(),
                address_validations: vec![],
                credentials: vec![],
                rules: vec![],
                metadata: None,
                created_at: OffsetDateTime::now_utc(),
                deleted_at: None,
            };
            i.write(self.store.clone()).await?;
            identity = Some(i);
        }

        assert!(identity.is_some());

        // If the validation was attached to another identity, unless surjection is allowed, it cannot be recorded.
        if !ADDRESS_VALIDATION_IDENTITY_SURJECTION
            && validation.identity_id.is_some()
            && identity.as_ref().map(|i| i.id) != validation.identity_id
        {
            warn!("validation failed: identity validation surjection is disallowed, but found existing identity for another account");
            validation.write(self.store.clone()).await?;
            return Err(SecdError::TooManyIdentities);
        }

        validation.identity_id = identity.map(|i| i.id);
        validation.validated_at = Some(OffsetDateTime::now_utc());
        validation.write(self.store.clone()).await?;

        let session = Session::new(validation.identity_id.expect("unreachable d3ded289-72eb-4a42-a37d-f5c9c697cc61 [assert(identity.is_some()) prevents this]"))?;
        session.write(self.store.clone()).await?;

        Ok(session)
    }

    pub async fn create_credential(
        &self,
        t: CredentialType,
        identity_id: Option<IdentityId>,
    ) -> Result<Identity, SecdError> {
        let identity = match identity_id {
            Some(id) => Identity::find(
                self.store.clone(),
                &IdentityLens {
                    id: Some(&id),
                    address_type: None,
                    validated_address: None,
                    session_token_hash: None,
                },
            )
            .await?
            .into_iter()
            .nth(0)
            .ok_or(SecdError::IdentityNotFound)?,

            None => {
                let id = Identity {
                    id: Uuid::new_v4(),
                    address_validations: vec![],
                    credentials: vec![],
                    rules: vec![],
                    metadata: None,
                    created_at: OffsetDateTime::now_utc(),
                    deleted_at: None,
                };
                id.write(self.store.clone()).await?;
                id
            }
        };

        let mut credential = match &Credential::find(
            self.store.clone(),
            &CredentialLens {
                id: None,
                identity_id: Some(identity.id),
                t: Some(&t),
                restrict_by_key: Some(false),
            },
        )
        .await?[..]
        {
            [] => Credential {
                id: Uuid::new_v4(),
                identity_id: identity.id,
                t,
                created_at: OffsetDateTime::now_utc(),
                revoked_at: None,
                deleted_at: None,
            },
            _ => return Err(SecdError::CredentialAlreadyExists),
        };

        credential.hash(&self.crypter)?;
        credential
            .write(self.store.clone())
            .await
            .map_err(|err| match err {
                StoreError::IdempotentCheckAlreadyExists => SecdError::CredentialAlreadyExists,
                err => SecdError::StoreError(err),
            })?;

        Ok(identity)
    }

    pub async fn validate_credential(
        &self,
        // t: CredentialType,
        // key: String,
        // value: Option<String>,
    ) -> Result<Session, SecdError> {
        // Credential::find(store, lens) use key here as unique index
        todo!()
    }

    pub async fn get_session(&self, t: &SessionToken) -> Result<Session, SecdError> {
        let token = hex::decode(t)?;
        let mut session = Session::find(
            self.store.clone(),
            &SessionLens {
                token_hash: Some(&util::hash(&token)),
                identity_id: None,
            },
        )
        .await?;
        assert!(session.len() <= 1, "get session failed: multiple sessions found for a single token. This is very _very_ bad.");

        if session.is_empty() {
            return Err(SecdError::InvalidSession);
        } else {
            let mut session = session.swap_remove(0);
            session.token = token;
            Ok(session)
        }
    }

    pub async fn get_identity(
        &self,
        i: Option<IdentityId>,
        t: Option<SessionToken>,
    ) -> Result<Identity, SecdError> {
        let token_hash = match t {
            Some(tok) => Some(util::hash(&hex::decode(&tok)?)),
            None => None,
        };

        let mut i = Identity::find(
            self.store.clone(),
            &IdentityLens {
                id: i.as_ref(),
                address_type: None,
                validated_address: None,
                session_token_hash: token_hash,
            },
        )
        .await?;

        assert!(
            i.len() <= 1,
            "The provided id refers to more than one identity. This is very _very_ bad."
        );

        if i.is_empty() {
            return Err(SecdError::IdentityNotFound);
        } else {
            Ok(i.swap_remove(0))
        }
    }

    pub async fn update_identity_metadata(
        &self,
        i: IdentityId,
        md: String,
    ) -> Result<Identity, SecdError> {
        let mut identity = Identity::find(
            self.store.clone(),
            &IdentityLens {
                id: Some(&i),
                address_type: None,
                validated_address: None,
                session_token_hash: None,
            },
        )
        .await?
        .into_iter()
        .nth(0)
        .ok_or(SecdError::IdentityNotFound)?;

        identity.metadata = Some(md);
        identity.write(self.store.clone()).await?;

        Ok(identity)
    }

    pub async fn revoke_session(&self, session: &mut Session) -> Result<(), SecdError> {
        session.revoked_at = Some(OffsetDateTime::now_utc());
        session.write(self.store.clone()).await?;
        Ok(())
    }
}