Skip to main content

basaltic/
config.rs

1use crate::{Credentials, Result, error::invalid};
2use reqwest::{Url, header::HeaderMap};
3use std::{collections::BTreeMap, time::Duration};
4
5/// Explicit configuration. Environment variables are read only by `from_env`.
6#[derive(Clone, Debug)]
7pub struct Config {
8    pub credentials: Credentials,
9    pub region: String,
10    pub account_id: String,
11    pub domain: String,
12    pub endpoints: BTreeMap<String, String>,
13    pub token_url: Option<String>,
14    pub timeout: Duration,
15    pub max_attempts: u8,
16    pub base_delay: Duration,
17    pub max_delay: Duration,
18}
19
20impl Default for Config {
21    fn default() -> Self {
22        Self {
23            credentials: Credentials::Missing,
24            region: String::new(),
25            account_id: String::new(),
26            domain: "basaltic.sh".into(),
27            endpoints: BTreeMap::new(),
28            token_url: None,
29            timeout: Duration::from_secs(30),
30            max_attempts: 4,
31            base_delay: Duration::from_millis(200),
32            max_delay: Duration::from_secs(20),
33        }
34    }
35}
36
37impl Config {
38    /// Read BASALTIC_ACCESS_TOKEN or the access-key pair, region, account, domain,
39    /// and `BASALTIC_ENDPOINT_URL_<SERVICE>` from the process environment.
40    pub fn from_env() -> Result<Self> {
41        let env = |key: &str| std::env::var(key).unwrap_or_default();
42        let token = env("BASALTIC_ACCESS_TOKEN");
43        let key = env("BASALTIC_ACCESS_KEY_ID");
44        let secret = env("BASALTIC_SECRET_ACCESS_KEY");
45        let credentials = if !token.is_empty() {
46            Credentials::bearer(token)?
47        } else if !key.is_empty() || !secret.is_empty() {
48            Credentials::access_key(key, secret)?
49        } else {
50            Credentials::Missing
51        };
52        let domain = env("BASALTIC_DOMAIN");
53        let value = Self {
54            credentials,
55            region: env("BASALTIC_REGION"),
56            account_id: env("BASALTIC_ACCOUNT_ID"),
57            domain: if domain.is_empty() {
58                "basaltic.sh".into()
59            } else {
60                domain
61            },
62            endpoints: std::env::vars()
63                .filter_map(|(k, v)| {
64                    k.strip_prefix("BASALTIC_ENDPOINT_URL_")
65                        .filter(|_| !v.is_empty())
66                        .map(|s| (s.to_ascii_lowercase(), v))
67                })
68                .collect(),
69            ..Self::default()
70        };
71        value.validate()?;
72        Ok(value)
73    }
74
75    pub(crate) fn validate(&self) -> Result<()> {
76        if matches!(self.credentials, Credentials::Missing) {
77            return Err(invalid("Provide credentials or explicit anonymous access"));
78        }
79        if self.domain.is_empty()
80            || !self.domain.split('.').all(|s| {
81                !s.is_empty()
82                    && !s.starts_with('-')
83                    && !s.ends_with('-')
84                    && s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')
85            })
86        {
87            return Err(invalid("Invalid API domain"));
88        }
89        validate_limits(self.timeout, self.max_attempts)?;
90        for endpoint in self.endpoints.values() {
91            validate_url(endpoint)?;
92        }
93        if let Some(url) = &self.token_url {
94            validate_url(url)?;
95        }
96        Ok(())
97    }
98
99    pub(crate) fn endpoint(&self, service: &str, template: &str) -> Result<String> {
100        if let Some(url) = self.endpoints.get(service) {
101            return Ok(url.trim_end_matches('/').to_string());
102        }
103        if template.contains("{region}")
104            && (self.region.is_empty()
105                || !self.region.split('-').all(|p| {
106                    !p.is_empty()
107                        && p.bytes()
108                            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
109                }))
110        {
111            return Err(invalid("A valid region is required for this service"));
112        }
113        let url = template
114            .replace("basaltic.sh", &self.domain)
115            .replace("{region}", &self.region);
116        validate_url(&url)?;
117        Ok(url.trim_end_matches('/').to_string())
118    }
119}
120
121#[derive(Clone, Debug, Default)]
122pub struct RequestOptions {
123    pub account_id: Option<String>,
124    pub idempotency_key: Option<String>,
125    pub headers: HeaderMap,
126    pub timeout: Option<Duration>,
127    pub max_attempts: Option<u8>,
128}
129
130pub(crate) fn validate_limits(timeout: Duration, attempts: u8) -> Result<()> {
131    if timeout.is_zero() || !(1..=10).contains(&attempts) {
132        return Err(invalid(
133            "Timeout must be positive and max_attempts must be between 1 and 10",
134        ));
135    }
136    Ok(())
137}
138
139pub(crate) fn validate_url(value: &str) -> Result<Url> {
140    let url = Url::parse(value).map_err(|_| invalid("Endpoint must be an absolute HTTP(S) URL"))?;
141    if !matches!(url.scheme(), "http" | "https")
142        || url.host_str().is_none()
143        || !url.username().is_empty()
144        || url.password().is_some()
145        || url.query().is_some()
146        || url.fragment().is_some()
147        || url.port() == Some(0)
148        || value.chars().any(char::is_whitespace)
149        || value.chars().any(char::is_control)
150    {
151        return Err(invalid(
152            "Endpoint must not contain credentials, a query, fragment or whitespace",
153        ));
154    }
155    Ok(url)
156}