aboutsummaryrefslogtreecommitdiff
path: root/azalea-auth/src/yggdrasil.rs
blob: 7eaa05897f8d569eb354419e52532a2c9897c760 (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
use std::path::PathBuf;

use reqwest::StatusCode;
use serde::{Deserialize, Serialize};
use serde_json::json;
use thiserror::Error;
use tracing::{debug, error};
use uuid::Uuid;

use crate::cache;

#[derive(Error, Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ErrorPayload {
    pub error: String,
    pub cause: Option<String>,
    pub error_message: String,
}

impl std::fmt::Display for ErrorPayload {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{}", self.error_message)
    }
}

#[derive(Debug, Error)]
pub enum YggdrasilAuthError {
    #[error("Error sending HTTP request to authserver: {0}")]
    HttpError(#[from] reqwest::Error),
    #[error("This account has been migrated")]
    Migrated,
    #[error("Forbidden operation: {0}")]
    ForbiddenOperation(ErrorPayload),
    #[error("Unauthorized: {0}")]
    Unauthorized(ErrorPayload),
    #[error("RateLimiter disallowed request")]
    RateLimited,
    #[error("Error reading password: {0}")]
    PasswordError(#[from] std::io::Error),
    #[error("Unexpected response from authserver (status code {status_code}): {body}")]
    UnexpectedResponse { status_code: u16, body: String },
}

#[derive(Debug, Deserialize)]
pub struct Property {
    pub name: String,
    pub value: String,
}

#[derive(Debug, Deserialize)]
pub struct User {
    pub id: Uuid,
    pub username: Option<String>,
    pub properties: Vec<Property>,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct YggdrasilAuthResult {
    pub access_token: String,
    pub client_token: String,
    pub user: User,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct YggdrasilCachedAccount {
    pub backend: String,
    pub username: String,
    pub access_token: String,
    pub client_token: String,
}

pub struct YggdrasilCacheKey<'a> {
    pub backend: &'a str,
    pub username: &'a str,
}

impl<'a, 'b> PartialEq<YggdrasilCacheKey<'b>> for YggdrasilCacheKey<'a> {
    fn eq(&self, other: &YggdrasilCacheKey<'b>) -> bool {
        self.backend == other.backend && self.username == other.username
    }
}

impl cache::CacheEntry for YggdrasilCachedAccount {
    type Key<'a> = YggdrasilCacheKey<'a>;

    fn key<'a>(&'a self) -> Self::Key<'a> {
        YggdrasilCacheKey {
            backend: &self.backend,
            username: &self.username,
        }
    }
}

#[derive(Default, Debug, Clone)]
pub struct YggdrasilAuthOpts {
    /// The directory to store the cache in.
    ///
    /// If this is `None`, azalea-auth will not keep its own cache.
    pub cache_file: Option<PathBuf>,
}

async fn handle_response(
    res: reqwest::Response,
) -> Result<YggdrasilAuthResult, YggdrasilAuthError> {
    match res.status() {
        StatusCode::OK => Ok(res.json::<YggdrasilAuthResult>().await?),
        StatusCode::FORBIDDEN => Err(YggdrasilAuthError::ForbiddenOperation(
            res.json::<ErrorPayload>().await?,
        )),
        StatusCode::UNAUTHORIZED => Err(YggdrasilAuthError::Unauthorized(
            res.json::<ErrorPayload>().await?,
        )),
        StatusCode::GONE => Err(YggdrasilAuthError::Migrated),
        StatusCode::TOO_MANY_REQUESTS => Err(YggdrasilAuthError::RateLimited),
        status_code => {
            // log the headers
            debug!("Error headers: {:#?}", res.headers());
            let body = res.text().await?;
            Err(YggdrasilAuthError::UnexpectedResponse {
                status_code: status_code.as_u16(),
                body,
            })
        }
    }
}

pub async fn authenticate(
    username: &str,
    password: &str,
    backend: &str,
) -> Result<YggdrasilAuthResult, YggdrasilAuthError> {
    let data = json!({
        "password": password,
        "username": username,
        "requestUser": true,
    });
    handle_response(
        reqwest::ClientBuilder::new()
            .build()?
            .post(format!("{backend}/authenticate"))
            .json(&data)
            .send()
            .await?,
    )
    .await
}

pub async fn refresh(
    access_token: &str,
    client_token: &str,
    backend: &str,
) -> Result<YggdrasilAuthResult, YggdrasilAuthError> {
    let data = json!({
        "accessToken": access_token,
        "clientToken": client_token,
        "requestUser": true,
    });
    handle_response(
        reqwest::ClientBuilder::new()
            .build()?
            .post(format!("{backend}/refresh"))
            .json(&data)
            .send()
            .await?,
    )
    .await
}

async fn new_session(
    username: &str,
    password: Option<&str>,
    backend: &str,
) -> Result<YggdrasilAuthResult, YggdrasilAuthError> {
    let password = match password {
        Some(x) => x,
        None => &rpassword::prompt_password(format!("Enter password for {username}: "))?,
    };
    authenticate(username, password, backend).await
}

pub async fn yggdrasil_auth(
    username: &str,
    password: Option<&str>,
    backend: &str,
    opts: YggdrasilAuthOpts,
) -> Result<YggdrasilAuthResult, YggdrasilAuthError> {
    let cached_account = if let Some(cache_file) = &opts.cache_file {
        cache::get_account_in_cache_g::<YggdrasilCachedAccount>(
            cache_file,
            YggdrasilCacheKey { username, backend },
        )
        .await
    } else {
        None
    };

    let result = match cached_account {
        Some(acc) => match refresh(&acc.access_token, &acc.client_token, backend).await {
            Ok(x) => x,
            Err(e) => {
                error!("While refreshing {}: {}", username, e);
                new_session(username, password, backend).await?
            }
        },
        None => new_session(username, password, backend).await?,
    };

    if let Some(cache_file) = &opts.cache_file
        && let Err(e) = cache::set_account_in_cache_g::<YggdrasilCachedAccount>(
            cache_file,
            YggdrasilCacheKey { username, backend },
            YggdrasilCachedAccount {
                backend: backend.to_owned(),
                username: username.to_owned(),
                access_token: result.access_token.clone(),
                client_token: result.client_token.clone(),
            },
        )
        .await
    {
        error!("{}", e);
    }

    Ok(result)
}