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