qcs_api_client_common/configuration/
settings.rs

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
use std::collections::HashMap;
use std::path::PathBuf;

use figment::providers::Format;
use figment::{providers::Toml, Figment};
use serde::{Deserialize, Serialize};

use super::{
    env_or_default_quilc_url, env_or_default_qvm_url, expand_path_from_env_or_default, LoadError,
    DEFAULT_API_URL, DEFAULT_GRPC_API_URL, DEFAULT_PROFILE_NAME, DEFAULT_QUILC_URL,
    DEFAULT_QVM_URL,
};

/// Setting the `QCS_SETTINGS_FILE_PATH` environment variable will change which file is used for loading [`Settings`].
pub const SETTINGS_PATH_VAR: &str = "QCS_SETTINGS_FILE_PATH";
/// The default path that [`Settings`] will be loaded from;
pub const DEFAULT_SETTINGS_PATH: &str = "~/.qcs/settings.toml";

#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub(crate) struct Settings {
    #[serde(default = "default_profile_name")]
    pub(crate) default_profile_name: String,
    #[serde(default = "default_profiles")]
    pub(crate) profiles: HashMap<String, Profile>,
    #[serde(default = "default_auth_servers")]
    pub(crate) auth_servers: HashMap<String, AuthServer>,
    #[serde(skip)]
    pub(crate) file_path: Option<PathBuf>,
}

impl Settings {
    pub(crate) fn load() -> Result<Self, LoadError> {
        let path = expand_path_from_env_or_default(SETTINGS_PATH_VAR, DEFAULT_SETTINGS_PATH)?;
        #[cfg(feature = "tracing")]
        tracing::debug!("loading QCS settings from {path:?}");
        let mut settings: Self = Figment::from(Toml::file(&path)).extract()?;
        settings.file_path = Some(path);
        Ok(settings)
    }
}

impl Default for Settings {
    fn default() -> Self {
        Self {
            default_profile_name: default_profile_name(),
            profiles: default_profiles(),
            auth_servers: default_auth_servers(),
            file_path: None,
        }
    }
}

fn default_profile_name() -> String {
    DEFAULT_PROFILE_NAME.to_string()
}

fn default_profiles() -> HashMap<String, Profile> {
    HashMap::from([(DEFAULT_PROFILE_NAME.to_string(), Profile::default())])
}

fn default_auth_servers() -> HashMap<String, AuthServer> {
    HashMap::from([(DEFAULT_PROFILE_NAME.to_string(), AuthServer::default())])
}

#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub(crate) struct Profile {
    /// URL of the QCS REST API.
    #[serde(default = "default_api_url")]
    pub(crate) api_url: String,
    /// URL of the QCS gRPC API.
    #[serde(default = "default_grpc_api_url")]
    pub(crate) grpc_api_url: String,
    /// Name of the auth server to use.
    #[serde(default = "default_profile_name")]
    pub(crate) auth_server_name: String,
    /// Name of the credentials to use.
    #[serde(default = "default_profile_name")]
    pub(crate) credentials_name: String,
    /// Application specific settings.
    #[serde(default)]
    pub(crate) applications: Applications,
}

impl Default for Profile {
    fn default() -> Self {
        Self {
            api_url: DEFAULT_API_URL.to_string(),
            grpc_api_url: DEFAULT_GRPC_API_URL.to_string(),
            auth_server_name: DEFAULT_PROFILE_NAME.to_string(),
            credentials_name: DEFAULT_PROFILE_NAME.to_string(),
            applications: Applications::default(),
        }
    }
}

fn default_api_url() -> String {
    DEFAULT_API_URL.to_string()
}

fn default_grpc_api_url() -> String {
    DEFAULT_GRPC_API_URL.to_string()
}

pub(crate) const QCS_DEFAULT_CLIENT_ID_PRODUCTION: &str = "0oa3ykoirzDKpkfzk357";
pub(crate) const QCS_DEFAULT_AUTH_ISSUER_PRODUCTION: &str =
    "https://auth.qcs.rigetti.com/oauth2/aus8jcovzG0gW2TUG355";

/// Okta authorization server.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[cfg_attr(feature = "python", pyo3::pyclass)]
pub struct AuthServer {
    /// Okta client id.
    client_id: String,
    /// Okta issuer URL.
    issuer: String,
}

impl Default for AuthServer {
    fn default() -> Self {
        Self {
            client_id: QCS_DEFAULT_CLIENT_ID_PRODUCTION.to_string(),
            issuer: QCS_DEFAULT_AUTH_ISSUER_PRODUCTION.to_string(),
        }
    }
}

impl AuthServer {
    /// Create a new [`AuthServer`] with a ``client_id`` and ``issuer``.
    #[must_use]
    pub const fn new(client_id: String, issuer: String) -> Self {
        Self { client_id, issuer }
    }

    /// Get the configured Okta client id.
    #[must_use]
    pub fn client_id(&self) -> &str {
        &self.client_id
    }

    /// Set an Okta client id.
    pub fn set_client_id(&mut self, id: String) {
        self.client_id = id;
    }

    /// Get the Okta issuer URL.
    #[must_use]
    pub fn issuer(&self) -> &str {
        &self.issuer
    }

    /// Set an Okta issuer URL.
    pub fn set_issuer(&mut self, issuer: String) {
        self.issuer = issuer;
    }
}

#[derive(Deserialize, Clone, Debug, Default, PartialEq, Serialize)]
pub(crate) struct Applications {
    #[serde(default)]
    pub(crate) pyquil: Pyquil,
}

#[derive(Deserialize, Clone, Debug, PartialEq, Serialize)]
pub(crate) struct Pyquil {
    #[serde(default = "env_or_default_quilc_url")]
    pub(crate) quilc_url: String,

    #[serde(default = "env_or_default_qvm_url")]
    pub(crate) qvm_url: String,
}

impl Default for Pyquil {
    fn default() -> Self {
        Self {
            quilc_url: DEFAULT_QUILC_URL.to_string(),
            qvm_url: DEFAULT_QVM_URL.to_string(),
        }
    }
}

#[cfg(test)]
mod test {
    use std::path::PathBuf;

    use super::{Settings, SETTINGS_PATH_VAR};

    #[test]
    fn returns_err_if_invalid_path_env() {
        figment::Jail::expect_with(|jail| {
            jail.set_env(SETTINGS_PATH_VAR, "/blah/doesnt_exist.toml");
            Settings::load().expect_err("Should return error when a file cannot be found.");
            Ok(())
        });
    }

    #[test]
    fn test_uses_defaults_incomplete_settings() {
        figment::Jail::expect_with(|jail| {
            let _ = jail.create_file("settings.toml", r#"default_profile_name = "TEST""#)?;
            jail.set_env(SETTINGS_PATH_VAR, "settings.toml");
            let loaded = Settings::load().expect("should load settings");
            let expected = Settings {
                default_profile_name: "TEST".to_string(),
                file_path: Some(PathBuf::from("settings.toml")),
                ..Settings::default()
            };

            assert_eq!(loaded, expected);

            Ok(())
        });
    }

    #[test]
    fn loads_from_env_var_path() {
        figment::Jail::expect_with(|jail| {
            let settings = Settings {
                default_profile_name: "TEST".to_string(),
                file_path: Some(PathBuf::from("secrets.toml")),
                ..Settings::default()
            };
            let settings_string =
                toml::to_string(&settings).expect("Should be able to serialize settings");

            _ = jail.create_file("secrets.toml", &settings_string)?;
            jail.set_env(SETTINGS_PATH_VAR, "secrets.toml");

            assert_eq!(settings, Settings::load().unwrap());

            Ok(())
        });
    }
}