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