summaryrefslogtreecommitdiff
path: root/src/api/auth/oauth.rs
blob: 25d615039b931e63dfed7dd97faf19a902047a7f (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
use std::collections::HashMap;

use rocket::serde::json::Json;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use sha2::Digest;
use subtle::ConstantTimeEq;
use time::{Duration, OffsetDateTime};

use crate::api::auth::WithVerifiedFxaLogin;
use crate::api::{Empty, EMPTY};
use crate::crypto::SessionToken;
use crate::db::DbConn;
use crate::types::oauth::{Scope, ScopeSet};
use crate::{
    api::auth,
    auth::Authenticated,
    crypto::SessionCredentials,
    types::{
        OauthAccessToken, OauthAccessType, OauthAuthorization, OauthAuthorizationID,
        OauthRefreshToken, OauthToken, OauthTokenID, SessionID, UserID,
    },
};

// MISSING get /oauth/client/{client_id}

pub(crate) struct OauthClient {
    pub(crate) id: &'static str,
    // NOTE not read so far, but good to have
    #[allow(dead_code)]
    pub(crate) name: &'static str,
    pub(crate) scopes: &'static [Scope<'static>],
}

const SESSION_SCOPE: Scope = Scope::borrowed("https://identity.mozilla.com/tokens/session");

// NOTE the telemetry scopes don't seem to be needed. since we'd have to give
// out keys for them (fxa does) we'll exclude them entirely.
// see fxa-auth-server/config/dev.json for lists of predefined clients and permissions.
pub(crate) const OAUTH_CLIENTS: [OauthClient; 2] = [
    OauthClient {
        id: "5882386c6d801776",
        name: "Firefox",
        scopes: &[
            Scope::borrowed("profile:write"),
            Scope::borrowed("https://identity.mozilla.com/apps/oldsync"),
            Scope::borrowed("https://identity.mozilla.com/tokens/session"),
            // "https://identity.mozilla.com/ids/ecosystem_telemetry",
        ],
    },
    OauthClient {
        id: "a2270f727f45f648",
        name: "Fenix",
        scopes: &[
            Scope::borrowed("profile"),
            Scope::borrowed("https://identity.mozilla.com/apps/oldsync"),
            Scope::borrowed("https://identity.mozilla.com/tokens/session"),
            // "https://identity.mozilla.com/ids/ecosystem_telemetry",
        ],
    },
];

// NOTE fxa dev config allows scoped keys only for:
//  - https://identity.mozilla.com/apps/notes
//  - https://identity.mozilla.com/apps/oldsync
//  - https://identity.mozilla.com/ids/ecosystem_telemetry
//  - https://identity.mozilla.com/apps/send
// we only implement sync because notes and send are dead and
// telemetry is of no use to us
const SCOPES_WITH_KEYS: [Scope; 1] = [Scope::borrowed("https://identity.mozilla.com/apps/oldsync")];

fn check_client_and_scopes(
    client_id: &str,
    scope: &ScopeSet,
) -> Result<&'static OauthClient, auth::Error> {
    let desc = match OAUTH_CLIENTS.iter().find(|&s| s.id == client_id) {
        Some(d) => d,
        None => return Err(auth::Error::UnknownClientID),
    };
    if !scope.is_allowed_by(desc.scopes) {
        return Err(auth::Error::ScopesNotAllowed);
    }
    Ok(desc)
}

#[derive(Debug, Deserialize)]
pub(crate) enum PkceChallengeType {
    S256,
}

#[derive(Debug, Deserialize)]
pub(crate) enum AuthResponseType {
    #[serde(rename = "code")]
    Code,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct OauthAuthReq {
    client_id: String,
    state: String,
    keys_jwe: Option<String>,
    scope: ScopeSet,
    access_type: OauthAccessType,
    // NOTE we don't support confidential clients, so PKCE is mandatory
    code_challenge: String,

    // MISSING redirect_uri
    // MISSING acr_value

    // for validation during deserialization only
    #[allow(dead_code)]
    code_challenge_method: PkceChallengeType,
    #[allow(dead_code)]
    response_type: AuthResponseType,
}

#[derive(Debug, Serialize)]
pub(crate) struct OauthAuthResp {
    code: OauthAuthorizationID,
    state: String,
    // MISSING redirect
}

#[post("/oauth/authorization", data = "<req>")]
pub(crate) async fn authorization(
    db: &DbConn,
    req: Authenticated<OauthAuthReq, WithVerifiedFxaLogin>,
) -> auth::Result<OauthAuthResp> {
    check_client_and_scopes(&req.body.client_id, &req.body.scope)?;
    let id = OauthAuthorizationID::random();
    db.add_oauth_authorization(
        &id,
        OauthAuthorization {
            user_id: req.context.uid,
            client_id: req.body.client_id,
            scope: req.body.scope,
            access_type: req.body.access_type,
            code_challenge: req.body.code_challenge,
            keys_jwe: req.body.keys_jwe,
            auth_at: req.context.created_at,
        },
    )
    .await?;
    Ok(Json(OauthAuthResp { code: id, state: req.body.state }))
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct ScopedKeysReq {
    client_id: String,
    scope: ScopeSet,
}

#[derive(Debug, Serialize)]
#[allow(non_snake_case)]
pub(crate) struct ScopedKey {
    identifier: String,
    keyRotationSecret: &'static str,
    keyRotationTimestamp: u64,
}

#[post("/account/scoped-key-data", data = "<data>")]
pub(crate) async fn scoped_key_data(
    data: Authenticated<ScopedKeysReq, WithVerifiedFxaLogin>,
) -> auth::Result<HashMap<String, ScopedKey>> {
    check_client_and_scopes(&data.body.client_id, &data.body.scope)?;
    // like fxa we'll stub out key rotation handling entirely and return the same constants.
    Ok(Json(
        data.body
            .scope
            .split()
            .filter(|s| SCOPES_WITH_KEYS.contains(s))
            .map(|scope| {
                (
                    scope.to_string(),
                    ScopedKey {
                        identifier: scope.to_string(),
                        keyRotationSecret:
                            "0000000000000000000000000000000000000000000000000000000000000000",
                        keyRotationTimestamp: 0,
                    },
                )
            })
            .collect(),
    ))
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct OauthDestroy {
    #[allow(dead_code)]
    client_id: String,
    token: OauthToken,
}

#[post("/oauth/destroy", data = "<data>")]
pub(crate) async fn destroy(db: &DbConn, data: Json<OauthDestroy>) -> auth::Result<Empty> {
    // MISSING api spec allows an optional basic auth header, but what for?
    // TODO fxa also checks the authorization header if present, but firefox doesn't send it
    // NOTE fxa does a constant-time check for whether the provided client_id matches that
    // of the token being destroyed. since we only support a public list we can skip that,
    // which also lets us more easily deal with firefox's habit of destroying tokens that are
    // already expired
    if db.delete_oauth_token(&data.token.hash()).await? {
        Ok(EMPTY)
    } else {
        Err(auth::Error::InvalidParameter)
    }
}

#[derive(Debug, Deserialize)]
#[serde(tag = "grant_type")]
enum TokenReqDetails {
    // we can't use deny_unknown_fields when flatten is involved, and multiple
    // flattens in the same struct cause problems if one of them is greedy (like map).
    // flatten an extra map into every variant instead and check each of them.
    #[serde(rename = "authorization_code")]
    AuthCode {
        code: OauthAuthorizationID,
        code_verifier: String,
        // NOTE only useful with redirect flows, which we kinda don't support at all
        #[allow(dead_code)]
        redirect_uri: Option<String>,
        #[serde(flatten)]
        extra: HashMap<String, Value>,
    },
    #[serde(rename = "refresh_token")]
    RefreshToken {
        refresh_token: OauthToken,
        scope: ScopeSet,
        #[serde(flatten)]
        extra: HashMap<String, Value>,
    },
    #[serde(rename = "fxa-credentials")]
    FxaCreds {
        scope: ScopeSet,
        access_type: Option<OauthAccessType>,
        #[serde(flatten)]
        extra: HashMap<String, Value>,
    },
}

impl TokenReqDetails {
    fn extra_is_empty(&self) -> bool {
        match self {
            TokenReqDetails::AuthCode { extra, .. } => extra.is_empty(),
            TokenReqDetails::RefreshToken { extra, .. } => extra.is_empty(),
            TokenReqDetails::FxaCreds { extra, .. } => extra.is_empty(),
        }
    }
}

// TODO log errors in all the places

#[derive(Debug, Deserialize)]
pub(crate) struct TokenReq {
    client_id: String,
    ttl: Option<u32>,
    #[serde(flatten)]
    details: TokenReqDetails,
    // MISSING client_secret
    // MISSING redirect_uri
    // MISSING ttl
    // MISSING ppid_seed
    // MISSING resource
}

#[derive(Debug, Serialize)]
pub(crate) enum TokenType {
    #[serde(rename = "bearer")]
    Bearer,
}

#[derive(Debug, Serialize)]
pub(crate) struct TokenResp {
    access_token: OauthToken,
    #[serde(skip_serializing_if = "Option::is_none")]
    refresh_token: Option<OauthToken>,
    // MISSING id_token
    #[serde(skip_serializing_if = "Option::is_none")]
    session_token: Option<SessionToken>,
    scope: ScopeSet,
    token_type: TokenType,
    expires_in: u32,
    #[serde(with = "time::serde::timestamp")]
    auth_at: OffsetDateTime,
    #[serde(skip_serializing_if = "Option::is_none")]
    keys_jwe: Option<String>,
}

#[post("/oauth/token", data = "<req>", rank = 1)]
pub(crate) async fn token_authenticated(
    db: &DbConn,
    req: Authenticated<TokenReq, WithVerifiedFxaLogin>,
) -> auth::Result<TokenResp> {
    match &req.body.details {
        TokenReqDetails::FxaCreds { .. } => (),
        _ => return Err(auth::Error::InvalidParameter),
    }
    token_impl(
        db,
        Some(req.context.uid),
        Some(req.context.created_at),
        req.body,
        None,
        Some(req.session),
    )
    .await
}

#[post("/oauth/token", data = "<req>", rank = 2)]
pub(crate) async fn token_unauthenticated(
    db: &DbConn,
    req: Json<TokenReq>,
) -> auth::Result<TokenResp> {
    let (parent_refresh, auth_at) = match &req.details {
        TokenReqDetails::RefreshToken { refresh_token, .. } => {
            let session = db.use_session_from_refresh(&refresh_token.hash()).await?;
            (Some(refresh_token.hash()), Some(session.1.created_at))
        },
        TokenReqDetails::AuthCode { .. } => (None, None),
        _ => return Err(auth::Error::InvalidParameter),
    };
    token_impl(db, None, auth_at, req.into_inner(), parent_refresh, None).await
}

async fn token_impl(
    db: &DbConn,
    user_id: Option<UserID>,
    auth_at: Option<OffsetDateTime>,
    req: TokenReq,
    parent_refresh: Option<OauthTokenID>,
    parent_session: Option<SessionID>,
) -> auth::Result<TokenResp> {
    if !req.details.extra_is_empty() {
        return Err(auth::Error::InvalidParameter);
    }
    let ttl = req.ttl.unwrap_or(3600).clamp(0, 7 * 86400);

    let (auth_at, scope, keys_jwe, user_id, access_type) = match req.details {
        TokenReqDetails::AuthCode { code, code_verifier, .. } => {
            let auth = match db.take_oauth_authorization(&code).await {
                Ok(a) => a,
                Err(_) => return Err(auth::Error::InvalidAuthToken),
            };
            if !bool::from(auth.client_id.as_bytes().ct_eq(req.client_id.as_bytes())) {
                return Err(auth::Error::UnknownClientID);
            }
            let mut sha = sha2::Sha256::new();
            sha.update(code_verifier.as_bytes());
            let challenge = base64::encode_config(&sha.finalize(), base64::URL_SAFE_NO_PAD);
            if !bool::from(challenge.as_bytes().ct_eq(auth.code_challenge.as_bytes())) {
                return Err(auth::Error::InvalidParameter);
            }
            (auth.auth_at, auth.scope, auth.keys_jwe, auth.user_id, Some(auth.access_type))
        },
        TokenReqDetails::RefreshToken { refresh_token, scope, .. } => {
            let auth_at =
                auth_at.expect("oauth token requests with refresh token must set auth_at");
            let base = db.get_refresh_token(&refresh_token.hash()).await?;
            if !bool::from(base.client_id.as_bytes().ct_eq(req.client_id.as_bytes())) {
                return Err(auth::Error::UnknownClientID);
            }
            check_client_and_scopes(&req.client_id, &scope)?;
            if !base.scope.implies_all(&scope) {
                return Err(auth::Error::ScopesNotAllowed);
            }
            (auth_at, scope, None, base.user_id, None)
        },
        TokenReqDetails::FxaCreds { scope, access_type, .. } => {
            let user_id = user_id.expect("oauth token requests with fxa must set user_id");
            let auth_at = auth_at.expect("oauth token requests with fxa must set auth_at");
            check_client_and_scopes(&req.client_id, &scope)?;
            (auth_at, scope, None, user_id, access_type)
        },
    };

    let access_token = OauthToken::random();
    db.add_access_token(
        &access_token.hash(),
        OauthAccessToken {
            user_id,
            client_id: req.client_id.clone(),
            scope: scope.clone(),
            parent_refresh,
            parent_session,
            expires_at: OffsetDateTime::now_utc() + Duration::seconds(ttl.into()),
        },
    )
    .await?;

    let (refresh_token, session_token) = if access_type == Some(OauthAccessType::Offline) {
        let (session_token, session_id) = if scope.implies(&SESSION_SCOPE) {
            let session_token = SessionToken::generate();
            let session = SessionCredentials::derive_from(&session_token);
            db.add_session(session.token_id, &user_id, session.req_hmac_key, true, None).await?;
            (Some(session_token), Some(session.token_id))
        } else {
            (None, None)
        };

        let refresh_token = OauthToken::random();
        db.add_refresh_token(
            &refresh_token.hash(),
            OauthRefreshToken {
                user_id,
                client_id: req.client_id,
                scope: scope.remove(&SESSION_SCOPE),
                session_id,
            },
        )
        .await?;
        (Some(refresh_token), session_token)
    } else {
        (None, None)
    };

    Ok(Json(TokenResp {
        access_token,
        refresh_token,
        session_token,
        scope: scope.remove(&SESSION_SCOPE),
        token_type: TokenType::Bearer,
        expires_in: ttl,
        auth_at,
        keys_jwe,
    }))
}