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
use serde::Serialize;
use sha2::Digest;
use std::time;
use url::Url;
pub struct Parameters {
pub method: String,
pub url: Url,
pub valid_for: time::Duration,
pub app_key: String,
pub shared_secret: String,
}
#[derive(thiserror::Error, Debug)]
pub enum AuthError {
#[error("JWT encoding failed: {0}")]
JwtError(#[from] jsonwebtoken::errors::Error),
#[error("system time error: {0}")]
TimeError(#[from] time::SystemTimeError),
}
fn create_query_string_hash(params: &Parameters) -> String {
let url = ¶ms.url;
let method = params.method.as_str().to_uppercase();
let path = url.path();
let mut query_pairs = url
.query_pairs()
.map(|(key, val)| format!("{}={}", key, val))
.collect::<Vec<_>>();
query_pairs.sort_unstable();
let canonical_request = format!("{}&{}&{}", method, path, query_pairs.join("&"));
format!("{:x}", sha2::Sha256::digest(canonical_request.as_bytes()))
}
#[derive(Debug, Serialize)]
struct Claims {
iss: String,
qsh: String,
iat: u64,
exp: u64,
}
impl Claims {
fn new(params: &Parameters) -> Result<Claims, AuthError> {
let now = time::SystemTime::now()
.duration_since(time::UNIX_EPOCH)?
.as_secs();
Ok(Claims {
iss: params.app_key.clone(),
qsh: create_query_string_hash(params),
iat: now,
exp: now + params.valid_for.as_secs(),
})
}
}
pub struct Header {
pub name: String,
pub value: String,
}
pub fn create_auth_header(params: &Parameters) -> Result<Header, AuthError> {
let claims = Claims::new(params)?;
let token = jsonwebtoken::encode(
&jsonwebtoken::Header::default(),
&claims,
&jsonwebtoken::EncodingKey::from_secret(params.shared_secret.as_bytes()),
)?;
Ok(Header {
name: "Authorization".into(),
value: format!("JWT {}", token),
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_query_string_hash() {
let params = Parameters {
method: "get".into(),
url: Url::parse(
"https://somecorp.atlassian.net/rest/api/3/project/search?query=myproject",
)
.unwrap(),
app_key: String::new(),
shared_secret: String::new(),
valid_for: time::Duration::new(0, 0),
};
assert_eq!(
create_query_string_hash(¶ms),
"29df35d41afcc61d322eba090286bf96b42fa3d7b5b5d1d2d261083d1cefd7fe"
);
}
}