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
extern crate futures;
#[macro_use]
extern crate hyper;
extern crate tokio_core;

extern crate serde;
extern crate serde_json;
extern crate serde_xml_rs;

#[macro_use]
extern crate serde_derive;

extern crate hyper_tls;

use std::io::{self, Write};
use futures::{Future, Stream};
use tokio_core::reactor::Core;
use hyper::{Client, Chunk, Method, Request, Headers};
use hyper::header::{ContentLength, ContentType, SetCookie, Accept, qitem, Cookie};
use self::futures::{future, Async, Poll};
use self::futures::task::{self, Task};
use hyper::mime;

static GET_SECURITY_TOKEN_URL: &'static str = "https://login.microsoftonline.com/extSTS.srf";
static GET_ACCESS_TOKEN_URL: &'static str = "https://{host}.sharepoint.com/_forms/default.aspx?wa=wsignin1.0";
static GET_REQUEST_DIGEST_URL: &'static str = "https://{host}.sharepoint.com/_api/contextinfo";

static GET_SECURITY_TOKEN_BODY_PAR: &'static str = r##"<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope"
      xmlns:a="http://www.w3.org/2005/08/addressing"
      xmlns:u="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
  <s:Header>
    <a:Action s:mustUnderstand="1">http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue</a:Action>
    <a:ReplyTo>
      <a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address>
    </a:ReplyTo>
    <a:To s:mustUnderstand="1">https://login.microsoftonline.com/extSTS.srf</a:To>
    <o:Security s:mustUnderstand="1"
       xmlns:o="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
      <o:UsernameToken>
        <o:Username>{user_name}</o:Username>
        <o:Password>{password}</o:Password>
      </o:UsernameToken>
    </o:Security>
  </s:Header>
  <s:Body>
    <t:RequestSecurityToken xmlns:t="http://schemas.xmlsoap.org/ws/2005/02/trust">
      <wsp:AppliesTo xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy">
        <a:EndpointReference>
          <a:Address>{host}.sharepoint.com</a:Address>
        </a:EndpointReference>
      </wsp:AppliesTo>
      <t:KeyType>http://schemas.xmlsoap.org/ws/2005/05/identity/NoProofKey</t:KeyType>
      <t:RequestType>http://schemas.xmlsoap.org/ws/2005/02/trust/Issue</t:RequestType>
      <t:TokenType>urn:oasis:names:tc:SAML:1.0:assertion</t:TokenType>
    </t:RequestSecurityToken>
  </s:Body>
</s:Envelope>
        "##;

#[derive(Debug, Deserialize, Default)]
struct HeaderItem {
    name: String,
    value: String,
}

#[derive(Clone)]
pub struct AccessTokenCookies {
    rt_fa: Option<String>,
    fed_auth: Option<String>,
}

header! { (XRequestDigest, "X-RequestDigest") => [String] }

fn process<'a, T>(url: String,
                  body: String,
                  access_token_cookies: Option<AccessTokenCookies>,
                  parser: fn(String, Vec<HeaderItem>, Vec<String>) -> Option<T>,
                  json: bool,
                  x_request_digest: Option<String>,
                  method: Method)
                  -> Option<T>
    where T: serde::Deserialize<'a>
{
    let mut core = ::tokio_core::reactor::Core::new().unwrap();

    let client = ::hyper::Client::configure()
        .connector(::hyper_tls::HttpsConnector::new(4, &core.handle()).unwrap())
        .build(&core.handle());

    let uri = url.parse().unwrap();

    let mut req = Request::new(method, uri);
    req.set_body(body.to_owned());

    req.headers_mut().set(ContentType::json());
    req.headers_mut().set(ContentLength(body.len() as u64));
    if access_token_cookies.is_some() {
        let atc = access_token_cookies.unwrap();
        let mut cookie = Cookie::new();
        let rt_fa = atc.rt_fa.unwrap();
        cookie.append("rtFa", rt_fa.to_owned());
        cookie.append("FedAuth", atc.fed_auth.unwrap());
        println!("rtFa:{}", rt_fa);
        req.headers_mut().set(cookie);
    };
    if json {
        req.headers_mut()
            .set(Accept(vec![qitem(mime::APPLICATION_JSON)]));
    }
    if x_request_digest.is_some() {
        req.headers_mut()
            .set(XRequestDigest(x_request_digest.unwrap().to_owned()));
    }

    let mut result: Option<T> = None;
    let mut headers: Vec<HeaderItem> = Vec::new();
    let mut header_cookies: Vec<String> = Vec::new();
    {
        let post = client
            .request(req)
            .and_then(|res| {
                headers = res.headers()
                    .iter()
                    .map(|q| {
                             HeaderItem {
                                 name: q.name().to_string(),
                                 value: q.value_string(),
                             }
                         })
                    .collect();

                if let Some(&SetCookie(ref cookies)) = res.headers().get() {
                    for cookie in cookies.iter() {
                        header_cookies.push(cookie.to_string());
                    }
                }

                res.body()
                    .fold(Vec::new(), |mut v, chunk| {
                        v.extend(&chunk[..]);
                        future::ok::<_, hyper::Error>(v)
                    })
                    .and_then(|chunks| {
                                  let s = String::from_utf8(chunks).unwrap();
                                  result = parser(s.to_owned(), headers, header_cookies);
                                  future::ok::<_, hyper::Error>(s)
                              })
            });

        core.run(post).unwrap();
    }

    result
}

use serde_xml_rs::deserialize;

#[derive(Debug, Deserialize, Default)]
struct Header {}

#[derive(Debug, Deserialize, Default)]
struct BinarySecurityToken {
    #[serde(rename="$value")]
    content: String,
}

#[derive(Debug, Deserialize, Default)]
struct RequestedSecurityToken {
    #[serde(rename = "BinarySecurityToken", default)]
    binary_security_token: BinarySecurityToken,
}

#[derive(Debug, Deserialize, Default)]
struct RequestSecurityTokenResponse {
    #[serde(rename = "RequestedSecurityToken", default)]
    requested_security_token: RequestedSecurityToken,
}

#[derive(Debug, Deserialize, Default)]
struct Body {
    #[serde(rename = "RequestSecurityTokenResponse", default)]
    request_security_token_response: RequestSecurityTokenResponse,
}

#[derive(Debug, Deserialize)]
struct Envelope {
    #[serde(rename = "Header", default)]
    pub header: Header,
    #[serde(rename = "Body", default)]
    pub body: Body,
}

#[derive(Debug, Deserialize, Default)]
struct FormDigestValue {
    #[serde(rename="$value")]
    content: String,
}

#[derive(Debug, Deserialize, Default)]
struct GetContextWebInformation {
    #[serde(rename = "FormDigestValue", default)]
    pub form_digest_value: FormDigestValue,
}

use serde_json::Value;

fn parse_json(body: String, _: Vec<HeaderItem>, _: Vec<String>) -> Option<Value> {
    println!("JSON Parsing '{:?}'", body);
    let v: Value = serde_json::from_str(&body).unwrap();
    Some(v)
}

fn parse_xml(body: String, _: Vec<HeaderItem>, _: Vec<String>) -> Option<Envelope> {
    println!("XML Parsing '{:?}'", body);
    let v: Envelope = deserialize(body.as_bytes()).unwrap();
    Some(v)
}

pub fn get_security_token(host: String, user_name: String, password: String) -> String {
    let s = GET_SECURITY_TOKEN_BODY_PAR
        .replace("{user_name}", &user_name)
        .replace("{password}", &password)
        .replace("{host}", &host);
    let res: Envelope = process(GET_SECURITY_TOKEN_URL.to_string(),
                                s.to_string(),
                                None,
                                parse_xml,
                                false,
                                None,
                                Method::Post)
            .unwrap();
    res.body
        .request_security_token_response
        .requested_security_token
        .binary_security_token
        .content
}

fn parse_cookies(_: String, _: Vec<HeaderItem>, cookies: Vec<String>) -> Option<(Vec<String>)> {
    let res: Vec<String> = cookies
        .iter()
        .map(|x| x.to_owned().split(";").next().unwrap().to_string())
        .filter(|x| x.starts_with("rtFa=") || x.starts_with("FedAuth="))
        .collect();
    Some(res)
}

pub fn get_access_token_cookies(host: String, security_token: String) -> AccessTokenCookies {
    let data = process(GET_ACCESS_TOKEN_URL.replace("{host}", &host),
                       security_token,
                       None,
                       parse_cookies,
                       false,
                       None,
                       Method::Post)
            .unwrap();
    let mut res = AccessTokenCookies {
        rt_fa: None,
        fed_auth: None,
    };
    for i in data.clone() {
        println!("Cookie:{}", i);
        if i.starts_with("rtFa=") {
            let right = i.split("rtFa=").nth(1).unwrap().to_string();
            res = AccessTokenCookies {
                rt_fa: Some(right),
                fed_auth: res.fed_auth,
            };
        }
        if i.starts_with("FedAuth=") {
            let right = i.split("FedAuth=").nth(1).unwrap().to_string();
            res = AccessTokenCookies {
                rt_fa: res.rt_fa,
                fed_auth: Some(right),
            };
        }
    }
    res
}

fn parse_digest(body: String,
                _: Vec<HeaderItem>,
                _: Vec<String>)
                -> Option<GetContextWebInformation> {
    println!("Parsing '{:?}'", body);
    let v: GetContextWebInformation = deserialize(body.as_bytes()).unwrap();
    Some(v)
}

pub fn get_the_request_digest(host: String, access_token_cookies: AccessTokenCookies) -> String {
    let res: GetContextWebInformation = process(GET_REQUEST_DIGEST_URL.replace("{host}", &host),
                                                "".to_string(),
                                                Some(access_token_cookies),
                                                parse_digest,
                                                false,
                                                None,
                                                Method::Post)
            .unwrap();
    res.form_digest_value.content
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::env;

    fn login_params() -> (String, String, String) {
        let LOGIN = env::var("RUST_USERNAME").unwrap();
        let PASSWORD = env::var("RUST_PASSWORD").unwrap();
        let HOST = env::var("RUST_HOST").unwrap();
        (LOGIN, PASSWORD, HOST)
    }


    #[test]
    fn json_works() {
        let res = process("https://httpbin.org/post".to_string(),
                          "".to_string(),
                          None,
                          parse_json,
                          true,
                          None,
                          Method::Post);
        println!("Got '{:?}'", res);
    }
    #[test]
    fn xml_works() {
        let (user_name, password, host) = login_params();
        let res = get_security_token(host.to_string(),
                                     user_name.to_string(),
                                     password.to_string());
        println!("Got '{:?}'", res);
    }
    #[test]
    fn get_access_token_cookies_works() {
        let (user_name, password, host) = login_params();
        let security_token = get_security_token(host.to_string(),
                                                user_name.to_string(),
                                                password.to_string());
        let access_token = get_access_token_cookies(host.to_string(), security_token);
        assert!(access_token.rt_fa.is_some());
        assert!(access_token.fed_auth.is_some());
    }
    #[test]
    fn get_the_request_digest_works() {
        let (user_name, password, host) = login_params();
        let security_token = get_security_token(host.to_string(),
                                                user_name.to_string(),
                                                password.to_string());
        let digest = get_the_request_digest(host.to_string(),
                                            get_access_token_cookies(host.to_string(),
                                                                     security_token));
        println!("Digest '{:?}'", digest);
        assert!(digest.len() > 0);
    }
    #[test]
    fn get_the_list() {
        let (user_name, password, host) = login_params();
        let security_token = get_security_token(host.to_string(),
                                                user_name.to_string(),
                                                password.to_string());

        let access_token_cookies = get_access_token_cookies(host.to_string(), security_token);
        let digest = get_the_request_digest(host.to_string(), access_token_cookies.clone());

        process(env::var("RUST_LIST_GET_URL").unwrap().to_string(),
                "".to_string(),
                Some(access_token_cookies),
                parse_json,
                true,
                Some(digest),
                Method::Get);
    }
}