Skip to main content

token_manager/
provider.rs

1use anyhow::{Result, bail, ensure};
2use reqwest::Url;
3use rust_decimal::Decimal;
4use serde::{Deserialize, Serialize};
5use serde_json::Value;
6use sha2::{Digest, Sha256};
7use std::{collections::BTreeMap, fs, path::Path, str::FromStr};
8
9include!(concat!(env!("OUT_DIR"), "/providers.rs"));
10
11#[derive(Clone, Deserialize, Serialize)]
12#[serde(deny_unknown_fields)]
13pub struct Provider {
14    pub id: String,
15    pub name: String,
16    pub base_url: String,
17    #[serde(default)]
18    pub path: String,
19    #[serde(default, skip_serializing_if = "RequestMethod::is_get")]
20    pub method: RequestMethod,
21    pub unsupported_reason: Option<String>,
22    #[serde(default)]
23    pub auth: Auth,
24    pub key_url: String,
25    pub billing_url: String,
26    pub credential_help: String,
27    pub source: String,
28    #[serde(default)]
29    pub experimental: bool,
30    #[serde(default, skip_serializing_if = "Option::is_none")]
31    pub pricing: Option<crate::prices::PricingMap>,
32    #[serde(default, skip_serializing_if = "Option::is_none")]
33    pub costs: Option<crate::costs::CostMap>,
34    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
35    pub headers: BTreeMap<String, String>,
36    pub balance: Option<BalanceMap>,
37    #[serde(default, skip_serializing_if = "Vec::is_empty")]
38    pub response_checks: Vec<ResponseCheck>,
39    #[serde(default)]
40    pub quotas: Vec<QuotaMap>,
41}
42#[derive(Clone, Copy, Default, Deserialize, Serialize, PartialEq, Eq)]
43#[serde(rename_all = "UPPERCASE")]
44pub enum RequestMethod {
45    #[default]
46    Get,
47    Post,
48}
49impl RequestMethod {
50    pub fn is_get(&self) -> bool {
51        *self == Self::Get
52    }
53}
54impl From<RequestMethod> for reqwest::Method {
55    fn from(method: RequestMethod) -> Self {
56        match method {
57            RequestMethod::Get => Self::GET,
58            RequestMethod::Post => Self::POST,
59        }
60    }
61}
62#[derive(Clone, Copy, Default, Deserialize, Serialize, PartialEq, Eq)]
63#[serde(rename_all = "snake_case")]
64pub enum ResetFormat {
65    #[default]
66    Text,
67    UnixSeconds,
68    UnixMilliseconds,
69}
70impl ResetFormat {
71    pub fn is_text(&self) -> bool {
72        *self == Self::Text
73    }
74}
75
76#[derive(Clone, Deserialize, Serialize)]
77#[serde(default, deny_unknown_fields)]
78pub struct Auth {
79    pub header: String,
80    pub prefix: String,
81}
82impl Default for Auth {
83    fn default() -> Self {
84        Self {
85            header: "Authorization".into(),
86            prefix: "Bearer ".into(),
87        }
88    }
89}
90
91#[derive(Clone, Deserialize, Serialize)]
92#[serde(deny_unknown_fields)]
93pub struct ResponseCheck {
94    pub path: String,
95    pub equals: Value,
96}
97
98#[derive(Clone, Deserialize, Serialize)]
99#[serde(deny_unknown_fields)]
100pub struct BalanceMap {
101    pub rows: String,
102    pub currency: Option<String>,
103    pub currency_path: Option<String>,
104    pub remaining: Option<String>,
105    pub total: Option<String>,
106    pub used: Option<String>,
107}
108#[derive(Clone, Deserialize, Serialize)]
109#[serde(deny_unknown_fields)]
110pub struct QuotaMap {
111    pub label: String,
112    pub percent: Option<String>,
113    #[serde(skip_serializing_if = "Option::is_none")]
114    pub used: Option<String>,
115    #[serde(skip_serializing_if = "Option::is_none")]
116    pub limit: Option<String>,
117    #[serde(skip_serializing_if = "Option::is_none")]
118    pub unit: Option<String>,
119    pub reset_at: Option<String>,
120    #[serde(default, skip_serializing_if = "ResetFormat::is_text")]
121    pub reset_format: ResetFormat,
122    #[serde(skip_serializing_if = "Option::is_none")]
123    pub unavailable_when: Option<String>,
124}
125#[derive(Clone, Deserialize, Serialize, Debug, PartialEq)]
126pub struct Balance {
127    pub currency: String,
128    pub remaining: String,
129    pub used: Option<String>,
130}
131#[derive(Clone, Deserialize, Serialize, Debug, PartialEq)]
132pub struct Quota {
133    pub label: String,
134    pub used: Option<String>,
135    pub limit: Option<String>,
136    pub unit: Option<String>,
137    pub used_percent: Option<String>,
138    pub reset_at: Option<String>,
139}
140#[derive(Clone, Default, Deserialize, Serialize, Debug, PartialEq)]
141pub struct AccountData {
142    #[serde(default, skip_serializing_if = "Vec::is_empty")]
143    pub costs: Vec<crate::costs::Cost>,
144    pub balances: Vec<Balance>,
145    pub quotas: Vec<Quota>,
146}
147pub fn identifier(value: &str) -> bool {
148    !value.is_empty()
149        && value.len() <= 64
150        && value
151            .bytes()
152            .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
153}
154fn pointer(value: &str) -> bool {
155    value.is_empty() || value.starts_with('/')
156}
157fn money(value: &Value, path: &str) -> Result<Decimal> {
158    let item = value
159        .pointer(path)
160        .ok_or_else(|| anyhow::anyhow!("required response field missing"))?;
161    let text = match item {
162        Value::String(s) => s.clone(),
163        Value::Number(n) => n.to_string(),
164        _ => bail!("expected a decimal response field"),
165    };
166    Decimal::from_str(&text).map_err(|_| anyhow::anyhow!("invalid decimal response field"))
167}
168impl Provider {
169    pub fn fingerprint(&self) -> String {
170        // Public catalog changes do not invalidate account credentials or caches.
171        let mut account_definition = self.clone();
172        account_definition.pricing = None;
173        format!(
174            "{:x}",
175            Sha256::digest(serde_json::to_vec(&account_definition).expect("serializable provider"))
176        )
177    }
178    pub fn endpoint(&self, allow_local_http: bool) -> Result<Url> {
179        let base = Url::parse(&self.base_url)?;
180        ensure!(
181            base.username().is_empty()
182                && base.password().is_none()
183                && base.query().is_none()
184                && base.fragment().is_none(),
185            "provider URL must not contain credentials, query or fragment"
186        );
187        let local = matches!(base.host_str(), Some("127.0.0.1" | "[::1]"));
188        ensure!(
189            base.scheme() == "https" || (allow_local_http && local && base.scheme() == "http"),
190            "providers require HTTPS; local fixture HTTP needs --allow-local-http"
191        );
192        ensure!(
193            self.path.starts_with('/') && !self.path.starts_with("//"),
194            "provider path must be an absolute same-origin path"
195        );
196        let endpoint = base.join(&self.path)?;
197        ensure!(
198            endpoint.origin() == base.origin() && endpoint.fragment().is_none(),
199            "provider request must stay on its origin"
200        );
201        Ok(endpoint)
202    }
203    pub fn validate(&self, allow_local_http: bool) -> Result<()> {
204        ensure!(identifier(&self.id), "invalid provider ID");
205        if let Some(map) = &self.pricing {
206            map.validate(self, allow_local_http)?;
207        }
208        for (name, value) in &self.headers {
209            ensure!(
210                (name.ends_with("-version") || name.ends_with("-beta"))
211                    && reqwest::header::HeaderName::from_bytes(name.as_bytes()).is_ok()
212                    && !name.eq_ignore_ascii_case(&self.auth.header),
213                "only public API version headers are supported"
214            );
215            ensure!(
216                value.len() <= 128 && reqwest::header::HeaderValue::from_str(value).is_ok(),
217                "invalid API version header"
218            );
219        }
220        if let Some(map) = &self.costs {
221            map.validate()?;
222            ensure!(
223                self.method.is_get() && self.balance.is_none() && self.quotas.is_empty(),
224                "cost mappings require a separate GET account adapter"
225            );
226        }
227        ensure!(
228            reqwest::header::HeaderName::from_bytes(self.auth.header.as_bytes()).is_ok(),
229            "invalid authentication header name"
230        );
231        ensure!(
232            self.auth.prefix.len() <= 64
233                && self
234                    .auth
235                    .prefix
236                    .bytes()
237                    .all(|b| b.is_ascii() && !b.is_ascii_control()),
238            "invalid authentication header prefix"
239        );
240        ensure!(
241            !self.name.is_empty()
242                && self.name.len() <= 80
243                && !self.name.chars().any(char::is_control),
244            "invalid provider name"
245        );
246        if self.unsupported_reason.is_none() {
247            self.endpoint(allow_local_http)?;
248        } else {
249            ensure!(
250                self.path.is_empty()
251                    && self.costs.is_none()
252                    && self.balance.is_none()
253                    && self.quotas.is_empty()
254                    && self.method.is_get(),
255                "unsupported providers must not declare request mappings"
256            );
257        }
258        for link in [&self.key_url, &self.billing_url] {
259            let url = Url::parse(link)?;
260            ensure!(
261                url.scheme() == "https" && url.username().is_empty() && url.password().is_none(),
262                "console links must be HTTPS without credentials"
263            );
264        }
265        ensure!(
266            self.unsupported_reason.is_some()
267                || self.costs.is_some()
268                || self.balance.is_some()
269                || !self.quotas.is_empty(),
270            "provider has no account-data mapping"
271        );
272        ensure!(self.response_checks.len() <= 8, "too many response checks");
273        for check in &self.response_checks {
274            ensure!(
275                pointer(&check.path)
276                    && matches!(
277                        check.equals,
278                        Value::String(_) | Value::Number(_) | Value::Bool(_)
279                    ),
280                "response checks require a pointer and scalar expected value"
281            );
282        }
283        ensure!(self.quotas.len() <= 16, "too many quota mappings");
284        if let Some(map) = &self.balance {
285            ensure!(pointer(&map.rows), "invalid rows JSON pointer");
286            ensure!(
287                map.currency.is_some() ^ map.currency_path.is_some(),
288                "choose currency or currency_path"
289            );
290            ensure!(
291                map.remaining.is_some() || (map.total.is_some() && map.used.is_some()),
292                "balance needs remaining or total and used"
293            );
294            for field in [&map.currency_path, &map.remaining, &map.total, &map.used]
295                .into_iter()
296                .flatten()
297            {
298                ensure!(pointer(field), "invalid balance JSON pointer");
299            }
300        }
301        for quota in &self.quotas {
302            ensure!(
303                !quota.label.is_empty()
304                    && quota.label.len() <= 40
305                    && !quota.label.chars().any(char::is_control),
306                "invalid quota label"
307            );
308            ensure!(
309                quota.used.is_some() == quota.limit.is_some(),
310                "quota used/limit must be paired"
311            );
312            ensure!(
313                quota.percent.is_some() || quota.used.is_some(),
314                "quota requires percent or used/limit"
315            );
316            ensure!(
317                quota.unit.as_ref().is_none_or(|unit| !unit.is_empty()
318                    && unit.len() <= 24
319                    && unit.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_')),
320                "invalid quota unit"
321            );
322            ensure!(
323                quota.used.is_none() || quota.unit.is_some(),
324                "absolute quotas require an explicit unit"
325            );
326            for path in [
327                &quota.percent,
328                &quota.used,
329                &quota.limit,
330                &quota.reset_at,
331                &quota.unavailable_when,
332            ]
333            .into_iter()
334            .flatten()
335            {
336                ensure!(pointer(path), "invalid quota JSON pointer");
337            }
338        }
339        Ok(())
340    }
341    pub fn extract(&self, value: &Value) -> Result<AccountData> {
342        for check in &self.response_checks {
343            ensure!(
344                value.pointer(&check.path) == Some(&check.equals),
345                "provider response check failed"
346            );
347        }
348        let mut result = AccountData::default();
349        if let Some(map) = &self.balance {
350            let rows = value
351                .pointer(&map.rows)
352                .ok_or_else(|| anyhow::anyhow!("balance data missing"))?;
353            let rows: Vec<&Value> = match rows {
354                Value::Object(_) => vec![rows],
355                Value::Array(rows) => rows.iter().collect(),
356                _ => bail!("balance rows must be object or array"),
357            };
358            ensure!(
359                !rows.is_empty() && rows.len() <= 32,
360                "missing or excessive balance rows"
361            );
362            for row in rows {
363                let currency = match &map.currency {
364                    Some(c) => c.clone(),
365                    None => row
366                        .pointer(map.currency_path.as_ref().unwrap())
367                        .and_then(Value::as_str)
368                        .ok_or_else(|| anyhow::anyhow!("currency missing"))?
369                        .to_owned(),
370                };
371                ensure!(
372                    !currency.is_empty()
373                        && currency.len() <= 8
374                        && currency.bytes().all(|b| b.is_ascii_uppercase()),
375                    "invalid currency"
376                );
377                let remaining = match &map.remaining {
378                    Some(p) => money(row, p)?,
379                    None => money(row, map.total.as_ref().unwrap())?
380                        .checked_sub(money(row, map.used.as_ref().unwrap())?)
381                        .ok_or_else(|| anyhow::anyhow!("balance arithmetic overflow"))?,
382                };
383                let used = map
384                    .used
385                    .as_ref()
386                    .map(|p| money(row, p).map(|n| n.normalize().to_string()))
387                    .transpose()?;
388                result.balances.push(Balance {
389                    currency,
390                    remaining: remaining.normalize().to_string(),
391                    used,
392                });
393            }
394        }
395        for quota in &self.quotas {
396            // Missing counters stay unknown. Zero limits never mean unlimited.
397            let optional_number = |path: &Option<String>| -> Result<Option<Decimal>> {
398                match path {
399                    Some(path) if value.pointer(path).is_some_and(|v| !v.is_null()) => {
400                        let number = money(value, path)?;
401                        ensure!(number >= Decimal::ZERO, "negative quota counter");
402                        Ok(Some(number))
403                    }
404                    _ => Ok(None),
405                }
406            };
407            let unavailable = match quota
408                .unavailable_when
409                .as_ref()
410                .and_then(|path| value.pointer(path))
411            {
412                None | Some(Value::Null) => false,
413                Some(Value::Bool(value)) => *value,
414                _ => bail!("quota unavailable flag must be boolean"),
415            };
416            let used = if unavailable {
417                None
418            } else {
419                optional_number(&quota.used)?
420            };
421            let limit = optional_number(&quota.limit)?;
422            let percent = if unavailable {
423                None
424            } else if quota.percent.is_some() {
425                optional_number(&quota.percent)?
426            } else if let (Some(used), Some(limit)) = (used, limit) {
427                if limit.is_zero() {
428                    None
429                } else {
430                    Some(
431                        used.checked_div(limit)
432                            .and_then(|v| v.checked_mul(Decimal::from(100)))
433                            .ok_or_else(|| anyhow::anyhow!("quota arithmetic overflow"))?,
434                    )
435                }
436            } else {
437                None
438            };
439            let used_percent = percent.map(|p| p.normalize().to_string());
440            let raw_reset = quota.reset_at.as_ref().and_then(|path| value.pointer(path));
441            let reset_at = if unavailable {
442                None
443            } else {
444                match raw_reset {
445                    None | Some(Value::Null) => None,
446                    Some(value) => Some(match quota.reset_format {
447                        ResetFormat::Text => value
448                            .as_str()
449                            .ok_or_else(|| anyhow::anyhow!("reset must be text"))?
450                            .to_owned(),
451                        format => {
452                            let timestamp = value
453                                .as_i64()
454                                .or_else(|| value.as_str().and_then(|v| v.parse().ok()))
455                                .ok_or_else(|| {
456                                    anyhow::anyhow!("reset must be integer epoch time")
457                                })?;
458                            ensure!(timestamp >= 0, "reset epoch time must be nonnegative");
459                            let date = if format == ResetFormat::UnixMilliseconds {
460                                chrono::DateTime::from_timestamp_millis(timestamp)
461                            } else {
462                                chrono::DateTime::from_timestamp(timestamp, 0)
463                            }
464                            .ok_or_else(|| anyhow::anyhow!("reset epoch time out of range"))?;
465                            date.to_rfc3339_opts(chrono::SecondsFormat::Millis, true)
466                        }
467                    }),
468                }
469            };
470            ensure!(
471                reset_at
472                    .as_ref()
473                    .is_none_or(|s| s.len() <= 64 && !s.chars().any(char::is_control)),
474                "invalid quota reset field"
475            );
476            result.quotas.push(Quota {
477                label: quota.label.clone(),
478                used: used.map(|n| n.normalize().to_string()),
479                limit: limit.map(|n| n.normalize().to_string()),
480                unit: quota.unit.clone(),
481                used_percent,
482                reset_at,
483            });
484        }
485        ensure!(
486            !result.balances.is_empty()
487                || result
488                    .quotas
489                    .iter()
490                    .any(|q| q.used_percent.is_some() || q.used.is_some() || q.limit.is_some()),
491            "no supported account data in response"
492        );
493        Ok(result)
494    }
495}
496pub fn providers(directory: &Path, allow_local_http: bool) -> Result<BTreeMap<String, Provider>> {
497    let mut result = BTreeMap::new();
498    for text in BUILTIN_PROVIDERS {
499        let provider: Provider = toml::from_str(text)?;
500        provider.validate(false)?;
501        ensure!(
502            result.insert(provider.id.clone(), provider).is_none(),
503            "duplicate built-in provider ID"
504        );
505    }
506    let mut custom_ids = std::collections::HashSet::new();
507    if directory.exists() {
508        for entry in fs::read_dir(directory)? {
509            let path = entry?.path();
510            if path.extension().is_none_or(|s| s != "toml") {
511                continue;
512            }
513            ensure!(
514                !path.is_symlink() && path.metadata()?.len() <= 65536,
515                "provider file must be a bounded regular file"
516            );
517            let provider: Provider = toml::from_str(&fs::read_to_string(path)?)
518                .map_err(|_| anyhow::anyhow!("invalid custom provider TOML"))?;
519            provider.validate(allow_local_http)?;
520            ensure!(
521                custom_ids.insert(provider.id.clone()),
522                "duplicate custom provider ID"
523            );
524            result.insert(provider.id.clone(), provider);
525        }
526    }
527    Ok(result)
528}