1use crate::errors::{AuthError, Result};
7use base64::Engine;
8use ring::hmac;
9use serde::{Deserialize, Serialize};
10use std::collections::BTreeMap;
11use std::time::{SystemTime, UNIX_EPOCH};
12use zeroize::Zeroizing;
13
14#[derive(Debug, Clone, Serialize, Deserialize)]
16pub struct OAuthConsumer {
17 pub key: String,
18 pub secret: Zeroizing<String>,
19}
20
21#[derive(Debug, Clone, Serialize, Deserialize)]
23pub struct OAuthToken {
24 pub token: String,
25 pub secret: Zeroizing<String>,
26}
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
30pub enum SignatureMethod {
31 HmacSha1,
32 HmacSha256,
33 Plaintext,
34}
35
36impl SignatureMethod {
37 pub fn as_str(&self) -> &'static str {
38 match self {
39 Self::HmacSha1 => "HMAC-SHA1",
40 Self::HmacSha256 => "HMAC-SHA256",
41 Self::Plaintext => "PLAINTEXT",
42 }
43 }
44}
45
46#[derive(Clone)]
48pub struct OAuthSignedRequest {
49 pub authorization_header: String,
51 pub signature_base_string: String,
53 pub signature: String,
55}
56
57impl std::fmt::Debug for OAuthSignedRequest {
58 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
59 let mut d = f.debug_struct("OAuthSignedRequest");
60 d.field(
61 "authorization_header",
62 &crate::utils::redact::redacted(&self.authorization_header),
63 );
64 d.field("signature_base_string", &self.signature_base_string);
65 d.field("signature", &self.signature);
66 d.finish()
67 }
68}
69
70#[derive(Clone, Serialize, Deserialize)]
72pub struct RequestTokenResponse {
73 pub oauth_token: String,
74 pub oauth_token_secret: Zeroizing<String>,
75 pub oauth_callback_confirmed: bool,
76}
77
78impl std::fmt::Debug for RequestTokenResponse {
79 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
80 let mut d = f.debug_struct("RequestTokenResponse");
81 d.field(
82 "oauth_token",
83 &crate::utils::redact::redacted(&self.oauth_token),
84 );
85 d.field(
86 "oauth_token_secret",
87 &crate::utils::redact::redacted(&*self.oauth_token_secret),
88 );
89 d.field("oauth_callback_confirmed", &self.oauth_callback_confirmed);
90 d.finish()
91 }
92}
93
94#[derive(Clone, Serialize, Deserialize)]
96pub struct AccessTokenResponse {
97 pub oauth_token: String,
98 pub oauth_token_secret: Zeroizing<String>,
99}
100
101impl std::fmt::Debug for AccessTokenResponse {
102 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
103 let mut d = f.debug_struct("AccessTokenResponse");
104 d.field(
105 "oauth_token",
106 &crate::utils::redact::redacted(&self.oauth_token),
107 );
108 d.field(
109 "oauth_token_secret",
110 &crate::utils::redact::redacted(&*self.oauth_token_secret),
111 );
112 d.finish()
113 }
114}
115
116pub struct OAuth1Client {
118 consumer: OAuthConsumer,
119 signature_method: SignatureMethod,
120}
121
122impl OAuth1Client {
123 pub fn new(consumer: OAuthConsumer, signature_method: SignatureMethod) -> Result<Self> {
125 if consumer.key.is_empty() || consumer.secret.is_empty() {
126 return Err(AuthError::validation(
127 "Consumer key and secret must not be empty",
128 ));
129 }
130 Ok(Self {
131 consumer,
132 signature_method,
133 })
134 }
135
136 pub fn sign_request(
140 &self,
141 method: &str,
142 url: &str,
143 token: Option<&OAuthToken>,
144 extra_params: Option<&BTreeMap<String, String>>,
145 ) -> Result<OAuthSignedRequest> {
146 let nonce = generate_nonce()?;
147 let timestamp = SystemTime::now()
148 .duration_since(UNIX_EPOCH)
149 .unwrap_or_default()
150 .as_secs()
151 .to_string();
152
153 let mut params = BTreeMap::new();
155 params.insert("oauth_consumer_key".to_string(), self.consumer.key.clone());
156 params.insert("oauth_nonce".to_string(), nonce);
157 params.insert(
158 "oauth_signature_method".to_string(),
159 self.signature_method.as_str().to_string(),
160 );
161 params.insert("oauth_timestamp".to_string(), timestamp);
162 params.insert("oauth_version".to_string(), "1.0".to_string());
163
164 if let Some(t) = token {
165 params.insert("oauth_token".to_string(), t.token.clone());
166 }
167
168 if let Some(extra) = extra_params {
169 for (k, v) in extra {
170 params.insert(k.clone(), v.clone());
171 }
172 }
173
174 let param_string: String = params
176 .iter()
177 .map(|(k, v)| format!("{}={}", percent_encode(k), percent_encode(v)))
178 .collect::<Vec<_>>()
179 .join("&");
180
181 let base_string = format!(
182 "{}&{}&{}",
183 method.to_uppercase(),
184 percent_encode(url),
185 percent_encode(¶m_string)
186 );
187
188 let token_secret = token.map(|t| t.secret.as_str()).unwrap_or("");
190 let signing_key = format!(
191 "{}&{}",
192 percent_encode(&self.consumer.secret),
193 percent_encode(token_secret)
194 );
195
196 let signature = match self.signature_method {
197 SignatureMethod::HmacSha1 => {
198 let key =
199 hmac::Key::new(hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY, signing_key.as_bytes());
200 let tag = hmac::sign(&key, base_string.as_bytes());
201 base64::engine::general_purpose::STANDARD.encode(tag.as_ref())
202 }
203 SignatureMethod::HmacSha256 => {
204 let key = hmac::Key::new(hmac::HMAC_SHA256, signing_key.as_bytes());
205 let tag = hmac::sign(&key, base_string.as_bytes());
206 base64::engine::general_purpose::STANDARD.encode(tag.as_ref())
207 }
208 SignatureMethod::Plaintext => signing_key.clone(),
209 };
210
211 params.insert("oauth_signature".to_string(), signature.clone());
213
214 let auth_header = format!(
215 "OAuth {}",
216 params
217 .iter()
218 .filter(|(k, _)| k.starts_with("oauth_"))
219 .map(|(k, v)| format!("{}=\"{}\"", percent_encode(k), percent_encode(v)))
220 .collect::<Vec<_>>()
221 .join(", ")
222 );
223
224 Ok(OAuthSignedRequest {
225 authorization_header: auth_header,
226 signature_base_string: base_string,
227 signature,
228 })
229 }
230
231 pub fn build_authorize_url(&self, base_url: &str, request_token: &str) -> String {
233 format!("{}?oauth_token={}", base_url, percent_encode(request_token))
234 }
235
236 pub fn parse_request_token_response(body: &str) -> Result<RequestTokenResponse> {
238 let params = parse_form_body(body);
239 let token = params
240 .get("oauth_token")
241 .ok_or_else(|| AuthError::validation("Missing oauth_token"))?
242 .clone();
243 let secret = params
244 .get("oauth_token_secret")
245 .ok_or_else(|| AuthError::validation("Missing oauth_token_secret"))?
246 .clone();
247 let confirmed = params
248 .get("oauth_callback_confirmed")
249 .map(|v| v == "true")
250 .unwrap_or(false);
251
252 Ok(RequestTokenResponse {
253 oauth_token: token,
254 oauth_token_secret: secret.into(),
255 oauth_callback_confirmed: confirmed,
256 })
257 }
258
259 pub fn parse_access_token_response(body: &str) -> Result<AccessTokenResponse> {
261 let params = parse_form_body(body);
262 let token = params
263 .get("oauth_token")
264 .ok_or_else(|| AuthError::validation("Missing oauth_token"))?
265 .clone();
266 let secret = params
267 .get("oauth_token_secret")
268 .ok_or_else(|| AuthError::validation("Missing oauth_token_secret"))?
269 .clone();
270
271 Ok(AccessTokenResponse {
272 oauth_token: token,
273 oauth_token_secret: secret.into(),
274 })
275 }
276}
277
278fn percent_encode(s: &str) -> String {
280 let mut encoded = String::with_capacity(s.len());
281 for byte in s.bytes() {
282 match byte {
283 b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
284 encoded.push(byte as char);
285 }
286 _ => {
287 encoded.push_str(&format!("%{:02X}", byte));
288 }
289 }
290 }
291 encoded
292}
293
294fn parse_form_body(body: &str) -> BTreeMap<String, String> {
296 body.split('&')
297 .filter_map(|pair| {
298 let mut parts = pair.splitn(2, '=');
299 let key = parts.next()?;
300 let value = parts.next().unwrap_or("");
301 Some((key.to_string(), value.to_string()))
302 })
303 .collect()
304}
305
306fn generate_nonce() -> Result<String> {
308 use ring::rand::{SecureRandom, SystemRandom};
309 let rng = SystemRandom::new();
310 let mut buf = [0u8; 16];
311 rng.fill(&mut buf)
312 .map_err(|_| AuthError::crypto("Failed to generate nonce".to_string()))?;
313 Ok(hex::encode(buf))
314}
315
316#[cfg(test)]
317mod tests {
318 use super::*;
319
320 fn test_consumer() -> OAuthConsumer {
321 OAuthConsumer {
322 key: "dpf43f3p2l4k3l03".to_string(),
323 secret: "kd94hf93k423kf44".to_string().into(),
324 }
325 }
326
327 #[test]
328 fn test_create_client() {
329 let client = OAuth1Client::new(test_consumer(), SignatureMethod::HmacSha1).unwrap();
330 assert_eq!(client.consumer.key, "dpf43f3p2l4k3l03");
331 }
332
333 #[test]
334 fn test_empty_consumer_rejected() {
335 let consumer = OAuthConsumer {
336 key: String::new(),
337 secret: "secret".to_string().into(),
338 };
339 assert!(OAuth1Client::new(consumer, SignatureMethod::HmacSha1).is_err());
340 }
341
342 #[test]
343 fn test_sign_request_hmac_sha1() {
344 let client = OAuth1Client::new(test_consumer(), SignatureMethod::HmacSha1).unwrap();
345 let signed = client
346 .sign_request("GET", "https://api.example.com/resource", None, None)
347 .unwrap();
348
349 assert!(signed.authorization_header.starts_with("OAuth "));
350 assert!(signed.authorization_header.contains("oauth_consumer_key="));
351 assert!(signed.authorization_header.contains("oauth_signature="));
352 assert!(signed.authorization_header.contains("oauth_nonce="));
353 assert!(!signed.signature.is_empty());
354 }
355
356 #[test]
357 fn test_sign_request_with_token() {
358 let client = OAuth1Client::new(test_consumer(), SignatureMethod::HmacSha1).unwrap();
359 let token = OAuthToken {
360 token: "nnch734d00sl2jdk".to_string(),
361 secret: "pfkkdhi9sl3r4s00".to_string().into(),
362 };
363 let signed = client
364 .sign_request("POST", "https://api.example.com/post", Some(&token), None)
365 .unwrap();
366
367 assert!(signed.authorization_header.contains("oauth_token="));
368 assert!(!signed.signature.is_empty());
369 }
370
371 #[test]
372 fn test_sign_request_hmac_sha256() {
373 let client = OAuth1Client::new(test_consumer(), SignatureMethod::HmacSha256).unwrap();
374 let signed = client
375 .sign_request("GET", "https://api.example.com/resource", None, None)
376 .unwrap();
377 assert!(signed.authorization_header.contains("HMAC-SHA256"));
378 }
379
380 #[test]
381 fn test_sign_request_plaintext() {
382 let client = OAuth1Client::new(test_consumer(), SignatureMethod::Plaintext).unwrap();
383 let signed = client
384 .sign_request("GET", "https://api.example.com/resource", None, None)
385 .unwrap();
386 assert!(signed.signature.contains("kd94hf93k423kf44"));
388 }
389
390 #[test]
391 fn test_percent_encode() {
392 assert_eq!(percent_encode("hello"), "hello");
393 assert_eq!(percent_encode("hello world"), "hello%20world");
394 assert_eq!(percent_encode("a&b=c"), "a%26b%3Dc");
395 assert_eq!(percent_encode("~.-_"), "~.-_");
396 }
397
398 #[test]
399 fn test_signature_base_string_format() {
400 let client = OAuth1Client::new(test_consumer(), SignatureMethod::HmacSha1).unwrap();
401 let signed = client
402 .sign_request("GET", "https://api.example.com/1/resource", None, None)
403 .unwrap();
404 assert!(signed.signature_base_string.starts_with("GET&"));
405 assert!(
406 signed
407 .signature_base_string
408 .contains("https%3A%2F%2Fapi.example.com%2F1%2Fresource")
409 );
410 }
411
412 #[test]
413 fn test_build_authorize_url() {
414 let client = OAuth1Client::new(test_consumer(), SignatureMethod::HmacSha1).unwrap();
415 let url =
416 client.build_authorize_url("https://api.example.com/authorize", "hh5s93j4hdidpola");
417 assert_eq!(
418 url,
419 "https://api.example.com/authorize?oauth_token=hh5s93j4hdidpola"
420 );
421 }
422
423 #[test]
424 fn test_parse_request_token_response() {
425 let body = "oauth_token=hh5s93j4hdidpola&oauth_token_secret=hdhd0244k9j7ao03&oauth_callback_confirmed=true";
426 let resp = OAuth1Client::parse_request_token_response(body).unwrap();
427 assert_eq!(resp.oauth_token, "hh5s93j4hdidpola");
428 assert_eq!(resp.oauth_token_secret.as_str(), "hdhd0244k9j7ao03");
429 assert!(resp.oauth_callback_confirmed);
430 }
431
432 #[test]
433 fn test_parse_request_token_missing_field() {
434 let body = "oauth_token=xyz";
435 assert!(OAuth1Client::parse_request_token_response(body).is_err());
436 }
437
438 #[test]
439 fn test_parse_access_token_response() {
440 let body = "oauth_token=nnch734d00sl2jdk&oauth_token_secret=pfkkdhi9sl3r4s00";
441 let resp = OAuth1Client::parse_access_token_response(body).unwrap();
442 assert_eq!(resp.oauth_token, "nnch734d00sl2jdk");
443 assert_eq!(resp.oauth_token_secret.as_str(), "pfkkdhi9sl3r4s00");
444 }
445
446 #[test]
447 fn test_different_consumers_different_signatures() {
448 let c1 = OAuth1Client::new(
449 OAuthConsumer {
450 key: "key1".to_string(),
451 secret: "secret1".to_string().into(),
452 },
453 SignatureMethod::HmacSha1,
454 )
455 .unwrap();
456 let c2 = OAuth1Client::new(
457 OAuthConsumer {
458 key: "key2".to_string(),
459 secret: "secret2".to_string().into(),
460 },
461 SignatureMethod::HmacSha1,
462 )
463 .unwrap();
464
465 let s1 = c1
466 .sign_request("GET", "https://example.com", None, None)
467 .unwrap();
468 let s2 = c2
469 .sign_request("GET", "https://example.com", None, None)
470 .unwrap();
471 assert_ne!(s1.signature, s2.signature);
472 }
473
474 #[test]
475 fn test_signature_method_as_str() {
476 assert_eq!(SignatureMethod::HmacSha1.as_str(), "HMAC-SHA1");
477 assert_eq!(SignatureMethod::HmacSha256.as_str(), "HMAC-SHA256");
478 assert_eq!(SignatureMethod::Plaintext.as_str(), "PLAINTEXT");
479 }
480}