use jiff::{SignedDuration, Timestamp};
use serde::Deserialize;
use serde_json::json;
use url::Url;
use crate::config::Config;
use crate::de::flexible_int;
use crate::envelope;
use crate::session::{Credentials, Session};
use crate::stamp::stamp_now;
use crate::{Error, Result};
const SERVICE_ID: &str = "ccsp-service-id";
const APP_ID: &str = "ccsp-application-id";
#[derive(Deserialize)]
struct DeviceRegistration {
#[serde(rename = "deviceId")]
device_id: String,
}
#[derive(Deserialize)]
struct SignIn {
#[serde(rename = "redirectUrl")]
redirect_url: Option<String>,
}
#[derive(Deserialize)]
struct TokenResponse {
token_type: String,
access_token: String,
refresh_token: Option<String>,
#[serde(default, deserialize_with = "flexible_int")]
expires_in: Option<i64>,
}
const MIN_TOKEN_LIFETIME: SignedDuration = SignedDuration::from_secs(60);
const MAX_TOKEN_LIFETIME: SignedDuration = SignedDuration::from_secs(30 * 24 * 60 * 60);
pub(crate) fn expiry_from_now(secs: i64) -> Timestamp {
let lifetime = SignedDuration::from_secs(secs).clamp(MIN_TOKEN_LIFETIME, MAX_TOKEN_LIFETIME);
Timestamp::now()
.checked_add(lifetime)
.unwrap_or_else(|_| Timestamp::now())
}
async fn send<T: serde::de::DeserializeOwned>(
req: reqwest::RequestBuilder,
) -> Result<envelope::Reply<T>> {
let resp = req.send().await.map_err(Error::http)?;
let status = resp.status();
let bytes = resp.bytes().await.map_err(Error::http)?;
envelope::parse(status, &bytes)
}
async fn send_oauth<T: serde::de::DeserializeOwned>(
req: reqwest::RequestBuilder,
) -> Result<envelope::Reply<T>> {
send(req).await.map_err(|e| match e {
Error::Api { code, message } if is_http_4xx(&code) => Error::Authentication(message),
other => other,
})
}
pub(crate) fn is_http_4xx(code: &str) -> bool {
code.len() == 3 && code.starts_with('4')
}
pub(crate) async fn register_device(http: &reqwest::Client, cfg: &Config) -> Result<String> {
let push_id = format!(
"{}{}",
uuid::Uuid::new_v4().simple(),
uuid::Uuid::new_v4().simple()
);
let body = json!({
"pushRegId": push_id,
"pushType": cfg.push_type,
"uuid": uuid::Uuid::new_v4().to_string(),
});
let reply: envelope::Reply<DeviceRegistration> = send(
http.post(cfg.url("/api/v1/spa/notifications/register"))
.header(SERVICE_ID, cfg.service_id)
.header(APP_ID, cfg.app_id)
.header("Stamp", stamp_now(cfg.app_id, &cfg.cfb))
.json(&body),
)
.await?;
tracing::debug!("registered device");
Ok(reply.body.device_id)
}
pub(crate) async fn login(
http: &reqwest::Client,
cfg: &Config,
creds: &Credentials,
) -> Result<Session> {
let device_id = register_device(http, cfg).await?;
let redirect_uri = cfg.url("/api/v1/user/oauth2/redirect").to_string();
http.get(cfg.url("/api/v1/user/oauth2/authorize"))
.query(&[
("response_type", "code"),
("state", "test"),
("client_id", cfg.service_id),
("redirect_uri", redirect_uri.as_str()),
])
.send()
.await
.and_then(reqwest::Response::error_for_status)
.map_err(Error::http)?;
let sign_in: envelope::Reply<SignIn> =
send_oauth(http.post(cfg.url("/api/v1/user/signin")).json(&json!({
"email": creds.username(),
"password": creds.password(),
})))
.await?;
let code = sign_in
.body
.redirect_url
.as_deref()
.and_then(|u| Url::parse(u).ok())
.and_then(|u| {
u.query_pairs()
.find(|(k, _)| k == "code")
.map(|(_, v)| v.into_owned())
})
.ok_or_else(|| Error::Authentication("wrong email or password".into()))?;
let tokens: envelope::Reply<TokenResponse> = send_oauth(
http.post(cfg.url("/api/v1/user/oauth2/token"))
.header("Authorization", cfg.basic_auth)
.header("Stamp", stamp_now(cfg.app_id, &cfg.cfb))
.form(&[
("grant_type", "authorization_code"),
("redirect_uri", redirect_uri.as_str()),
("code", code.as_str()),
]),
)
.await?;
tracing::debug!("logged in");
session_from(tokens.body, None, device_id)
}
pub(crate) async fn refresh(
http: &reqwest::Client,
cfg: &Config,
old: &Session,
) -> Result<Session> {
let tokens: envelope::Reply<TokenResponse> = send_oauth(
http.post(cfg.url("/api/v1/user/oauth2/token"))
.header("Authorization", cfg.basic_auth)
.header("Stamp", stamp_now(cfg.app_id, &cfg.cfb))
.form(&[
("grant_type", "refresh_token"),
("refresh_token", old.refresh_token.as_str()),
]),
)
.await?;
tracing::debug!("refreshed access token");
session_from(tokens.body, Some(&old.refresh_token), old.device_id.clone())
}
fn session_from(
t: TokenResponse,
previous_refresh: Option<&str>,
device_id: String,
) -> Result<Session> {
let refresh_token = t
.refresh_token
.or_else(|| previous_refresh.map(str::to_owned))
.ok_or_else(|| Error::UnexpectedResponse("token response had no refresh token".into()))?;
Ok(Session::new(
format!("{} {}", t.token_type, t.access_token),
refresh_token,
expiry_from_now(t.expires_in.unwrap_or(3600)),
device_id,
))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn expiry_is_clamped_and_never_panics() {
let now = Timestamp::now();
for secs in [i64::MAX, i64::MIN, 0, -5, 10] {
let at = expiry_from_now(secs);
assert!(at > now && at <= now + MAX_TOKEN_LIFETIME + SignedDuration::from_secs(5));
}
let hour = expiry_from_now(3600);
assert!(hour > now + SignedDuration::from_secs(3590));
}
}