Skip to main content

auth_framework/protocols/
oauth1.rs

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