aboutsummaryrefslogtreecommitdiff
path: root/crates/secd/src/lib.rs
blob: 17186c8c0e00cf337355c23402afd06cf3a1708e (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
mod client;
mod command;
mod util;

use std::sync::Arc;

use clap::ValueEnum;
use client::{EmailMessenger, EmailMessengerError, Store};
use derive_more::Display;
use email_address::EmailAddress;
use serde::{Deserialize, Serialize};
use sqlx::FromRow;
use strum_macros::{EnumString, EnumVariantNames};
use time::OffsetDateTime;
use url::Url;
use util::get_oauth_identity_data;
use uuid::Uuid;

const SESSION_SIZE_BYTES: usize = 32;
const SESSION_DURATION: i64 = 60 /* seconds*/ * 60 /* minutes */ * 24 /* hours */ * 360 /* days */;
const EMAIL_VALIDATION_DURATION: i64 = 60 /* seconds*/ * 15 /* minutes */;
const VALIDATION_CODE_SIZE: usize = 6;

const INTERNAL_ERR_MSG: &str = "It seems an invariant was borked or something non-deterministic happened. Please file a bug with secd.";

#[derive(sqlx::FromRow, Debug, Serialize)]
pub struct ApiKey {
    pub public_key: String,
    pub private_key: String,
}

#[derive(sqlx::FromRow, Debug, Serialize)]
pub struct Authorization {
    session: Session,
}

#[derive(sqlx::FromRow, Debug, Serialize)]
pub struct Identity {
    #[sqlx(rename = "identity_public_id")]
    id: Uuid,
    #[serde(skip_serializing_if = "Option::is_none")]
    data: Option<String>,
    created_at: OffsetDateTime,
    #[serde(skip_serializing_if = "Option::is_none")]
    deleted_at: Option<OffsetDateTime>,
}

#[derive(sqlx::FromRow, Debug, Serialize)]
pub struct Session {
    #[sqlx(rename = "identity_public_id")]
    pub identity_id: IdentityId,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[sqlx(default)]
    pub secret: Option<SessionSecret>,
    #[serde(with = "time::serde::timestamp")]
    pub created_at: OffsetDateTime,
    #[serde(with = "time::serde::timestamp")]
    pub expired_at: OffsetDateTime,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub revoked_at: Option<OffsetDateTime>,
}

#[async_trait::async_trait]
trait Validation {
    fn expired(&self) -> bool;
    fn is_validated(&self) -> bool;
    async fn find_associated_identities(
        &self,
        store: Arc<dyn Store + Send + Sync>,
    ) -> anyhow::Result<Option<Identity>>;
    async fn validate(
        &mut self,
        i: &Identity,
        store: Arc<dyn Store + Send + Sync>,
    ) -> anyhow::Result<()>;
}

#[async_trait::async_trait]
impl Validation for EmailValidation {
    fn expired(&self) -> bool {
        let now = OffsetDateTime::now_utc();
        self.expired_at < now
            || self.revoked_at.map(|t| t < now).unwrap_or(false)
            || self.deleted_at.map(|t| t < now).unwrap_or(false)
    }
    fn is_validated(&self) -> bool {
        self.validated_at
            .map(|t| t >= OffsetDateTime::now_utc())
            .unwrap_or(false)
    }
    async fn find_associated_identities(
        &self,
        store: Arc<dyn Store + Send + Sync>,
    ) -> anyhow::Result<Option<Identity>> {
        store.find_identity(None, Some(&self.email_address)).await
    }
    async fn validate(
        &mut self,
        i: &Identity,
        store: Arc<dyn Store + Send + Sync>,
    ) -> anyhow::Result<()> {
        self.identity_id = Some(i.id);
        self.validated_at = Some(OffsetDateTime::now_utc());
        store.write_email_validation(&self).await?;
        Ok(())
    }
}

#[async_trait::async_trait]
impl Validation for OauthValidation {
    fn expired(&self) -> bool {
        let now = OffsetDateTime::now_utc();
        self.revoked_at.map(|t| t < now).unwrap_or(false)
            || self.deleted_at.map(|t| t < now).unwrap_or(false)
    }
    fn is_validated(&self) -> bool {
        self.validated_at
            .map(|t| t >= OffsetDateTime::now_utc())
            .unwrap_or(false)
    }
    async fn find_associated_identities(
        &self,
        store: Arc<dyn Store + Send + Sync>,
    ) -> anyhow::Result<Option<Identity>> {
        let oauth_identity = get_oauth_identity_data(&self).await?;

        let identity = store
            .find_identity(None, oauth_identity.email.as_deref())
            .await?;

        let now = OffsetDateTime::now_utc();
        if let Some(email) = oauth_identity.email.clone() {
            let identity = identity.unwrap_or(Identity {
                id: Uuid::new_v4(),
                data: None,
                created_at: OffsetDateTime::now_utc(),
                deleted_at: None,
            });
            store.write_identity(&identity).await?;
            store.write_email(&email).await?;
            store
                .write_email_validation(&EmailValidation {
                    id: Some(Uuid::new_v4()),
                    identity_id: Some(identity.id),
                    email_address: email,
                    code: None,
                    is_oauth_derived: true,
                    created_at: now,
                    expired_at: now,
                    validated_at: Some(now),
                    revoked_at: None,
                    deleted_at: None,
                })
                .await?;
            Ok(Some(identity))
        } else {
            Ok(identity)
        }
    }
    async fn validate(
        &mut self,
        i: &Identity,
        store: Arc<dyn Store + Send + Sync>,
    ) -> anyhow::Result<()> {
        self.identity_id = Some(i.id);
        self.validated_at = Some(OffsetDateTime::now_utc());
        store.write_oauth_validation(&self).await?;
        Ok(())
    }
}

#[derive(Debug, EnumString)]
pub enum ValidationType {
    Email,
    Oauth,
}

#[derive(sqlx::FromRow, Debug)]
pub struct EmailValidation {
    #[sqlx(rename = "email_validation_public_id")]
    id: Option<Uuid>,
    #[sqlx(rename = "identity_public_id")]
    identity_id: Option<IdentityId>,
    #[sqlx(rename = "address")]
    email_address: String,
    code: Option<String>,
    is_oauth_derived: bool,
    created_at: OffsetDateTime,
    expired_at: OffsetDateTime,
    validated_at: Option<OffsetDateTime>,
    revoked_at: Option<OffsetDateTime>,
    deleted_at: Option<OffsetDateTime>,
}

#[derive(Debug)]
pub struct OauthValidation {
    id: Option<Uuid>,
    identity_id: Option<IdentityId>,
    oauth_provider: OauthProvider,
    access_token: Option<String>,
    raw_response: Option<String>,
    created_at: OffsetDateTime,
    validated_at: Option<OffsetDateTime>,
    revoked_at: Option<OffsetDateTime>,
    deleted_at: Option<OffsetDateTime>,
}

#[derive(Debug, Clone)]
pub struct OauthProvider {
    pub name: OauthProviderName,
    pub flow: Option<String>,
    pub base_url: Url,
    pub response: OauthResponseType,
    pub default_scope: String,
    pub client_id: String,
    pub client_secret: String,
    pub redirect_url: Url,
    pub created_at: OffsetDateTime,
    pub deleted_at: Option<OffsetDateTime>,
}

#[derive(Debug, Display, Clone, Copy, ValueEnum, EnumString)]
pub enum OauthResponseType {
    Code,
    IdToken,
    None,
    Token,
}

// TODO: feature gate ValueEnum since it's only needed for iam builds
#[derive(Copy, Display, Clone, Debug, ValueEnum, EnumString)]
pub enum OauthProviderName {
    Amazon,
    Apple,
    Dropbox,
    Facebook,
    Github,
    Gitlab,
    Google,
    Instagram,
    LinkedIn,
    Microsoft,
    Paypal,
    Reddit,
    Spotify,
    Strava,
    Stripe,
    Twitch,
    Twitter,
    WeChat,
}

#[derive(Display, Debug, Serialize, Deserialize, EnumString, EnumVariantNames)]
#[strum(ascii_case_insensitive)]
pub enum AuthStore {
    Sqlite,
    Postgres,
    MySql,
    Mongo,
    Dynamo,
    Redis,
}

#[derive(Display, Debug, Serialize, Deserialize, EnumString, EnumVariantNames)]
#[strum(ascii_case_insensitive)]
pub enum AuthEmail {
    LocalStub,
    Ses,
    Mailgun,
    Sendgrid,
}

pub type IdentityId = Uuid;
pub type SessionSecret = String;
pub type SessionSecretHash = String;
pub type ValidationRequestId = Uuid;
pub type ValidationSecretCode = String;
pub type OauthRedirectAuthUrl = Url;

#[derive(Debug, derive_more::Display, thiserror::Error)]
pub enum SecdError {
    EmailSendError(#[from] EmailMessengerError),
    EmailValidationExpiryOverflow,
    EmailValidationRequestError,
    OauthValidationRequestError,
    IdentityIdShouldExistInvariant,
    InitializationFailure(sqlx::Error),
    InvalidCode,
    InvalidEmailAddress,
    InputValidation(String),
    InternalError(String),
    NotImplemented(String),
    SessionExpiryOverflow,
    Unauthenticated,
    Todo,
}

pub struct Secd {
    store: Arc<dyn Store + Send + Sync + 'static>,
    email_messenger: Arc<dyn EmailMessenger + Send + Sync + 'static>,
}

impl Secd {
    /// get_identity
    ///
    /// Return all information associated with the identity id.
    pub async fn get_identity(&self, identity: IdentityId) -> Result<Identity, SecdError> {
        unimplemented!()
    }
    /// get_authorization
    ///
    /// Return the authorization for this session. If the session is
    /// invalid, expired or otherwise unauthenticated, an error will
    /// be returned.
    pub async fn get_authorization(
        &self,
        secret: SessionSecret,
    ) -> Result<Authorization, SecdError> {
        match self.store.read_session(&secret).await {
            Ok(session)
                if session.expired_at > OffsetDateTime::now_utc()
                    || session.revoked_at > Some(OffsetDateTime::now_utc()) =>
            {
                Ok(Authorization { session })
            }
            Ok(_) => Err(SecdError::Unauthenticated),
            Err(_e) => Err(SecdError::Todo),
        }
    }
    /// revoke_session
    ///
    /// Revokes a session such that it may no longer be used to authenticate
    /// the associated identity.
    pub async fn revoke_session(&self, secret_hash: SessionSecretHash) -> Result<(), SecdError> {
        unimplemented!()
    }
    /// revoke_identity
    ///
    /// Soft delete an identity such that all associated resources are
    /// deleted as well.
    ///
    /// NOTE: This operation cannot be undone. Although it may not be undone
    /// a separate call to delete_identity is required to cleanup necessary
    /// resources.
    ///
    /// You may configure secd to periodically clean all revoked
    /// identities and associated resources with AUTOCLEAN_REVOKED.
    pub async fn revoke_identity(&self, identity_id: IdentityId) -> Result<(), SecdError> {
        unimplemented!()
    }
    /// delete_identity
    ///
    /// Delete an identity and all associated resources (e.g. session,
    /// authorization structures, etc...). This is a hard delete and permanently
    /// removes all stored information.
    ///
    /// NOTE: An identity _must_ be revoked before it can be deleted. Otherwise,
    /// secd will return an error.
    pub async fn delete_identity(&self, identity_id: IdentityId) -> Result<(), SecdError> {
        unimplemented!()
    }

    // register service
    // register service_action(service_id, action)
    // list services
    // list service actions

    // create permission
    // create group (name, identities)
    // create role (name, permissios)
    // list group
    // list role
    // list permission
    // describe group
    // describe role
    // describe permission
    // add_identity_to_group
    // remove_identity_from_group
    // add_permission_to_role
    // remove_permission_from_role
    // attach_role_to_group
    // attach_permission_to_group (just creates single role and attaches it)
}