//! OpenCode **server** types, transport policy and capability probe. //! //! OpenCode is an agent application, not an OpenAI-compatible inference //! endpoint. A TCP connect, a health check or an HTTP 200 is not proof that a //! model is configured, that the selected model exists, or that it can produce //! a valid Phoebus proposal. The probe reports a typed state for each of those //! distinctions, and only a real inference (`OpenCodeClient::one_shot`) can //! reach [`ConnectionState::Ready`]. //! //! The probe uses the shared [`HttpClient`] transport (curl through [`Exec`]), //! never a second handwritten HTTP parser, and it keeps only ids and model //! names from the provider catalog: upstream's catalog can contain credentials, //! so raw bodies are never retained or surfaced. //! //! ## Transport policy //! //! Plain `http://` is accepted only when the resolved destination is loopback; //! remote access must be `https://` (certificate-verified by curl) or an //! authenticated encrypted tunnel terminating on loopback. The policy resolves //! the host and the connection is pinned to the checked address, so a DNS //! answer that changes after the check cannot move the destination. use std::net::{SocketAddr, ToSocketAddrs}; use std::time::Duration; use phoebus_ai::AiError; use phoebus_core::SecretString; use crate::opencode_client::{parse_catalog, Catalog, HttpClient, HttpRequest, HttpResponse}; /// The URL scheme of an endpoint. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Scheme { Http, Https, } impl Scheme { pub fn as_str(self) -> &'static str { match self { Scheme::Http => "http", Scheme::Https => "https", } } } /// A parsed `scheme://host:port` server endpoint. No path, query, fragment or /// userinfo is accepted. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Endpoint { pub scheme: Scheme, pub host: String, pub port: u16, } #[derive(Debug, Clone, PartialEq, Eq)] pub enum EndpointError { Empty, UnsupportedScheme, UserInfo, PathNotAllowed, BadHost, BadPort, } impl std::fmt::Display for EndpointError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let text = match self { EndpointError::Empty => "empty endpoint", EndpointError::UnsupportedScheme => "only http:// and https:// are accepted", EndpointError::UserInfo => "userinfo (@) is not allowed in the endpoint", EndpointError::PathNotAllowed => "a path, query or fragment is not allowed", EndpointError::BadHost => "the host is missing or contains an unsafe character", EndpointError::BadPort => "the port is missing or invalid", }; f.write_str(text) } } impl Endpoint { pub fn parse(value: &str) -> Result { let text = value.trim(); if text.is_empty() { return Err(EndpointError::Empty); } let (scheme, rest) = if let Some(rest) = text.strip_prefix("http://") { (Scheme::Http, rest) } else if let Some(rest) = text.strip_prefix("https://") { (Scheme::Https, rest) } else { return Err(EndpointError::UnsupportedScheme); }; if rest.is_empty() { return Err(EndpointError::BadHost); } if rest.contains('@') { return Err(EndpointError::UserInfo); } if rest.contains('/') || rest.contains('?') || rest.contains('#') { return Err(EndpointError::PathNotAllowed); } if rest .chars() .any(|c| c.is_whitespace() || c.is_control() || c == '"' || c == '\\') { return Err(EndpointError::BadHost); } // IPv6 literals are bracketed: [::1]:4096 let (host, port) = if let Some(rest) = rest.strip_prefix('[') { let end = rest.find(']').ok_or(EndpointError::BadHost)?; let host = &rest[..end]; let after = &rest[end + 1..]; let port = after.strip_prefix(':').ok_or(EndpointError::BadPort)?; (host.to_string(), port) } else { let (host, port) = rest.rsplit_once(':').ok_or(EndpointError::BadPort)?; (host.to_string(), port) }; if host.is_empty() { return Err(EndpointError::BadHost); } let port: u16 = port.parse().map_err(|_| EndpointError::BadPort)?; if port == 0 { return Err(EndpointError::BadPort); } Ok(Endpoint { scheme, host, port }) } pub fn base(&self) -> String { if self.host.contains(':') { format!("{}://[{}]:{}", self.scheme.as_str(), self.host, self.port) } else { format!("{}://{}:{}", self.scheme.as_str(), self.host, self.port) } } /// Resolve the endpoint and enforce the transport policy. /// /// Returns the address the connection must be pinned to. `http` requires /// every resolved address to be loopback; `https` requires a valid /// certificate (checked by curl, never disabled). pub fn checked_target(&self) -> Result { let addrs: Vec = (self.host.as_str(), self.port) .to_socket_addrs() .map_err(|e| AiError::Provider(format!("cannot resolve {}: {e}", self.host)))? .collect(); if addrs.is_empty() { return Err(AiError::Rejected(format!( "{} did not resolve to any address", self.host ))); } if self.scheme == Scheme::Http { for addr in &addrs { if !addr.ip().is_loopback() { return Err(AiError::Rejected(format!( "refusing plain http to {} ({}); use https or a loopback tunnel", self.host, addr.ip() ))); } } } Ok(addrs[0]) } } /// The connection state a frontend should display. Only [`ConnectionState::Ready`] /// follows a real, validated model response for the current connection/model. #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum ConnectionState { /// The destination did not satisfy the transport policy. InsecureTransport, /// The server could not be reached. Unreachable, /// The server demanded authentication we did not supply. AuthenticationRequired, /// The server rejected the authentication we supplied. AuthenticationRejected, /// A health response arrived but the API is not the expected shape. Incompatible, /// Healthy server with no model catalog. Reachable, /// Healthy server with an available model catalog. ModelCatalog, /// The selected provider/model is not in the catalog. SelectedModelUnavailable, /// A real model response was obtained and validated for this connection. Ready, } #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct Capability { pub state: ConnectionState, pub tcp_reachable: bool, pub healthy: bool, pub server_version: Option, pub provider_count: usize, pub model_count: usize, pub connected_model_count: usize, pub selected_provider: Option, pub selected_model: Option, pub selected_model_available: bool, pub detail: String, } impl Capability { fn new(state: ConnectionState, detail: impl Into) -> Self { Self { state, tcp_reachable: false, healthy: false, server_version: None, provider_count: 0, model_count: 0, connected_model_count: 0, selected_provider: None, selected_model: None, selected_model_available: false, detail: detail.into(), } } } /// Inputs for a probe. `auth` is the server basic-auth password (distinct from /// any model provider credential). pub struct ProbeRequest { pub auth: Option, /// The provider the frontend intends to use, if any. pub provider: Option, /// The model the frontend intends to use, if any. pub model: Option, pub timeout: Duration, } impl ProbeRequest { pub fn new() -> Self { Self { auth: None, provider: None, model: None, timeout: Duration::from_secs(10), } } } impl Default for ProbeRequest { fn default() -> Self { Self::new() } } #[derive(Debug, serde::Deserialize)] struct HealthBody { #[serde(default)] healthy: bool, #[serde(default)] version: Option, } fn http_base(endpoint: &Endpoint) -> String { endpoint.base() } fn auth_required_state(auth_supplied: bool, status: u16) -> ConnectionState { match (auth_supplied, status) { (true, _) => ConnectionState::AuthenticationRejected, (false, 403) => ConnectionState::AuthenticationRejected, _ => ConnectionState::AuthenticationRequired, } } /// Probe the server and classify the connection without claiming model /// readiness. The connection is pinned to the policy-checked address. pub fn probe(http: &H, endpoint: &Endpoint, request: &ProbeRequest) -> Capability { let target = match endpoint.checked_target() { Ok(target) => target, Err(error) => { return Capability::new(ConnectionState::InsecureTransport, error.to_string()) } }; let resolve = Some((endpoint.host.clone(), endpoint.port, target.ip())); // The `/provider` catalog can be several MiB on a server with many // configured providers; health is tiny. Both are bounded. const HEALTH_MAX_BODY: u64 = 64 * 1024; const CATALOG_MAX_BODY: u64 = 16 * 1024 * 1024; let make = |path: &str, max_body: u64| -> HttpRequest { let mut req = HttpRequest::get(format!("{}{path}", http_base(endpoint))); req.timeout = request.timeout; req.connect_timeout = request.timeout.min(Duration::from_secs(10)); req.max_body = max_body; req.resolve = resolve.clone(); req.auth = request.auth.clone(); req }; // Health is the API-compatibility signal. let health = match http.request(&make("/global/health", HEALTH_MAX_BODY)) { Ok(response) => response, Err(error) => { return Capability::new(ConnectionState::Unreachable, error.to_string()); } }; let mut capability = classify_health(health, request.auth.is_some()); if capability.state != ConnectionState::Reachable { // Health did not produce a usable server; report that state now. if matches!( capability.state, ConnectionState::AuthenticationRequired | ConnectionState::AuthenticationRejected ) { capability.tcp_reachable = true; } return capability; } capability.tcp_reachable = true; // Catalog: metadata only, credentials never retained. let catalog_response = match http.request(&make("/provider", CATALOG_MAX_BODY)) { Ok(response) => response, Err(error) => { capability.state = ConnectionState::Incompatible; capability.detail = format!("provider catalog request failed: {error}"); return capability; } }; if !catalog_response.is_success() { capability.state = match catalog_response.status { 401 => auth_required_state(request.auth.is_some(), 401), 403 => ConnectionState::AuthenticationRejected, _ => ConnectionState::Incompatible, }; capability.detail = auth_detail(capability.state, catalog_response.status); return capability; } let catalog: Catalog = match parse_catalog(&catalog_response.body) { Ok(catalog) => catalog, Err(error) => { capability.state = ConnectionState::Incompatible; capability.detail = format!("provider catalog was not usable: {error}"); return capability; } }; apply_catalog(&mut capability, &catalog, request); capability } fn classify_health(response: HttpResponse, auth_supplied: bool) -> Capability { if response.status == 401 || response.status == 403 { let state = auth_required_state(auth_supplied, response.status); return Capability::new(state, auth_detail(state, response.status)); } if !response.is_success() { return Capability::new( ConnectionState::Incompatible, format!("/global/health returned HTTP {}", response.status), ); } let health: HealthBody = match serde_json::from_str(&response.body) { Ok(health) => health, Err(_) => { return Capability::new( ConnectionState::Incompatible, "/global/health was not the expected JSON", ) } }; if !health.healthy { return Capability::new(ConnectionState::Incompatible, "server reported unhealthy"); } let mut capability = Capability::new(ConnectionState::Reachable, "healthy server"); capability.healthy = true; capability.sign_healthy(health.version); capability } impl Capability { fn sign_healthy(&mut self, version: Option) { self.server_version = version; self.tcp_reachable = true; } } fn auth_detail(state: ConnectionState, status: u16) -> String { match state { ConnectionState::AuthenticationRequired => { format!("server requires authentication (HTTP {status})") } ConnectionState::AuthenticationRejected => { format!("server rejected the supplied authentication (HTTP {status})") } _ => format!("HTTP {status}"), } } fn apply_catalog(capability: &mut Capability, catalog: &Catalog, request: &ProbeRequest) { capability.provider_count = catalog .providers .iter() .filter(|p| !p.models.is_empty()) .count(); capability.model_count = catalog.model_count(); capability.connected_model_count = catalog.connected_model_count(); if let Some(provider) = &request.provider { capability.selected_provider = Some(provider.clone()); if let Some(model) = &request.model { capability.selected_model = Some(model.clone()); capability.selected_model_available = catalog.has_model(provider, model); } } if capability.selected_provider.is_some() && !capability.selected_model_available { capability.state = ConnectionState::SelectedModelUnavailable; capability.detail = format!( "provider/model {}:{} is not available in the catalog", request.provider.as_deref().unwrap_or("?"), request.model.as_deref().unwrap_or("?") ); } else if capability.model_count > 0 { capability.state = ConnectionState::ModelCatalog; capability.detail = format!( "{} provider(s), {} model(s), {} connected", capability.provider_count, capability.model_count, capability.connected_model_count ); } else { capability.state = ConnectionState::Reachable; capability.detail = "server is healthy but no model is configured".into(); } } #[cfg(test)] mod tests { use super::*; use std::sync::Mutex; struct FakeHttp { responses: Mutex>, requests: Mutex>, } impl FakeHttp { fn new(responses: Vec<(u16, &str)>) -> Self { Self { responses: Mutex::new( responses .into_iter() .map(|(status, body)| HttpResponse { status, body: body.to_string(), }) .collect(), ), requests: Mutex::new(Vec::new()), } } } impl HttpClient for FakeHttp { fn request(&self, request: &HttpRequest) -> Result { self.requests.lock().unwrap().push(request.clone()); let mut responses = self.responses.lock().unwrap(); if responses.is_empty() { return Err(AiError::Provider("connection refused".into())); } Ok(responses.remove(0)) } } fn health() -> &'static str { r#"{"healthy":true,"version":"1.18.32"}"# } fn catalog() -> &'static str { r#"{"all":[ {"id":"deepseek","name":"DeepSeek","key":"sk-SECRET","models":{"deepseek-chat":{}}}, {"id":"empty","name":"Empty","models":{}}], "connected":["deepseek"], "default":{"deepseek":"deepseek-chat"}}"# } fn endpoint() -> Endpoint { Endpoint::parse("http://127.0.0.1:4096").unwrap() } #[test] fn parses_endpoints_and_rejects_unsafe_forms() { assert_eq!( Endpoint::parse("http://127.0.0.1:4096").unwrap(), Endpoint { scheme: Scheme::Http, host: "127.0.0.1".into(), port: 4096 } ); let v6 = Endpoint::parse("https://[::1]:4096").unwrap(); assert_eq!(v6.host, "::1"); assert_eq!(v6.scheme, Scheme::Https); assert_eq!( Endpoint::parse("ftp://host:1"), Err(EndpointError::UnsupportedScheme) ); assert_eq!( Endpoint::parse("http://user:pw@host:1"), Err(EndpointError::UserInfo) ); assert_eq!( Endpoint::parse("http://host:1/v1/chat"), Err(EndpointError::PathNotAllowed) ); assert_eq!(Endpoint::parse("http://host"), Err(EndpointError::BadPort)); assert_eq!( Endpoint::parse("http://host:0"), Err(EndpointError::BadPort) ); assert_eq!( Endpoint::parse("http://host:99999"), Err(EndpointError::BadPort) ); assert_eq!( Endpoint::parse("http://ho st:1"), Err(EndpointError::BadHost) ); assert_eq!( Endpoint::parse("http://host:1\nX: y"), Err(EndpointError::BadHost) ); assert!(EndpointError::Empty.to_string().contains("empty")); } #[test] fn transport_policy_enforces_loopback_for_plain_http() { // An IP literal avoids DNS and works offline. let public = Endpoint::parse("http://93.184.216.34:80").unwrap(); let err = public.checked_target().unwrap_err().to_string(); assert!(err.contains("refusing plain http"), "{err}"); // https is allowed (certificate verification happens in the transport). let secure = Endpoint::parse("https://93.184.216.34:443").unwrap(); assert!(secure.checked_target().is_ok()); // loopback http is allowed and pinned. let target = endpoint().checked_target().unwrap(); assert!(target.ip().is_loopback()); } #[test] fn probe_reports_a_model_catalog_without_leaking_keys() { let http = FakeHttp::new(vec![(200, health()), (200, catalog())]); let capability = probe(&http, &endpoint(), &ProbeRequest::new()); assert_eq!(capability.state, ConnectionState::ModelCatalog); assert_eq!(capability.model_count, 1); assert_eq!(capability.connected_model_count, 1); let debug = format!("{capability:?}"); assert!( !debug.contains("SECRET"), "capability leaked a key: {debug}" ); // The catalog request carried no credentials. assert!(http.requests.lock().unwrap()[0].auth.is_none()); } #[test] fn probe_reports_selected_model_unavailable() { let http = FakeHttp::new(vec![(200, health()), (200, catalog())]); let mut request = ProbeRequest::new(); request.provider = Some("deepseek".into()); request.model = Some("does-not-exist".into()); let capability = probe(&http, &endpoint(), &request); assert_eq!(capability.state, ConnectionState::SelectedModelUnavailable); assert!(!capability.selected_model_available); // The available model is accepted. let http = FakeHttp::new(vec![(200, health()), (200, catalog())]); let mut request = ProbeRequest::new(); request.provider = Some("deepseek".into()); request.model = Some("deepseek-chat".into()); let capability = probe(&http, &endpoint(), &request); assert_eq!(capability.state, ConnectionState::ModelCatalog); assert!(capability.selected_model_available); } #[test] fn probe_distinguishes_authentication_states() { // No credential supplied → required. let http = FakeHttp::new(vec![(401, r#"{"error":"unauthorized"}"#)]); let capability = probe(&http, &endpoint(), &ProbeRequest::new()); assert_eq!(capability.state, ConnectionState::AuthenticationRequired); // A credential was supplied and rejected. let http = FakeHttp::new(vec![(401, "{}")]); let mut request = ProbeRequest::new(); request.auth = Some(SecretString::new("wrong")); let capability = probe(&http, &endpoint(), &request); assert_eq!(capability.state, ConnectionState::AuthenticationRejected); // Authentication accepted, then health+catalog. let http = FakeHttp::new(vec![(200, health()), (200, catalog())]); let request = ProbeRequest { auth: Some(SecretString::new("right")), ..ProbeRequest::new() }; let capability = probe(&http, &endpoint(), &request); assert_eq!(capability.state, ConnectionState::ModelCatalog); // The credential is presented to the server but never returned. assert!(http.requests.lock().unwrap()[0].auth.is_some()); } #[test] fn probe_reports_incompatible_and_unreachable() { let http = FakeHttp::new(vec![(404, "{}")]); assert_eq!( probe(&http, &endpoint(), &ProbeRequest::new()).state, ConnectionState::Incompatible ); let http = FakeHttp::new(vec![(200, "hi")]); assert_eq!( probe(&http, &endpoint(), &ProbeRequest::new()).state, ConnectionState::Incompatible ); let http = FakeHttp::new(vec![]); assert_eq!( probe(&http, &endpoint(), &ProbeRequest::new()).state, ConnectionState::Unreachable ); } #[test] fn probe_rejects_an_insecure_destination_before_any_request() { let http = FakeHttp::new(vec![(200, health()), (200, catalog())]); let public = Endpoint::parse("http://93.184.216.34:80").unwrap(); let capability = probe(&http, &public, &ProbeRequest::new()); assert_eq!(capability.state, ConnectionState::InsecureTransport); assert!( http.requests.lock().unwrap().is_empty(), "no request may be sent" ); } #[test] fn a_misleading_success_shaped_500_does_not_produce_a_catalog() { // Health OK, but the catalog endpoint returns a providers-shaped body // with a 500 status: it must not be parsed. let shaped = r#"{"all":[{"id":"deepseek","models":{"m":{}}}],"connected":[]}"#; let http = FakeHttp::new(vec![(200, health()), (500, shaped)]); let capability = probe(&http, &endpoint(), &ProbeRequest::new()); assert_eq!(capability.state, ConnectionState::Incompatible); assert_eq!(capability.model_count, 0); } #[test] fn an_empty_catalog_is_reachable_not_ready() { let http = FakeHttp::new(vec![(200, health()), (200, r#"{"all":[],"connected":[]}"#)]); let capability = probe(&http, &endpoint(), &ProbeRequest::new()); assert_eq!(capability.state, ConnectionState::Reachable); assert_ne!(capability.state, ConnectionState::Ready); } #[test] fn capability_serialisation_has_no_credential_fields() { let capability = Capability::new(ConnectionState::Ready, "1 provider(s)"); let json = serde_json::to_string(&capability).unwrap(); assert!(!json.to_lowercase().contains("key")); } }