dsh_api 0.9.0

DSH resource management API client
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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
//! # DSH API client factory
//!
//! This module provides factories for creating [`DshApiClient`] instances,
//! based on the platform and the tenant's name.
//! These parameters can either be provided via environment variables
//! or via explicit function arguments.
//!
//! There are two factory types, `DshApiClientFactory` and `DshApiPlatformClientFactory`.
//!
//! ### [`DshApiClientFactory`]
//! * Single platform and single tenant.
//! * Authentication and authorization using robot password or single-sign-on pattern.
//! * Token fetcher supports long-lived applications.
//! * Each created client has its own rest-client which might result in prblems when a large
//!   number of requests are made simultaneously..
//!
//! ### [`DshApiPlatformClientFactory`]
//! * Single platform and one or more tenants.
//! * Authentication and authorization using single-sign-on pattern.
//! * Static token can expire so applicable for short-lived applications only.
//! * Created clients share one rest-client, which improves performance when a large number of
//!   requests are made simultaneously.
//!
//! Once you have created a client factory you can use its methods to get a [`DshApiClient`]
//! instance. The clients generated by either type of factory are functionally the same.
//!
//! ## Example
//!
//! In this example explicit tenant parameters are used to create a `DshApiClientFactory` and a
//! `DshApiClient`.
//!
//! ```ignore
//! # use dsh_api::dsh_api_client_factory::DshApiClientFactory;
//! # use dsh_api::dsh_api_tenant::DshApiTenant;
//! # use dsh_api::platform::DshPlatform;
//! # use dsh_api::DshApiError;
//! # async fn hide() -> DshApiResult<()> {
//! let tenant = DshApiTenant::new("my-tenant", DshPlatform::new("nplz"));
//! let password = "...";
//! let client_factory = DshApiClientFactory::create_with_token_factory(tenant, password)?;
//! let client = client_factory.client().await?;
//! ...
//! # Ok(())
//! # }
//! ```
use crate::dsh_api_client::DshApiClient;
use crate::dsh_api_tenant::DshApiTenant;
use crate::error::DshApiResult;
use crate::platform::DshPlatform;
use crate::token_fetcher::TokenFetcher;
use crate::DshApiError;
use log::{debug, error};
use reqwest::Client;
use std::env;
use std::io::ErrorKind;

/// # DSH API client factory
///
/// This module provides factories for creating [`DshApiClient`] instances for one tenant on one
/// platform. The tenant and platform names can either be provided via environment variables
/// or via explicit function parameters.
///
/// There are three ways to acquire a `DshApiClientFactory`:
/// * [`DshApiClientFactory::default`] - Create a factory configured from the environment
///   variables listed below.
/// * [`DshApiClientFactory::create_from_static_token`] - Create a factory from the provided
///   `tenant` (also contains the platform) and single-sign-on `static_token` parameters.
/// * [`DshApiClientFactory::create_with_token_fetcher`] - Create a factory from the provided
///   `tenant` (also contains the platform) and `robot_password` parameters.
///
/// Once you have the `DshApiClientFactory` you can call its
/// [`client()`](DshApiClientFactory::client)
/// method to get a [`DshApiClient`]. Note that each call to this method will create a new client
/// instance.
///
/// ## Example
///
/// In this example explicit tenant parameters are used to create a `DshApiClientFactory`.
///
/// ```ignore
/// # use dsh_api::dsh_api_client_factory::DshApiClientFactory;
/// # use dsh_api::dsh_api_tenant::DshApiTenant;
/// # use dsh_api::platform::DshPlatform;
/// # use dsh_api::DshApiResult;
/// # async fn hide() -> DshApiResult<()> {
/// let tenant = DshApiTenant::new("my-tenant", DshPlatform::try_from("np-aws-lz-dsh")?);
/// let robot_password = "...";
/// let client_factory = DshApiClientFactory::create_with_token_factory(tenant, robot_password)?;
/// let client = client_factory.client().await?;
/// ...
/// # Ok(())
/// # }
#[derive(Debug)]
pub struct DshApiClientFactory {
  client: Option<Client>,
  tenant: DshApiTenant,
  static_token: Option<String>,
  robot_password: Option<String>,
}

impl DshApiClientFactory {
  /// # Create default factory for DSH API client
  ///
  /// This function will create a new `DshApiClientFactory` from the default environment variables.
  ///
  /// # Examples
  /// ```no_run
  /// use dsh_api::dsh_api_client_factory::DshApiClientFactory;
  ///
  /// # async fn hide() {
  /// let client_factory = DshApiClientFactory::new();
  /// if let Ok(client) = client_factory.client().await {
  ///   println!("tenant is {}", client.tenant());
  /// }
  /// # }
  /// ```
  ///
  /// # Panics
  ///
  /// This function will panic if it cannot create a new `DshApiClientFactory` from the default
  /// environment variables. If you want to capture such a failure, use:
  /// * [try_default()](Self::try_default),
  /// * [create_from_static_token()](Self::create_from_static_token) or
  /// * [create_with_token_fetcher()](Self::create_with_token_fetcher).
  ///
  /// # Environment variables
  ///
  /// The following environment variables will be checked:
  ///
  /// * `DSH_API_PLATFORM` - Platform on which the tenant's environment lives.
  /// * `DSH_API_TENANT` - Tenant name for the client tenant that is making the API requests.
  /// * `DSH_API_PASSWORD_[platform]_[tenant]` - Secret API robot password for the client tenant.
  ///   The placeholders `[platform]` and `[tenant]` need to be substituted with the platform name
  ///   and the tenant name in all capitals, with hyphens (`-`) replaced by underscores (`_`).
  ///   E.g. if the platform is `np-aws-lz-dsh` and the tenant name is `my-tenant`, the
  ///   environment variable must be `DSH_API_PASSWORD_NP_AWS_LZ_DSH_MY_TENANT`.
  pub fn new() -> DshApiClientFactory {
    DshApiClientFactory::default()
  }

  /// # Create factory for DSH API client with token fetcher
  ///
  /// This function will create a new `DshApiClientFactory` from the provided parameters. This
  /// factory will contain a token fetcher, which means that a new token will be fetched whenever
  /// necessary. This method should be used to create a factory that can be used in a long-lived
  /// program (in principle indefinite).
  ///
  /// # Parameters
  /// * `tenant` - Tenant struct, containing the platform and tenant name.
  /// * `robot_password` - The secret robot password used to retrieve the DSH API tokens
  ///   by the token fetcher.
  ///
  /// # Returns
  /// * [DshApiClientFactory] - Created client factory.
  ///
  /// ## Example
  ///
  /// In this example explicit tenant parameters are used to create a `DshApiClientFactory` based
  /// on a token fetcher.
  ///
  /// # Examples
  /// ```no_run
  /// use dsh_api::dsh_api_client_factory::DshApiClientFactory;
  /// use dsh_api::dsh_api_tenant::DshApiTenant;
  ///
  /// # use dsh_api::error::DshApiResult;
  /// # async fn hide() -> DshApiResult<()> {
  /// let tenant = DshApiTenant::from_tenant("my-tenant")?;
  /// let robot_password = "...";
  /// let client_factory =
  ///   DshApiClientFactory::create_with_token_fetcher(tenant, robot_password);
  /// let client = client_factory.client().await?;
  /// println!("tenant is {}", client.tenant());
  /// # Ok(())
  /// # }
  /// ```
  pub fn create_with_token_fetcher<T>(tenant: DshApiTenant, robot_password: T) -> Self
  where
    T: Into<String>,
  {
    debug!("create dsh api client factory with token fetcher for '{}'", tenant);
    DshApiClientFactory { client: None, tenant, static_token: None, robot_password: Some(robot_password.into()) }
  }

  /// # Create factory for DSH API client with static token
  ///
  /// This function will create a new `DshApiClientFactory` from the provided parameters. This
  /// factory will contain a static token, which means that it will likely expire after
  /// some time, typically 30 minutes. This method should be used to create a factory that can be
  /// only be used in a short-lived program.
  ///
  /// # Parameters
  /// * `tenant` - Tenant struct, containing the platform and tenant name.
  /// * `static_token` - The static token used to access the API.
  ///
  /// # Returns
  /// * [DshApiClientFactory] - Created client factory.
  ///
  /// # Examples
  /// ```no_run
  /// use dsh_api::dsh_api_client_factory::DshApiClientFactory;
  /// use dsh_api::dsh_api_tenant::DshApiTenant;
  ///
  /// # use dsh_api::error::DshApiResult;
  /// # async fn hide() -> DshApiResult<()> {
  /// let tenant = DshApiTenant::from_tenant("my-tenant")?;
  /// let static_token = "...";
  /// let client_factory = DshApiClientFactory::create_from_static_token(tenant, static_token);
  /// let client = client_factory.client().await?;
  /// println!("tenant is {}", client.tenant());
  /// # Ok(())
  /// # }
  /// ```
  pub fn create_from_static_token<T>(tenant: DshApiTenant, static_token: T) -> Self
  where
    T: Into<String>,
  {
    debug!("create dsh api client factory with static token for '{}'", tenant);
    DshApiClientFactory { client: None, tenant, static_token: Some(static_token.into()), robot_password: None }
  }

  /// # Create factory for DSH API client
  ///
  /// Deprecated, use [create_with_token_fetcher()](Self::create_with_token_fetcher).
  #[deprecated]
  pub fn create(tenant: DshApiTenant, password: String) -> DshApiResult<Self> {
    Ok(Self::create_with_token_fetcher(tenant, password))
  }

  /// # Create default factory for DSH API client with token fetcher
  ///
  /// This function will create a new `DshApiClientFactory` with token fetcher from the
  /// default platform and tenant. This method works the same as the [DshApiClientFactory::new]
  /// method, but will return `Err` instead of panicking when something is wrong.
  ///
  /// # Returns
  /// * `Ok<DshApiClientFactory>` - Created client factory.
  /// * `Err<DshApiError>` - When the client factory could not be created.
  ///
  /// # Examples
  /// ```no_run
  /// use dsh_api::dsh_api_client_factory::DshApiClientFactory;
  ///
  /// # use dsh_api::error::DshApiResult;
  /// # async fn hide() -> DshApiResult<()> {
  /// let client_factory = DshApiClientFactory::try_default_with_token_fetcher()?;
  /// let client = client_factory.client().await?;
  /// println!("tenant is {}", client.tenant());
  /// # Ok(())
  /// # }
  /// ```
  pub fn try_default_with_token_fetcher() -> DshApiResult<Self> {
    let tenant = DshApiTenant::try_default()?;
    match get_robot_password(&tenant)? {
      Some(robot_password) => {
        debug!("default dsh api client factory with token fetcher");
        Ok(DshApiClientFactory::create_with_token_fetcher(tenant, robot_password))
      }
      None => Err(DshApiError::configuration("missing default configuration for token fetcher")),
    }
  }

  /// # Create default factory for DSH API client with static token
  ///
  /// This function will create a new `DshApiClientFactory` with token fetcher from the default
  /// platform and tenant.
  ///
  /// # Returns
  /// * `Ok<DshApiClientFactory>` - Created client factory.
  /// * `Err<DshApiError>` - When the client factory could not be created.
  ///
  /// # Examples
  /// ```no_run
  /// use dsh_api::dsh_api_client_factory::DshApiClientFactory;
  ///
  /// # use dsh_api::error::DshApiResult;
  /// # async fn hide() -> DshApiResult<()> {
  /// let client_factory = DshApiClientFactory::try_default_from_static_token()?;
  /// let client = client_factory.client().await?;
  /// println!("tenant is {}", client.tenant());
  /// # Ok(())
  /// # }
  /// ```
  pub fn try_default_from_static_token() -> DshApiResult<Self> {
    let tenant = DshApiTenant::try_default()?;
    match get_static_token(&tenant)? {
      Some(static_token) => {
        debug!("default dsh api client factory with static token");
        Ok(DshApiClientFactory::create_from_static_token(tenant, static_token))
      }
      None => Err(DshApiError::configuration("missing default configuration for static token")),
    }
  }

  /// # Create default factory for DSH API client
  ///
  /// This function will create a new `DshApiClientFactory` with either a token fetcher or a
  /// static token from the default platform and tenant.
  /// This function will fail if both a robot password and a static token are configured.
  ///
  /// # Returns
  /// * `Ok<DshApiClientFactory>` - Created client factory.
  /// * `Err<DshApiError>` - When the client factory could not be created.
  ///
  /// # Examples
  /// ```no_run
  /// use dsh_api::dsh_api_client_factory::DshApiClientFactory;
  ///
  /// # use dsh_api::error::DshApiResult;
  /// # async fn hide() -> DshApiResult<()> {
  /// let client_factory = DshApiClientFactory::try_default()?;
  /// let client = client_factory.client().await?;
  /// println!("tenant is {}", client.tenant());
  /// # Ok(())
  /// # }
  /// ```
  pub fn try_default() -> DshApiResult<Self> {
    let tenant = DshApiTenant::try_default()?;
    match get_robot_password(&tenant)? {
      Some(robot_password) => {
        debug!("default dsh api client factory with token fetcher");
        Ok(DshApiClientFactory::create_with_token_fetcher(tenant, robot_password))
      }
      None => match get_static_token(&tenant)? {
        Some(static_token) => {
          debug!("default dsh api client factory with static token");
          Ok(DshApiClientFactory::create_from_static_token(tenant, static_token))
        }
        None => Err(DshApiError::configuration("missing robot password or static token configuration")),
      },
    }
  }

  /// # Returns the factories platform
  pub fn platform(&self) -> &DshPlatform {
    self.tenant.platform()
  }

  /// # Returns the factories tenant
  pub fn tenant(&self) -> &DshApiTenant {
    &self.tenant
  }

  /// # Returns the name of the factories tenant
  pub fn tenant_name(&self) -> &str {
    self.tenant.name()
  }

  /// # Create an DSH API client
  ///
  /// This function will create a new `DshApiClient`.
  ///
  /// # Returns
  /// * `Ok<DshApiClient>` - Created client.
  /// * `Err<DshApiError>` - Error message when the client could not be created.
  ///
  /// # Examples
  /// ```no_run
  /// use dsh_api::dsh_api_client_factory::DshApiClientFactory;
  ///
  /// # use dsh_api::error::DshApiResult;
  /// # async fn hide() -> DshApiResult<()> {
  /// let client_factory = DshApiClientFactory::new();
  /// match client_factory.client().await {
  ///   Ok(client) => println!("tenant is {}", client.tenant()),
  ///   Err(error) => println!("could not create client ({})", error),
  /// }
  /// # Ok(())
  /// # }
  /// ```
  pub async fn client(self) -> DshApiResult<DshApiClient> {
    if let Some(robot_password) = self.robot_password {
      let token_fetcher = TokenFetcher::new(self.tenant.clone(), robot_password, None, None);
      Ok(DshApiClient::with_token_fetcher(token_fetcher, self.client, self.tenant.clone()))
    } else if let Some(static_token) = self.static_token {
      debug!("dsh api client created with static token");
      Ok(DshApiClient::with_static_token(static_token, self.client, self.tenant.clone()))
    } else {
      unreachable!()
    }
  }
}

impl Default for DshApiClientFactory {
  /// # Create default factory for DSH API client
  ///
  /// For the explanation, see the [`new()`](DshApiClientFactory::new) function,
  /// which delegates to the default implementation.
  ///
  /// # Panics
  /// This function will panic if it cannot create a new `DshApiClientFactory` from the default
  /// environment variables. If you want to capture such a failure, use the
  /// [`try_default()`](DshApiClientFactory::try_default) function.
  fn default() -> Self {
    match Self::try_default() {
      Ok(factory) => factory,
      Err(error) => panic!("{}", error),
    }
  }
}

/// # Platform factory for DSH API client
///
/// This module provides a factory for creating [`DshApiClient`] instances,
/// based on a platform and a single-sign-on static token for that platform.
///
/// The `DshApiClient`s for the different tenant name all share the same API client which uses a
/// pool to connect to the resource management API. This gives much better performance than
/// creating a separate client for each tenant and avoids network and dns problems.
///
/// This factory should be used with the single-sign-on authentication and authorization pattern.
/// For creating clients that authenticate and authorize with a robot password the
/// [`DshApiClientFactory`] should be used.
///
/// Create a factory by providing the `platform` and `static_token` parameters to the
/// [`create_from_static_token`](DshApiPlatformClientFactory::create_from_static_token) function.
///
/// Once you have the `DshApiPlatformClientFactory` you can call its
/// [`client()`](DshApiPlatformClientFactory::client) method with a tenant name as parameter
/// to get a [`DshApiClient`].
///
/// ## Example
///
/// In this example explicit platform and static token parameters are used to create a
/// `DshApiPlatformClientFactory`.
///
/// ```ignore
/// # use dsh_api::DshApiError;
/// # async fn hide() -> DshApiResult<()> {
/// use dsh_api::platform::DshPlatform;
/// use dsh_api::dsh_api_platform_client_factory::DshApiPlatformClientFactory;
/// let platform = DshPlatform::try_from("np-aws-lz-dsh")?;
/// let static_token = "...";
/// let client_factory =
///   DshApiPlatformClientFactory::create_from_static_token(platform, static_token)?;
/// let client = client_factory.client("my-tenant").await?;
/// ...
/// # Ok(())
/// # }
/// ```
#[derive(Debug)]
pub struct DshApiPlatformClientFactory {
  client: Client,
  platform: DshPlatform,
  static_token: String,
}

impl DshApiPlatformClientFactory {
  /// # Create platform factory for DSH API client with static token
  ///
  /// This function will create a new `DshApiPlatformClientFactory` from the provided parameters.
  ///
  /// # Parameters
  /// * `platform` - Platform for which the factory will be created.
  /// * `static_token` - The static token used to access the API for the platform.
  ///
  /// # Examples
  /// ```no_run
  /// # use dsh_api::error::DshApiResult;
  /// use dsh_api::platform::DshPlatform;
  /// use dsh_api::dsh_api_client_factory::DshApiPlatformClientFactory;
  ///
  /// # async fn hide() -> DshApiResult<()> {
  /// let platform = DshPlatform::new("nplz");
  /// let static_token = "...";
  /// let client_factory =
  ///   DshApiPlatformClientFactory::create_from_static_token(platform, static_token)?;
  /// let client = client_factory.client("my-tenant").await?;
  /// println!("tenant is {}", client.tenant());
  /// # Ok(())
  /// # }
  /// ```
  pub fn create_from_static_token<T>(platform: DshPlatform, static_token: T) -> DshApiResult<Self>
  where
    T: Into<String>,
  {
    debug!("create dsh api platform client factory with static token for '{}'", platform);
    #[cfg(not(target_arch = "wasm32"))]
    let client = {
      let dur = std::time::Duration::from_secs(15);
      reqwest::ClientBuilder::new().connect_timeout(dur).timeout(dur).build()?
    };
    #[cfg(target_arch = "wasm32")]
    let client = reqwest::ClientBuilder::new().build()?;
    Ok(DshApiPlatformClientFactory { client, platform, static_token: static_token.into() })
  }

  /// # Returns the factories platform
  pub fn platform(&self) -> &DshPlatform {
    &self.platform
  }

  /// # Create an DSH API client
  ///
  /// This function will create a new `DshApiClient` for the platform and the provided tenant name.
  ///
  /// # Parameters
  /// * `tenant_name` - Name of the tenant for which the client will be created.
  ///
  /// # Returns
  /// * `Ok<DshApiClient>` - Created client.
  /// * `Err<DshApiError>` - Error message when the client could not be created.
  ///
  /// # Examples
  /// ```no_run
  /// use dsh_api::dsh_api_client_factory::DshApiPlatformClientFactory;
  ///
  /// # use dsh_api::error::DshApiResult;
  /// # use dsh_api::platform::DshPlatform;
  /// # async fn hide() -> DshApiResult<()> {
  /// let platform = DshPlatform::try_from("np-aws-lz-dsh")?;
  /// let static_token = "...";
  /// let client_factory = DshApiPlatformClientFactory::create_from_static_token(platform, static_token)?;
  /// match client_factory.client("my-tenant").await {
  ///   Ok(client) => println!("tenant is {}", client.tenant()),
  ///   Err(error) => println!("could not create client ({})", error),
  /// }
  /// # Ok(())
  /// # }
  /// ```
  pub async fn client<T>(&self, tenant_name: T) -> DshApiResult<DshApiClient>
  where
    T: Into<String>,
  {
    let tenant = DshApiTenant::new(tenant_name.into(), self.platform.clone());
    Ok(DshApiClient::with_static_token(self.static_token.clone(), Some(self.client.clone()), tenant))
  }
}

const ENV_VAR_STATIC_TOKEN_PREFIX: &str = "DSH_API_STATIC_TOKEN";
const ENV_VAR_STATIC_TOKEN_FILE_PREFIX: &str = "DSH_API_STATIC_TOKEN_FILE";

fn get_static_token(tenant: &DshApiTenant) -> DshApiResult<Option<String>> {
  get_password(tenant, ENV_VAR_STATIC_TOKEN_PREFIX, ENV_VAR_STATIC_TOKEN_FILE_PREFIX)
}

const ENV_VAR_PASSWORD_PREFIX: &str = "DSH_API_PASSWORD";
const ENV_VAR_PASSWORD_FILE_PREFIX: &str = "DSH_API_PASSWORD_FILE";

pub(crate) fn get_robot_password(tenant: &DshApiTenant) -> DshApiResult<Option<String>> {
  get_password(tenant, ENV_VAR_PASSWORD_PREFIX, ENV_VAR_PASSWORD_FILE_PREFIX)
}

fn get_password(tenant: &DshApiTenant, password_env_var_prefix: &str, password_file_env_var_prefix: &str) -> DshApiResult<Option<String>> {
  let password_file_env_var = environment_variable(password_file_env_var_prefix, tenant.platform(), tenant.name());
  match env::var(&password_file_env_var) {
    Ok(password_file_from_env_var) => match std::fs::read_to_string(&password_file_from_env_var) {
      Ok(password_from_file) => {
        let trimmed_password = password_from_file.trim();
        if trimmed_password.is_empty() {
          let message = format!(
            "password file '{}' is empty (environment variable '{}')",
            password_file_from_env_var, password_file_env_var
          );
          error!("{}", message);
          Err(DshApiError::configuration(message))
        } else {
          debug!(
            "password read from file '{}' (environment variable '{}')",
            password_file_from_env_var, password_file_env_var
          );
          Ok(Some(trimmed_password.to_string()))
        }
      }
      Err(io_error) => match io_error.kind() {
        ErrorKind::NotFound => {
          let message = format!(
            "password file '{}' not found (environment variable '{}')",
            password_file_from_env_var, password_file_env_var
          );
          error!("{}", message);
          Err(DshApiError::NotFound { message: Some(message) })
        }
        _ => {
          let message = format!(
            "password file '{}' could not be read (environment variable '{}')",
            password_file_from_env_var, password_file_env_var
          );
          error!("{}", message);
          Err(DshApiError::Unexpected { message, cause: Some(io_error.to_string()) })
        }
      },
    },
    Err(_) => {
      let password_env_var = environment_variable(password_env_var_prefix, tenant.platform(), tenant.name());
      match env::var(&password_env_var) {
        Ok(password_from_env_var) => {
          debug!("password read (environment variable '{}')", password_env_var);
          Ok(Some(password_from_env_var))
        }
        Err(_) => {
          debug!("environment variable '{}' not set", password_env_var);
          Ok(None)
        }
      }
    }
  }
}

fn environment_variable(env_var_prefix: &str, platform: &DshPlatform, tenant_name: &str) -> String {
  format!(
    "{}_{}_{}",
    env_var_prefix,
    platform.name().to_ascii_uppercase().replace('-', "_"),
    tenant_name.to_ascii_uppercase().replace('-', "_")
  )
}