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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
//! Yet yet yet another OAuth 1 client library.
//!
//! # Usage
//!
//! Add this to your `Cargo.toml`:
//!
//! ```toml
//! [dependencies]
//! oauth = { version = "0.4", package = "oauth1-request" }
//! ```
//!
//! For brevity, we refer to the crate name as `oauth` throughout the documentation,
//! since the API is designed in favor of qualified paths like `oauth::get`.
//!
//! ## Create a request
//!
//! A typical authorization flow looks like this:
//!
//! ```
//! # extern crate oauth1_request as oauth;
//! #
//! // Define a type to represent your request.
//! #[derive(oauth::Request)]
//! struct CreateComment<'a> {
//!     article_id: u64,
//!     text: &'a str,
//! }
//!
//! let uri = "https://example.com/api/v1/comments/create.json";
//!
//! let request = CreateComment {
//!     article_id: 123456789,
//!     text: "A request signed with OAuth & Rust 🦀 🔏",
//! };
//!
//! // Prepare your credentials.
//! let token =
//!     oauth::Token::from_parts("consumer_key", "consumer_secret", "token", "token_secret");
//!
//! // Create the `Authorization` header.
//! let authorization_header = oauth::post(uri, &request, &token, oauth::HmacSha1);
//! # // Override the above value to pin the nonce and timestamp value.
//! # let mut builder = oauth::Builder::new(token.client, oauth::HmacSha1);
//! # builder.token(token.token);
//! # builder.nonce("Dk-OGluFEQ4f").timestamp(std::num::NonZeroU64::new(1234567890));
//! # let authorization_header = builder.post(uri, &request);
//! // `oauth_nonce` and `oauth_timestamp` vary on each execution.
//! assert_eq!(
//!     authorization_header,
//!     "OAuth \
//!          oauth_consumer_key=\"consumer_key\",\
//!          oauth_nonce=\"Dk-OGluFEQ4f\",\
//!          oauth_signature_method=\"HMAC-SHA1\",\
//!          oauth_timestamp=\"1234567890\",\
//!          oauth_token=\"token\",\
//!          oauth_signature=\"n%2FrUgos4CFFZbZK8Z8wFR7drU4c%3D\"",
//! );
//!
//! // You can create an `x-www-form-urlencoded` string or a URI with query pairs from the request.
//!
//! let form = oauth::to_form_urlencoded(&request);
//! assert_eq!(
//!     form,
//!     "article_id=123456789&text=A%20request%20signed%20with%20OAuth%20%26%20Rust%20%F0%9F%A6%80%20%F0%9F%94%8F",
//! );
//!
//! let uri = oauth::to_uri_query(uri.to_owned(), &request);
//! assert_eq!(
//!     uri,
//!     "https://example.com/api/v1/comments/create.json?article_id=123456789&text=A%20request%20signed%20with%20OAuth%20%26%20Rust%20%F0%9F%A6%80%20%F0%9F%94%8F",
//! );
//! ```
//!
//! Use [`oauth::Builder`][Builder] if you need to specify a callback URI or verifier:
//!
//! ```rust
//! # extern crate oauth1_request as oauth;
//! #
//! let uri = "https://example.com/oauth/request_temp_credentials";
//! let callback = "https://client.example.net/oauth/callback";
//!
//! let client = oauth::Credentials::new("consumer_key", "consumer_secret");
//!
//! let authorization_header = oauth::Builder::<_, _>::new(client, oauth::HmacSha1)
//!     .callback(callback)
//!     .post(uri, &());
//! ```
//!
//! See [`Request`][oauth1_request_derive::Request] for more details on the derive macro.

#![doc(html_root_url = "https://docs.rs/oauth1-request/0.4.2")]
#![deny(broken_intra_doc_links)]
#![warn(missing_docs, rust_2018_idioms)]

#[macro_use]
mod util;

pub mod serializer;
pub mod signature_method;

mod request;

#[cfg(feature = "derive")]
#[doc(inline)]
pub use oauth1_request_derive::Request;
#[doc(no_inline)]
pub use oauth_credentials::{Credentials, Token};

pub use request::Request;
#[cfg(feature = "hmac-sha1")]
pub use signature_method::HmacSha1;
pub use signature_method::Plaintext;

use std::borrow::Borrow;
use std::fmt::{Debug, Display};
use std::num::NonZeroU64;
use std::str;

use serializer::auth::{self, Authorizer};
use serializer::Urlencoder;
use signature_method::SignatureMethod;

/// A builder for OAuth `Authorization` header string.
#[derive(Clone, Debug)]
pub struct Builder<'a, SM, C = String, T = C> {
    signature_method: SM,
    client: Credentials<C>,
    token: Option<Credentials<T>>,
    options: auth::Options<'a>,
}

impl<'a, SM: SignatureMethod, C: Borrow<str>, T: Borrow<str>> Builder<'a, SM, C, T> {
    /// Creates a `Builder` that signs requests using the specified client credentials
    /// and signature method.
    pub fn new(client: Credentials<C>, signature_method: SM) -> Self {
        Builder {
            signature_method,
            client,
            token: None,
            options: auth::Options::new(),
        }
    }

    /// Creates a `Builder` that uses the token credentials from `token`.
    pub fn with_token(token: Token<C, T>, signature_method: SM) -> Self {
        let mut ret = Builder::new(token.client, signature_method);
        ret.token(token.token);
        ret
    }

    /// Sets/unsets the token credentials pair to sign requests with.
    pub fn token(&mut self, token: impl Into<Option<Credentials<T>>>) -> &mut Self {
        self.token = token.into();
        self
    }

    /// Sets/unsets the `oauth_callback` URI.
    pub fn callback(&mut self, callback: impl Into<Option<&'a str>>) -> &mut Self {
        self.options.callback(callback);
        self
    }

    /// Sets/unsets the `oauth_verifier` value.
    pub fn verifier(&mut self, verifier: impl Into<Option<&'a str>>) -> &mut Self {
        self.options.verifier(verifier);
        self
    }

    /// Sets/unsets the `oauth_nonce` value.
    ///
    /// By default, `Builder` generates a random nonce for each request.
    /// This method overrides that behavior and forces the `Builder` to use the specified nonce.
    ///
    /// This method is for debugging/testing purpose only and should not be used in production.
    pub fn nonce(&mut self, nonce: impl Into<Option<&'a str>>) -> &mut Self {
        self.options.nonce(nonce);
        self
    }

    /// Sets/unsets the `oauth_timestamp` value.
    ///
    /// By default, `Builder` uses the timestamp of the time when `build`(-like) method is called.
    /// This method overrides that behavior and forces the `Builder` to use the specified timestamp.
    ///
    /// This method is for debugging/testing purpose only and should not be used in production.
    pub fn timestamp(&mut self, timestamp: impl Into<Option<NonZeroU64>>) -> &mut Self {
        self.options.timestamp(timestamp);
        self
    }

    /// Sets whether to include the `oauth_version` value in requests.
    pub fn version(&mut self, version: bool) -> &mut Self {
        self.options.version(version);
        self
    }

    /// Authorizes a `GET` request to `uri`.
    ///
    /// `uri` must not contain a query part, which would result in a wrong signature.
    pub fn get<U: Display, R: Request + ?Sized>(&self, uri: U, request: &R) -> String
    where
        SM: Clone,
    {
        self.build("GET", uri, request)
    }

    /// Authorizes a `PUT` request to `uri`.
    ///
    /// `uri` must not contain a query part, which would result in a wrong signature.
    pub fn put<U: Display, R: Request + ?Sized>(&self, uri: U, request: &R) -> String
    where
        SM: Clone,
    {
        self.build("PUT", uri, request)
    }

    /// Authorizes a `POST` request to `uri`.
    ///
    /// `uri` must not contain a query part, which would result in a wrong signature.
    pub fn post<U: Display, R: Request + ?Sized>(&self, uri: U, request: &R) -> String
    where
        SM: Clone,
    {
        self.build("POST", uri, request)
    }

    /// Authorizes a `DELETE` request to `uri`.
    ///
    /// `uri` must not contain a query part, which would result in a wrong signature.
    pub fn delete<U: Display, R: Request + ?Sized>(&self, uri: U, request: &R) -> String
    where
        SM: Clone,
    {
        self.build("DELETE", uri, request)
    }

    /// Authorizes an `OPTIONS` request to `uri`.
    ///
    /// `uri` must not contain a query part, which would result in a wrong signature.
    pub fn options<U: Display, R: Request + ?Sized>(&self, uri: U, request: &R) -> String
    where
        SM: Clone,
    {
        self.build("OPTIONS", uri, request)
    }

    /// Authorizes a `HEAD` request to `uri`.
    ///
    /// `uri` must not contain a query part, which would result in a wrong signature.
    pub fn head<U: Display, R: Request + ?Sized>(&self, uri: U, request: &R) -> String
    where
        SM: Clone,
    {
        self.build("HEAD", uri, request)
    }

    /// Authorizes a `CONNECT` request to `uri`.
    ///
    /// `uri` must not contain a query part, which would result in a wrong signature.
    pub fn connect<U: Display, R: Request + ?Sized>(&self, uri: U, request: &R) -> String
    where
        SM: Clone,
    {
        self.build("CONNECT", uri, request)
    }

    /// Authorizes a `PATCH` request to `uri`.
    ///
    /// `uri` must not contain a query part, which would result in a wrong signature.
    pub fn patch<U: Display, R: Request + ?Sized>(&self, uri: U, request: &R) -> String
    where
        SM: Clone,
    {
        self.build("PATCH", uri, request)
    }

    /// Authorizes a `TRACE` request to `uri`.
    ///
    /// `uri` must not contain a query part, which would result in a wrong signature.
    pub fn trace<U: Display, R: Request + ?Sized>(&self, uri: U, request: &R) -> String
    where
        SM: Clone,
    {
        self.build("TRACE", uri, request)
    }

    /// Authorizes a request to `uri` with a custom HTTP request method.
    ///
    /// `uri` must not contain a query part, which would result in a wrong signature.
    pub fn build<U: Display, R: Request + ?Sized>(
        &self,
        method: &str,
        uri: U,
        request: &R,
    ) -> String
    where
        SM: Clone,
    {
        let serializer = Authorizer::with_signature_method(
            self.signature_method.clone(),
            method,
            uri,
            self.client.as_ref(),
            self.token.as_ref().map(Credentials::as_ref),
            &self.options,
        );

        request.serialize(serializer)
    }

    /// Authorizes a request and consumes `self`.
    ///
    /// This may be more efficient than `build` if the signature method holds a non-`Copy` data
    /// (e.g. RSA private key). However, the cost is the same as `build` for the signature methods
    /// bundled with this library (`HmacSha1` and `Plaintext`).
    pub fn consume<U: Display, R: Request + ?Sized>(
        self,
        method: &str,
        uri: U,
        request: &R,
    ) -> String {
        let serializer = Authorizer::with_signature_method(
            self.signature_method,
            method,
            uri,
            self.client.as_ref(),
            self.token.as_ref().map(Credentials::as_ref),
            &self.options,
        );

        request.serialize(serializer)
    }
}

macro_rules! def_shorthand {
    ($($(#[$attr:meta])* $name:ident($method:expr);)*) => {$(
        $(#[$attr])*
        pub fn $name<U, R, C, T, SM>(
            uri: U,
            request: &R,
            token: &Token<C, T>,
            signature_method: SM,
        ) -> String
        where
            U: Display,
            R: Request + ?Sized,
            C: Borrow<str>,
            T: Borrow<str>,
            SM: SignatureMethod,
        {
            authorize($method, uri, request, token, signature_method)
        }
    )*};
}

def_shorthand! {
    /// Authorizes a `GET` request to `uri` using the given credentials.
    ///
    /// `uri` must not contain a query part, which would result in a wrong signature.
    get("GET");

    /// Authorizes a `PUT` request to `uri` using the given credentials.
    ///
    /// `uri` must not contain a query part, which would result in a wrong signature.
    put("PUT");

    /// Authorizes a `POST` request to `uri` using the given credentials.
    ///
    /// `uri` must not contain a query part, which would result in a wrong signature.
    post("POST");

    /// Authorizes a `DELETE` request to `uri` using the given credentials.
    ///
    /// `uri` must not contain a query part, which would result in a wrong signature.
    delete("DELETE");

    /// Authorizes an `OPTIONS` request to `uri` using the given credentials.
    ///
    /// `uri` must not contain a query part, which would result in a wrong signature.
    options("OPTIONS");

    /// Authorizes a `HEAD` request to `uri` using the given credentials.
    ///
    /// `uri` must not contain a query part, which would result in a wrong signature.
    head("HEAD");

    /// Authorizes a `CONNECT` request to `uri` using the given credentials.
    ///
    /// `uri` must not contain a query part, which would result in a wrong signature.
    connect("CONNECT");

    /// Authorizes a `PATCH` request to `uri` using the given credentials.
    ///
    /// `uri` must not contain a query part, which would result in a wrong signature.
    patch("PATCH");

    /// Authorizes a `TRACE` request to `uri` using the given credentials.
    ///
    /// `uri` must not contain a query part, which would result in a wrong signature.
    trace("TRACE");
}

/// Authorizes a request to `uri` using the given credentials.
///
/// `uri` must not contain a query part, which would result in a wrong signature.
pub fn authorize<U, R, C, T, SM>(
    method: &str,
    uri: U,
    request: &R,
    token: &Token<C, T>,
    signature_method: SM,
) -> String
where
    U: Display,
    R: Request + ?Sized,
    C: Borrow<str>,
    T: Borrow<str>,
    SM: SignatureMethod,
{
    fn inner<U, R, SM>(
        method: &str,
        uri: U,
        request: &R,
        token: Token<&str, &str>,
        signature_method: SM,
    ) -> String
    where
        U: Display,
        R: Request + ?Sized,
        SM: SignatureMethod,
    {
        Builder::with_token(token, signature_method).consume(method, uri, request)
    }
    inner(method, uri, request, token.as_ref(), signature_method)
}

/// Turns a `Request` into an `x-www-form-urlencoded` string.
pub fn to_form_urlencoded<R>(request: &R) -> String
where
    R: Request + ?Sized,
{
    request.serialize(Urlencoder::form())
}

/// Turns a `Request` to a query string and appends it to the given URI.
///
/// This function naively concatenates a query string to `uri` and if `uri` already has
/// a query part, it will have a duplicate query part like `?foo=bar?baz=qux`.
pub fn to_uri_query<R>(uri: String, request: &R) -> String
where
    R: Request + ?Sized,
{
    request.serialize(Urlencoder::query(uri))
}