bitwarden_core/platform/
get_user_api_key.rs

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
use std::sync::Arc;

use bitwarden_api_api::{
    apis::accounts_api::accounts_api_key_post,
    models::{ApiKeyResponseModel, SecretVerificationRequestModel},
};
use bitwarden_crypto::{HashPurpose, MasterKey};
use log::{debug, info};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

use super::SecretVerificationRequest;
use crate::{
    client::{LoginMethod, UserLoginMethod},
    error::{Error, Result},
    require, Client,
};

pub(crate) async fn get_user_api_key(
    client: &Client,
    input: &SecretVerificationRequest,
) -> Result<UserApiKeyResponse> {
    info!("Getting Api Key");
    debug!("{:?}", input);

    let auth_settings = get_login_method(client)?;
    let request = get_secret_verification_request(&auth_settings, input)?;

    let config = client.internal.get_api_configurations().await;

    let response = accounts_api_key_post(&config.api, Some(request)).await?;
    UserApiKeyResponse::process_response(response)
}

fn get_login_method(client: &Client) -> Result<Arc<LoginMethod>> {
    if client.internal.is_authed() {
        client
            .internal
            .get_login_method()
            .ok_or(Error::NotAuthenticated)
    } else {
        Err(Error::NotAuthenticated)
    }
}

fn get_secret_verification_request(
    login_method: &LoginMethod,
    input: &SecretVerificationRequest,
) -> Result<SecretVerificationRequestModel> {
    if let LoginMethod::User(UserLoginMethod::Username { email, kdf, .. }) = login_method {
        let master_password_hash = input
            .master_password
            .as_ref()
            .map(|p| {
                let master_key = MasterKey::derive(p, email, kdf)?;

                master_key.derive_master_key_hash(p.as_bytes(), HashPurpose::ServerAuthorization)
            })
            .transpose()?;
        Ok(SecretVerificationRequestModel {
            master_password_hash,
            otp: input.otp.as_ref().cloned(),
            secret: None,
            auth_request_access_code: None,
        })
    } else {
        Err("Unsupported login method".into())
    }
}

#[derive(Serialize, Deserialize, Debug, JsonSchema)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct UserApiKeyResponse {
    /// The user's API key, which represents the client_secret portion of an oauth request.
    api_key: String,
}

impl UserApiKeyResponse {
    pub(crate) fn process_response(response: ApiKeyResponseModel) -> Result<UserApiKeyResponse> {
        let api_key = require!(response.api_key);
        Ok(UserApiKeyResponse { api_key })
    }
}