summaryrefslogtreecommitdiff
path: root/src/api/profile/mod.rs
blob: 28d1e0314629cf44522cca7d015652a66876b8cb (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
use std::sync::Arc;

use either::Either;
use rocket::{
    data::ToByteUnit,
    http::{uri::Absolute, ContentType, Status},
    response::{self, Responder},
    serde::json::Json,
    Request, Response, State,
};
use serde::{Deserialize, Serialize};
use serde_json::json;
use sha2::{Digest, Sha256};
use Either::{Left, Right};

use crate::{
    api::Empty,
    auth::{Authenticated, WithBearer, AuthenticatedRequest},
    cache::Immutable,
    db::Db,
    types::{oauth::Scope, UserID},
    utils::DeferAction,
};
use crate::{db::DbConn, types::AvatarID, Config};
use crate::{push::PushClient, types::Avatar};

use super::EMPTY;

// we don't provide any additional fields. some we can't provide anyway (eg
// invalid parameter `validation`), others are implied by the request body (eg
// account exists `email`), and *our* client doesn't care about them anyway
#[derive(Debug)]
pub(crate) enum Error {
    Unauthorized,
    InvalidParameter,
    PayloadTooLarge,
    NotFound,

    // this is actually a response from the auth api (not the profile api),
    // but firefox needs the *exact response* of this auth error to refresh
    // profile fetch oauth tokens for its ui. :(
    InvalidAuthToken,

    Other(anyhow::Error),
    UnexpectedStatus(Status),
}

#[rustfmt::skip]
impl<'r> Responder<'r, 'static> for Error {
    fn respond_to(self, request: &'r Request<'_>) -> response::Result<'static> {
        let (code, errno, msg) = match self {
            Error::Unauthorized => (Status::Forbidden, 100, "unauthorized"),
            Error::InvalidParameter => (Status::BadRequest, 101, "invalid parameter in request body"),
            Error::PayloadTooLarge => (Status::PayloadTooLarge, 999, "payload too large"),
            Error::NotFound => (Status::NotFound, 999, "not found"),

            Error::InvalidAuthToken => (Status::Unauthorized, 110, "invalid authentication token"),

            Error::Other(e) => {
                error!("non-api error during request: {:?}", e);
                (Status::InternalServerError, 999, "internal error")
            },
            Error::UnexpectedStatus(s) => (s, 999, ""),
        };
        let body = json!({
            "code": code.code,
            "errno": errno,
            "error": code.reason_lossy(),
            "message": msg
        });
        Response::build_from(Json(body).respond_to(request)?).status(code).ok()
    }
}

impl From<sqlx::Error> for Error {
    fn from(e: sqlx::Error) -> Self {
        Error::Other(anyhow!(e))
    }
}

impl From<anyhow::Error> for Error {
    fn from(e: anyhow::Error) -> Self {
        Error::Other(e)
    }
}

pub(crate) type Result<T> = std::result::Result<Json<T>, Error>;

#[catch(default)]
pub(crate) fn catch_all(status: Status, r: &Request<'_>) -> Error {
    match status.code {
        // these three are caused by Json<T> errors
        400 | 422 => Error::InvalidParameter,
        413 => Error::PayloadTooLarge,
        // translate forbidden-because-token to the auth api error for firefox
        401 if r.invalid_token_used() => Error::InvalidAuthToken,
        // generic unauthorized instead of 404 for eg wrong method or nonexistant endpoints
        401 | 404 => Error::Unauthorized,
        _ => {
            error!("caught unexpected error {status}");
            Error::UnexpectedStatus(status)
        },
    }
}

// MISSING GET /v1/email
// MISSING GET /v1/subscriptions
// MISSING GET /v1/uid
// MISSING GET /v1/display_name
// MISSING DELETE /v1/cache/:uid
// MISSING send profile:change webchannel event an avatar/name changes

#[derive(Debug, Serialize)]
#[allow(non_snake_case)]
pub(crate) struct ProfileResp {
    uid: Option<UserID>,
    email: Option<String>,
    locale: Option<String>,
    amrValues: Option<Vec<String>>,
    twoFactorAuthentication: bool,
    displayName: Option<String>,
    // NOTE spec does not exist, fxa-profile-server schema says this field is optional,
    // but fenix exceptions if it's null.
    // NOTE it also *must* be a valid url, or fenix crashes entirely.
    avatar: Absolute<'static>,
    avatarDefault: bool,
    subscriptions: Option<Vec<String>>,
}

#[get("/profile")]
pub(crate) async fn profile(
    db: &DbConn,
    cfg: &State<Config>,
    auth: Authenticated<(), WithBearer>,
) -> Result<ProfileResp> {
    let has_scope = |s| auth.context.implies(&Scope::borrowed(s));

    let user = db.get_user_by_id(&auth.session).await?;
    let (avatar, avatar_default) = if has_scope("profile:avatar") {
        match db.get_user_avatar_id(&auth.session).await? {
            Some(id) => (uri!(cfg.avatars_prefix(), avatar_get_img(id = id.to_string())), false),
            None => (
                uri!(cfg.avatars_prefix(), avatar_get_img("00000000000000000000000000000000")),
                true,
            ),
        }
    } else {
        (uri!(cfg.avatars_prefix(), avatar_get_img("00000000000000000000000000000000")), true)
    };
    Ok(Json(ProfileResp {
        uid: if has_scope("profile:uid") { Some(auth.session) } else { None },
        email: if has_scope("profile:email") { Some(user.email) } else { None },
        locale: None,
        amrValues: None,
        twoFactorAuthentication: false,
        displayName: if has_scope("profile:display_name") { user.display_name } else { None },
        avatar,
        avatarDefault: avatar_default,
        subscriptions: None,
    }))
}

#[derive(Debug, Deserialize)]
#[allow(non_snake_case)]
pub(crate) struct DisplayNameReq {
    displayName: String,
}

#[post("/display_name", data = "<req>")]
pub(crate) async fn display_name_post(
    db: &DbConn,
    db_pool: &Db,
    pc: &State<Arc<PushClient>>,
    defer: &DeferAction,
    req: Authenticated<DisplayNameReq, WithBearer>,
) -> Result<Empty> {
    if !req.context.implies(&Scope::borrowed("profile:display_name:write")) {
        return Err(Error::Unauthorized);
    }

    db.set_user_name(&req.session, &req.body.displayName).await?;
    match db.get_devices(&req.session).await {
        Ok(devs) => defer.spawn_after_success("api::profile/display_name(post)", {
            let (pc, db) = (Arc::clone(pc), db_pool.clone());
            async move {
                let db = db.begin().await?;
                pc.profile_updated(&db, &devs).await;
                db.commit().await?;
                Ok(())
            }
        }),
        Err(e) => warn!("profile_updated push failed: {e}"),
    }
    Ok(EMPTY)
}

#[derive(Serialize)]
#[allow(non_snake_case)]
pub(crate) struct AvatarResp {
    id: AvatarID,
    avatarDefault: bool,
    avatar: Absolute<'static>,
}

#[get("/avatar")]
pub(crate) async fn avatar_get(
    db: &DbConn,
    cfg: &State<Config>,
    req: Authenticated<(), WithBearer>,
) -> Result<AvatarResp> {
    if !req.context.implies(&Scope::borrowed("profile:avatar")) {
        return Err(Error::Unauthorized);
    }

    let resp = match db.get_user_avatar_id(&req.session).await? {
        Some(id) => {
            let url = uri!(cfg.avatars_prefix(), avatar_get_img(id = id.to_string()));
            AvatarResp { id, avatarDefault: false, avatar: url }
        },
        None => {
            let url =
                uri!(cfg.avatars_prefix(), avatar_get_img("00000000000000000000000000000000"));
            AvatarResp { id: AvatarID([0; 16]), avatarDefault: true, avatar: url }
        },
    };
    Ok(Json(resp))
}

#[get("/<id>")]
pub(crate) async fn avatar_get_img(
    db: &DbConn,
    id: &str,
) -> std::result::Result<(ContentType, Immutable<Either<Vec<u8>, &'static [u8]>>), Error> {
    let id = id.parse().map_err(|_| Error::NotFound)?;

    if id == AvatarID([0; 16]) {
        return Ok((
            ContentType::SVG,
            Immutable(Right(include_bytes!("../../../Raven-Silhouette.svg"))),
        ));
    }

    match db.get_user_avatar(&id).await? {
        Some(avatar) => {
            let ct = avatar.content_type.parse().expect("invalid content type in db");
            Ok((ct, Immutable(Left(avatar.data))))
        },
        None => Err(Error::NotFound),
    }
}

#[derive(Serialize)]
#[allow(non_snake_case)]
pub(crate) struct AvatarUploadResp {
    url: Absolute<'static>,
}

#[post("/avatar/upload", data = "<data>")]
pub(crate) async fn avatar_upload(
    db: &DbConn,
    db_pool: &Db,
    pc: &State<Arc<PushClient>>,
    defer: &DeferAction,
    cfg: &State<Config>,
    ct: &ContentType,
    req: Authenticated<(), WithBearer>,
    data: Vec<u8>,
) -> Result<AvatarUploadResp> {
    if !req.context.implies(&Scope::borrowed("profile:avatar:write")) {
        return Err(Error::Unauthorized);
    }
    if data.len() >= 128.kibibytes() {
        return Err(Error::PayloadTooLarge);
    }

    if !ct.is_png()
        && !ct.is_gif()
        && !ct.is_bmp()
        && !ct.is_jpeg()
        && !ct.is_webp()
        && !ct.is_avif()
        && !ct.is_svg()
    {
        return Err(Error::InvalidParameter);
    }

    let mut sha = Sha256::new();
    sha.update(&req.session.0);
    sha.update(&data);
    let id = AvatarID(sha.finalize()[0..16].try_into().unwrap());

    db.set_user_avatar(&req.session, Avatar { id: id.clone(), data, content_type: ct.to_string() })
        .await?;
    match db.get_devices(&req.session).await {
        Ok(devs) => defer.spawn_after_success("api::profile/avatar/upload(post)", {
            let (pc, db) = (Arc::clone(pc), db_pool.clone());
            async move {
                let db = db.begin().await?;
                pc.profile_updated(&db, &devs).await;
                db.commit().await?;
                Ok(())
            }
        }),
        Err(e) => warn!("profile_updated push failed: {e}"),
    }

    let url = uri!(cfg.avatars_prefix(), avatar_get_img(id = id.to_string()));
    Ok(Json(AvatarUploadResp { url }))
}

#[delete("/avatar/<id>")]
pub(crate) async fn avatar_delete(
    db: &DbConn,
    id: &str,
    req: Authenticated<(), WithBearer>,
) -> Result<Empty> {
    if !req.context.implies(&Scope::borrowed("profile:avatar:write")) {
        return Err(Error::Unauthorized);
    }
    let id = id.parse().map_err(|_| Error::NotFound)?;

    db.delete_user_avatar(&req.session, &id).await?;
    Ok(EMPTY)
}