| 1 | use std::sync::Arc; |
| 2 | |
| 3 | use codewhale_config::PluginAuthority; |
| 4 | use codewhale_plugins::PluginRegistry; |
| 5 | use codewhale_plugins::activation::{ |
| 6 | PluginActivationCapability, PolicyScope, extension_host_policy_enabled, |
| 7 | }; |
| 8 | use codewhale_plugins::install::dsh::{plan_npm_install, refusal_text}; |
| 9 | use codewhale_plugins::providers::{PluginProviderDeclaration, validate_declarations}; |
| 10 | use codewhale_plugins::recommend::{ |
| 11 | PluginMatchSource, PluginNextStep, PluginTaskRecommendation, lookup_reviewable_plugin, |
| 12 | }; |
| 13 | use codewhale_plugins::registry::verify_plugin_component_authority; |
| 14 | use serde::Deserialize; |
| 15 | use serde_json::{Value, json}; |
| 16 | |
| 17 | use super::dsh_broker::{ |
| 18 | BrokerCall, BrokerEffect, BrokerFuture, BrokerMethods, BrokerRefusal, decode, |
| 19 | }; |
| 20 | use super::protocol::DshService; |
| 21 | use crate::pricing::BalanceInfo; |
| 22 | |
| 23 | #[derive(Deserialize)] |
| 24 | #[serde(tag = "method", content = "input", deny_unknown_fields)] |
| 25 | enum CatalogMethod { |
| 26 | #[serde(rename = "install.plan")] |
| 27 | InstallPlan(InstallRequest), |
| 28 | #[serde(rename = "routes.list")] |
| 29 | RoutesList(NoInput), |
| 30 | #[serde(rename = "routes.resolve")] |
| 31 | RoutesResolve(RouteRequest), |
| 32 | #[serde(rename = "balance")] |
| 33 | Balance(NoInput), |
| 34 | } |
| 35 | |
| 36 | impl BrokerMethods for CatalogMethod { |
| 37 | const NAMES: &'static [&'static str] = |
| 38 | &["install.plan", "routes.list", "routes.resolve", "balance"]; |
| 39 | } |
| 40 | |
| 41 | #[derive(Deserialize)] |
| 42 | #[serde(deny_unknown_fields)] |
| 43 | struct NoInput {} |
| 44 | |
| 45 | #[derive(Deserialize)] |
| 46 | #[serde(deny_unknown_fields)] |
| 47 | struct InstallRequest { |
| 48 | package: String, |
| 49 | version: String, |
| 50 | #[serde(default)] |
| 51 | registry: Option<String>, |
| 52 | } |
| 53 | |
| 54 | #[derive(Deserialize)] |
| 55 | #[serde(deny_unknown_fields)] |
| 56 | struct RouteRequest { |
| 57 | provider: String, |
| 58 | #[serde(default)] |
| 59 | model: Option<String>, |
| 60 | } |
| 61 | |
| 62 | pub(super) struct AccountBalance { |
| 63 | pub available: bool, |
| 64 | pub reading: Option<BalanceInfo>, |
| 65 | } |
| 66 | |
| 67 | type ApprovedRoutes = Vec<(String, PluginProviderDeclaration)>; |
| 68 | |
| 69 | pub(super) fn serve(call: BrokerCall) -> BrokerFuture { |
| 70 | serve_with(call, None) |
| 71 | } |
| 72 | |
| 73 | pub(super) fn serve_with(call: BrokerCall, account: Option<AccountBalance>) -> BrokerFuture { |
| 74 | Box::pin(async move { |
| 75 | let caller = call.owner.plugin_id.clone(); |
| 76 | match decode::<CatalogMethod>(&call)? { |
| 77 | CatalogMethod::InstallPlan(request) => { |
| 78 | let plugins = plugins(&call)?; |
| 79 | call.context |
| 80 | .act("install.plan", BrokerEffect::Read, Some(&request.package)) |
| 81 | .await?; |
| 82 | install_plan(&plugins, &caller, request) |
| 83 | } |
| 84 | CatalogMethod::RoutesList(NoInput {}) => { |
| 85 | let plugins = plugins(&call)?; |
| 86 | call.context |
| 87 | .act("routes.list", BrokerEffect::Read, None) |
| 88 | .await?; |
| 89 | let routes = approved_routes(plugins, &caller).await?; |
| 90 | let routes: Vec<Value> = routes |
| 91 | .iter() |
| 92 | .map(|(name, declaration)| route(name, declaration)) |
| 93 | .collect(); |
| 94 | Ok(json!({ "routes": routes })) |
| 95 | } |
| 96 | CatalogMethod::RoutesResolve(request) => { |
| 97 | let plugins = plugins(&call)?; |
| 98 | call.context |
| 99 | .act( |
| 100 | "routes.resolve", |
| 101 | BrokerEffect::Read, |
| 102 | Some(&request.provider), |
| 103 | ) |
| 104 | .await?; |
| 105 | let routes = approved_routes(plugins, &caller).await?; |
| 106 | resolve_route(&caller, routes, request) |
| 107 | } |
| 108 | CatalogMethod::Balance(NoInput {}) => { |
| 109 | call.context |
| 110 | .act("balance", BrokerEffect::Read, None) |
| 111 | .await?; |
| 112 | Ok(balance(account)) |
| 113 | } |
| 114 | } |
| 115 | }) |
| 116 | } |
| 117 | |
| 118 | fn plugins(call: &BrokerCall) -> Result<Arc<PluginRegistry>, BrokerRefusal> { |
| 119 | call.context |
| 120 | .tool() |
| 121 | .plugin_registry |
| 122 | .clone() |
| 123 | .ok_or(BrokerRefusal::NotAvailable(DshService::Catalog)) |
| 124 | } |
| 125 | |
| 126 | fn refused(message: impl Into<String>) -> BrokerRefusal { |
| 127 | BrokerRefusal::Refused { |
| 128 | service: DshService::Catalog, |
| 129 | message: message.into(), |
| 130 | } |
| 131 | } |
| 132 | |
| 133 | fn review_command(name: &str, next_step: PluginNextStep) -> String { |
| 134 | PluginTaskRecommendation { |
| 135 | name: name.to_string(), |
| 136 | source: PluginMatchSource::Installed { |
| 137 | id: name.to_string(), |
| 138 | }, |
| 139 | matched_terms: Vec::new(), |
| 140 | score: 0, |
| 141 | next_step, |
| 142 | } |
| 143 | .command() |
| 144 | } |
| 145 | |
| 146 | fn install_plan( |
| 147 | plugins: &PluginRegistry, |
| 148 | caller: &str, |
| 149 | request: InstallRequest, |
| 150 | ) -> Result<Value, BrokerRefusal> { |
| 151 | let plan = plan_npm_install( |
| 152 | &request.package, |
| 153 | &request.version, |
| 154 | request.registry.as_deref(), |
| 155 | ) |
| 156 | .map_err(|reason| { |
| 157 | tracing::info!(target: "codewhale::dsh_catalog", plugin = %caller, "install plan refused"); |
| 158 | refused(reason) |
| 159 | })?; |
| 160 | let existing = plugins.get(&plan.plugin_name); |
| 161 | let (status, command, message) = match existing { |
| 162 | Some(existing) => { |
| 163 | let command = lookup_reviewable_plugin(existing.name(), plugins, &[]) |
| 164 | .map(|reviewable| reviewable.command()) |
| 165 | .unwrap_or_else(|| review_command(existing.name(), PluginNextStep::Inspect)); |
| 166 | let message = format!( |
| 167 | "A plugin named `{}` is already present; nothing was installed. Review it with `{command}`. A market listing does not establish that it is the same bundle.", |
| 168 | existing.name() |
| 169 | ); |
| 170 | ("already_present", command, message) |
| 171 | } |
| 172 | None => { |
| 173 | let command = review_command( |
| 174 | &plan.plugin_name, |
| 175 | PluginNextStep::SourceInstall { |
| 176 | spec: plan.spec.clone(), |
| 177 | }, |
| 178 | ); |
| 179 | let message = format!( |
| 180 | "Codewhale installs a plugin only through its reviewed install flow; nothing was installed. Review and install {}@{} with `{command}`.", |
| 181 | request.package, request.version |
| 182 | ); |
| 183 | ("review_required", command, message) |
| 184 | } |
| 185 | }; |
| 186 | tracing::info!( |
| 187 | target: "codewhale::dsh_catalog", |
| 188 | plugin = %caller, |
| 189 | package = %request.package, |
| 190 | version = %request.version, |
| 191 | status, |
| 192 | "install planned for review; nothing installed" |
| 193 | ); |
| 194 | let mut answer = json!({ |
| 195 | "status": status, |
| 196 | "package": request.package, |
| 197 | "version": request.version, |
| 198 | "plugin": plan.plugin_name, |
| 199 | "command": command, |
| 200 | "message": message, |
| 201 | }); |
| 202 | if existing.is_none() { |
| 203 | answer["spec"] = Value::String(plan.spec); |
| 204 | } |
| 205 | Ok(answer) |
| 206 | } |
| 207 | |
| 208 | fn declared_routes( |
| 209 | plugins: &PluginRegistry, |
| 210 | caller: &str, |
| 211 | ) -> Result<Option<(ApprovedRoutes, PluginAuthority)>, String> { |
| 212 | let Some(plugin) = plugins.get(caller).filter(|plugin| plugin.active()) else { |
| 213 | return Ok(None); |
| 214 | }; |
| 215 | if plugin.manifest.providers.is_empty() { |
| 216 | return Ok(None); |
| 217 | } |
| 218 | validate_declarations(&plugin.manifest.providers)?; |
| 219 | let authority = plugins |
| 220 | .authority_for(caller) |
| 221 | .ok_or("the plugin has no review receipt")?; |
| 222 | let routes = plugin |
| 223 | .manifest |
| 224 | .providers |
| 225 | .iter() |
| 226 | .map(|(name, declaration)| (name.clone(), declaration.clone())) |
| 227 | .collect(); |
| 228 | Ok(Some((routes, authority))) |
| 229 | } |
| 230 | |
| 231 | async fn approved_routes( |
| 232 | plugins: Arc<PluginRegistry>, |
| 233 | caller: &str, |
| 234 | ) -> Result<ApprovedRoutes, BrokerRefusal> { |
| 235 | let receipt = |reason: String| { |
| 236 | tracing::info!( |
| 237 | target: "codewhale::dsh_catalog", |
| 238 | plugin = %caller, |
| 239 | reason = %reason, |
| 240 | "provider routes refused: the review receipt does not hold" |
| 241 | ); |
| 242 | refused( |
| 243 | "the review that approved this plugin's provider routes no longer holds; review the plugin again in Codewhale", |
| 244 | ) |
| 245 | }; |
| 246 | let Some((routes, authority)) = declared_routes(&plugins, caller).map_err(receipt)? else { |
| 247 | return Ok(Vec::new()); |
| 248 | }; |
| 249 | let policy = extension_host_policy_enabled(); |
| 250 | #[cfg(any(test, feature = "test-support"))] |
| 251 | let env_scope = crate::test_support::env_scope_ticket(); |
| 252 | let verified = tokio::task::spawn_blocking(move || { |
| 253 | #[cfg(any(test, feature = "test-support"))] |
| 254 | let _env_scope = crate::test_support::join_env_scope(env_scope); |
| 255 | let _policy = PolicyScope::propagate(policy); |
| 256 | verify_plugin_component_authority(&authority, PluginActivationCapability::Providers) |
| 257 | }) |
| 258 | .await; |
| 259 | match verified { |
| 260 | Ok(Ok(())) => Ok(routes), |
| 261 | Ok(Err(reason)) => Err(receipt(reason)), |
| 262 | Err(error) => Err(receipt(error.to_string())), |
| 263 | } |
| 264 | } |
| 265 | |
| 266 | fn resolve_route( |
| 267 | caller: &str, |
| 268 | routes: ApprovedRoutes, |
| 269 | request: RouteRequest, |
| 270 | ) -> Result<Value, BrokerRefusal> { |
| 271 | let Some((name, declaration)) = routes |
| 272 | .into_iter() |
| 273 | .find(|(name, _)| *name == request.provider) |
| 274 | else { |
| 275 | tracing::info!( |
| 276 | target: "codewhale::dsh_catalog", |
| 277 | plugin = %caller, |
| 278 | "provider route refused: not approved for this plugin" |
| 279 | ); |
| 280 | return Err(refused(format!( |
| 281 | "`{}` is not a provider route approved for this plugin. A plugin cannot register a model adapter in Codewhale: a model route is a provider route you approve in the plugin's review", |
| 282 | refusal_text(&request.provider) |
| 283 | ))); |
| 284 | }; |
| 285 | let model = match request.model { |
| 286 | None => declaration.model.clone(), |
| 287 | Some(model) => { |
| 288 | let offered = if declaration.models.is_empty() { |
| 289 | declaration |
| 290 | .model |
| 291 | .as_deref() |
| 292 | .is_none_or(|default| default == model) |
| 293 | } else { |
| 294 | declaration.models.contains(&model) |
| 295 | }; |
| 296 | if !offered { |
| 297 | return Err(refused(format!( |
| 298 | "model `{}` is not on the approved provider route `{name}`", |
| 299 | refusal_text(&model) |
| 300 | ))); |
| 301 | } |
| 302 | Some(model) |
| 303 | } |
| 304 | }; |
| 305 | Ok(json!({ "route": route(&name, &declaration), "model": model })) |
| 306 | } |
| 307 | |
| 308 | fn route(name: &str, declaration: &PluginProviderDeclaration) -> Value { |
| 309 | json!({ |
| 310 | "provider": name, |
| 311 | "base_url": declaration.base_url, |
| 312 | "default_model": declaration.model, |
| 313 | "models": declaration.models, |
| 314 | }) |
| 315 | } |
| 316 | |
| 317 | fn balance(account: Option<AccountBalance>) -> Value { |
| 318 | let Some(account) = account else { |
| 319 | return json!({ "status": "unknown" }); |
| 320 | }; |
| 321 | if !account.available { |
| 322 | return json!({ "status": "absent" }); |
| 323 | } |
| 324 | match account |
| 325 | .reading |
| 326 | .filter(|reading| !reading.total_balance.trim().is_empty()) |
| 327 | { |
| 328 | Some(reading) => json!({ |
| 329 | "status": "known", |
| 330 | "currency": reading.currency, |
| 331 | "total": reading.total_balance, |
| 332 | "topped_up": reading.topped_up_balance, |
| 333 | "granted": reading.granted_balance, |
| 334 | }), |
| 335 | None => json!({ "status": "unknown" }), |
| 336 | } |
| 337 | } |
| 338 |