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