    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

    /*
     * Copyright (C) 2022  Aravinth Manivannan <realaravinth@batsense.net>
     *
     * This program is free software: you can redistribute it and/or modify
     * it under the terms of the GNU Affero General Public License as
     * published by the Free Software Foundation, either version 3 of the
     * License, or (at your option) any later version.
     *
     * This program is distributed in the hope that it will be useful,
     * but WITHOUT ANY WARRANTY; without even the implied warranty of
     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     * GNU Affero General Public License for more details.
     *
     * You should have received a copy of the GNU Affero General Public License
     * along with this program.  If not, see <https://www.gnu.org/licenses/>.
     */
    use actix_identity::Identity;
    use actix_web::{web, HttpResponse, Responder};
    use libmcaptcha::defense::Level;
    use libmcaptcha::master::messages::RenameBuilder;
    use serde::{Deserialize, Serialize};

    use db_core::errors::DBError;
    use db_core::CreateCaptcha;

    use super::create::MCaptchaDetails;
    use super::get_random;
    use crate::errors::*;
    use crate::AppData;

    #[my_codegen::post(
        path = "crate::V1_API_ROUTES.captcha.update_key",
        wrap = "crate::api::v1::get_middleware()"
    )]
    pub async fn update_key(
        payload: web::Json<MCaptchaDetails>,
        data: AppData,
        id: Identity,
    ) -> ServiceResult<impl Responder> {
        let username = id.identity().unwrap();
        let mut key;

        loop {
            key = get_random(32);

            match data
                .db
                .update_captcha_key(&username, &payload.key, &key)
                .await
            {
                Ok(_) => break,
                Err(DBError::SecretTaken) => continue,
                Err(e) => return Err(e.into()),
            }
        }

        let payload = payload.into_inner();
        let rename = RenameBuilder::default()
            .name(payload.key)
            .rename_to(key.clone())
            .build()
            .unwrap();
        data.captcha.rename(rename).await?;

        let resp = MCaptchaDetails {
            key,
            name: payload.name,
        };

        Ok(HttpResponse::Ok().json(resp))
    }

    #[derive(Serialize, Deserialize)]
    pub struct UpdateCaptcha {
        pub levels: Vec<Level>,
        pub duration: u32,
        pub description: String,
        pub key: String,
    }

    #[my_codegen::post(
        path = "crate::V1_API_ROUTES.captcha.update",
        wrap = "crate::api::v1::get_middleware()"
    )]
    pub async fn update_captcha(
        payload: web::Json<UpdateCaptcha>,
        data: AppData,
        id: Identity,
    ) -> ServiceResult<impl Responder> {
        let username = id.identity().unwrap();
        runner::update_captcha(&payload, &data, &username).await?;
        Ok(HttpResponse::Ok())
    }

    pub mod runner {
        use libmcaptcha::{master::messages::RemoveCaptcha, DefenseBuilder};

        use super::*;

        pub async fn update_captcha(
            payload: &UpdateCaptcha,
            data: &AppData,
            username: &str,
        ) -> ServiceResult<()> {
            let mut defense = DefenseBuilder::default();

            for level in payload.levels.iter() {
                defense.add_level(*level)?;
            }

            // I feel this is necessary as both difficulty factor _and_ visitor threshold of a
            // level could change so doing this would not require us to send level_id to client
            // still, needs to be benchmarked
            defense.build()?;

            data.db
                .delete_captcha_levels(username, &payload.key)
                .await?;

            let m = CreateCaptcha {
                key: &payload.key,
                duration: payload.duration as i32,
                description: &payload.description,
            };

            data.db.update_captcha_metadata(username, &m).await?;

            data.db
                .add_captcha_levels(username, &payload.key, &payload.levels)
                .await?;
            if let Err(ServiceError::CaptchaError(e)) = data
                .captcha
                .remove(RemoveCaptcha(payload.key.clone()))
                .await
            {
                log::error!(
                    "Deleting captcha key {} while updating it, error: {:?}",
                    &payload.key,
                    e
                );
            }
            Ok(())
        }
    }

    #[cfg(test)]
    mod tests {
        use actix_web::http::StatusCode;
        use actix_web::test;

        use crate::api::v1::mcaptcha::create::MCaptchaDetails;
        use crate::api::v1::mcaptcha::stats::StatsPayload;
        use crate::api::v1::ROUTES;
        use crate::tests::*;
        use crate::*;

        #[actix_rt::test]
        async fn update_and_get_mcaptcha_works_pg() {
            let data = crate::tests::pg::get_data().await;
            update_and_get_mcaptcha_works(data).await;
        }

        #[actix_rt::test]
        async fn update_and_get_mcaptcha_works_maria() {
            let data = crate::tests::maria::get_data().await;
            update_and_get_mcaptcha_works(data).await;
        }

        async fn update_and_get_mcaptcha_works(data: ArcData) {
            const NAME: &str = "updateusermcaptcha";
            const PASSWORD: &str = "longpassworddomain";
            const EMAIL: &str = "testupdateusermcaptcha@a.com";
            let data = &data;
            delete_user(data, NAME).await;

            // 1. add mcaptcha token
            register_and_signin(data, NAME, EMAIL, PASSWORD).await;
            let (_, signin_resp, token_key) = add_levels_util(data, NAME, PASSWORD).await;
            let cookies = get_cookie!(signin_resp);
            let app = get_app!(data).await;

            // 2. update token key
            let update_token_resp = test::call_service(
                &app,
                post_request!(&token_key, ROUTES.captcha.update_key)
                    .cookie(cookies.clone())
                    .to_request(),
            )
            .await;
            assert_eq!(update_token_resp.status(), StatusCode::OK);
            let updated_token: MCaptchaDetails =
                test::read_body_json(update_token_resp).await;

            // get levels with updated key
            let get_token_resp = test::call_service(
                &app,
                post_request!(&updated_token, ROUTES.captcha.get)
                    .cookie(cookies.clone())
                    .to_request(),
            )
            .await;
            // if updated key doesn't exist in database, a non 200 result will bereturned
            assert_eq!(get_token_resp.status(), StatusCode::OK);

            // get stats
            let paylod = StatsPayload { key: token_key.key };
            let get_statis_resp = test::call_service(
                &app,
                post_request!(&paylod, ROUTES.captcha.stats.get)
                    .cookie(cookies.clone())
                    .to_request(),
            )
            .await;
            // if updated key doesn't exist in database, a non 200 result will bereturned
            assert_eq!(get_statis_resp.status(), StatusCode::OK);
        }
    }