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
use base64;
use futures::Stream;
use hyper::header;
use v2::*;

/// Convenience alias for future `TokenAuth` result.
pub type FutureTokenAuth = Box<futures::Future<Item = TokenAuth, Error = Error> + 'static>;

#[derive(Debug, Default, Deserialize, Serialize)]
pub struct TokenAuth {
    token: String,
    expires_in: Option<u32>,
    issued_at: Option<String>,
    refresh_token: Option<String>,
}

impl TokenAuth {
    pub fn token(&self) -> &str {
        self.token.as_str()
    }
}

type FutureString = Box<futures::Future<Item = String, Error = self::Error>>;

impl Client {
    fn get_token_provider(&self) -> FutureString {
        let url = {
            let ep = format!("{}/v2/", self.base_url);
            match hyper::Uri::from_str(ep.as_str()) {
                Ok(url) => url,
                Err(e) => {
                    return Box::new(futures::future::err::<_, _>(Error::from(format!(
                        "failed to parse url from string: {}",
                        e
                    ))))
                }
            }
        };
        let req = match self.new_request(hyper::Method::GET, url) {
            Ok(r) => r,
            Err(e) => {
                let msg = format!("new_request failed: {}", e);
                error!("{}", msg);
                return Box::new(futures::future::err::<_, _>(Error::from(msg)));
            }
        };
        let freq = self.hclient.request(req);
        let www_auth = freq
            .from_err()
            .and_then(|r| {
                let a = r
                    .headers()
                    .get(hyper::header::WWW_AUTHENTICATE)
                    .ok_or_else(|| Error::from("get_token: missing Auth header"))?;
                let chal = String::from_utf8(a.as_bytes().to_vec())?;
                Ok(chal)
            }).and_then(move |hdr| {
                let mut auth_ep = "".to_owned();
                let mut service = None;
                for item in hdr.trim_left_matches("Bearer ").split(',') {
                    let kv: Vec<&str> = item.split('=').collect();
                    match (kv.get(0), kv.get(1)) {
                        (Some(&"realm"), Some(v)) => auth_ep = v.trim_matches('"').to_owned(),
                        (Some(&"service"), Some(v)) => service = Some(v.trim_matches('"')),
                        (Some(&"scope"), _) => {}
                        (_, _) => return Err("unsupported key".to_owned().into()),
                    };
                }
                trace!("Token provider: {}", auth_ep);
                if let Some(sv) = service {
                    auth_ep += &format!("?service={}", sv);
                    trace!("Service identity: {}", sv);
                }
                Ok(auth_ep)
            });
        Box::new(www_auth)
    }

    /// Set the token to be used for further registry requests.
    pub fn set_token(&mut self, token: Option<&str>) -> &Self {
        if let Some(ref t) = token {
            self.token = Some(t.to_string());
        }
        self
    }

    /// Perform registry authentication and return an authenticated token.
    ///
    /// On success, the returned token will be valid for all requested scopes.
    pub fn login(&self, scopes: &[&str]) -> FutureTokenAuth {
        let subclient = self.hclient.clone();
        let creds = self.credentials.clone();
        let scope = scopes
            .iter()
            .fold("".to_string(), |acc, &s| acc + "&scope=" + s);
        let auth = self
            .get_token_provider()
            .and_then(move |token_ep| {
                let auth_ep = token_ep + scope.as_str();
                trace!("Token endpoint: {}", auth_ep);
                hyper::Uri::from_str(auth_ep.as_str()).map_err(|e| e.into())
            }).and_then(move |u| {
                let mut auth_req = hyper::Request::default();
                *auth_req.method_mut() = hyper::Method::GET;
                *auth_req.uri_mut() = u;
                if let Some(c) = creds {
                    let plain = format!("{}:{}", c.0, c.1);
                    let basic = format!("Basic {}", base64::encode(&plain));
                    if let Ok(basic_header) = header::HeaderValue::from_str(&basic) {
                        auth_req
                            .headers_mut()
                            .append(header::AUTHORIZATION, basic_header);
                    } else {
                        let msg = format!("could not parse HeaderValue from '{}'", basic);
                            error!("{}", msg);
                            // TODO: return an error. seems difficult to match the error type for the whole closure
                    };
                };
                subclient.request(auth_req).map_err(|e| e.into())
            })
            .and_then(|r| {
                let status = r.status();
                trace!("Got status {}", status);
                match status {
                    hyper::StatusCode::OK => Ok(r),
                    _ => Err(format!("login: wrong HTTP status '{}'", status).into()),
                }
            }).and_then(|r| {
                r.into_body()
                    .concat2()
                    .map_err(|e| format!("login: failed to fetch the whole body: {}", e).into())
            }).and_then(|body| {
                let s = String::from_utf8(body.into_bytes().to_vec())?;
                serde_json::from_slice(s.as_bytes()).map_err(|e| e.into())
            }).inspect(|_| {
                trace!("Got token");
            });
        Box::new(auth)
    }

    /// Check whether the client is authenticated with the registry.
    pub fn is_auth(&self, token: Option<&str>) -> FutureBool {
        let url = match hyper::Uri::from_str((self.base_url.clone() + "/v2/").as_str()) {
            Ok(url) => url,
            Err(e) => return Box::new(futures::future::err(e.into())),
        };
        let mut req = match self.new_request(hyper::Method::GET, url.clone()) {
            Ok(r) => r,
            Err(e) => {
                let msg = format!("new_request failed: {}", e);
                error!("{}", msg);
                return Box::new(futures::future::err(Error::from(msg)));
            }
        };
        if let Some(t) = token {
            let bearer = format!("Bearer {}", t);
            if let Ok(basic_header) = header::HeaderValue::from_str(&bearer) {
                req.headers_mut()
                    .append(header::AUTHORIZATION, basic_header);
            } else {
                let msg = format!("could not parse HeaderValue from '{}'", bearer);
                error!("{}", msg);
                return Box::new(futures::future::err(Error::from(msg)));
            };
        };

        let freq = self.hclient.request(req);
        let fres = freq
            .from_err()
            .inspect(move |_| {
                trace!("GET {:?}", url);
            }).and_then(move |r| {
                let status = r.status();
                trace!("Got status {}", status);
                match status {
                    hyper::StatusCode::OK => Ok(true),
                    hyper::StatusCode::UNAUTHORIZED => Ok(false),
                    _ => Err(format!("is_auth: wrong HTTP status '{}'", status).into()),
                }
            });
        Box::new(fres)
    }
}