htsget-config 0.22.0

Used to configure htsget-rs by using a config file or reading environment variables.
Documentation
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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
//! JWT authorization configuration and response structures.
//!
//! This module provides configuration structures for JWT token validation and authorization
//! service integration, enabling fine-grained access control over genomic data.
//!

use crate::config::advanced::HttpClient;
use crate::config::advanced::auth::authorization::{ForwardExtensions, UrlOrStatic};
use crate::config::advanced::auth::jwt::AuthMode;
use crate::config::service_info::PackageInfo;
use crate::error::{Error, Result};
use crate::http::client::HttpClientConfig;
use reqwest_middleware::ClientWithMiddleware;
pub use response::{AuthorizationRestrictions, AuthorizationRule, ReferenceNameRestriction};
use serde::Deserialize;

pub mod authorization;
pub mod jwt;
pub mod response;

/// Configuration for JWT authorization.
#[derive(Deserialize, Debug, Clone)]
#[serde(deny_unknown_fields, try_from = "AuthConfigBuilder")]
pub struct AuthConfig {
  auth_mode: Option<AuthMode>,
  validate_audience: Option<Vec<String>>,
  validate_issuer: Option<Vec<String>>,
  validate_subject: Option<String>,
  authorization_url: Option<UrlOrStatic>,
  forward_headers: Vec<String>,
  forward_endpoint_type: bool,
  forward_id: bool,
  passthrough_auth: bool,
  forward_extensions: Vec<ForwardExtensions>,
  http_client: HttpClient,
  #[cfg(feature = "experimental")]
  suppress_errors: bool,
  #[cfg(feature = "experimental")]
  add_hint: bool,
}

impl AuthConfig {
  /// Whether to suppress errors and return any available regions.
  #[cfg(feature = "experimental")]
  pub fn suppress_errors(&self) -> bool {
    self.suppress_errors
  }

  /// Whether the client gets a hint about which regions are allowed.
  #[cfg(feature = "experimental")]
  pub fn add_hint(&self) -> bool {
    self.add_hint
  }

  /// Get the http client.
  pub fn http_client(&mut self) -> Result<&ClientWithMiddleware> {
    self.http_client.as_inner_built()
  }

  /// Get a mutable reference to the inner client builder.
  pub fn inner_client_mut(&mut self) -> &mut HttpClient {
    &mut self.http_client
  }

  /// Get the authorization mode.
  pub fn auth_mode(&self) -> Option<&AuthMode> {
    self.auth_mode.as_ref()
  }

  /// Get the authorization mode.
  pub fn auth_mode_mut(&mut self) -> Option<&mut AuthMode> {
    self.auth_mode.as_mut()
  }

  /// Get the validate audience list.
  pub fn validate_audience(&self) -> Option<&[String]> {
    self.validate_audience.as_deref()
  }

  /// Get the validate issuer list.
  pub fn validate_issuer(&self) -> Option<&[String]> {
    self.validate_issuer.as_deref()
  }

  /// Get the validate issuer list.
  pub fn validate_subject(&self) -> Option<&str> {
    self.validate_subject.as_deref()
  }

  /// Get the authorization url.
  pub fn authorization_url(&self) -> Option<&UrlOrStatic> {
    self.authorization_url.as_ref()
  }

  /// Get the headers to forward.
  pub fn forward_headers(&self) -> &[String] {
    self.forward_headers.as_slice()
  }

  /// Get whether to forward the endpoint type of the request.
  pub fn forward_endpoint_type(&self) -> bool {
    self.forward_endpoint_type
  }

  /// Get whether to forward the id of the request.
  pub fn forward_id(&self) -> bool {
    self.forward_id
  }

  /// Get whether to pass through the auth header.
  pub fn passthrough_auth(&self) -> bool {
    self.passthrough_auth
  }

  /// Get the extensions to forward.
  pub fn forward_extensions(&self) -> &[ForwardExtensions] {
    self.forward_extensions.as_slice()
  }

  /// Set the user-agent information from the package info.
  pub fn set_from_package_info(&mut self, info: &PackageInfo) -> Result<()> {
    self.inner_client_mut().set_from_package_info(info)
  }
}

/// Builder for `AuthConfig`.
#[derive(Deserialize, Debug, Clone)]
#[serde(deny_unknown_fields, default)]
pub struct AuthConfigBuilder {
  #[serde(flatten, skip_serializing)]
  auth_mode: Option<AuthMode>,
  validate_audience: Option<Vec<String>>,
  validate_issuer: Option<Vec<String>>,
  validate_subject: Option<String>,
  authorization_url: Option<UrlOrStatic>,
  forward_headers: Vec<String>,
  forward_endpoint_type: bool,
  forward_id: bool,
  passthrough_auth: bool,
  forward_extensions: Vec<ForwardExtensions>,
  #[serde(rename = "http", alias = "tls", skip_serializing)]
  http_client: Option<HttpClient>,
  #[cfg(feature = "experimental")]
  suppress_errors: bool,
  #[cfg(feature = "experimental")]
  add_hint: bool,
}

impl AuthConfigBuilder {
  /// Set the HTTP client.
  pub fn http_client(mut self, http_client: HttpClient) -> Self {
    self.http_client = Some(http_client);
    self
  }

  /// Suppress errors and return any allowed regions if available.
  #[cfg(feature = "experimental")]
  pub fn suppress_errors(mut self, suppress_errors: bool) -> Self {
    self.suppress_errors = suppress_errors;
    self
  }

  /// Add a hint that shows the client which regions are allowed in ticket responses.
  #[cfg(feature = "experimental")]
  pub fn add_hint(mut self, add_hint: bool) -> Self {
    self.add_hint = add_hint;
    self
  }

  /// Set the auth mode.
  pub fn auth_mode(mut self, auth_mode: AuthMode) -> Self {
    self.auth_mode = Some(auth_mode);
    self
  }

  /// Set audiences to validate.
  pub fn validate_audience(mut self, validate_audience: Vec<String>) -> Self {
    self.validate_audience = Some(validate_audience);
    self
  }

  /// Set the issuers to validate.
  pub fn validate_issuer(mut self, validate_issuer: Vec<String>) -> Self {
    self.validate_issuer = Some(validate_issuer);
    self
  }

  /// Set the subject to validate.
  pub fn validate_subject(mut self, validate_subject: String) -> Self {
    self.validate_subject = Some(validate_subject);
    self
  }

  /// Set the authorization url.
  pub fn authorization_url(mut self, authorization_url: UrlOrStatic) -> Self {
    self.authorization_url = Some(authorization_url);
    self
  }

  /// Set the headers to forward.
  pub fn forward_headers(mut self, forward_headers: Vec<String>) -> Self {
    self.forward_headers = forward_headers;
    self
  }

  /// Set whether to forward the endpoint type.
  pub fn forward_endpoint_type(mut self, forward_endpoint_type: bool) -> Self {
    self.forward_endpoint_type = forward_endpoint_type;
    self
  }

  /// Set whether to forward the id.
  pub fn forward_id(mut self, forward_id: bool) -> Self {
    self.forward_id = forward_id;
    self
  }

  /// Set whether to pass through auth.
  pub fn passthrough_auth(mut self, passthrough_auth: bool) -> Self {
    self.passthrough_auth = passthrough_auth;
    self
  }

  /// Set the extensions to forward
  pub fn forward_extensions(mut self, forward_extensions: Vec<ForwardExtensions>) -> Self {
    self.forward_extensions = forward_extensions;
    self
  }

  /// Build the auth config.
  pub fn build(self) -> Result<AuthConfig> {
    Ok(AuthConfig {
      auth_mode: self.auth_mode,
      validate_audience: self.validate_audience,
      validate_issuer: self.validate_issuer,
      validate_subject: self.validate_subject,
      authorization_url: self.authorization_url,
      forward_headers: self.forward_headers,
      forward_endpoint_type: self.forward_endpoint_type,
      forward_id: self.forward_id,
      passthrough_auth: self.passthrough_auth,
      forward_extensions: self.forward_extensions,
      http_client: self
        .http_client
        .unwrap_or(HttpClient::from(HttpClientConfig::default())),
      #[cfg(feature = "experimental")]
      suppress_errors: self.suppress_errors,
      #[cfg(feature = "experimental")]
      add_hint: self.add_hint,
    })
  }
}

impl Default for AuthConfigBuilder {
  fn default() -> Self {
    // Satisfy https://rust-lang.github.io/rust-clippy/master/index.html#derivable_impls
    // when `experimental` is not enabled.
    let authorization_url = None;
    Self {
      auth_mode: None,
      validate_audience: None,
      validate_issuer: None,
      validate_subject: None,
      authorization_url,
      forward_headers: vec![],
      forward_endpoint_type: false,
      forward_id: false,
      passthrough_auth: false,
      forward_extensions: vec![],
      http_client: None,
      #[cfg(feature = "experimental")]
      suppress_errors: false,
      #[cfg(feature = "experimental")]
      add_hint: true,
    }
  }
}

impl TryFrom<AuthConfigBuilder> for AuthConfig {
  type Error = Error;

  fn try_from(builder: AuthConfigBuilder) -> Result<Self> {
    builder.build()
  }
}

#[cfg(test)]
mod tests {
  use super::*;
  use crate::config::advanced::auth::response::{
    AuthorizationRestrictionsBuilder, AuthorizationRuleBuilder,
  };
  use crate::config::location::{Location, PrefixOrId, SimpleLocation};
  use crate::http::tests::with_test_certificates;
  use crate::storage::Backend;
  use http::Uri;
  use serde_json::to_string;
  use std::io::Write;
  use tempfile::NamedTempFile;

  #[test]
  fn auth_config_public_key() {
    with_test_certificates(|path, _, _| {
      let key_path = path.join("key.pem");

      let config: AuthConfig = toml::from_str(&format!(
        r#"
        public_key = '{}'
        "#,
        key_path.to_string_lossy()
      ))
      .unwrap();

      assert!(matches!(
        config.auth_mode().unwrap(),
        AuthMode::PublicKey(_)
      ));
    });
  }

  #[test]
  fn auth_config_no_mode() {
    let config = toml::from_str::<AuthConfig>(
      r#"
      validate_audience = ["aud1", "aud2"]
      validate_issuer = ["iss1"]
      validate_subject = sub
      "#,
    );
    assert!(config.is_err());
  }

  #[test]
  fn auth_config_both_modes() {
    let config = toml::from_str::<AuthConfig>(
      r#"
      jwks_url = "https://www.example.com"
      public_key = "public_key"
      validate_audience = ["aud1", "aud2"]
      validate_issuer = ["iss1"]
      validate_subject = sub
      "#,
    );
    assert!(config.is_err());
  }

  #[test]
  fn auth_config_no_authentication() {
    let config: AuthConfig = toml::from_str(
      r#"
      authorization_url = "https://www.example.com"
      "#,
    )
    .unwrap();

    assert_eq!(
      config.authorization_url().unwrap(),
      &UrlOrStatic::Url("https://www.example.com".parse::<Uri>().unwrap())
    );
  }

  #[test]
  fn auth_config_static_auth() {
    let mut temp = NamedTempFile::new().unwrap();
    let restrictions = AuthorizationRestrictionsBuilder::default()
      .rule(
        AuthorizationRuleBuilder::default()
          .location(Location::Simple(Box::new(SimpleLocation::new(
            Backend::default(),
            String::default(),
            Some(PrefixOrId::Id("path".to_string())),
          ))))
          .build()
          .unwrap(),
      )
      .build()
      .unwrap();
    temp
      .write_all(to_string(&restrictions).unwrap().as_bytes())
      .unwrap();

    let config: AuthConfig = toml::from_str(&format!(
      r#"
      authorization_url = 'file://{}'
      "#,
      temp.path().to_string_lossy()
    ))
    .unwrap();

    assert_eq!(
      config.authorization_url().unwrap(),
      &UrlOrStatic::Static(restrictions)
    );
  }

  #[test]
  fn auth_config() {
    let config: AuthConfig = toml::from_str(
      r#"
      jwks_url = "https://www.example.com"
      validate_audience = ["aud1", "aud2"]
      validate_issuer = ["iss1"]
      validate_subject = "sub"
      authorization_url = "https://www.example.com"
      passthrough_auth = true
      forward_headers = ["header"]
      forward_endpoint_type = true
      forward_id = true
      forward_extensions = [ { json_path = '$.extension', name = 'Extension'} ]
      "#,
    )
    .unwrap();

    assert_eq!(
      config.auth_mode().unwrap(),
      &AuthMode::Jwks("https://www.example.com/".parse().unwrap())
    );
    assert_eq!(
      config.validate_audience().unwrap().to_vec(),
      vec!["aud1".to_string(), "aud2".to_string()]
    );
    assert_eq!(
      config.validate_issuer().unwrap().to_vec(),
      vec!["iss1".to_string()]
    );
    assert_eq!(
      config.authorization_url().unwrap(),
      &UrlOrStatic::Url("https://www.example.com".parse::<Uri>().unwrap())
    );
    assert!(config.passthrough_auth());
    assert_eq!(config.forward_headers(), ["header".to_string()]);
    assert!(config.forward_endpoint_type());
    assert!(config.forward_id());
    assert_eq!(
      config.forward_extensions(),
      [ForwardExtensions::new(
        "$.extension".to_string(),
        "Extension".to_string()
      )]
    );
  }

  #[cfg(feature = "experimental")]
  #[test]
  fn auth_config_experimental() {
    let config: AuthConfig = toml::from_str(
      r#"
      jwks_url = "https://www.example.com"
      validate_audience = ["aud1", "aud2"]
      validate_issuer = ["iss1"]
      authorization_url = "https://www.example.com"
      add_hint = false
      suppress_errors = true
      "#,
    )
    .unwrap();

    assert!(!config.add_hint());
    assert!(config.suppress_errors());
  }

  #[test]
  fn test_authorization_restrictions_builder() {
    let rule = AuthConfigBuilder::default()
      .auth_mode(AuthMode::Jwks("https://www.example.com/".parse().unwrap()))
      .authorization_url(UrlOrStatic::Url(
        "https://www.example.com".parse::<Uri>().unwrap(),
      ))
      .build()
      .unwrap();
    assert_eq!(
      rule.authorization_url.as_ref().unwrap(),
      &UrlOrStatic::Url("https://www.example.com".parse::<Uri>().unwrap())
    );
    assert_eq!(
      rule.clone().auth_mode.unwrap(),
      AuthMode::Jwks("https://www.example.com/".parse().unwrap())
    );
    assert_eq!(rule.validate_audience(), None);
    assert_eq!(rule.validate_issuer(), None);
    assert_eq!(rule.validate_subject(), None);
  }
}