summaryrefslogtreecommitdiff
path: root/src/api/auth/account.rs
blob: d96229d7ce65e464c94afe3c5686d34289b3d3cf (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
use std::sync::Arc;

use anyhow::Result;
use password_hash::SaltString;
use rand::{thread_rng, Rng};
use rocket::request::FromRequest;
use rocket::State;
use rocket::{serde::json::Json, Request};
use serde::{Deserialize, Serialize};
use time::OffsetDateTime;
use validator::Validate;

use crate::api::{Empty, EMPTY};
use crate::crypto::{random_bytes, KeyFetchToken, SessionToken};
use crate::db::{Db, DbConn};
use crate::mailer::Mailer;
use crate::push::PushClient;
use crate::types::{AccountResetID, HawkKey};
use crate::utils::DeferAction;
use crate::Config;
use crate::{
    api::auth,
    auth::{AuthSource, Authenticated},
    crypto::{AuthPW, KeyBundle, KeyFetchReq, SessionCredentials},
    types::{KeyFetchID, OauthToken, SecretKey, User, UserID, VerifyHash},
};

// TODO better error handling

// MISSING get /account/profile
// MISSING get /account/status
// MISSING post /account/status
// MISSING post /account/reset

#[derive(Deserialize, Debug, Validate)]
#[serde(deny_unknown_fields)]
#[allow(non_snake_case)]
pub(crate) struct Create {
    #[validate(email, length(min = 3, max = 256))]
    email: String,
    authPW: AuthPW,
    // MISSING service
    // MISSING redirectTo
    // MISSING resume
    // MISSING metricsContext
    // NOTE we misuse style to communicate an invite token!
    style: Option<String>,
    // MISSING verificationMethod
}

#[derive(Serialize, Debug)]
#[allow(non_snake_case)]
#[serde(deny_unknown_fields)]
pub(crate) struct CreateResp {
    uid: UserID,
    sessionToken: SessionToken,
    #[serde(skip_serializing_if = "Option::is_none")]
    keyFetchToken: Option<KeyFetchToken>,
    #[serde(with = "time::serde::timestamp")]
    authAt: OffsetDateTime,
    // MISSING verificationMethod
}

// MISSING arg: service
#[post("/account/create?<keys>", data = "<data>")]
pub(crate) async fn create(
    db: &DbConn,
    cfg: &State<Config>,
    mailer: &State<Arc<Mailer>>,
    keys: Option<bool>,
    data: Json<Create>,
) -> auth::Result<CreateResp> {
    let keys = keys.unwrap_or(false);
    let data = data.into_inner();
    data.validate().map_err(|_| auth::Error::InvalidParameter)?;

    if db.user_email_exists(&data.email).await? {
        return Err(auth::Error::AccountExists);
    }

    match (cfg.invite_only, data.style) {
        (false, Some(_)) => return Err(auth::Error::InvalidParameter),
        (false, None) => (),
        (true, None) => return Err(auth::Error::InviteOnly),
        (true, Some(code)) => {
            db.use_invite_code(&code).await.map_err(|e| match e {
                sqlx::Error::RowNotFound => auth::Error::InviteNotFound,
                e => auth::Error::Other(anyhow!(e)),
            })?;
        },
    }

    let ka = SecretKey::generate();
    let wrapwrap_kb = SecretKey::generate();
    let auth_salt = SaltString::generate(rand::rngs::OsRng);
    let stretched = data.authPW.stretch(auth_salt.as_salt())?;
    let verify_hash = stretched.verify_hash();
    let session_token = SessionToken::generate();
    let session = SessionCredentials::derive_from(&session_token);
    let key_fetch_token = if keys {
        let key_fetch_token = KeyFetchToken::generate();
        let req = KeyFetchReq::derive_from(&key_fetch_token);
        let wrapped = req
            .derive_resp()
            .wrap_keys(&KeyBundle { ka, wrap_kb: stretched.decrypt_wwkb(&wrapwrap_kb) });
        db.add_key_fetch(req.token_id, &req.req_hmac_key, &wrapped).await?;
        Some(key_fetch_token)
    } else {
        None
    };
    let uid = db
        .add_user(User {
            auth_salt,
            email: data.email.to_owned(),
            ka,
            wrapwrap_kb,
            verify_hash: VerifyHash(verify_hash),
            display_name: None,
            verified: false,
        })
        .await?;
    let auth_at = db.add_session(session.token_id, &uid, session.req_hmac_key, false, None).await?;
    let verify_code = hex::encode(&random_bytes::<16>());
    db.add_verify_code(&uid, &session.token_id, &verify_code).await?;
    // NOTE we send the email in this context rather than a spawn to signal
    // send errors to the client.
    mailer.send_account_verify(&uid, &data.email, &verify_code).await.map_err(|e| {
        error!("failed to send email: {e}");
        auth::Error::EmailFailed
    })?;
    Ok(Json(CreateResp {
        uid,
        sessionToken: session_token,
        keyFetchToken: key_fetch_token,
        authAt: auth_at,
    }))
}

#[derive(Deserialize, Debug, Validate)]
#[serde(deny_unknown_fields)]
#[allow(non_snake_case)]
pub(crate) struct Login {
    #[validate(email, length(min = 3, max = 256))]
    email: String,
    authPW: AuthPW,
    // MISSING service
    // MISSING redirectTo
    // MISSING resume
    // MISSING reason
    // MISSING unblockCode
    // MISSING originalLoginEmail
    // MISSING verificationMethod
}

#[derive(Serialize, Debug)]
#[allow(non_snake_case)]
#[serde(deny_unknown_fields)]
pub(crate) struct LoginResp {
    uid: UserID,
    sessionToken: SessionToken,
    #[serde(skip_serializing_if = "Option::is_none")]
    keyFetchToken: Option<KeyFetchToken>,
    // MISSING verificationMethod
    // MISSING verificationReason
    // NOTE this is the *account* verified status, not the session status.
    // the spec doesn't say.
    verified: bool,
    #[serde(with = "time::serde::timestamp")]
    authAt: OffsetDateTime,
    // MISSING metricsEnabled
}

// MISSING arg: service
// MISSING arg: verificationMethod
#[post("/account/login?<keys>", data = "<data>")]
pub(crate) async fn login(
    db: &DbConn,
    mailer: &State<Arc<Mailer>>,
    keys: Option<bool>,
    data: Json<Login>,
) -> auth::Result<LoginResp> {
    let keys = keys.unwrap_or(false);
    let data = data.into_inner();
    data.validate().map_err(|_| auth::Error::InvalidParameter)?;

    let (uid, user) = db.get_user(&data.email).await.map_err(|_| auth::Error::UnknownAccount)?;
    if user.email != data.email {
        return Err(auth::Error::IncorrectEmailCase);
    }
    if !user.verified {
        return Err(auth::Error::UnverifiedAccount);
    }

    let stretched = data.authPW.stretch(user.auth_salt.as_salt())?;
    if stretched.verify_hash() != user.verify_hash.0 {
        return Err(auth::Error::IncorrectPassword);
    }

    let session_token = SessionToken::generate();
    let session = SessionCredentials::derive_from(&session_token);
    let key_fetch_token = if keys {
        let key_fetch_token = KeyFetchToken::generate();
        let req = KeyFetchReq::derive_from(&key_fetch_token);
        let wrapped = req.derive_resp().wrap_keys(&KeyBundle {
            ka: user.ka,
            wrap_kb: stretched.decrypt_wwkb(&user.wrapwrap_kb),
        });
        db.add_key_fetch(req.token_id, &req.req_hmac_key, &wrapped).await?;
        Some(key_fetch_token)
    } else {
        None
    };

    let verify_code = format!("{:06}", thread_rng().gen_range(0..=999999));
    let auth_at = db
        .add_session(session.token_id, &uid, session.req_hmac_key, false, Some(&verify_code))
        .await?;
    // NOTE we send the email in this context rather than a spawn to signal
    // send errors to the client.
    mailer.send_session_verify(&data.email, &verify_code).await.map_err(|e| {
        error!("failed to send email: {e}");
        auth::Error::EmailFailed
    })?;
    Ok(Json(LoginResp {
        uid,
        sessionToken: session_token,
        keyFetchToken: key_fetch_token,
        verified: true,
        authAt: auth_at,
    }))
}

#[derive(Deserialize, Debug, Validate)]
#[serde(deny_unknown_fields)]
#[allow(non_snake_case)]
pub(crate) struct Destroy {
    #[validate(email, length(min = 3, max = 256))]
    email: String,
    authPW: AuthPW,
}

// TODO may also be authenticated with a verified session
#[post("/account/destroy", data = "<data>")]
pub(crate) async fn destroy(
    db: &DbConn,
    db_pool: &Db,
    defer: &DeferAction,
    pc: &State<Arc<PushClient>>,
    data: Json<Destroy>,
) -> auth::Result<Empty> {
    let data = data.into_inner();
    data.validate().map_err(|_| auth::Error::InvalidParameter)?;

    let (uid, user) = db.get_user(&data.email).await.map_err(|_| auth::Error::UnknownAccount)?;
    if user.email != data.email {
        return Err(auth::Error::IncorrectEmailCase);
    }

    let stretched = data.authPW.stretch(user.auth_salt.as_salt())?;
    if stretched.verify_hash() != user.verify_hash.0 {
        return Err(auth::Error::IncorrectPassword);
    }

    let devs = db.get_devices(&uid).await;
    db.delete_user(&data.email).await?;
    match devs {
        Ok(devs) => defer.spawn_after_success("api::account/destroy(post)", {
            let (pc, db) = (Arc::clone(pc), db_pool.clone());
            async move {
                let db = db.begin().await?;
                pc.account_destroyed(&devs, &uid).await;
                db.commit().await?;
                Ok(())
            }
        }),
        Err(e) => warn!("account_destroyed push failed: {e}"),
    }

    Ok(EMPTY)
}

#[derive(Deserialize, Serialize, Debug)]
#[serde(deny_unknown_fields)]
pub(crate) struct KeysResp {
    bundle: String,
}

// NOTE the key fetch endpoint must delete a key fetch token from the database
// once it has identified it, regardless of whether the request succeeds or
// fails. we'll do this with a single-use auth source that sets the db to always
// commit. the auth source must not be used for anything else. we can get away
// with using a request guard because we'll always commit even if the guard
// fails, but this is only allowable because this is the only handler for the path.

#[derive(Debug)]
pub(crate) struct WithKeyFetch;

#[async_trait]
impl AuthSource for WithKeyFetch {
    type ID = KeyFetchID;
    type Context = Vec<u8>;
    async fn hawk(r: &Request<'_>, id: &KeyFetchID) -> Result<(HawkKey, Self::Context)> {
        let db = Authenticated::<(), Self>::get_conn(r).await?;
        db.always_commit().await?;
        Ok(db.finish_key_fetch(id).await?)
    }
    async fn bearer_token(_: &Request<'_>, _: &OauthToken) -> Result<(KeyFetchID, Self::Context)> {
        // key fetch tokens are only valid in hawk requests
        bail!("invalid key fetch authentication")
    }
}

#[get("/account/keys")]
pub(crate) async fn keys(auth: Authenticated<(), WithKeyFetch>) -> Json<KeysResp> {
    // NOTE contrary to its own api spec fxa does not delete a key fetch if the
    // associated session is not verified. we don't duplicate this special case
    // because we control the clients, and requesting keys on an unverified session
    // can be interpreted as a protocol violation anyway.
    Json(KeysResp { bundle: hex::encode(&auth.context) })
}

#[derive(Debug)]
pub(crate) struct WithResetToken;

#[async_trait]
impl AuthSource for WithResetToken {
    type ID = AccountResetID;
    type Context = UserID;
    async fn hawk(r: &Request<'_>, id: &AccountResetID) -> Result<(HawkKey, Self::Context)> {
        // unlike key fetch we'll use a separate transaction here since the body of the
        // handler can fail.
        let pool = <&Db as FromRequest>::from_request(r)
            .await
            .success_or_else(|| anyhow!("could not open db connection"))?;
        let db = pool.begin().await?;
        let result = db.finish_account_reset(id).await?;
        db.commit().await?;
        Ok(result)
    }
    async fn bearer_token(
        _: &Request<'_>,
        _: &OauthToken,
    ) -> Result<(AccountResetID, Self::Context)> {
        bail!("invalid password change authentication")
    }
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
#[allow(non_snake_case)]
pub(crate) struct AccountResetReq {
    authPW: AuthPW,
    // MISSING wrapKb
    // MISSING recoveryKeyId
    // MISSING sessionToken
}

// NOTE resetting an account does not clear active sync data on the storage server,
// so an account may be reported as disconnected for a while. this is not an error,
// just an inconvenience we haven't found out how to fix yet.

// MISSING arg: keys
#[post("/account/reset", data = "<data>")]
pub(crate) async fn reset(
    db: &DbConn,
    mailer: &State<Arc<Mailer>>,
    client: &State<Arc<PushClient>>,
    defer: &DeferAction,
    data: Authenticated<AccountResetReq, WithResetToken>,
) -> auth::Result<Empty> {
    let user = db.get_user_by_id(&data.context).await?;

    let notify_devs = db.get_devices(&data.context).await?;

    let wrapwrap_kb = SecretKey::generate();
    let auth_salt = SaltString::generate(rand::rngs::OsRng);
    let stretched = data.body.authPW.stretch(auth_salt.as_salt())?;
    let verify_hash = stretched.verify_hash();

    db.reset_user_auth(&data.context, auth_salt, wrapwrap_kb, VerifyHash(verify_hash)).await?;

    defer.spawn_after_success("api::auth/account/reset(post)", {
        let client = Arc::clone(client);
        async move {
            client.password_reset(&notify_devs).await;
            Ok(())
        }
    });

    mailer
        .send_account_reset(&user.email)
        .await
        .map_err(|e| {
            warn!("account reset email send failed: {e}");
        })
        .ok();

    Ok(EMPTY)
}