返回 CodeWhale
providers.rs
根目录 / crates / plugins / src / providers.rs
1 //! Provider adapter for the existing reviewed plugin manifest and route catalog.
2 //!
3 //! Declarations are data, never executable callbacks. Only OpenAI-compatible
4 //! inference and public OAuth PKCE clients are supported. Plugin changes require
5 //! a restart to add/remove routes; receipt checks revoke existing routes immediately.
6 use std::collections::{BTreeMap, BTreeSet};
7 use std::net::{Ipv4Addr, TcpListener};
8 use std::sync::{Arc, OnceLock};
9
10 use anyhow::{Context, Result};
11 use serde::{Deserialize, Serialize};
12
13 use super::{
14 PluginRegistry, activation::PluginActivationCapability,
15 registry::verify_plugin_component_authority,
16 };
17 use codewhale_config::ProviderKind;
18 use codewhale_runtime::config::{Config, ProviderConfig};
19
20 pub fn load_config(path: Option<std::path::PathBuf>, profile: Option<&str>) -> Result<Config> {
21 Config::load_with(
22 path,
23 profile,
24 codewhale_runtime::config::ConfigEnvironmentPolicy::Runtime,
25 &mut apply_startup_providers,
26 )
27 }
28
29 pub fn load_config_structural(
30 path: Option<std::path::PathBuf>,
31 profile: Option<&str>,
32 ) -> Result<Config> {
33 Config::load_with(
34 path,
35 profile,
36 codewhale_runtime::config::ConfigEnvironmentPolicy::StructuralDiagnostic,
37 &mut apply_startup_providers,
38 )
39 }
40
41 static STARTUP_REGISTRY: OnceLock<Arc<PluginRegistry>> = OnceLock::new();
42
43 #[cfg(any(test, feature = "test-support"))]
44 thread_local! {
45 pub static TEST_REGISTRY: std::cell::RefCell<Option<Arc<PluginRegistry>>> = const { std::cell::RefCell::new(None) };
46 }
47
48 /// Restore the calling test's previous registry even if its operation panics.
49 #[cfg(any(test, feature = "test-support"))]
50 pub fn with_test_registry<T>(registry: Arc<PluginRegistry>, operation: impl FnOnce() -> T) -> T {
51 struct Restore(Option<Arc<PluginRegistry>>);
52 impl Drop for Restore {
53 fn drop(&mut self) {
54 TEST_REGISTRY.with(|slot| {
55 let _ = slot.replace(self.0.take());
56 });
57 }
58 }
59 let _restore = Restore(TEST_REGISTRY.with(|slot| slot.replace(Some(registry))));
60 operation()
61 }
62
63 #[derive(Debug, Clone, Deserialize, Serialize)]
64 #[serde(deny_unknown_fields)]
65 pub struct PluginProviderDeclaration {
66 pub base_url: String,
67 #[serde(default, skip_serializing_if = "Option::is_none")]
68 pub model: Option<String>,
69 #[serde(default, skip_serializing_if = "Vec::is_empty")]
70 pub models: Vec<String>,
71 pub oauth: codewhale_runtime::oauth::PluginOAuthConfig,
72 /// Public routing/application metadata only. Authentication stays host-owned.
73 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
74 pub http_headers: BTreeMap<String, String>,
75 }
76
77 impl PluginProviderDeclaration {
78 pub(super) fn endpoints(&self) -> [&str; 4] {
79 [
80 &self.base_url,
81 &self.oauth.issuer,
82 &self.oauth.authorization_endpoint,
83 &self.oauth.token_endpoint,
84 ]
85 }
86 }
87
88 pub fn validate_declarations(
89 declarations: &BTreeMap<String, PluginProviderDeclaration>,
90 ) -> Result<(), String> {
91 if declarations.len() > 32 {
92 return Err("plugin declares more than 32 providers".into());
93 }
94 for (name, declaration) in declarations {
95 if !super::agent_plugin::is_standard_plugin_name(name)
96 || ProviderKind::parse(name).is_some()
97 {
98 return Err("plugin provider name must be a custom lowercase provider identity".into());
99 }
100 let endpoint = reqwest::Url::parse(&declaration.base_url)
101 .map_err(|_| "plugin provider base_url is invalid")?;
102 let loopback = matches!(
103 endpoint.host_str(),
104 Some("127.0.0.1" | "localhost" | "[::1]")
105 );
106 if !(endpoint.scheme() == "https" || (endpoint.scheme() == "http" && loopback))
107 || endpoint.host_str().is_none()
108 || !endpoint.username().is_empty()
109 || endpoint.password().is_some()
110 || endpoint.query().is_some()
111 || endpoint.fragment().is_some()
112 {
113 return Err(
114 "plugin provider base_url must be HTTPS (or HTTP loopback) without credentials, query or fragment"
115 .into(),
116 );
117 }
118 if declaration.http_headers.len() > 32 {
119 return Err("plugin provider declares more than 32 HTTP headers".into());
120 }
121 let mut header_names = BTreeSet::new();
122 for (name, value) in &declaration.http_headers {
123 let header = reqwest::header::HeaderName::from_bytes(name.as_bytes())
124 .map_err(|_| "plugin provider HTTP header name is invalid")?;
125 if !header_names.insert(header.as_str().to_owned())
126 || codewhale_config::is_upstream_auth_header(header.as_str())
127 || matches!(
128 header.as_str(),
129 "cookie"
130 | "set-cookie"
131 | "proxy-authorization"
132 | "host"
133 | "content-length"
134 | "transfer-encoding"
135 | "connection"
136 | "proxy-connection"
137 | "te"
138 | "trailer"
139 | "upgrade"
140 )
141 {
142 return Err("plugin provider HTTP headers must be unique public metadata, never authentication or transport controls".into());
143 }
144 if value.len() > 4096 || reqwest::header::HeaderValue::from_str(value).is_err() {
145 return Err(
146 "plugin provider HTTP header value is invalid or exceeds 4096 bytes".into(),
147 );
148 }
149 }
150 declaration
151 .oauth
152 .validate()
153 .map_err(|error| format!("plugin provider OAuth declaration is invalid: {error}"))?;
154 if declaration.models.len() > 256 {
155 return Err("plugin provider declares more than 256 models".into());
156 }
157 let mut seen = BTreeSet::new();
158 for model in &declaration.models {
159 if model.is_empty()
160 || model.len() > 256
161 || model.chars().any(char::is_control)
162 || !seen.insert(model)
163 {
164 return Err(
165 "plugin provider model identities must be bounded, unique nonempty strings"
166 .into(),
167 );
168 }
169 }
170 if let Some(model) = &declaration.model
171 && (model.is_empty()
172 || model.len() > 256
173 || model.chars().any(char::is_control)
174 || (!declaration.models.is_empty() && !seen.contains(model)))
175 {
176 return Err("plugin provider default model must be a declared model identity".into());
177 }
178 }
179 Ok(())
180 }
181
182 /// Called with the registry captured before workspace dotenv loading.
183 pub fn install_startup_registry(registry: Arc<PluginRegistry>) {
184 let _ = STARTUP_REGISTRY.set(registry);
185 }
186
187 pub fn apply_startup_providers(config: &mut Config) -> anyhow::Result<()> {
188 #[cfg(any(test, feature = "test-support"))]
189 if let Some(registry) = TEST_REGISTRY.with(|slot| slot.borrow().clone()) {
190 return apply_providers(config, &registry);
191 }
192 if let Some(registry) = STARTUP_REGISTRY.get() {
193 apply_providers(config, registry)?;
194 }
195 Ok(())
196 }
197
198 /// Core-owned standard public-client PKCE login. Blocking sockets and secure
199 /// storage stay on the dedicated worker; plugins never receive token material.
200 pub async fn plugin_oauth_login(
201 provider: String,
202 base_url: String,
203 descriptor: codewhale_runtime::oauth::PluginOAuthConfig,
204 authority: codewhale_config::PluginAuthority,
205 ) -> Result<()> {
206 let policy = crate::activation::extension_host_policy_enabled();
207 tokio::task::spawn_blocking(move || {
208 let _scope = crate::activation::PolicyScope::propagate(policy);
209 crate::providers::verify_provider_binding(
210 &authority,
211 &provider,
212 &base_url,
213 &descriptor,
214 None,
215 )
216 .map_err(anyhow::Error::msg)?;
217 let slot = codewhale_runtime::oauth::plugin_oauth_slot(&provider, &base_url, &descriptor)?;
218 let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0))?;
219 listener.set_nonblocking(true)?;
220 let redirect_uri = format!(
221 "http://127.0.0.1:{}{}",
222 listener.local_addr()?.port(),
223 descriptor.callback_path
224 );
225 let pkce = codewhale_runtime::oauth::generate_pkce();
226 let state = codewhale_runtime::oauth::generate_state();
227 let authorize_url = descriptor.authorize_url(&redirect_uri, &state, &pkce)?;
228 eprintln!("{provider} sign-in (PKCE)\n Open: {authorize_url}");
229 if std::env::var_os("CODEWHALE_PLUGIN_OAUTH_NO_BROWSER").is_none() {
230 let _ = webbrowser::open(&authorize_url);
231 }
232 let (code, _) = codewhale_runtime::oauth::wait_for_callback_validated(
233 &[listener],
234 &descriptor.callback_params(),
235 &state,
236 Some(&descriptor.issuer),
237 )?;
238 crate::providers::verify_provider_binding(
239 &authority,
240 &provider,
241 &base_url,
242 &descriptor,
243 None,
244 )
245 .map_err(anyhow::Error::msg)?;
246 let mut form = vec![
247 ("grant_type", "authorization_code"),
248 ("client_id", descriptor.client_id.as_str()),
249 ("redirect_uri", redirect_uri.as_str()),
250 ("code", code.as_str()),
251 ("code_verifier", pkce.verifier.as_str()),
252 ];
253 if let Some(resource) = &descriptor.resource {
254 form.push(("resource", resource));
255 }
256 let token = codewhale_runtime::oauth::plugin_token_response(&descriptor, &form, None)?;
257 crate::providers::verify_provider_binding(
258 &authority,
259 &provider,
260 &base_url,
261 &descriptor,
262 None,
263 )
264 .map_err(anyhow::Error::msg)?;
265 codewhale_secrets::Secrets::auto_detect().set(&slot, &serde_json::to_string(&token)?)?;
266 Ok(())
267 })
268 .await
269 .context("Plugin OAuth login worker failed")?
270 }
271
272 pub fn plugin_auth_entry(config: &Config, provider: &str) -> anyhow::Result<ProviderConfig> {
273 let mut entry = config
274 .providers
275 .as_ref()
276 .and_then(|providers| providers.custom_provider_config(provider))
277 .ok_or_else(|| anyhow::anyhow!("No enabled plugin contributes provider `{provider}`"))?
278 .clone();
279 entry.plugin_authority.as_ref().ok_or_else(|| {
280 anyhow::anyhow!("Provider `{provider}` is not contributed by a reviewed plugin")
281 })?;
282 if entry.base_url.is_none() || entry.oauth.is_none() {
283 return Err(anyhow::anyhow!("Plugin provider has no OAuth route"));
284 }
285 // Login, logout, readiness and inference must address the same normalized
286 // route, even when a declaration includes a trailing slash.
287 let identity = config
288 .resolve_provider_pin_identity(provider)
289 .map_err(anyhow::Error::msg)?;
290 anyhow::ensure!(
291 identity.provider == ProviderKind::Custom,
292 "plugin provider must have an admitted custom identity"
293 );
294 entry.base_url = Some(config.base_url_for_route(&identity));
295 Ok(entry)
296 }
297
298 /// Bind an effective route to the exact reviewed declaration, not merely to
299 /// a still-valid receipt. Call this on a blocking worker at the use boundary.
300 /// `None` skips public-header comparison for login/logout; inference must pass
301 /// `Some` with its effective configured headers, including an empty map.
302 pub fn verify_provider_binding(
303 authority: &codewhale_config::PluginAuthority,
304 name: &str,
305 base_url: &str,
306 oauth: &codewhale_runtime::oauth::PluginOAuthConfig,
307 http_headers: Option<&std::collections::HashMap<String, String>>,
308 ) -> anyhow::Result<()> {
309 verify_plugin_component_authority(authority, PluginActivationCapability::Providers)
310 .map_err(anyhow::Error::msg)?;
311 let staged = super::manifest::PluginManifest::validate_from_path(&authority.staged_manifest)
312 .map_err(anyhow::Error::msg)?;
313 anyhow::ensure!(
314 staged.content_hash == authority.content_hash
315 && staged.capability_hash == authority.capability_hash,
316 "plugin provider runtime snapshot changed while checking its route"
317 );
318 let declaration = staged.manifest.providers.get(name).ok_or_else(|| {
319 anyhow::anyhow!("reviewed plugin does not declare this provider identity")
320 })?;
321 anyhow::ensure!(
322 codewhale_runtime::config::normalize_base_url(base_url)
323 == codewhale_runtime::config::normalize_base_url(&declaration.base_url),
324 "plugin provider endpoint differs from its reviewed declaration"
325 );
326 anyhow::ensure!(
327 &declaration.oauth == oauth,
328 "plugin provider OAuth differs from its reviewed declaration"
329 );
330 if let Some(headers) = http_headers {
331 anyhow::ensure!(
332 headers.len() == declaration.http_headers.len()
333 && declaration
334 .http_headers
335 .iter()
336 .all(|(key, value)| headers.get(key) == Some(value)),
337 "plugin provider public headers differ from its reviewed declaration"
338 );
339 }
340 Ok(())
341 }
342
343 // This exhaustive pattern deliberately has no `..`: adding a provider field
344 // must revisit this boundary instead of silently allowing a new route override.
345 fn model_preference(entry: &ProviderConfig) -> Option<&str> {
346 match entry {
347 ProviderConfig {
348 vendor: None,
349 api_key: None,
350 base_url: None,
351 model: Some(model),
352 context_window: None,
353 model_context_windows: None,
354 mode: None,
355 wire: None,
356 auth_mode: None,
357 oauth: None,
358 oauth_credential_generation: None,
359 insecure_skip_tls_verify: None,
360 allow_insecure_http: None,
361 http_headers: None,
362 path_suffix: None,
363 reasoning_stream_style: None,
364 max_concurrency: None,
365 auth: None,
366 external_credentials: None,
367 kind: None,
368 plugin_authority: None,
369 api_key_env: None,
370 responses_profile: None,
371 } if !model.trim().is_empty() && !model.chars().any(char::is_control) => Some(model),
372 _ => None,
373 }
374 }
375
376 pub fn is_account_catalog_scope(provider: &str, fingerprint: &str) -> bool {
377 STARTUP_REGISTRY.get().is_some_and(|registry| {
378 registry.active_plugins().into_iter().any(|plugin| {
379 plugin.manifest.providers.iter().any(|(name, declaration)| {
380 provider == format!("custom:{name}")
381 && fingerprint
382 == codewhale_config::catalog::base_url_fingerprint(&declaration.base_url)
383 })
384 })
385 })
386 }
387
388 pub fn apply_providers(config: &mut Config, registry: &PluginRegistry) -> anyhow::Result<()> {
389 // Validate every collision and authority before mutating configuration.
390 let mut additions = BTreeMap::new();
391 for plugin in registry.active_plugins() {
392 if plugin.manifest.providers.is_empty() {
393 continue;
394 }
395 validate_declarations(&plugin.manifest.providers).map_err(anyhow::Error::msg)?;
396 let authority = registry
397 .authority_for(plugin.id.as_str())
398 .ok_or_else(|| anyhow::anyhow!("active provider plugin has no review receipt"))?;
399 verify_plugin_component_authority(&authority, PluginActivationCapability::Providers)
400 .map_err(anyhow::Error::msg)?;
401 for (name, declaration) in &plugin.manifest.providers {
402 if additions.contains_key(name) {
403 anyhow::bail!("plugin provider `{name}` collides with another plugin provider");
404 }
405 let mut declaration = declaration.clone();
406 if let Some(existing) = config
407 .providers
408 .as_ref()
409 .and_then(|providers| providers.custom.get(name))
410 {
411 declaration.model = Some(
412 model_preference(existing)
413 .ok_or_else(|| {
414 anyhow::anyhow!(
415 "plugin provider `{name}` collides with a configured provider route"
416 )
417 })?
418 .to_owned(),
419 );
420 }
421 additions.insert(name.clone(), (declaration, authority.clone()));
422 }
423 }
424 for (name, (declaration, authority)) in additions {
425 config
426 .providers
427 .get_or_insert_with(Default::default)
428 .custom
429 .insert(
430 name.clone(),
431 ProviderConfig {
432 base_url: Some(declaration.base_url.clone()),
433 model: declaration.model,
434 kind: Some("openai-compatible".into()),
435 auth_mode: Some("oauth".into()),
436 oauth: Some(declaration.oauth),
437 http_headers: (!declaration.http_headers.is_empty())
438 .then(|| declaration.http_headers.into_iter().collect()),
439 plugin_authority: Some(authority),
440 ..Default::default()
441 },
442 );
443 for id in declaration.models {
444 let model = serde_json::from_value(
445 serde_json::json!({"provider": name, "base_url": declaration.base_url, "id": id}),
446 )?;
447 config
448 .custom_models
449 .get_or_insert_with(Default::default)
450 .push(model);
451 }
452 }
453 Ok(())
454 }
455
456 #[cfg(test)]
457 mod tests {
458 use super::*;
459
460 fn declaration() -> PluginProviderDeclaration {
461 serde_json::from_value(serde_json::json!({
462 "base_url": "https://gateway.example/api",
463 "model": "tiny-model", "models": ["tiny-model"],
464 "oauth": {"issuer":"https://gateway.example", "authorization_endpoint":"https://gateway.example/authorize", "token_endpoint":"https://gateway.example/token", "client_id":"custom-cli", "scopes":["models:invoke"]}
465 })).unwrap()
466 }
467
468 #[test]
469 fn provider_declarations_reject_builtin_names_and_credential_routes() {
470 let mut declarations = BTreeMap::from([("openai".into(), declaration())]);
471 assert!(validate_declarations(&declarations).is_err());
472 let mut entry = declarations.remove("openai").unwrap();
473 entry.base_url = "https://secret@gateway.example/api".into();
474 declarations.insert("gateway".into(), entry);
475 assert!(validate_declarations(&declarations).is_err());
476 declarations.get_mut("gateway").unwrap().base_url = "https://gateway.example/api".into();
477 validate_declarations(&declarations).unwrap();
478 declarations.get_mut("gateway").unwrap().model = Some("undeclared".into());
479 assert!(validate_declarations(&declarations).is_err());
480 }
481
482 #[test]
483 fn provider_headers_allow_routing_metadata_but_never_credentials_or_transport_controls() {
484 let mut declaration = declaration();
485 declaration
486 .http_headers
487 .insert("X-Route-Group".into(), "public-group".into());
488 let mut declarations = BTreeMap::from([("gateway".into(), declaration)]);
489 validate_declarations(&declarations).unwrap();
490 for name in [
491 "Authorization",
492 "X-Api-Key",
493 "Cookie",
494 "Set-Cookie",
495 "Proxy-Authorization",
496 "Host",
497 "Content-Length",
498 "Transfer-Encoding",
499 "Connection",
500 ] {
501 let headers = &mut declarations.get_mut("gateway").unwrap().http_headers;
502 headers.insert(name.into(), "blocked".into());
503 assert!(
504 validate_declarations(&declarations).is_err(),
505 "accepted protected header {name}"
506 );
507 declarations
508 .get_mut("gateway")
509 .unwrap()
510 .http_headers
511 .remove(name);
512 }
513 declarations
514 .get_mut("gateway")
515 .unwrap()
516 .http_headers
517 .insert("x-route-group".into(), "duplicate".into());
518 assert!(validate_declarations(&declarations).is_err());
519 let headers = &mut declarations.get_mut("gateway").unwrap().http_headers;
520 headers.remove("x-route-group");
521 headers.insert("X-Test".into(), "injected\r\nAuthorization: secret".into());
522 assert!(validate_declarations(&declarations).is_err());
523 }
524 }
525
525 lines RUST