#[derive(Debug, Clone)]
pub enum AuthTransport {
Bearer(String),
Basic(BasicAuth),
License(String),
Query(String),
}
#[derive(Debug, Clone)]
pub enum BasicAuth {
EmailPassword {
email: String,
password: String,
},
Token(String),
LicenseKey(String),
}
impl BasicAuth {
fn to_user_pass(&self) -> String {
match self {
BasicAuth::EmailPassword { email, password } => format!("{email}:{password}"),
BasicAuth::Token(token) => format!("{token}:"),
BasicAuth::LicenseKey(key) => format!("license:{key}"),
}
}
fn to_base64(&self) -> String {
use base64::Engine as _;
base64::engine::general_purpose::STANDARD.encode(self.to_user_pass())
}
}
const AUTHORIZATION: &str = "Authorization";
const QUERY_PARAM_TOKEN: &str = "token";
impl AuthTransport {
pub fn header(&self) -> Option<(&'static str, String)> {
match self {
AuthTransport::Bearer(token) => Some((AUTHORIZATION, format!("Bearer {token}"))),
AuthTransport::Basic(basic) => {
Some((AUTHORIZATION, format!("Basic {}", basic.to_base64())))
}
AuthTransport::License(key) => Some((AUTHORIZATION, format!("License {key}"))),
AuthTransport::Query(_) => None,
}
}
pub fn query_param(&self) -> Option<(&'static str, &str)> {
match self {
AuthTransport::Query(token) => Some((QUERY_PARAM_TOKEN, token.as_str())),
_ => None,
}
}
}
pub fn sanitize_version(version: &str) -> String {
version
.chars()
.filter(|c| c.is_ascii_alphanumeric() || *c == '.' || *c == '-')
.take(32)
.collect()
}
pub const DEFAULT_API_VERSION: &str = "1.8";
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct RateLimitInfo {
pub limit: Option<u64>,
pub remaining: Option<u64>,
pub reset: Option<u64>,
pub window: Option<u64>,
}
impl RateLimitInfo {
pub fn from_headers(headers: &reqwest::header::HeaderMap) -> Self {
let num = |name: &str| {
headers
.get(name)
.and_then(|v| v.to_str().ok())
.map(str::trim)
.and_then(|v| v.parse::<u64>().ok())
};
RateLimitInfo {
limit: num("x-ratelimit-limit"),
remaining: num("x-ratelimit-remaining"),
reset: num("x-ratelimit-reset"),
window: num("x-ratelimit-window"),
}
}
pub fn is_present(&self) -> bool {
self.limit.is_some()
|| self.remaining.is_some()
|| self.reset.is_some()
|| self.window.is_some()
}
pub fn seconds_until_reset(&self, now_unix: u64) -> Option<u64> {
self.reset.map(|reset| reset.saturating_sub(now_unix))
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct ResponseInfo {
pub tamga_version: Option<String>,
pub tamga_edition: Option<String>,
pub tamga_mode: Option<String>,
pub request_id: Option<String>,
pub rate_limit: RateLimitInfo,
}
impl ResponseInfo {
pub fn from_headers(headers: &reqwest::header::HeaderMap) -> Self {
let get = |name: &str| {
headers
.get(name)
.and_then(|v| v.to_str().ok())
.map(str::to_owned)
};
ResponseInfo {
tamga_version: get("Tamga-Version"),
tamga_edition: get("Tamga-Edition"),
tamga_mode: get("Tamga-Mode"),
request_id: get("X-Request-Id"),
rate_limit: RateLimitInfo::from_headers(headers),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn bearer_produces_authorization_header() {
let transport = AuthTransport::Bearer("tok-abc123".to_string());
assert_eq!(
transport.header(),
Some(("Authorization", "Bearer tok-abc123".to_string()))
);
assert_eq!(transport.query_param(), None);
}
#[test]
fn license_produces_authorization_header() {
let transport = AuthTransport::License("lic-xyz789".to_string());
assert_eq!(
transport.header(),
Some(("Authorization", "License lic-xyz789".to_string()))
);
}
#[test]
fn query_produces_token_param_not_header() {
let transport = AuthTransport::Query("tok-abc123".to_string());
assert_eq!(transport.header(), None);
assert_eq!(transport.query_param(), Some(("token", "tok-abc123")));
}
#[test]
fn basic_email_password_encodes_correctly() {
let transport = AuthTransport::Basic(BasicAuth::EmailPassword {
email: "user@example.com".to_string(),
password: "hunter2".to_string(),
});
let expected = "dXNlckBleGFtcGxlLmNvbTpodW50ZXIy";
assert_eq!(
transport.header(),
Some(("Authorization", format!("Basic {expected}")))
);
}
#[test]
fn basic_token_uses_empty_password() {
let transport = AuthTransport::Basic(BasicAuth::Token("tok-abc123".to_string()));
let expected = "dG9rLWFiYzEyMzo=";
assert_eq!(
transport.header(),
Some(("Authorization", format!("Basic {expected}")))
);
}
#[test]
fn basic_license_key_prefixes_with_license_literal() {
let transport = AuthTransport::Basic(BasicAuth::LicenseKey("lic-xyz789".to_string()));
let expected = "bGljZW5zZTpsaWMteHl6Nzg5";
assert_eq!(
transport.header(),
Some(("Authorization", format!("Basic {expected}")))
);
}
#[test]
fn sanitize_version_keeps_allowed_characters() {
assert_eq!(sanitize_version("1.8"), "1.8");
assert_eq!(sanitize_version("v1.0-beta"), "v1.0-beta");
}
#[test]
fn sanitize_version_strips_disallowed_characters() {
assert_eq!(sanitize_version("1.8; DROP TABLE"), "1.8DROPTABLE");
assert_eq!(sanitize_version("a/b c"), "abc");
}
#[test]
fn sanitize_version_truncates_to_32_chars() {
let long = "a".repeat(50);
let sanitized = sanitize_version(&long);
assert_eq!(sanitized.len(), 32);
assert_eq!(sanitized, "a".repeat(32));
}
#[test]
fn response_info_extracts_known_headers() {
let mut headers = reqwest::header::HeaderMap::new();
headers.insert("Tamga-Version", "1.8".parse().unwrap());
headers.insert("Tamga-Edition", "CE".parse().unwrap());
headers.insert("Tamga-Mode", "multiplayer".parse().unwrap());
headers.insert("X-Request-Id", "req-123".parse().unwrap());
let info = ResponseInfo::from_headers(&headers);
assert_eq!(info.tamga_version, Some("1.8".to_string()));
assert_eq!(info.tamga_edition, Some("CE".to_string()));
assert_eq!(info.tamga_mode, Some("multiplayer".to_string()));
assert_eq!(info.request_id, Some("req-123".to_string()));
}
#[test]
fn response_info_defaults_missing_headers_to_none() {
let headers = reqwest::header::HeaderMap::new();
let info = ResponseInfo::from_headers(&headers);
assert_eq!(info, ResponseInfo::default());
}
#[test]
fn rate_limit_headers_are_read_back_off_a_response() {
let mut headers = reqwest::header::HeaderMap::new();
headers.insert("x-ratelimit-limit", "20".parse().unwrap());
headers.insert("x-ratelimit-remaining", "0".parse().unwrap());
headers.insert("x-ratelimit-reset", "1767225600".parse().unwrap());
headers.insert("x-ratelimit-window", "1".parse().unwrap());
let info = ResponseInfo::from_headers(&headers);
assert_eq!(info.rate_limit.limit, Some(20));
assert_eq!(info.rate_limit.remaining, Some(0));
assert_eq!(info.rate_limit.reset, Some(1_767_225_600));
assert_eq!(info.rate_limit.window, Some(1));
assert!(info.rate_limit.is_present());
}
#[test]
fn absent_rate_limit_headers_mean_no_information_not_no_limit() {
let headers = reqwest::header::HeaderMap::new();
let info = ResponseInfo::from_headers(&headers);
assert_eq!(info.rate_limit, RateLimitInfo::default());
assert!(!info.rate_limit.is_present());
assert_eq!(info.rate_limit.remaining, None);
}
#[test]
fn a_garbled_rate_limit_header_is_dropped_not_fatal() {
let mut headers = reqwest::header::HeaderMap::new();
headers.insert("x-ratelimit-limit", "not-a-number".parse().unwrap());
headers.insert("x-ratelimit-remaining", "-1".parse().unwrap());
headers.insert("x-ratelimit-reset", " 1767225600 ".parse().unwrap());
let rl = RateLimitInfo::from_headers(&headers);
assert_eq!(rl.limit, None);
assert_eq!(rl.remaining, None, "a negative count is not a u64");
assert_eq!(
rl.reset,
Some(1_767_225_600),
"surrounding space is trimmed"
);
assert!(rl.is_present());
}
#[test]
fn reset_is_an_absolute_timestamp_not_a_delay() {
let mut headers = reqwest::header::HeaderMap::new();
headers.insert("x-ratelimit-reset", "1767225600".parse().unwrap());
let rl = RateLimitInfo::from_headers(&headers);
assert_eq!(rl.seconds_until_reset(1_767_225_598), Some(2));
assert_eq!(rl.seconds_until_reset(1_767_225_999), Some(0));
assert_eq!(RateLimitInfo::default().seconds_until_reset(0), None);
}
}
pub(crate) fn jitter_millis(attempt: u32) -> u64 {
let seed = u64::from(std::process::id())
.wrapping_mul(2_654_435_761)
.wrapping_add(u64::from(attempt).wrapping_mul(40_503));
seed % 1000
}
#[cfg(test)]
mod backoff_tests {
use super::jitter_millis;
#[test]
fn jitter_stays_under_a_second() {
for attempt in 0..10 {
assert!(jitter_millis(attempt) < 1000);
}
}
#[test]
fn jitter_varies_between_attempts() {
let values: std::collections::BTreeSet<u64> = (0..8).map(jitter_millis).collect();
assert!(
values.len() > 1,
"jitter must not be constant across attempts"
);
}
}