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
use std::path::PathBuf;
use std::sync::Arc;
use futures::future::try_join;
use jsonwebtoken::{decode, errors::Error as JWTError, Algorithm, DecodingKey, Validation};
use serde::{Deserialize, Serialize};
use tokio::sync::{Mutex, MutexGuard};
use secrets::Secrets;
pub use secrets::SECRETS_PATH_VAR;
pub use settings::SETTINGS_PATH_VAR;
use settings::{AuthServer, Settings};
use crate::configuration::LoadError::AuthServerNotFound;
mod path;
mod secrets;
mod settings;
pub const DEFAULT_API_URL: &str = "https://api.qcs.rigetti.com";
pub const DEFAULT_GRPC_API_URL: &str = "https://legacy.grpc.qcs.rigetti.com:443";
pub const DEFAULT_QVM_URL: &str = "http://127.0.0.1:5000";
pub const DEFAULT_QUILC_URL: &str = "tcp://127.0.0.1:5555";
#[derive(Clone, Debug, Default)]
pub struct Tokens {
pub bearer_access_token: Option<String>,
pub refresh_token: Option<String>,
}
#[derive(Clone, Debug)]
#[allow(clippy::module_name_repetitions)]
pub struct ClientConfiguration {
tokens: Arc<Mutex<Tokens>>,
api_url: String,
auth_server: AuthServer,
quilc_url: String,
qvm_url: String,
grpc_api_url: String,
}
impl ClientConfiguration {
#[must_use]
pub fn api_url(&self) -> &str {
&self.api_url
}
#[must_use]
pub fn grpc_api_url(&self) -> &str {
&self.grpc_api_url
}
#[must_use]
pub fn quilc_url(&self) -> &str {
&self.quilc_url
}
#[must_use]
pub fn qvm_url(&self) -> &str {
&self.qvm_url
}
}
pub const PROFILE_NAME_VAR: &str = "QCS_PROFILE_NAME";
#[derive(Debug, thiserror::Error)]
pub enum RefreshError {
#[error("No refresh token is in secrets")]
NoRefreshToken,
#[error("Error fetching new token")]
FetchError(#[from] reqwest::Error),
#[error("Error validating existing token: {0}")]
ValidationError(#[from] JWTError),
}
#[derive(Debug, thiserror::Error)]
pub enum LoadError {
#[error("Expected profile {0} in settings.profiles but it didn't exist")]
ProfileNotFound(String),
#[error("Expected auth server {0} in settings.auth_servers but it didn't exist")]
AuthServerNotFound(String),
#[error("Failed to determine home directory. You can use an explicit path by setting the {env} environment variable")]
HomeDirError {
env: String,
},
#[error("Could not open file at {path}: {source}")]
FileOpenError {
path: PathBuf,
source: std::io::Error,
},
#[error("Could not parse TOML file at {path}: {source}")]
FileParseError {
path: PathBuf,
source: toml::de::Error,
},
}
impl ClientConfiguration {
pub async fn load() -> Result<Self, LoadError> {
let (settings, secrets) = try_join(settings::load(), secrets::load()).await?;
Self::new(settings, secrets)
}
pub async fn set_tokens(&mut self, tokens: Tokens) {
let mut lock = self.tokens.lock().await;
*lock = tokens;
}
fn validate_bearer_access_token(lock: &mut MutexGuard<Tokens>) -> Result<String, RefreshError> {
match &lock.bearer_access_token {
None => Err(RefreshError::NoRefreshToken),
Some(token) => {
let dummy_key = DecodingKey::from_secret(&[]);
let mut validation = Validation::new(Algorithm::RS256);
validation.validate_exp = true;
validation.leeway = 0;
validation.insecure_disable_signature_validation();
decode::<toml::Value>(token, &dummy_key, &validation)
.map(|_| token.to_string())
.map_err(RefreshError::from)
}
}
}
pub async fn get_bearer_access_token(&self) -> Result<String, RefreshError> {
let mut lock = self.tokens.lock().await;
match Self::validate_bearer_access_token(&mut lock) {
Ok(token) => Ok(token),
Err(_) => self.internal_refresh(&mut lock).await,
}
}
pub async fn refresh(&self) -> Result<String, RefreshError> {
let mut lock = self.tokens.lock().await;
self.internal_refresh(&mut lock).await
}
async fn internal_refresh<'a>(
&'a self,
lock: &mut MutexGuard<'a, Tokens>,
) -> Result<String, RefreshError> {
let refresh_token = lock
.refresh_token
.as_deref()
.ok_or(RefreshError::NoRefreshToken)?;
let token_url = format!("{}/v1/token", &self.auth_server.issuer);
let data = TokenRequest::new(&self.auth_server.client_id, refresh_token);
let resp = reqwest::Client::builder()
.user_agent(format!(
"QCS API Client (Rust)/{}",
env!("CARGO_PKG_VERSION")
))
.timeout(std::time::Duration::from_secs(10))
.build()?
.post(token_url)
.form(&data)
.send()
.await?;
let response_data: TokenResponse = resp.error_for_status()?.json().await?;
lock.bearer_access_token = Some(response_data.access_token.clone());
lock.refresh_token = Some(response_data.refresh_token);
Ok(response_data.access_token)
}
fn new(settings: Settings, mut secrets: Secrets) -> Result<Self, LoadError> {
let Settings {
default_profile_name,
mut profiles,
mut auth_servers,
} = settings;
let profile_name = std::env::var(PROFILE_NAME_VAR).unwrap_or(default_profile_name);
let profile = profiles
.remove(&profile_name)
.ok_or(LoadError::ProfileNotFound(profile_name))?;
let auth_server = auth_servers
.remove(&profile.auth_server_name)
.ok_or_else(|| AuthServerNotFound(profile.auth_server_name.clone()))?;
let credential = secrets.credentials.remove(&profile.credentials_name);
let (access_token, refresh_token) = match credential {
Some(secrets::Credential {
token_payload: Some(token_payload),
}) => (token_payload.access_token, token_payload.refresh_token),
_ => (None, None),
};
Ok(Self {
api_url: profile.api_url,
tokens: Arc::new(Mutex::new(Tokens {
bearer_access_token: access_token,
refresh_token,
})),
auth_server,
quilc_url: profile.applications.pyquil.quilc_url,
qvm_url: profile.applications.pyquil.qvm_url,
grpc_api_url: profile.grpc_api_url,
})
}
}
#[derive(Debug, Serialize)]
struct TokenRequest<'a> {
grant_type: &'static str,
client_id: &'a str,
refresh_token: &'a str,
}
impl<'a> TokenRequest<'a> {
const fn new(client_id: &'a str, refresh_token: &'a str) -> TokenRequest<'a> {
Self {
grant_type: "refresh_token",
client_id,
refresh_token,
}
}
}
#[derive(Deserialize, Debug)]
struct TokenResponse {
refresh_token: String,
access_token: String,
}
impl Default for ClientConfiguration {
fn default() -> Self {
Self {
quilc_url: DEFAULT_QUILC_URL.to_string(),
qvm_url: DEFAULT_QVM_URL.to_string(),
api_url: DEFAULT_API_URL.to_string(),
grpc_api_url: DEFAULT_GRPC_API_URL.to_string(),
auth_server: AuthServer::default(),
tokens: Arc::default(),
}
}
}