Skip to main content

ctrader_connector/open_api/
token.rs

1//! Token pairs and their refresh over the token endpoint.
2//!
3//! A refresh rotates the pair: the old access and refresh tokens stop working once the server
4//! has answered, so the caller must store the new pair before doing anything else with it.
5//!
6//! The endpoint is queried with a single HTTP `GET` over the same TLS stack the connection uses;
7//! the reply is a small JSON document.
8
9use std::fmt::Write as _;
10use std::time::Duration;
11
12use serde_json::Value;
13use tokio::io::{AsyncReadExt, AsyncWriteExt};
14use tokio::time::timeout;
15
16use crate::common::config::{AccessToken, ConfigurationOpenApi, RefreshToken};
17use crate::common::errors::{ConfigError, ConnectorError, TokenError, TransportError};
18use crate::open_api::messages::ProtoOaRefreshTokenRes;
19use crate::open_api::transport::Connect;
20
21const HTTPS_PORT: u16 = 443;
22const MAX_RESPONSE_LENGTH: usize = 64 * 1024;
23const READ_CHUNK: usize = 4 * 1024;
24const HEAD_END: &[u8] = b"\r\n\r\n";
25const LINE_END: &[u8] = b"\r\n";
26
27/// Access token together with the refresh token that renews it.
28///
29/// Both tokens are redacted in `Debug` output.
30#[derive(Debug, Clone, PartialEq, Eq)]
31#[non_exhaustive]
32pub struct TokenPair {
33    /// Token authorising access to trading accounts.
34    pub access: AccessToken,
35    /// Token exchanged for the next pair.
36    pub refresh: RefreshToken,
37    /// Time the access token stays valid, counted from the refresh.
38    pub expires_in: Duration,
39    /// Kind of the access token, `bearer` in practice.
40    pub token_type: String,
41}
42
43impl TokenPair {
44    fn new(
45        access: String,
46        refresh: String,
47        expires_in: u64,
48        token_type: String,
49    ) -> Result<Self, TokenError> {
50        Ok(Self {
51            access: AccessToken::new(access).map_err(|_| TokenError::Malformed("accessToken"))?,
52            refresh: RefreshToken::new(refresh)
53                .map_err(|_| TokenError::Malformed("refreshToken"))?,
54            expires_in: Duration::from_secs(expires_in),
55            token_type,
56        })
57    }
58}
59
60impl TryFrom<ProtoOaRefreshTokenRes> for TokenPair {
61    type Error = TokenError;
62
63    fn try_from(response: ProtoOaRefreshTokenRes) -> Result<Self, Self::Error> {
64        let expires_in =
65            u64::try_from(response.expires_in).map_err(|_| TokenError::Malformed("expiresIn"))?;
66        Self::new(
67            response.access_token,
68            response.refresh_token,
69            expires_in,
70            response.token_type,
71        )
72    }
73}
74
75/// Reads a token pair from the JSON document the token endpoint answers with.
76///
77/// # Errors
78///
79/// Returns [`TokenError::Refused`] when the document reports an error and
80/// [`TokenError::Malformed`] when it is not JSON or lacks a field. The document itself is
81/// never copied into the error.
82pub fn parse_token_response(body: &str) -> Result<TokenPair, TokenError> {
83    let document: Value = serde_json::from_str(body).map_err(|_| TokenError::Malformed("JSON"))?;
84    let text = |key: &str| document.get(key).and_then(Value::as_str).map(str::to_owned);
85    if let Some(code) = text("errorCode") {
86        return Err(TokenError::Refused {
87            code,
88            description: text("description").unwrap_or_default(),
89        });
90    }
91    let expires_in = document
92        .get("expiresIn")
93        .and_then(Value::as_u64)
94        .ok_or(TokenError::Malformed("expiresIn"))?;
95    TokenPair::new(
96        text("accessToken").ok_or(TokenError::Malformed("accessToken"))?,
97        text("refreshToken").ok_or(TokenError::Malformed("refreshToken"))?,
98        expires_in,
99        text("tokenType").unwrap_or_else(|| "bearer".to_owned()),
100    )
101}
102
103#[derive(Debug, PartialEq, Eq)]
104struct Endpoint {
105    host: String,
106    port: u16,
107    path: String,
108}
109
110impl Endpoint {
111    fn parse(url: &str) -> Result<Self, ConfigError> {
112        let invalid = || ConfigError::InvalidTokenUrl(url.to_owned());
113        let rest = url.strip_prefix("https://").ok_or_else(invalid)?;
114        let (authority, path) = match rest.find(['/', '?']) {
115            Some(index) => rest.split_at(index),
116            None => (rest, ""),
117        };
118        let (host, port) = match authority.rsplit_once(':') {
119            Some((host, port)) => (host, port.parse().map_err(|_| invalid())?),
120            None => (authority, HTTPS_PORT),
121        };
122        if host.is_empty() || port == 0 {
123            return Err(invalid());
124        }
125        let path = if path.starts_with('/') {
126            path.to_owned()
127        } else {
128            format!("/{path}")
129        };
130        Ok(Self {
131            host: host.to_owned(),
132            port,
133            path,
134        })
135    }
136
137    fn target(&self, parameters: &[(&str, &str)]) -> String {
138        let mut target = self.path.clone();
139        let mut separator = if target.contains('?') { '&' } else { '?' };
140        for (name, value) in parameters {
141            target.push(separator);
142            target.push_str(name);
143            target.push('=');
144            percent_encode(value, &mut target);
145            separator = '&';
146        }
147        target
148    }
149}
150
151fn percent_encode(value: &str, out: &mut String) {
152    for byte in value.bytes() {
153        if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~') {
154            out.push(char::from(byte));
155        } else {
156            let _ = write!(out, "%{byte:02X}");
157        }
158    }
159}
160
161fn find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
162    haystack
163        .windows(needle.len())
164        .position(|window| window == needle)
165}
166
167fn unchunk(mut rest: &[u8]) -> Result<Vec<u8>, TokenError> {
168    let malformed = TokenError::Malformed("chunked body");
169    let mut body = Vec::new();
170    loop {
171        let line_end = find(rest, LINE_END).ok_or(malformed.clone())?;
172        let (line, after) = rest.split_at(line_end);
173        let size = std::str::from_utf8(line)
174            .ok()
175            .and_then(|line| line.split(';').next())
176            .and_then(|digits| usize::from_str_radix(digits.trim(), 16).ok())
177            .ok_or(malformed.clone())?;
178        let data = after.get(LINE_END.len()..).ok_or(malformed.clone())?;
179        if size == 0 {
180            return Ok(body);
181        }
182        let (chunk, after) = data.split_at_checked(size).ok_or(malformed.clone())?;
183        body.extend_from_slice(chunk);
184        rest = after.get(LINE_END.len()..).ok_or(malformed.clone())?;
185    }
186}
187
188fn http_body(raw: &[u8]) -> Result<(u16, String), TokenError> {
189    let malformed = TokenError::Malformed("HTTP response");
190    let head_end = find(raw, HEAD_END).ok_or(malformed.clone())?;
191    let (head, rest) = raw.split_at(head_end);
192    let head = std::str::from_utf8(head).map_err(|_| malformed.clone())?;
193    let status = head
194        .split_whitespace()
195        .nth(1)
196        .and_then(|code| code.parse().ok())
197        .ok_or(malformed.clone())?;
198    let chunked = head.lines().skip(1).any(|line| {
199        let line = line.to_ascii_lowercase();
200        line.starts_with("transfer-encoding:") && line.contains("chunked")
201    });
202    let body = rest.get(HEAD_END.len()..).unwrap_or_default();
203    let body = if chunked {
204        unchunk(body)?
205    } else {
206        body.to_vec()
207    };
208    let body = String::from_utf8(body).map_err(|_| malformed)?;
209    Ok((status, body))
210}
211
212async fn exchange<C: Connect>(
213    connector: &C,
214    endpoint: &Endpoint,
215    request: &str,
216) -> Result<Vec<u8>, TransportError> {
217    let mut stream = connector.connect(&endpoint.host, endpoint.port).await?;
218    stream.write_all(request.as_bytes()).await?;
219    stream.flush().await?;
220    let mut raw = Vec::new();
221    let mut chunk = [0_u8; READ_CHUNK];
222    while raw.len() < MAX_RESPONSE_LENGTH {
223        match stream.read(&mut chunk).await {
224            Ok(read) => match chunk.get(..read) {
225                Some(bytes) if read > 0 => raw.extend_from_slice(bytes),
226                _ => break,
227            },
228            Err(error) if error.kind() == std::io::ErrorKind::UnexpectedEof => break,
229            Err(error) => return Err(error.into()),
230        }
231    }
232    Ok(raw)
233}
234
235/// Exchanges a refresh token for a new pair at the token endpoint of the configuration.
236///
237/// The endpoint is reached through `connector`, which is the TLS connector outside tests. The
238/// old pair is invalid once this returns a new one.
239///
240/// # Errors
241///
242/// Returns [`ConnectorError::Token`] when the endpoint refuses the refresh or answers with
243/// something else than a token document, [`ConnectorError::Timeout`] when it does not answer
244/// within the timeout of the configuration, [`ConnectorError::Transport`] when the exchange
245/// fails, and [`ConnectorError::Config`] when the token URL has no usable host.
246pub async fn refresh_over_http<C: Connect>(
247    connector: &C,
248    configuration: &ConfigurationOpenApi,
249    refresh: &RefreshToken,
250) -> Result<TokenPair, ConnectorError> {
251    let endpoint = Endpoint::parse(configuration.token_url())?;
252    let target = endpoint.target(&[
253        ("grant_type", "refresh_token"),
254        ("refresh_token", refresh.expose()),
255        ("client_id", configuration.client_id().as_str()),
256        ("client_secret", configuration.client_secret().expose()),
257    ]);
258    let request = format!(
259        "GET {target} HTTP/1.1\r\nHost: {}\r\nAccept: application/json\r\nUser-Agent: \
260         ctrader-connector/{}\r\nConnection: close\r\n\r\n",
261        endpoint.host,
262        crate::VERSION
263    );
264    let limit = configuration.timeout();
265    let raw = timeout(limit, exchange(connector, &endpoint, &request))
266        .await
267        .map_err(|_| ConnectorError::Timeout(limit))??;
268    let (status, body) = http_body(&raw)?;
269    match parse_token_response(&body) {
270        Err(TokenError::Malformed(_)) if !(200..300).contains(&status) => {
271            Err(TokenError::Status(status).into())
272        }
273        outcome => Ok(outcome?),
274    }
275}
276
277#[cfg(test)]
278mod tests {
279    use std::time::Duration;
280
281    use super::{Endpoint, TokenPair, http_body, parse_token_response, percent_encode, unchunk};
282    use crate::common::errors::{ConfigError, TokenError};
283    use crate::open_api::messages::ProtoOaRefreshTokenRes;
284
285    #[test]
286    fn token_document_is_parsed() {
287        let pair = parse_token_response(
288            r#"{"accessToken":"a1","refreshToken":"r1","expiresIn":2628000,"tokenType":"bearer","errorCode":null}"#,
289        )
290        .expect("pair");
291        assert_eq!(pair.access.expose(), "a1");
292        assert_eq!(pair.refresh.expose(), "r1");
293        assert_eq!(pair.expires_in, Duration::from_secs(2_628_000));
294        assert_eq!(pair.token_type, "bearer");
295        let debug = format!("{pair:?}");
296        assert!(!debug.contains("a1") && !debug.contains("r1"), "{debug}");
297        let untyped =
298            parse_token_response(r#"{"accessToken":"a","refreshToken":"r","expiresIn":1}"#)
299                .expect("pair");
300        assert_eq!(untyped.token_type, "bearer");
301    }
302
303    #[test]
304    fn refusal_keeps_code_and_description() {
305        assert_eq!(
306            parse_token_response(r#"{"errorCode":"ACCESS_DENIED","description":"no"}"#),
307            Err(TokenError::Refused {
308                code: "ACCESS_DENIED".to_owned(),
309                description: "no".to_owned(),
310            })
311        );
312        assert_eq!(
313            parse_token_response(r#"{"errorCode":"X"}"#),
314            Err(TokenError::Refused {
315                code: "X".to_owned(),
316                description: String::new(),
317            })
318        );
319    }
320
321    #[test]
322    fn incomplete_documents_name_the_missing_part_only() {
323        let cases = [
324            ("not json", "JSON"),
325            (r#"{"refreshToken":"r","expiresIn":1}"#, "accessToken"),
326            (r#"{"accessToken":"a","expiresIn":1}"#, "refreshToken"),
327            (r#"{"accessToken":"a","refreshToken":"r"}"#, "expiresIn"),
328            (
329                r#"{"accessToken":"","refreshToken":"r","expiresIn":1}"#,
330                "accessToken",
331            ),
332            (
333                r#"{"accessToken":"a","refreshToken":" ","expiresIn":1}"#,
334                "refreshToken",
335            ),
336        ];
337        for (body, part) in cases {
338            assert_eq!(
339                parse_token_response(body),
340                Err(TokenError::Malformed(part)),
341                "{part}"
342            );
343        }
344    }
345
346    #[test]
347    fn socket_response_becomes_a_pair() {
348        let response = ProtoOaRefreshTokenRes {
349            payload_type: None,
350            access_token: "a".to_owned(),
351            token_type: "bearer".to_owned(),
352            expires_in: 60,
353            refresh_token: "r".to_owned(),
354        };
355        let pair = TokenPair::try_from(response.clone()).expect("pair");
356        assert_eq!(pair.expires_in, Duration::from_secs(60));
357        let negative = ProtoOaRefreshTokenRes {
358            expires_in: -1,
359            ..response
360        };
361        assert_eq!(
362            TokenPair::try_from(negative),
363            Err(TokenError::Malformed("expiresIn"))
364        );
365    }
366
367    #[test]
368    fn endpoint_is_split_into_host_port_and_path() {
369        let endpoint = |host: &str, port, path: &str| Endpoint {
370            host: host.to_owned(),
371            port,
372            path: path.to_owned(),
373        };
374        assert_eq!(
375            Endpoint::parse("https://example.com/apps/token"),
376            Ok(endpoint("example.com", 443, "/apps/token"))
377        );
378        assert_eq!(
379            Endpoint::parse("https://example.com:8443"),
380            Ok(endpoint("example.com", 8443, "/"))
381        );
382        assert_eq!(
383            Endpoint::parse("https://example.com?x=1"),
384            Ok(endpoint("example.com", 443, "/?x=1"))
385        );
386        for url in [
387            "http://example.com/",
388            "https://:1/",
389            "https://example.com:0/",
390            "https://example.com:port/",
391        ] {
392            assert_eq!(
393                Endpoint::parse(url),
394                Err(ConfigError::InvalidTokenUrl(url.to_owned()))
395            );
396        }
397    }
398
399    #[test]
400    fn parameters_are_percent_encoded_into_the_target() {
401        let endpoint = Endpoint::parse("https://example.com/token").expect("endpoint");
402        assert_eq!(
403            endpoint.target(&[("a", "x y"), ("b", "1+2/3=~")]),
404            "/token?a=x%20y&b=1%2B2%2F3%3D~"
405        );
406        let with_query = Endpoint::parse("https://example.com/token?v=2").expect("endpoint");
407        assert_eq!(with_query.target(&[("a", "b")]), "/token?v=2&a=b");
408        let mut out = String::new();
409        percent_encode("A-z_0.9~é", &mut out);
410        assert_eq!(out, "A-z_0.9~%C3%A9");
411    }
412
413    #[test]
414    fn http_response_is_split_into_status_and_body() {
415        assert_eq!(
416            http_body(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\n{}"),
417            Ok((200, "{}".to_owned()))
418        );
419        assert_eq!(
420            http_body(
421                b"HTTP/1.1 400 Bad\r\nTransfer-Encoding: chunked\r\n\r\n3\r\n{\"a\r\n4;x=1\r\n\":1}\r\n0\r\n\r\n"
422            ),
423            Ok((400, "{\"a\":1}".to_owned()))
424        );
425        assert_eq!(
426            http_body(b"HTTP/1.1 204 No Content\r\n\r\n"),
427            Ok((204, String::new()))
428        );
429        for raw in [
430            &b"HTTP/1.1 200 OK\r\n"[..],
431            b"HTTP/1.1\r\n\r\n",
432            b"HTTP/1.1 abc OK\r\n\r\n",
433            b"\xff\xfe 200\r\n\r\n",
434            b"HTTP/1.1 200 OK\r\n\r\n\xff",
435        ] {
436            assert_eq!(http_body(raw), Err(TokenError::Malformed("HTTP response")));
437        }
438    }
439
440    #[test]
441    fn broken_chunks_are_rejected() {
442        for raw in [
443            &b"5\r\nab"[..],
444            b"zz\r\nab\r\n0\r\n\r\n",
445            b"2\r\nab",
446            b"2",
447            b"\xff\r\n",
448            b"2\r\nab\r\n",
449        ] {
450            assert_eq!(unchunk(raw), Err(TokenError::Malformed("chunked body")));
451        }
452        assert_eq!(unchunk(b"0\r\n\r\n"), Ok(Vec::new()));
453    }
454}