Skip to main content

systemprompt_models/services/providers/
mod.rs

1//! Provider registry: the single source of upstream connectivity.
2//!
3//! [`ProviderRegistry`] is the `providers:` list of the services tree
4//! (`services/ai/providers.yaml` by convention, merged across includes). It is
5//! implementation configuration shipped with the deployment, not a
6//! per-environment profile section: the same catalog boots every environment
7//! and only the credentials it names differ. Each [`ProviderEntry`] declares
8//! one upstream exactly once — its
9//! [`WireProtocol`], endpoint, credential ([`SecretName`]), extra headers, and
10//! the model catalog it serves. The two policy layers reference entries by
11//! [`ProviderId`] and never re-declare connectivity: the gateway policy
12//! (`services.gateway`) routes external model names to a provider, and the AI
13//! policy (`services/ai/config.yaml`) selects an agent default and per-provider
14//! overrides.
15//!
16//! Validation here is the authority for connectivity: unique provider names,
17//! SSRF-guarded endpoints, and globally-unique model ids/aliases. The gateway
18//! and AI layers validate only their references *into* this registry.
19//!
20//! Copyright (c) systemprompt.io — Business Source License 1.1.
21//! See <https://systemprompt.io> for licensing details.
22
23mod discovery_report;
24mod error;
25mod protocol;
26mod rate_card;
27mod surface;
28
29use std::collections::{HashMap, HashSet};
30
31use serde::{Deserialize, Serialize};
32use systemprompt_identifiers::{ModelId, ProviderId, SecretName};
33
34use crate::services::ai::{ModelCapabilities, ModelGovernance, ModelLimits, ModelPricing};
35
36pub use discovery_report::DiscoveryReport;
37pub use error::{ProviderRegistryError, ProviderRegistryResult};
38pub use protocol::WireProtocol;
39pub use rate_card::{
40    DocumentedLaunchStage, RETIREMENT_NOTICE_DAYS, VertexRateCard, VertexRateCardEntry,
41};
42pub use surface::ApiSurface;
43
44const DEFAULT_CATALOG_YAML: &str = include_str!("default_catalog.yaml");
45
46#[derive(Deserialize)]
47struct DefaultCatalogFile {
48    providers: Vec<ProviderEntry>,
49}
50
51#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
52#[serde(deny_unknown_fields)]
53pub struct ProviderModel {
54    pub id: ModelId,
55
56    #[serde(default, skip_serializing_if = "Vec::is_empty")]
57    pub aliases: Vec<ModelId>,
58
59    #[serde(default, skip_serializing_if = "Option::is_none")]
60    pub upstream_model: Option<String>,
61
62    #[serde(default)]
63    pub pricing: ModelPricing,
64
65    #[serde(default)]
66    pub capabilities: ModelCapabilities,
67
68    #[serde(default)]
69    pub limits: ModelLimits,
70
71    #[serde(default, skip_serializing_if = "Option::is_none")]
72    pub governance: Option<ModelGovernance>,
73}
74
75impl ProviderModel {
76    #[must_use]
77    pub fn matches(&self, requested: &str) -> bool {
78        self.id.as_str() == requested || self.aliases.iter().any(|a| a.as_str() == requested)
79    }
80
81    #[must_use]
82    pub fn effective_upstream_model<'a>(&'a self, requested: &'a str) -> &'a str {
83        self.upstream_model.as_deref().unwrap_or(requested)
84    }
85}
86
87#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
88#[serde(deny_unknown_fields)]
89pub struct ProviderEntry {
90    pub name: ProviderId,
91
92    pub wire: WireProtocol,
93
94    pub surface: ApiSurface,
95
96    pub endpoint: String,
97
98    pub api_key_secret: SecretName,
99
100    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
101    pub extra_headers: HashMap<String, String>,
102
103    #[serde(default, skip_serializing_if = "Vec::is_empty")]
104    pub models: Vec<ProviderModel>,
105
106    #[serde(default)]
107    pub governance: ModelGovernance,
108}
109
110impl ProviderEntry {
111    #[must_use]
112    pub fn find_model(&self, requested: &str) -> Option<&ProviderModel> {
113        self.models.iter().find(|m| m.matches(requested))
114    }
115
116    #[must_use]
117    pub fn upstream_model_for<'a>(
118        &'a self,
119        route_override: Option<&'a str>,
120        requested: &'a str,
121    ) -> &'a str {
122        let name = route_override.unwrap_or(requested);
123        self.find_model(name)
124            .map_or(name, |model| model.effective_upstream_model(name))
125    }
126
127    #[must_use]
128    pub fn effective_governance(&self, requested: &str) -> ModelGovernance {
129        self.find_model(requested)
130            .and_then(|m| m.governance)
131            .unwrap_or(self.governance)
132    }
133}
134
135#[derive(Debug, Clone, Default, Serialize, Deserialize, schemars::JsonSchema)]
136#[serde(transparent)]
137pub struct ProviderRegistry {
138    pub providers: Vec<ProviderEntry>,
139}
140
141impl ProviderRegistry {
142    pub fn default_seed() -> ProviderRegistryResult<Self> {
143        let file: DefaultCatalogFile = serde_yaml::from_str(DEFAULT_CATALOG_YAML)
144            .map_err(|e| ProviderRegistryError::InvalidDefaultCatalog(e.to_string()))?;
145        Ok(Self {
146            providers: file.providers,
147        })
148    }
149
150    #[must_use]
151    pub fn find_provider(&self, name: &str) -> Option<&ProviderEntry> {
152        self.providers.iter().find(|p| p.name.as_str() == name)
153    }
154
155    #[must_use]
156    pub fn contains_model(&self, requested: &str) -> bool {
157        self.providers
158            .iter()
159            .any(|p| p.find_model(requested).is_some())
160    }
161
162    pub fn advertised_providers(&self) -> impl Iterator<Item = &ProviderEntry> {
163        self.providers
164            .iter()
165            .filter(|entry| entry.surface.is_advertised())
166    }
167
168    #[must_use]
169    pub fn advertised_model_ids(&self, surfaces: &[ApiSurface]) -> Vec<String> {
170        self.advertised_providers()
171            .filter(|entry| surfaces.is_empty() || surfaces.contains(&entry.surface))
172            .flat_map(|entry| {
173                entry.models.iter().flat_map(|m| {
174                    std::iter::once(m.id.as_str().to_owned())
175                        .chain(m.aliases.iter().map(|a| a.as_str().to_owned()))
176                })
177            })
178            .collect()
179    }
180
181    pub fn validate(&self) -> ProviderRegistryResult<()> {
182        let trusted = crate::net::trusted_http_hosts_from_env();
183        let mut seen_providers: HashSet<&str> = HashSet::with_capacity(self.providers.len());
184        let mut seen_models: HashSet<&str> = HashSet::new();
185
186        for provider in &self.providers {
187            if !seen_providers.insert(provider.name.as_str()) {
188                return Err(ProviderRegistryError::DuplicateProvider {
189                    name: provider.name.as_str().to_owned(),
190                });
191            }
192            if provider.endpoint.is_empty() {
193                return Err(ProviderRegistryError::EmptyEndpoint {
194                    name: provider.name.as_str().to_owned(),
195                });
196            }
197            crate::net::validate_outbound_url_with_trust(&provider.endpoint, &trusted).map_err(
198                |e| ProviderRegistryError::BlockedEndpoint {
199                    provider: provider.name.as_str().to_owned(),
200                    endpoint: provider.endpoint.clone(),
201                    reason: e.to_string(),
202                },
203            )?;
204            if names_a_project_literally(&provider.endpoint) {
205                return Err(ProviderRegistryError::LiteralProjectInEndpoint {
206                    provider: provider.name.as_str().to_owned(),
207                    endpoint: provider.endpoint.clone(),
208                });
209            }
210
211            for model in &provider.models {
212                if model.id.as_str().is_empty() {
213                    return Err(ProviderRegistryError::EmptyModelId {
214                        id: provider.name.as_str().to_owned(),
215                    });
216                }
217                if !seen_models.insert(model.id.as_str()) {
218                    return Err(ProviderRegistryError::DuplicateModel {
219                        id: model.id.as_str().to_owned(),
220                    });
221                }
222                for alias in &model.aliases {
223                    if !seen_models.insert(alias.as_str()) {
224                        return Err(ProviderRegistryError::DuplicateModel {
225                            id: alias.as_str().to_owned(),
226                        });
227                    }
228                }
229            }
230        }
231        Ok(())
232    }
233}
234
235pub const PROJECT_PLACEHOLDER: &str = "{project}";
236
237// Why: the placeholder names live here, beside the registry that validates
238// endpoints, so that the credential layer that fills them and the validator
239// that polices them can never disagree about their spelling. `{region}` has
240// no filler today — no shipped credential type carries a region — and an
241// endpoint using it is refused until one does, which is the intended shape:
242// a coordinate is served by the credential or not at all.
243pub const REGION_PLACEHOLDER: &str = "{region}";
244
245// Why: a Google Cloud project id is a tenant identifier, and Vertex reports it
246// verbatim in every IAM error it returns, which the gateway relays to the
247// caller. A catalog that names one literally therefore ships that id to every
248// installation of the image and every client that trips a 403. The id lives in
249// exactly one place, the service-account key, and the endpoint says
250// `{project}` instead.
251#[must_use]
252pub fn names_a_project_literally(endpoint: &str) -> bool {
253    let Ok(url) = url::Url::parse(endpoint) else {
254        return false;
255    };
256    let on_vertex = url.host_str().is_some_and(|host| {
257        host.eq_ignore_ascii_case("aiplatform.googleapis.com")
258            || host
259                .to_ascii_lowercase()
260                .ends_with("-aiplatform.googleapis.com")
261    });
262    if !on_vertex {
263        return false;
264    }
265    let mut segments = url.path_segments().into_iter().flatten();
266    while let Some(segment) = segments.next() {
267        if segment == "projects" {
268            return segments
269                .next()
270                .is_some_and(|id| id != "%7Bproject%7D" && id != PROJECT_PLACEHOLDER);
271        }
272    }
273    false
274}