| 1 | use std::time::Duration; |
| 2 | |
| 3 | use base64::Engine as _; |
| 4 | use base64::engine::general_purpose::STANDARD as BASE64_STANDARD; |
| 5 | use codewhale_config::PluginAuthority; |
| 6 | |
| 7 | use super::protocol::{ |
| 8 | CoreRequest, PluginRouteDispatchParams, PluginRouteDispatchResult, PluginRouteHeaderWire, |
| 9 | }; |
| 10 | use super::supervisor::HostCallError; |
| 11 | |
| 12 | pub const MAX_PLUGIN_ROUTE_REQUEST_BYTES: usize = 4 * 1024 * 1024; |
| 13 | pub const MAX_PLUGIN_ROUTE_RESPONSE_BYTES: usize = 8 * 1024 * 1024; |
| 14 | pub const PLUGIN_ROUTE_DISPATCH_DEADLINE: Duration = Duration::from_secs(15); |
| 15 | |
| 16 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 17 | pub struct PluginRouteRequest { |
| 18 | pub method: String, |
| 19 | pub path: String, |
| 20 | pub query: Option<String>, |
| 21 | pub headers: Vec<(String, String)>, |
| 22 | pub body: Vec<u8>, |
| 23 | } |
| 24 | |
| 25 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 26 | pub struct PluginRouteResponse { |
| 27 | pub status: u16, |
| 28 | pub headers: Vec<(String, String)>, |
| 29 | pub body: Vec<u8>, |
| 30 | } |
| 31 | |
| 32 | #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] |
| 33 | pub enum PluginRouteError { |
| 34 | #[error("plugin host is unavailable: {0}")] |
| 35 | HostUnavailable(String), |
| 36 | #[error("plugin did not register a handler for this route")] |
| 37 | NotFound, |
| 38 | #[error("plugin route request body exceeds 4 MiB limit")] |
| 39 | RequestTooLarge, |
| 40 | #[error("plugin route response body exceeds 8 MiB limit")] |
| 41 | ResponseTooLarge, |
| 42 | #[error("plugin route timed out")] |
| 43 | Timeout, |
| 44 | #[error("plugin route execution failed: {0}")] |
| 45 | ExecutionFailed(String), |
| 46 | } |
| 47 | |
| 48 | pub async fn dispatch_plugin_route( |
| 49 | authority: &PluginAuthority, |
| 50 | request: PluginRouteRequest, |
| 51 | ) -> Result<PluginRouteResponse, PluginRouteError> { |
| 52 | if request.body.len() > MAX_PLUGIN_ROUTE_REQUEST_BYTES { |
| 53 | return Err(PluginRouteError::RequestTooLarge); |
| 54 | } |
| 55 | let (host, owner) = super::manager() |
| 56 | .shared |
| 57 | .live_host_for_plugin_authority(authority) |
| 58 | .await |
| 59 | .map_err(PluginRouteError::HostUnavailable)?; |
| 60 | let path = if request.path.starts_with('/') { |
| 61 | request.path |
| 62 | } else { |
| 63 | format!("/{}", request.path) |
| 64 | }; |
| 65 | let body_base64 = (!request.body.is_empty()).then(|| BASE64_STANDARD.encode(&request.body)); |
| 66 | let plugin_id = owner.plugin_id.clone(); |
| 67 | let params = PluginRouteDispatchParams { |
| 68 | owner, |
| 69 | method: request.method, |
| 70 | path, |
| 71 | query: request.query.filter(|q| !q.is_empty()), |
| 72 | headers: request |
| 73 | .headers |
| 74 | .into_iter() |
| 75 | .map(|(name, value)| PluginRouteHeaderWire { name, value }) |
| 76 | .collect(), |
| 77 | body_base64, |
| 78 | deadline_ms: PLUGIN_ROUTE_DISPATCH_DEADLINE.as_millis() as u64, |
| 79 | }; |
| 80 | let value = host |
| 81 | .call(CoreRequest::PluginRouteDispatch(params), Some(plugin_id)) |
| 82 | .await |
| 83 | .map_err(|error| match error { |
| 84 | HostCallError::Timeout { .. } => PluginRouteError::Timeout, |
| 85 | HostCallError::Exited(reason) => PluginRouteError::HostUnavailable(reason), |
| 86 | HostCallError::Rpc { message, .. } => PluginRouteError::ExecutionFailed(message), |
| 87 | other => PluginRouteError::ExecutionFailed(other.to_string()), |
| 88 | })?; |
| 89 | let result: PluginRouteDispatchResult = serde_json::from_value(value) |
| 90 | .map_err(|error| PluginRouteError::ExecutionFailed(format!("invalid response: {error}")))?; |
| 91 | if !result.matched { |
| 92 | return Err(PluginRouteError::NotFound); |
| 93 | } |
| 94 | if !(100..=599).contains(&result.status) { |
| 95 | return Err(PluginRouteError::ExecutionFailed(format!( |
| 96 | "invalid HTTP status code {}", |
| 97 | result.status |
| 98 | ))); |
| 99 | } |
| 100 | let body = match result.body_base64 { |
| 101 | Some(encoded) if !encoded.is_empty() => { |
| 102 | if encoded.len() > (MAX_PLUGIN_ROUTE_RESPONSE_BYTES / 3 + 2) * 4 { |
| 103 | return Err(PluginRouteError::ResponseTooLarge); |
| 104 | } |
| 105 | let decoded = BASE64_STANDARD.decode(&encoded).map_err(|error| { |
| 106 | PluginRouteError::ExecutionFailed(format!("invalid base64 response body: {error}")) |
| 107 | })?; |
| 108 | if decoded.len() > MAX_PLUGIN_ROUTE_RESPONSE_BYTES { |
| 109 | return Err(PluginRouteError::ResponseTooLarge); |
| 110 | } |
| 111 | decoded |
| 112 | } |
| 113 | _ => Vec::new(), |
| 114 | }; |
| 115 | let headers = result |
| 116 | .headers |
| 117 | .into_iter() |
| 118 | .map(|h| (h.name, h.value)) |
| 119 | .collect(); |
| 120 | Ok(PluginRouteResponse { |
| 121 | status: result.status, |
| 122 | headers, |
| 123 | body, |
| 124 | }) |
| 125 | } |
| 126 |