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
use directories::ProjectDirs;
use serde_json::Value;

use dialoguer::{Input, Password};
use std::{
    collections::HashMap,
    fs::{create_dir_all, File},
    io::{Read, Write},
    path::PathBuf,
};

use termion::color;

use crate::error::Error;

/// docs --> https://cray-hpe.github.io/docs-csm/en-12/operations/security_and_authentication/api_authorization/
///      --> https://cray-hpe.github.io/docs-csm/en-12/operations/security_and_authentication/retrieve_an_authentication_token/
pub async fn get_api_token(
    shasta_base_url: &str,
    shasta_root_cert: &[u8],
    keycloak_base_url: &str,
    site_name: &str,
) -> Result<String, Error> {
    let mut shasta_token: String;

    // Look for authentication token in environment variable
    for (env, value) in std::env::vars() {
        if env.eq_ignore_ascii_case("MANTA_CSM_TOKEN") {
            log::info!(
                "Looking for CSM authentication token in envonment variable 'MANTA_CSM_TOKEN'"
            );

            shasta_token = value;

            match is_token_valid(shasta_base_url, &shasta_token, shasta_root_cert).await {
                Ok(_) => return Ok(shasta_token),
                Err(_) => return Err(Error::Message("Authentication unsucessful".to_string())),
            }
        }
    }

    // Look for authentication token in fielsystem
    log::info!("Looking for CSM authentication token in filesystem file");

    let mut file;

    let project_dirs = ProjectDirs::from(
        "local", /*qualifier*/
        "cscs",  /*organization*/
        "manta", /*application*/
    );

    let mut path = PathBuf::from(project_dirs.unwrap().cache_dir());

    let mut attempts = 0;

    create_dir_all(&path)?;

    path.push(site_name.to_string() + "_auth"); // ~/.cache/manta/<site name>_http is the file containing the Shasta authentication
                                                // token
    log::debug!("Cache file: {:?}", path);

    shasta_token = if path.exists() {
        get_token_from_local_file(path.as_os_str()).unwrap()
    } else {
        String::new()
    };

    while !is_token_valid(shasta_base_url, &shasta_token, shasta_root_cert)
        .await
        .unwrap()
        && attempts < 3
    {
        println!(
            "Please type your {}Keycloak credentials{}",
            color::Fg(color::Green),
            color::Fg(color::Reset)
        );
        let username: String = Input::new().with_prompt("username").interact_text()?;
        let password = Password::new().with_prompt("password").interact()?;

        match get_token_from_shasta_endpoint(
            keycloak_base_url,
            shasta_root_cert,
            &username,
            &password,
        )
        .await
        {
            Ok(shasta_token_aux) => {
                log::debug!("Shasta token received");
                file = File::create(&path).expect("Error encountered while creating file!");
                file.write_all(shasta_token_aux.as_bytes())
                    .expect("Error while writing to file");
                shasta_token = get_token_from_local_file(path.as_os_str()).unwrap();
            }
            Err(_) => {
                eprintln!("Failed in getting token from Shasta API");
            }
        }

        attempts += 1;
    }

    if attempts < 3 {
        shasta_token = get_token_from_local_file(path.as_os_str()).unwrap();
        Ok(shasta_token)
    } else {
        Err(Error::Message("Authentication unsucessful".to_string())) // Black magic conversion from Err(Box::new("my error msg")) which does not
    }
}

pub fn get_token_from_local_file(path: &std::ffi::OsStr) -> Result<String, reqwest::Error> {
    let mut shasta_token = String::new();
    File::open(path)
        .unwrap()
        .read_to_string(&mut shasta_token)
        .unwrap();
    Ok(shasta_token.to_string())
}

pub async fn is_token_valid(
    shasta_base_url: &str,
    shasta_token: &str,
    shasta_root_cert: &[u8],
) -> Result<bool, reqwest::Error> {
    let client;

    let client_builder = reqwest::Client::builder()
        .add_root_certificate(reqwest::Certificate::from_pem(shasta_root_cert)?);

    // Build client
    if std::env::var("SOCKS5").is_ok() {
        // socks5 proxy
        log::debug!("SOCKS5 enabled");
        let socks5proxy = reqwest::Proxy::all(std::env::var("SOCKS5").unwrap())?;

        // rest client to authenticate
        client = client_builder.proxy(socks5proxy).build()?;
    } else {
        client = client_builder.build()?;
    }

    let api_url = shasta_base_url.to_owned() + "/cfs/healthz";

    log::info!("Validate Shasta token against {}", api_url);

    let resp_rslt = client
        //.get(format!("{}/cfs/healthz", shasta_base_url))
        .get(api_url)
        .bearer_auth(shasta_token)
        .send()
        .await;

    if let Ok(resp) = resp_rslt {
        if resp.status().is_success() {
            log::info!("Shasta token is valid");
            Ok(true)
        } else {
            log::error!("Token is not valid - {}", resp.text().await?);
            Ok(false)
        }
    } else {
        eprintln!("Error connecting to Shasta API. Exit");
        log::debug!("Response:\n{:#?}", resp_rslt);
        std::process::exit(1);
    }
}

pub async fn get_token_from_shasta_endpoint(
    keycloak_base_url: &str,
    shasta_root_cert: &[u8],
    username: &str,
    password: &str,
) -> Result<String, reqwest::Error> {
    let mut params = HashMap::new();
    params.insert("grant_type", "password");
    params.insert("client_id", "shasta");
    params.insert("username", username);
    params.insert("password", password);

    let client;

    let client_builder = reqwest::Client::builder()
        .add_root_certificate(reqwest::Certificate::from_pem(shasta_root_cert)?);

    // Build client
    if std::env::var("SOCKS5").is_ok() {
        // socks5 proxy
        let socks5proxy = reqwest::Proxy::all(std::env::var("SOCKS5").unwrap())?;

        // rest client to authenticate
        client = client_builder.proxy(socks5proxy).build()?;
    } else {
        client = client_builder.build()?;
    }

    Ok(client
        .post(format!(
            "{}/realms/shasta/protocol/openid-connect/token",
            keycloak_base_url
        ))
        .form(&params)
        .send()
        .await?
        .error_for_status()?
        .json::<Value>()
        .await?["access_token"]
        .as_str()
        .unwrap()
        .to_string())
}