aboutsummaryrefslogtreecommitdiff
path: root/crates/secd/src/auth/n.rs
blob: 12a5411d540bca551b03c7f730fdf523a0697ea7 (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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
use crate::{
    client::{
        email::{
            parse_email_template, EmailValidationMessage, Sendable, DEFAULT_SIGNIN_EMAIL,
            DEFAULT_SIGNUP_EMAIL,
        },
        store::{
            AddressLens, AddressValidationLens, CredentialLens, IdentityLens, ImpersonatorLens,
            Storable, StoreError,
        },
    },
    util::{self, ErrorContext},
    Address, AddressType, AddressValidation, AddressValidationId, AddressValidationMethod,
    Credential, CredentialId, CredentialType, Identity, IdentityId, Impersonator, Secd, SecdError,
    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 tokio::join;
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()
                .and_then(|s| s.parse().ok())
                .unwrap_or("SecD <noreply@secd.com>".parse().unwrap()),
            replyto_address: self
                .cfg
                .email_address_replyto
                .clone()
                .and_then(|s| s.parse().ok())
                .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<Credential, 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),
            },
        )
        .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![],
                new_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 mut session = Credential::new_session(validation.identity_id.expect("unreachable d3ded289-72eb-4a42-a37d-f5c9c697cc61 [assert(identity.is_some()) prevents this]"))?;
        let plaintext_type = session.t.clone();

        session.hash(&self.crypter)?;
        session.write(self.store.clone()).await?;

        session.t = plaintext_type;

        Ok(session)
    }

    pub async fn create_identity_with_credential(
        &self,
        t: CredentialType,
        identity_id: IdentityId,
        metadata: Option<String>,
    ) -> Result<Identity, SecdError> {
        let identity = Identity::find(
            self.store.clone(),
            &IdentityLens {
                id: Some(&identity_id),
                address_type: None,
                validated_address: None,
            },
        )
        .await?;

        if !identity.is_empty() {
            log::error!("identity was found while creating a new identity with a credential");
            return Err(SecdError::IdentityAlreadyExists);
        }

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

        self.create_credential(t, Some(identity_id), None).await
    }

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

            None => {
                let id = Identity {
                    id: Uuid::new_v4(),
                    address_validations: vec![],
                    credentials: vec![],
                    new_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),
            },
        )
        .await?[..]
        {
            [] => Credential {
                id: Uuid::new_v4(),
                identity_id: identity.id,
                t: t.clone(),
                created_at: OffsetDateTime::now_utc(),
                revoked_at: expires_at,
                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),
            })?;

        identity.new_credentials.push(Credential {
            id: credential.id,
            identity_id: credential.identity_id,
            t,
            created_at: credential.created_at,
            revoked_at: credential.revoked_at,
            deleted_at: credential.deleted_at,
        });

        Ok(identity)
    }

    pub async fn validate_credential(&self, t: &CredentialType) -> Result<Credential, SecdError> {
        let mut retrieved = Credential::find(
            self.store.clone(),
            &CredentialLens {
                id: None,
                identity_id: None,
                t: Some(t),
            },
        )
        .await?
        .into_iter()
        .next()
        .ok_or(SecdError::InvalidCredential)?;

        match retrieved.revoked_at {
            Some(t) if t <= OffsetDateTime::now_utc() => {
                log::debug!("credential was revoked");
                Err(SecdError::InvalidCredential)
            }
            _ => Ok(()),
        }?;

        match retrieved.deleted_at {
            Some(t) if t <= OffsetDateTime::now_utc() => {
                log::debug!("credential was deleted");
                Err(SecdError::InvalidCredential)
            }
            _ => Ok(()),
        }?;

        retrieved.hash_compare(&t, &self.crypter)?;

        // Return the initially provided plaintext credential since it's valid
        retrieved.t = t.clone();

        Ok(retrieved)
    }

    pub async fn get_identity(
        &self,
        i: Option<IdentityId>,
        t: Option<CredentialType>,
    ) -> Result<Identity, SecdError> {
        if i.is_none() && t.is_none() {
            log::error!("get_identity expects that at least one of IdentityId or CredentialType is provided. None were found.");
            return Err(SecdError::IdentityNotFound);
        }

        let c = Credential::find(
            self.store.clone(),
            &CredentialLens {
                id: None,
                identity_id: i,
                t: t.as_ref(),
            },
        )
        .await?;

        assert!(
            c.len() <= 1,
            "The provided credential refers to more than one identity. This is very _very_ bad."
        );
        let identity_id = c
            .into_iter()
            .next()
            .ok_or(SecdError::InvalidCredential)
            .ctx("No identities were found for the provided identity_id and credential_type")?
            .identity_id;

        if i.is_some() && i != Some(identity_id) {
            log::error!(
                "The provided identity does not match the identity associated with this credential"
            );
            return Err(SecdError::InvalidCredential);
        }

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

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

        if i.is_empty() {
            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,
            },
        )
        .await?
        .into_iter()
        .next()
        .ok_or(SecdError::IdentityNotFound)?;

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

        Ok(identity)
    }

    pub async fn revoke_credential(&self, credential_id: CredentialId) -> Result<(), SecdError> {
        let mut credential = Credential::find(
            self.store.clone(),
            &CredentialLens {
                id: Some(credential_id),
                identity_id: None,
                t: None,
            },
        )
        .await?
        .into_iter()
        .next()
        .ok_or(SecdError::InvalidCredential)?;

        credential.revoked_at = Some(OffsetDateTime::now_utc());
        credential.write(self.store.clone()).await?;
        Ok(())
    }

    pub async fn impersonate(
        &self,
        impersonator_id: &IdentityId,
        target_id: &IdentityId,
    ) -> Result<Credential, SecdError> {
        let impersonator_lens = IdentityLens {
            id: Some(&impersonator_id),
            address_type: None,
            validated_address: None,
        };
        let target_lens = IdentityLens {
            id: Some(&target_id),
            address_type: None,
            validated_address: None,
        };
        let (i, t) = join!(
            Identity::find(self.store.clone(), &impersonator_lens,),
            Identity::find(self.store.clone(), &target_lens,)
        );

        let (i, t) = (
            i.ctx("failed to retrieve impersonator identity")?,
            t.ctx("failed to retrieve target identity")?,
        );
        if i.is_empty() || t.is_empty() {
            return Err(SecdError::IdentityNotFound)
                .ctx("failed to retrieve impersonator or target identity for impersonation");
        }

        let existing_impersonation = Impersonator::find(
            self.store.clone(),
            &ImpersonatorLens {
                impersonator_id: Some(impersonator_id),
                target_id: Some(target_id),
            },
        )
        .await
        .ctx("failed to find existing impersonation")?;

        // TODO: We could expire the session chain, but I think we want to handle this more intelligently.
        // For now, just revoke the credential manually...pita I know...
        if !existing_impersonation.is_empty() {
            return Err(SecdError::ImpersonatorAlreadyExists)
                .ctx("Target already being impersonated by the provided impersonator identity");
        }

        let new_identity = self
            .create_credential(
                Credential::new_session(*target_id)?.t,
                Some(*target_id),
                OffsetDateTime::now_utc().checked_add(Duration::minutes(30)),
            )
            .await
            .ctx("failed to create new credential for target identity")?;

        let new_session = new_identity
            .new_credentials
            .iter()
            .next()
            .ok_or(SecdError::InvalidCredential)
            .ctx("failed to retrieve new session from newly created target credential")?
            .clone();

        Impersonator {
            impersonator: i
                .into_iter()
                .next()
                .ok_or(SecdError::IdentityNotFound)
                .ctx("failed to find impersonator identity")?,
            target: new_identity,
            created_at: OffsetDateTime::now_utc(),
        }
        .write(self.store.clone())
        .await
        .ctx("failed to write new impersonator")?;

        Ok(new_session)
    }
}