1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
use std::{borrow::Cow, collections::HashMap};

use crate::{SecretsProvider, SignResult, SignerError};
use crate::{
    OAUTH_CALLBACK_KEY, OAUTH_CONSUMER_KEY, OAUTH_KEY_PREFIX, OAUTH_NONCE_KEY,
    OAUTH_SIGNATURE_METHOD_KEY, OAUTH_TIMESTAMP_KEY, OAUTH_TOKEN_KEY, OAUTH_VERIFIER_KEY,
    OAUTH_VERSION_KEY, REALM_KEY,
};
use http::Method;
use oauth1_request::signature_method::SignatureMethod;
use oauth1_request::signer::Signer as OAuthSigner;
use oauth1_request::{HmacSha1, Options};
use url::Url;

/**
Provides OAuth signature with [oauth1-request](https://crates.io/crates/oauth1-request).

# Note

This struct is intended for internal use.

You may consider use the struct provided from oauth1-request crate directly
instead of this struct.

*/
#[derive(Debug, Clone)]
pub struct Signer<'a, TSecrets, TSM>
where
    TSecrets: SecretsProvider + Clone,
    TSM: SignatureMethod + Clone,
{
    secrets: TSecrets,
    parameters: Result<OAuthParameters<'a, TSM>, SignerError>,
}

impl<'a, TSecretsProvider, TSM> Signer<'a, TSecretsProvider, TSM>
where
    TSecretsProvider: SecretsProvider + Clone,
    TSM: SignatureMethod + Clone,
{
    pub fn new(secrets: TSecretsProvider, parameters: OAuthParameters<'a, TSM>) -> Self {
        Signer {
            secrets,
            parameters: Ok(parameters),
        }
    }

    pub fn override_oauth_parameter(mut self, parameters: HashMap<String, String>) -> Self {
        for (key, value) in parameters {
            self.parameters = match self.parameters {
                Ok(p) => match key.as_str() {
                    // always success
                    OAUTH_CALLBACK_KEY => Ok(p.callback(value)),
                    OAUTH_NONCE_KEY => Ok(p.nonce(value)),
                    OAUTH_VERIFIER_KEY => Ok(p.verifier(value)),
                    REALM_KEY => Ok(p.realm(value)),
                    // potential to fail
                    OAUTH_TIMESTAMP_KEY => match value.parse::<u64>() {
                        Ok(v) => Ok(p.timestamp(v)),
                        Err(_) => Err(SignerError::InvalidTimestamp(value)),
                    },
                    OAUTH_VERSION_KEY => match value.as_str() {
                        "1.0" => Ok(p.version(true)),
                        "" => Ok(p.version(false)),
                        _ => Err(SignerError::InvalidVersion(value)),
                    },
                    // always fail
                    OAUTH_SIGNATURE_METHOD_KEY | OAUTH_CONSUMER_KEY | OAUTH_TOKEN_KEY => {
                        Err(SignerError::UnconfigurableParameter(key))
                    }
                    _ => Err(SignerError::UnknownParameter(key)),
                },
                Err(e) => Err(e),
            };
        }

        self
    }

    /// Generate OAuth signature with specified parameters.
    pub(crate) fn generate_signature(
        self,
        method: Method,
        url: Url,
        payload: &str,
        is_url_query: bool,
    ) -> SignResult<String> {
        let (consumer_key, consumer_secret) = self.secrets.get_consumer_key_pair();
        let (token, token_secret) = self.secrets.get_token_option_pair();
        // build oauth option
        let params = self.parameters?;
        let options = params.build_options(token);

        // destructure query and sort by alphabetical order
        let parsed_payload: Vec<(Cow<str>, Cow<str>)> =
            url::form_urlencoded::parse(payload.as_bytes())
                .into_iter()
                .collect();
        // add `oauth_` key to identify where to divide
        let oauth_identifier = vec![(Cow::from(OAUTH_KEY_PREFIX), Cow::from(""))];
        let mut sorted_query = [parsed_payload, oauth_identifier].concat();

        // then, sort by alphabetical order (that is required by OAuth specification)
        sorted_query.sort();

        // divide key-value items by the element has "oauth_" key
        let mut divided = sorted_query
            .splitn(2, |(k, _)| k == &OAUTH_KEY_PREFIX)
            .into_iter();
        let query_before_oauth = divided.next().unwrap();
        let query_after_oauth = divided.next().unwrap_or_default();

        // generate signature
        // Step 0. instantiate sign generator
        let sig_method = params.signature_method.clone();
        // println!("signing url: {:#?}", url);
        let mut signer = generate_signer(
            sig_method,
            method.as_str(),
            url,
            consumer_secret,
            token_secret,
            is_url_query,
        );

        // Step 1. key [a ~ oauth_)
        for (key, value) in query_before_oauth {
            if !key.starts_with(OAUTH_KEY_PREFIX) {
                // not an oauth_* parameter
                signer.parameter(key, value);
            }
        }
        // Step 2. add oauth_* parameters
        let mut signer = signer.oauth_parameters(consumer_key, &options);
        // Step 3. key (oauth_ ~ z]
        for (key, value) in query_after_oauth {
            if !key.starts_with(OAUTH_KEY_PREFIX) {
                // not an oauth_* parameter
                signer.parameter(key, value);
            }
        }

        // signature is generated.
        let sign = signer.finish().authorization;

        if let Some(realm) = params.realm {
            // OAuth oauth_...,realm="realm"
            Ok(format!("{},{}=\"{}\"", sign, REALM_KEY, realm.as_ref()))
        } else {
            // OAuth oauth_...
            Ok(sign)
        }
    }
}

fn generate_signer<TSM>(
    signature_method: TSM,
    method: &str,
    url: Url,
    consumer_secret: &str,
    token_secret: Option<&str>,
    is_url_query: bool,
) -> OAuthSigner<TSM>
where
    TSM: SignatureMethod,
{
    if is_url_query {
        OAuthSigner::with_signature_method(
            signature_method,
            method,
            url,
            consumer_secret,
            token_secret,
        )
    } else {
        OAuthSigner::form_with_signature_method(
            signature_method,
            method,
            url,
            consumer_secret,
            token_secret,
        )
    }
}

/**
Represents OAuth parameters including oauth_nonce, oauth_timestamp, realm, and others.

# Basic usage

```rust
use reqwest_oauth1::OAuthClientProvider;

let consumer_key = "[CONSUMER_KEY]";
let consumer_secret = "[CONSUMER_SECRET]";
let secrets = reqwest_oauth1::Secrets::new(consumer_key, consumer_secret);

let nonce = "[NONCE]";
let timestamp = 100_000_001u64;
let callback = "http://example.com/ready";

let params = reqwest_oauth1::OAuthParameters::new()
    .nonce(nonce)
    .timestamp(timestamp)
    .callback(callback);

let req = reqwest::Client::new()
    .oauth1_with_params(secrets, params)
    .post("http://example.com/")
    // and so on...
    ;
```

# Note

You can specify same parameters as get/post queries and they will superseded
with the specified one in the OAuthParameters.

```rust
use reqwest_oauth1::OAuthClientProvider;

let consumer_key = "[CONSUMER_KEY]";
let consumer_secret = "[CONSUMER_SECRET]";
let secrets = reqwest_oauth1::Secrets::new(consumer_key, consumer_secret);

let params = reqwest_oauth1::OAuthParameters::new()
    .nonce("ThisNonceWillBeSuperseded");
let req = reqwest::Client::new()
    .oauth1_with_params(secrets, params)
    .get("http://example.com/")
    .query(&[("nonce", "ThisNonceWillSupersedeTheOldOne")])
    // and so on...
    ;
```

*/
#[derive(Debug, Clone)]
pub struct OAuthParameters<'a, TSM>
where
    TSM: SignatureMethod + Clone,
{
    callback: Option<Cow<'a, str>>,
    nonce: Option<Cow<'a, str>>,
    realm: Option<Cow<'a, str>>,
    signature_method: TSM,
    timestamp: Option<u64>,
    verifier: Option<Cow<'a, str>>,
    version: bool,
}

impl Default for OAuthParameters<'static, HmacSha1> {
    fn default() -> Self {
        OAuthParameters {
            callback: None,
            nonce: None,
            realm: None,
            signature_method: HmacSha1,
            timestamp: None,
            verifier: None,
            version: false,
        }
    }
}

impl OAuthParameters<'_, HmacSha1> {
    pub fn new() -> Self {
        Default::default()
    }
}

impl<'a, TSM> OAuthParameters<'a, TSM>
where
    TSM: SignatureMethod + Clone,
{
    /// set the oauth_callback value
    pub fn callback<T>(self, callback: T) -> Self
    where
        T: Into<Cow<'a, str>>,
    {
        OAuthParameters {
            callback: Some(callback.into()),
            ..self
        }
    }

    /// set the oauth_nonce value
    pub fn nonce<T>(self, nonce: T) -> Self
    where
        T: Into<Cow<'a, str>>,
    {
        OAuthParameters {
            nonce: Some(nonce.into()),
            ..self
        }
    }

    /// set the realm value
    ///
    /// # Note
    /// this parameter will not be included in the signature-base string.
    /// cf. https://tools.ietf.org/html/rfc5849#section-3.4.1.3.1
    pub fn realm<T>(self, realm: T) -> Self
    where
        T: Into<Cow<'a, str>>,
    {
        OAuthParameters {
            realm: Some(realm.into()),
            ..self
        }
    }

    /// set the oauth_timestamp value
    pub fn timestamp<T>(self, timestamp: T) -> Self
    where
        T: Into<u64>,
    {
        OAuthParameters {
            timestamp: Some(timestamp.into()),
            ..self
        }
    }

    /// set the oauth_verifier value
    pub fn verifier<T>(self, verifier: T) -> Self
    where
        T: Into<Cow<'a, str>>,
    {
        OAuthParameters {
            verifier: Some(verifier.into()),
            ..self
        }
    }

    /// set the oauth_version value (boolean)
    ///
    /// # Note
    /// When the version has value `true`, oauth_version will be set with "1.0".
    /// Otherwise, oauth_version will not be included in your request.
    /// In oauth1, oauth_version value must be "1.0" or not specified.
    pub fn version<T>(self, version: T) -> Self
    where
        T: Into<bool>,
    {
        OAuthParameters {
            version: version.into(),
            ..self
        }
    }
    pub fn signature_method<T>(self, signature_method: T) -> OAuthParameters<'a, T>
    where
        T: SignatureMethod + Clone,
    {
        OAuthParameters {
            signature_method,
            callback: None,
            nonce: None,
            realm: None,
            timestamp: None,
            verifier: None,
            version: false,
        }
    }
}

impl<T> OAuthParameters<'_, T>
where
    T: SignatureMethod + Clone,
{
    fn build_options<'a>(&'a self, token: Option<&'a str>) -> Options<'a> {
        let mut opt = Options::new();

        // NOTE: items must be added by alphabetical order

        if let Some(ref callback) = self.callback {
            opt.callback(callback.as_ref());
        }
        if let Some(ref nonce) = self.nonce {
            opt.nonce(nonce.as_ref());
        }
        if let Some(timestamp) = self.timestamp {
            opt.timestamp(timestamp);
        }
        if let Some(token) = token {
            opt.token(token);
        }
        if let Some(ref verifier) = self.verifier {
            opt.verifier(verifier.as_ref());
        }
        opt.version(self.version);
        if self.version {}

        opt
    }
}