aboutsummaryrefslogtreecommitdiff
path: root/crates/secd/src/lib.rs
blob: 15a92a82a519b65b64ee316edcdb492b4640b73f (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
pub mod auth;
mod client;
mod util;

use client::{
    email::{EmailMessenger, EmailMessengerError, LocalMailer},
    spice::Spice,
    store::{
        sql_db::{PgClient, SqliteClient},
        Store, StoreError,
    },
};
use email_address::EmailAddress;
use log::{error, info};
use serde::{Deserialize, Serialize};
use serde_with::{serde_as, DisplayFromStr};
use std::{env::var, str::FromStr, sync::Arc};
use strum_macros::{Display, EnumString, EnumVariantNames};
use time::OffsetDateTime;
use url::Url;
use uuid::Uuid;

pub const ENV_AUTH_STORE_CONN_STRING: &str = "SECD_AUTH_STORE_CONN_STRING";
pub const ENV_EMAIL_MESSENGER: &str = "SECD_EMAIL_MESSENGER";
pub const ENV_EMAIL_MESSENGER_CLIENT_ID: &str = "SECD_EMAIL_MESSENGER_CLIENT_ID";
pub const ENV_EMAIL_MESSENGER_CLIENT_SECRET: &str = "SECD_EMAIL_MESSENGER_CLIENT_SECRET";
pub const ENV_SPICE_SECRET: &str = "SECD_SPICE_SECRET";
pub const ENV_SPICE_SERVER: &str = "SECD_SPICE_SERVER";

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 ADDRESSS_VALIDATION_CODE_SIZE: u8 = 6;
const ADDRESS_VALIDATION_ALLOWS_ATTEMPTS: u8 = 5;
const ADDRESS_VALIDATION_IDENTITY_SURJECTION: bool = true;

pub type AddressId = Uuid;
pub type AddressValidationId = Uuid;
pub type CredentialId = Uuid;
pub type IdentityId = Uuid;
pub type MotifId = Uuid;
pub type PhoneNumber = String;
pub type RefId = Uuid;
pub type SessionToken = String;

#[derive(Debug, derive_more::Display, thiserror::Error)]
pub enum SecdError {
    AddressValidationFailed,
    AddressValidationSessionExchangeFailed,
    AddressValidationExpiredOrConsumed,

    TooManyIdentities,
    IdentityNotFound,

    EmailMessengerError(#[from] EmailMessengerError),
    InvalidEmaillAddress(#[from] email_address::Error),

    FailedToProvideSessionIdentity(String),
    InvalidSession,

    StoreError(#[from] StoreError),
    StoreInitFailure(String),

    FailedToDecodeInput(#[from] hex::FromHexError),

    AuthorizationNotSupported(String),
    Todo,
}

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

#[derive(Display, Debug, Serialize, Deserialize, EnumString, EnumVariantNames)]
#[strum(ascii_case_insensitive)]
pub enum AuthStore {
    Sqlite { conn: String },
    Postgres { conn: String },
    Redis { conn: String },
}

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

#[serde_with::skip_serializing_none]
#[derive(Debug, Serialize)]
pub struct Address {
    id: AddressId,
    t: AddressType,
    #[serde(with = "time::serde::timestamp")]
    created_at: OffsetDateTime,
}

#[serde_as]
#[serde_with::skip_serializing_none]
#[derive(Debug, Serialize)]
pub struct AddressValidation {
    pub id: AddressValidationId,
    pub identity_id: Option<IdentityId>,
    pub address: Address,
    pub method: AddressValidationMethod,
    #[serde(with = "time::serde::timestamp")]
    pub created_at: OffsetDateTime,
    #[serde(with = "time::serde::timestamp")]
    pub expires_at: OffsetDateTime,
    #[serde(with = "time::serde::timestamp::option")]
    pub revoked_at: Option<OffsetDateTime>,
    #[serde(with = "time::serde::timestamp::option")]
    pub validated_at: Option<OffsetDateTime>,
    pub attempts: i32,
    #[serde_as(as = "serde_with::hex::Hex")]
    hashed_token: Vec<u8>,
    #[serde_as(as = "serde_with::hex::Hex")]
    hashed_code: Vec<u8>,
}

#[derive(Debug, Display, Serialize, EnumString)]
pub enum AddressValidationMethod {
    Email,
    Sms,
    Oauth,
}

#[derive(Debug, Display, Serialize, EnumString)]
pub enum AddressType {
    Email { email_address: Option<EmailAddress> },
    Sms { phone_number: Option<PhoneNumber> },
}

#[derive(Debug, Serialize)]
pub struct Credential {
    pub id: CredentialId,
    pub identity_id: IdentityId,
    pub t: CredentialType,
}

#[serde_as]
#[derive(Debug, Serialize)]
pub enum CredentialType {
    Passphrase {
        key: String,
        value: String,
    },
    Oicd {
        value: String,
    },
    OneTimeCodes {
        codes: Vec<String>,
    },
    Totp {
        #[serde_as(as = "DisplayFromStr")]
        url: Url,
        code: String,
    },
    WebAuthn {
        value: String,
    },
}

#[serde_with::skip_serializing_none]
#[derive(Debug, Serialize)]
pub struct Identity {
    pub id: IdentityId,
    pub address_validations: Vec<AddressValidation>,
    pub credentials: Vec<Credential>,
    pub rules: Vec<String>, // TODO: rules for (e.g. mfa reqs)
    pub metadata: Option<String>,
    #[serde(with = "time::serde::timestamp")]
    pub created_at: OffsetDateTime,
    #[serde(with = "time::serde::timestamp::option")]
    pub deleted_at: Option<OffsetDateTime>,
}

#[serde_as]
#[serde_with::skip_serializing_none]
#[derive(Debug, Serialize)]
pub struct Session {
    pub identity_id: IdentityId,
    #[serde_as(as = "serde_with::hex::Hex")]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub token: Vec<u8>,
    #[serde(with = "time::serde::timestamp")]
    pub created_at: OffsetDateTime,
    #[serde(with = "time::serde::timestamp")]
    pub expired_at: OffsetDateTime,
    #[serde(with = "time::serde::timestamp::option")]
    pub revoked_at: Option<OffsetDateTime>,
}

impl Secd {
    /// init
    ///
    /// Initialize SecD with the specified configuration, established the necessary
    /// constraints, persistance stores, and options.
    pub async fn init(z_schema: Option<&str>) -> Result<Self, SecdError> {
        let auth_store = AuthStore::from(var(ENV_AUTH_STORE_CONN_STRING).ok());
        let email_messenger = AuthEmailMessenger::from_str(
            &var(ENV_EMAIL_MESSENGER).unwrap_or(AuthEmailMessenger::Local.to_string()),
        )
        .expect("unreachable f4ad0f48-0812-427f-b477-0f9c67bb69c5");
        let email_messenger_client_id = var(ENV_EMAIL_MESSENGER_CLIENT_ID).ok();
        let email_messenger_client_secret = var(ENV_EMAIL_MESSENGER_CLIENT_SECRET).ok();

        info!("starting client with auth_store: {:?}", auth_store);
        info!("starting client with email_messenger: {:?}", auth_store);

        let store = match auth_store {
            AuthStore::Sqlite { conn } => {
                if z_schema.is_some() {
                    return Err(SecdError::AuthorizationNotSupported(
                        "sqlite is currently unsupported".into(),
                    ));
                }

                SqliteClient::new(
                    sqlx::sqlite::SqlitePoolOptions::new()
                        .connect(&conn)
                        .await
                        .map_err(|e| {
                            SecdError::StoreInitFailure(format!("failed to init sqlite: {}", e))
                        })?,
                )
                .await
            }
            AuthStore::Postgres { conn } => {
                PgClient::new(
                    sqlx::postgres::PgPoolOptions::new()
                        .connect(&conn)
                        .await
                        .map_err(|e| {
                            SecdError::StoreInitFailure(format!("failed to init sqlite: {}", e))
                        })?,
                )
                .await
            }
            rest @ _ => {
                error!(
                    "requested an AuthStore which has not yet been implemented: {:?}",
                    rest
                );
                unimplemented!()
            }
        };

        let email_sender = match email_messenger {
            AuthEmailMessenger::Local => LocalMailer {},
            _ => unimplemented!(),
        };

        let spice = match z_schema {
            Some(schema) => {
                let c: Arc<Spice> = Arc::new(Spice::new().await);
                c.write_schema(schema)
                    .await
                    .expect("failed to write authorization schema".into());
                Some(c)
            }
            None => None,
        };

        Ok(Secd {
            store,
            email_messenger: Arc::new(email_sender),
            spice,
        })
    }
}