use base64::Engine;
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
use crate::{IdentityError, Result};
pub(crate) const MAX_BODY_BYTES: usize = 1 << 20;
#[derive(serde::Deserialize)]
pub(crate) struct OAuthErrorBody {
#[serde(default)]
pub error: String,
#[serde(default)]
pub error_description: Option<String>,
#[serde(default)]
pub error_uri: Option<String>,
}
pub(crate) fn basic_auth_header(client_id: &str, client_secret: &str) -> String {
let credentials = format!(
"{}:{}",
form_urlencode(client_id),
form_urlencode(client_secret)
);
format!("Basic {}", BASE64_STANDARD.encode(credentials))
}
pub(crate) fn form_urlencode(value: &str) -> String {
let mut out = String::with_capacity(value.len());
for byte in value.bytes() {
match byte {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
out.push(byte as char)
}
b' ' => out.push('+'),
_ => out.push_str(&format!("%{byte:02X}")),
}
}
out
}
pub(crate) async fn read_capped_body(mut response: reqwest::Response) -> Result<Vec<u8>> {
let mut body = Vec::new();
while let Some(chunk) = response
.chunk()
.await
.map_err(|e| IdentityError::Http(format!("read response body: {e}")))?
{
if body.len() + chunk.len() > MAX_BODY_BYTES {
return Err(IdentityError::Http(format!(
"response body exceeds {MAX_BODY_BYTES} bytes"
)));
}
body.extend_from_slice(&chunk);
}
Ok(body)
}
pub(crate) fn body_snippet(body: &[u8]) -> String {
const MAX: usize = 200;
let text = String::from_utf8_lossy(body);
let text = text.trim().replace('\n', " ");
if text.chars().count() > MAX {
format!("{}…", text.chars().take(MAX).collect::<String>())
} else {
text
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn basic_auth_header_urlencodes_credentials() {
let header = basic_auth_header("id with space", "p@ss:word");
let expected = format!(
"Basic {}",
BASE64_STANDARD.encode("id+with+space:p%40ss%3Aword")
);
assert_eq!(header, expected);
}
#[test]
fn basic_auth_header_plain_credentials() {
let header = basic_auth_header("client-1", "s3cr3t");
assert_eq!(
header,
format!("Basic {}", BASE64_STANDARD.encode("client-1:s3cr3t"))
);
}
#[test]
fn form_urlencode_encodes_reserved_and_space() {
assert_eq!(form_urlencode("a b"), "a+b");
assert_eq!(form_urlencode("p@ss:word/1"), "p%40ss%3Aword%2F1");
assert_eq!(form_urlencode("unreserved-._~"), "unreserved-._~");
}
#[test]
fn body_snippet_trims_and_truncates() {
assert_eq!(body_snippet(b" hello\nworld "), "hello world");
let long = "x".repeat(250);
let snip = body_snippet(long.as_bytes());
assert!(snip.ends_with('…'));
assert_eq!(snip.chars().count(), 201); }
}