diff --git a/Cargo.lock b/Cargo.lock index 84a6d3e..f2c8318 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -32,15 +32,6 @@ version = "1.0.103" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2a4385e2e34eb35d6b3efe798b9eb88096925d87726c0798709bf56d9ed84af3" -[[package]] -name = "arbitrary" -version = "1.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1" -dependencies = [ - "derive_arbitrary", -] - [[package]] name = "async-stream" version = "0.3.6" @@ -77,9 +68,9 @@ checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" [[package]] name = "aws-lc-rs" -version = "1.17.0" +version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ec2f1fc3ec205783a5da9a7e6c1509cc69dedf09a1949e412c1e18469326d00" +checksum = "048006790404103c488e6c5616b3e7e702a71292aadda08e8f7698a9e0d2eb53" dependencies = [ "aws-lc-sys", "zeroize", @@ -87,14 +78,15 @@ dependencies = [ [[package]] name = "aws-lc-sys" -version = "0.41.0" +version = "0.47.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a2f9779ce85b93ab6170dd940ad0169b5766ff848247aff13bb788b832fe3f4" +checksum = "8bfbe32ac36b3c428696ce315464181bc4029d689fd58e3f2a4e58c252242f52" dependencies = [ "cc", "cmake", "dunce", "fs_extra", + "pkg-config", ] [[package]] @@ -329,6 +321,15 @@ version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" +[[package]] +name = "constant_time_eq" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "144e7f1de087984240b7816d47f698b414979faa6f40839c5b86d6bd47db57b7" +dependencies = [ + "rustversion", +] + [[package]] name = "cookie" version = "0.18.1" @@ -469,17 +470,6 @@ version = "0.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" -[[package]] -name = "derive_arbitrary" -version = "1.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e567bd82dcff979e4b03460c307b3cdc9e96fde3d73bed1496d2bc75d9dd62a" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.118", -] - [[package]] name = "dialoguer" version = "0.12.0" @@ -585,12 +575,6 @@ dependencies = [ "zeroize", ] -[[package]] -name = "either" -version = "1.16.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91622ff5e7162018101f2fea40d6ebf4a78bbe5a49736a2020649edf9693679e" - [[package]] name = "encode_unicode" version = "1.0.0" @@ -813,9 +797,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" dependencies = [ "cfg-if", + "js-sys", "libc", "r-efi 6.0.0", "rand_core 0.10.1", + "wasm-bindgen", ] [[package]] @@ -1340,6 +1326,18 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "nix" +version = "0.31.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" +dependencies = [ + "bitflags", + "cfg-if", + "cfg_aliases", + "libc", +] + [[package]] name = "nu-ansi-term" version = "0.50.3" @@ -1427,6 +1425,12 @@ dependencies = [ "spki", ] +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + [[package]] name = "portable-atomic" version = "1.13.1" @@ -1466,15 +1470,6 @@ dependencies = [ "unicode-ident", ] -[[package]] -name = "quick-xml" -version = "0.38.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b66c2058c55a409d601666cffe35f04333cf1013010882cec174a7467cd4e21c" -dependencies = [ - "memchr", -] - [[package]] name = "quinn" version = "0.11.11" @@ -1743,9 +1738,9 @@ dependencies = [ [[package]] name = "rustls" -version = "0.23.43" +version = "0.23.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0283386ce02abc0151e1761d08802dfe86c173b0b494af5cbc086574e453da06" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" dependencies = [ "aws-lc-rs", "log", @@ -1808,9 +1803,9 @@ checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f" [[package]] name = "rustls-webpki" -version = "0.103.13" +version = "0.103.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" dependencies = [ "aws-lc-rs", "ring", @@ -1890,16 +1885,14 @@ dependencies = [ [[package]] name = "self_update" -version = "0.44.0" +version = "1.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e79722b5a505d4ddc77527455a97244e9e8c4c07533ff44cf4421cce7bb6d17" +checksum = "db894dc81dc2d26b41c4966e3e67ab2e0c21289912edd262012a07da9e4e0201" dependencies = [ - "either", "flate2", "http", "indicatif", "log", - "quick-xml", "regex", "reqwest", "self-replace", @@ -2277,6 +2270,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "85c17d80feb7334b40c484e45ed1a5273dfd8bfda537c3be2e74a06a6686f327" dependencies = [ "deranged", + "js-sys", "num-conv", "powerfmt", "serde_core", @@ -2616,6 +2610,12 @@ dependencies = [ "thiserror", ] +[[package]] +name = "typed-path" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ce898823d8cd0f028662d2f349694b1af0a5cc9be83f1d213a00d3147445e1e" + [[package]] name = "typenum" version = "1.20.1" @@ -3228,6 +3228,20 @@ name = "zeroize" version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.118", +] [[package]] name = "zerotrie" @@ -3264,24 +3278,30 @@ dependencies = [ [[package]] name = "zip" -version = "6.0.0" +version = "9.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb2a05c7c36fde6c09b08576c9f7fb4cda705990f73b58fe011abf7dfb24168b" +checksum = "2d8dbe089cf6b0448b78f5fc50139ab5aaa40d08ac07cdc1baf2c13add35fcce" dependencies = [ - "arbitrary", + "constant_time_eq", "crc32fast", "flate2", + "getrandom 0.4.3", "indexmap", + "libc", "memchr", + "nix", "time", + "typed-path", + "windows-sys 0.61.2", + "zeroize", "zopfli", ] [[package]] name = "zipsign-api" -version = "0.1.5" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dba6063ff82cdbd9a765add16d369abe81e520f836054e997c2db217ceca40c0" +checksum = "00d866e1d567fd67738668647c2e06587851e0e3583df84298cc363c14602316" dependencies = [ "base64 0.22.1", "ed25519-dalek", diff --git a/Cargo.toml b/Cargo.toml index 8a52752..15b6fb2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -37,7 +37,7 @@ tracing = "0.1" tracing-subscriber = { version = "0.3", features = ["env-filter"] } tiktoken-rs = "0.12" dialoguer = { version = "0.12", default-features = false, features = ["fuzzy-select", "password"] } -self_update = { version = "0.44", default-features = false, features = ["reqwest", "rustls", "archive-tar", "compression-flate2", "archive-zip", "compression-zip-deflate"] } +self_update = { version = "1.3.3", default-features = false, features = ["github", "progress-bar", "reqwest", "rustls", "compression-tar-gz", "compression-zip-deflate"] } toml = "1.1" [dev-dependencies] diff --git a/docs/api.md b/docs/api.md index a8379c1..74e5139 100644 --- a/docs/api.md +++ b/docs/api.md @@ -17,6 +17,11 @@ require a key on the LLM endpoints; see [Authentication](#authentication) below. ## Endpoints +Inference HTTP requests accept JSON objects up to 32 MiB. There is a shared +limit of 262,144 field values and array elements across the request, including +nested objects and arrays. Invalid JSON, non-object requests, or requests over +the value limit receive HTTP 400; exceeding the byte limit returns HTTP 413. + | Method & path | Description | |---------------|-------------| | `POST /v1/chat/completions` | OpenAI chat completions (also `/chat/completions`) | diff --git a/docs/claude-code.md b/docs/claude-code.md index 5aa0faf..a539e31 100644 --- a/docs/claude-code.md +++ b/docs/claude-code.md @@ -97,12 +97,11 @@ A `model` already in the file is treated as a deliberate choice and kept; the recommended default is only written when the config has none. The provider uses command-backed authentication through `ghc-proxy codex-auth-token`. -Besides supplying the current local `api_key` (or a harmless -placeholder when authentication is disabled), this tells Codex to refresh the -provider's model catalog. No OpenAI account or exported environment variable is -required. When an `api_key` is active during setup, its resolved value is also -written as `x-api-key`; this keeps environment-only proxy launches working when -ChatGPT Desktop does not inherit the server's shell environment. +The helper returns a non-secret placeholder so Codex refreshes the provider's +model catalog; it never prints the proxy API key. When authentication is +enabled, setup writes the resolved key as the provider's `x-api-key` header. +Re-run Codex setup after enabling or rotating the key, including when upgrading +a configuration that relied on the command alone. Keep the Codex config private. Codex requests `GET /v1/models?client_version=...`; the proxy recognizes that query and returns Codex-native model metadata with `context_window` and diff --git a/docs/configuration.md b/docs/configuration.md index 0c8ce97..54378d7 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -88,7 +88,9 @@ rewritten to follow them: see [Schema upgrades](#schema-upgrades). ### Account type -Controls the upstream base URL only: +Selects one of three fixed HTTPS origins. An unrecognized tier logs a warning +and uses `individual`; it cannot supply a custom upstream host. +Credentialed upstream HTTP requests do not follow redirects. | `account_type` | Upstream base URL | |----------------|-------------------| diff --git a/scripts/ws_probe.py b/scripts/ws_probe.py index 6da5ef4..87fc95b 100644 --- a/scripts/ws_probe.py +++ b/scripts/ws_probe.py @@ -71,6 +71,7 @@ def handshake(host: str, path: str, token: str, extra: dict[str, str]) -> tuple[ raw = f"GET {path} HTTP/1.1\r\n" + "".join(f"{k}: {v}\r\n" for k, v in headers.items()) + "\r\n" ctx = ssl.create_default_context() + ctx.minimum_version = ssl.TLSVersion.TLSv1_2 with socket.create_connection((host, 443), timeout=20) as sock: with ctx.wrap_socket(sock, server_hostname=host) as tls: tls.sendall(raw.encode()) diff --git a/src/config.rs b/src/config.rs index b9bb88d..836d5cd 100644 --- a/src/config.rs +++ b/src/config.rs @@ -60,6 +60,39 @@ pub const DEFAULT_ADDRESS: &str = "127.0.0.1"; /// Default listen port. pub const DEFAULT_PORT: u16 = 8314; +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize, serde::Serialize)] +#[serde(from = "String", rename_all = "lowercase")] +pub enum AccountType { + #[default] + Individual, + Business, + Enterprise, +} + +impl From for AccountType { + fn from(value: String) -> Self { + match value.as_str() { + "individual" => Self::Individual, + "business" => Self::Business, + "enterprise" => Self::Enterprise, + _ => { + tracing::warn!("Unknown account_type; using the individual Copilot endpoint"); + Self::Individual + } + } + } +} + +impl std::fmt::Display for AccountType { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(match self { + Self::Individual => "individual", + Self::Business => "business", + Self::Enterprise => "enterprise", + }) + } +} + /// Model name mapping table (exact + prefix). #[derive(Debug, Clone, Default, Deserialize)] pub struct ModelMappings { @@ -80,8 +113,8 @@ pub struct Config { pub port: u16, #[serde(default)] pub debug: bool, - #[serde(default = "default_account_type")] - pub account_type: String, + #[serde(default)] + pub account_type: AccountType, #[serde(default = "default_vscode_version")] pub vscode_version: String, #[serde(default = "default_api_version")] @@ -174,9 +207,6 @@ fn default_port() -> u16 { fn default_true() -> bool { true } -fn default_account_type() -> String { - "individual".to_string() -} fn default_vscode_version() -> String { VSCODE_VERSION.to_string() } @@ -210,7 +240,7 @@ impl Default for Config { address: default_address(), port: default_port(), debug: false, - account_type: default_account_type(), + account_type: AccountType::default(), vscode_version: default_vscode_version(), api_version: default_api_version(), copilot_version: default_copilot_version(), @@ -235,11 +265,11 @@ impl Default for Config { impl Config { /// Upstream Copilot API base URL, derived from the configured account type. - pub fn copilot_base_url(&self) -> String { - if self.account_type == "individual" { - "https://api.githubcopilot.com".to_string() - } else { - format!("https://api.{}.githubcopilot.com", self.account_type) + pub fn copilot_base_url(&self) -> &'static str { + match self.account_type { + AccountType::Individual => "https://api.githubcopilot.com", + AccountType::Business => "https://api.business.githubcopilot.com", + AccountType::Enterprise => "https://api.enterprise.githubcopilot.com", } } @@ -621,11 +651,8 @@ pub fn load_config_with_options(write_back_on_migration: bool) -> Config { tracing::info!("✓ Overriding debug from GHC_PROXY_DEBUG: {}", cfg.debug); } if let Ok(val) = std::env::var("GHC_PROXY_ACCOUNT_TYPE") { - tracing::info!( - "✓ Overriding account_type from GHC_PROXY_ACCOUNT_TYPE: {}", - val - ); - cfg.account_type = val; + cfg.account_type = val.into(); + tracing::info!("✓ Overriding account_type from GHC_PROXY_ACCOUNT_TYPE"); } if let Ok(val) = std::env::var("GHC_PROXY_VSCODE_VERSION") { tracing::info!( @@ -869,6 +896,22 @@ fn migrate_config(cfg: &mut Config) -> bool { mod tests { use super::*; + #[test] + fn account_types_select_fixed_origins_without_discarding_other_settings() { + for (tier, origin) in [ + ("individual", "https://api.githubcopilot.com"), + ("business", "https://api.business.githubcopilot.com"), + ("enterprise", "https://api.enterprise.githubcopilot.com"), + ("unknown", "https://api.githubcopilot.com"), + ] { + let cfg: Config = + serde_norway::from_str(&format!("account_type: {tier}\napi_key: test-only\n")) + .unwrap(); + assert_eq!(cfg.copilot_base_url(), origin); + assert_eq!(cfg.api_key.as_deref(), Some("test-only")); + } + } + #[test] fn auto_upgrade_is_on_by_default_including_for_legacy_configs() { assert!(Config::default().auto_upgrade); diff --git a/src/main.rs b/src/main.rs index 1fa1015..5d3894d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -268,7 +268,7 @@ fn configure_claude_code(cfg: &ghc_proxy::config::Config) -> std::io::Result Router { Router::new() @@ -64,7 +68,7 @@ pub fn router(state: SharedState) -> Router { state.clone(), auth_middleware, )) - .layer(DefaultBodyLimit::max(20 * 1024 * 1024 * 1024)) // 20 GB limit + .layer(DefaultBodyLimit::max(MAX_REQUEST_BODY_BYTES)) .with_state(state) } @@ -257,12 +261,17 @@ fn capture_str(state: &SharedState, body: &str) -> Option { #[allow(clippy::result_large_err)] fn parse_body(body: &Bytes) -> Result { - serde_json::from_slice::(body).map_err(|e| { - ( + if body.len() > MAX_REQUEST_BODY_BYTES { + return Err(error_response( + StatusCode::PAYLOAD_TOO_LARGE, + "Request exceeds 32 MiB".into(), + )); + } + request_json::parse_object(body).map_err(|_| { + error_response( StatusCode::BAD_REQUEST, - Json(json!({"error": format!("Invalid JSON body: {e}")})), + "Expected a JSON object within the request complexity limit".into(), ) - .into_response() }) } @@ -1249,7 +1258,7 @@ async fn responses(State(state): State, body: Bytes) -> Response { set_initiator(&mut headers, agent); let req_size = body.len(); - let url = format!("{}/responses", state.copilot_base_url()); + let url = state.copilot_url(CopilotEndpoint::Responses); let is_stream = req.get("stream").and_then(|s| s.as_bool()).unwrap_or(false); let payload = serde_json::to_vec(&req).unwrap_or_default(); log_debug_request(&state, "/v1/responses", &req); @@ -1910,7 +1919,7 @@ async fn messages_direct( .await; set_initiator(&mut headers, agent); - let url = format!("{}/v1/messages", state.copilot_base_url()); + let url = state.copilot_url(CopilotEndpoint::Messages); let is_stream = req.get("stream").and_then(|s| s.as_bool()).unwrap_or(false); let mut current = req.clone(); @@ -1925,9 +1934,8 @@ async fn messages_direct( log_debug_request(&state, "/v1/messages", &sanitized); if is_stream { - let upstream = state - .http - .post(&url) + let upstream = url + .post(&state.http) .headers(headers.clone()) .body(payload) .send() @@ -2155,7 +2163,7 @@ async fn messages_translated( }) }) .unwrap_or(false); - let url = format!("{}/chat/completions", state.copilot_base_url()); + let url = state.copilot_url(CopilotEndpoint::ChatCompletions); let mut headers = state.copilot_headers(vision).await; set_initiator(&mut headers, agent); let payload = serde_json::to_vec(&openai_req).unwrap_or_default(); @@ -2284,13 +2292,13 @@ async fn count_tokens( client_headers: HeaderMap, body: Bytes, ) -> Response { - if state.ensure_copilot_token().await.is_err() { - return Json(json!({"input_tokens": 1})).into_response(); - } let mut req = match parse_body(&body) { Ok(v) => v, - Err(_) => return Json(json!({"input_tokens": 1})).into_response(), + Err(response) => return response, }; + if state.ensure_copilot_token().await.is_err() { + return Json(json!({"input_tokens": 1})).into_response(); + } let original_model = req .get("model") .and_then(|m| m.as_str()) @@ -2329,7 +2337,7 @@ async fn count_tokens( translate::split_context_1m(&original_model).1, ) .await; - let url = format!("{}/v1/messages/count_tokens", state.copilot_base_url()); + let url = state.copilot_url(CopilotEndpoint::CountTokens); // Counting writes no cache entry, so the ttl is irrelevant here. let payload = serde_json::to_vec(&anthropic::sanitize_anthropic_request(&req, false)) .unwrap_or_default(); @@ -2550,7 +2558,7 @@ fn collect_text_for_count(openai_req: &Value) -> String { #[allow(clippy::too_many_arguments)] async fn stream_gemini( state: SharedState, - url: &str, + url: &CopilotUrl, headers: HeaderMap, payload: Vec, original_model: String, @@ -2561,9 +2569,8 @@ async fn stream_gemini( let req_body = state .is_debug() .then(|| String::from_utf8_lossy(&payload).into_owned()); - let upstream = state - .http - .post(url) + let upstream = url + .post(&state.http) .headers(headers) .body(payload) .send() @@ -2714,7 +2721,7 @@ async fn embeddings(State(state): State, body: Bytes) -> Response { .to_string(); let req_size = body.len(); let headers = state.copilot_headers(false).await; - let url = format!("{}/embeddings", state.copilot_base_url()); + let url = state.copilot_url(CopilotEndpoint::Embeddings); let payload = serde_json::to_vec(&req).unwrap_or_default(); log_debug_request(&state, "/v1/embeddings", &req); @@ -2935,7 +2942,7 @@ fn anthropic_error(status: StatusCode, msg: String) -> Response { #[allow(clippy::too_many_arguments)] async fn stream_openai( state: SharedState, - url: &str, + url: &CopilotUrl, headers: HeaderMap, mut req: Value, endpoint: &'static str, @@ -2948,9 +2955,8 @@ async fn stream_openai( let mut payload = serde_json::to_vec(&req).unwrap_or_default(); let mut retried_param = false; let upstream = loop { - let upstream = state - .http - .post(url) + let upstream = url + .post(&state.http) .headers(headers.clone()) .body(payload.clone()) .send() @@ -3123,7 +3129,7 @@ async fn stream_openai( #[allow(clippy::too_many_arguments)] async fn stream_responses( state: SharedState, - url: &str, + url: &CopilotUrl, headers: HeaderMap, payload: Vec, req: Value, @@ -3133,9 +3139,8 @@ async fn stream_responses( start: Instant, ) -> Response { let req_body = capture_json(&state, &req); - let upstream = state - .http - .post(url) + let upstream = url + .post(&state.http) .headers(headers) .body(payload) .send() @@ -3404,7 +3409,7 @@ async fn stream_anthropic_direct( #[allow(clippy::too_many_arguments)] async fn stream_anthropic_translated( state: SharedState, - url: &str, + url: &CopilotUrl, headers: HeaderMap, payload: Vec, original_model: String, @@ -3416,9 +3421,8 @@ async fn stream_anthropic_translated( let req_body = state .is_debug() .then(|| String::from_utf8_lossy(&payload).into_owned()); - let upstream = state - .http - .post(url) + let upstream = url + .post(&state.http) .headers(headers) .body(payload) .send() @@ -4457,6 +4461,27 @@ async fn api_audit_summary(State(state): State) -> Response { #[cfg(test)] mod tests { + #[test] + fn inference_bodies_must_be_bounded_json_objects() { + assert_eq!( + parse_body(&Bytes::from_static(br#" {"extra":true} "#)).unwrap()["extra"], + true + ); + for input in [b"[]".as_slice(), b"null", b"{", b"{} {}"] { + assert_eq!( + parse_body(&Bytes::from_static(input)).unwrap_err().status(), + StatusCode::BAD_REQUEST + ); + } + let mut body = vec![b' '; MAX_REQUEST_BODY_BYTES]; + body[..2].copy_from_slice(b"{}"); + body.push(b' '); + assert_eq!( + parse_body(&Bytes::from(body)).unwrap_err().status(), + StatusCode::PAYLOAD_TOO_LARGE + ); + } + #[test] fn output_tokens_stay_provisional_until_message_delta() { let mut st = super::DirectStreamState::default(); diff --git a/src/server/request_json.rs b/src/server/request_json.rs new file mode 100644 index 0000000..0d97c33 --- /dev/null +++ b/src/server/request_json.rs @@ -0,0 +1,106 @@ +use serde::de::{self, DeserializeSeed, Deserializer, MapAccess, SeqAccess, Visitor}; +use serde_json::{Map, Value}; +use std::fmt; + +// The wire-size limit alone doesn't bound the size of the resulting Value tree: +// a short scalar can occupy considerably more space in memory than on the wire. +const MAX_VALUES: usize = 262_144; + +pub(super) fn parse_object(input: &[u8]) -> serde_json::Result { + parse_with_limit(input, MAX_VALUES) +} + +fn parse_with_limit(input: &[u8], limit: usize) -> serde_json::Result { + let mut parser = serde_json::Deserializer::from_slice(input); + let mut remaining = limit; + let object = parser.deserialize_map(BoundedValue(&mut remaining))?; + parser.end()?; + Ok(object) +} + +// Charge each field value and array element before parsing it. A single budget +// covers all containers, including repeated keys, rather than resetting per list. +struct BoundedValue<'a>(&'a mut usize); + +impl<'de> DeserializeSeed<'de> for BoundedValue<'_> { + type Value = Value; + + fn deserialize>(self, parser: D) -> Result { + *self.0 = self + .0 + .checked_sub(1) + .ok_or_else(|| de::Error::custom("too many JSON values"))?; + parser.deserialize_any(self) + } +} + +impl<'de> Visitor<'de> for BoundedValue<'_> { + type Value = Value; + + fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("a JSON value") + } + + fn visit_map>(self, mut fields: A) -> Result { + let mut object = Map::new(); + while let Some(key) = fields.next_key::()? { + object.insert(key, fields.next_value_seed(BoundedValue(self.0))?); + } + Ok(Value::Object(object)) + } + + fn visit_seq>(self, mut items: A) -> Result { + let mut array = Vec::new(); + while let Some(value) = items.next_element_seed(BoundedValue(self.0))? { + array.push(value); + } + Ok(Value::Array(array)) + } + + fn visit_unit(self) -> Result { + Ok(Value::Null) + } + fn visit_bool(self, v: bool) -> Result { + Ok(v.into()) + } + fn visit_u64(self, v: u64) -> Result { + Ok(v.into()) + } + fn visit_i64(self, v: i64) -> Result { + Ok(v.into()) + } + fn visit_f64(self, v: f64) -> Result { + Ok(v.into()) + } + fn visit_str(self, v: &str) -> Result { + Ok(v.into()) + } + fn visit_string(self, v: String) -> Result { + Ok(v.into()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn charges_one_shared_budget_across_nested_containers_and_duplicate_keys() { + let input = br#"{"a":[true,{"b":null}],"a":2}"#; + assert_eq!( + parse_with_limit(input, 5).unwrap(), + serde_json::json!({"a": 2}) + ); + assert!(parse_with_limit(input, 4).is_err()); + } + + #[test] + fn preserves_provider_json_and_rejects_incomplete_or_trailing_input() { + let input = br#"{"extra":["a\nb",-4,18446744073709551615,1.25,false,{},[]]}"#; + let expected: Value = serde_json::from_slice(input).unwrap(); + assert_eq!(parse_object(input).unwrap(), expected); + for invalid in [b"[]".as_slice(), b"null", br#"{"a":}"#, b"{} []"] { + assert!(parse_object(invalid).is_err()); + } + } +} diff --git a/src/setup.rs b/src/setup.rs index 66f9e08..8f543e8 100644 --- a/src/setup.rs +++ b/src/setup.rs @@ -12,7 +12,7 @@ use std::sync::Arc; use dialoguer::theme::ColorfulTheme; use dialoguer::{Confirm, FuzzySelect, Input, Select}; -use ghc_proxy::config::{self, Config, ModelMappings}; +use ghc_proxy::config::{self, AccountType, Config, ModelMappings}; use ghc_proxy::{auth, state::AppState}; /// The result of a completed wizard run. @@ -125,7 +125,7 @@ fn cancelled() -> Option { struct ServerSettings { address: String, port: u16, - account_type: String, + account_type: AccountType, } fn prompt_server_settings(defaults: &Config) -> dialoguer::Result { @@ -142,7 +142,11 @@ fn prompt_server_settings(defaults: &Config) -> dialoguer::Result dialoguer::Result u64 { /// under the ~60s idle cutoff typical of load balancers and NAT tables. const UPSTREAM_KEEPALIVE_INTERVAL: Duration = Duration::from_secs(20); +/// Credentialed requests only target entries in this closed set. No request +/// field, API key or config string is used to serialize any part of the URL. +pub(crate) enum CopilotEndpoint { + Models, + ChatCompletions, + Responses, + Messages, + CountTokens, + Embeddings, +} + +pub struct CopilotUrl(&'static str); + +impl CopilotUrl { + fn new(tier: config::AccountType, endpoint: CopilotEndpoint) -> Self { + macro_rules! urls { + ($path:literal) => { + [ + concat!("https://api.githubcopilot.com", $path), + concat!("https://api.business.githubcopilot.com", $path), + concat!("https://api.enterprise.githubcopilot.com", $path), + ] + }; + } + let urls = match endpoint { + CopilotEndpoint::Models => urls!("/models"), + CopilotEndpoint::ChatCompletions => urls!("/chat/completions"), + CopilotEndpoint::Responses => urls!("/responses"), + CopilotEndpoint::Messages => urls!("/v1/messages"), + CopilotEndpoint::CountTokens => urls!("/v1/messages/count_tokens"), + CopilotEndpoint::Embeddings => urls!("/embeddings"), + }; + let index = match tier { + config::AccountType::Individual => 0, + config::AccountType::Business => 1, + config::AccountType::Enterprise => 2, + }; + Self(urls[index]) + } + + pub(crate) fn post(&self, client: &reqwest::Client) -> reqwest::RequestBuilder { + client.post(self.0) + } +} + /// How long to serve local token estimates after the upstream counting endpoint /// reports a rate limit. const COUNTING_COOLDOWN: Duration = Duration::from_secs(60); @@ -164,6 +209,14 @@ fn now_millis() -> u128 { .unwrap_or(0) } +fn with_read_timeout(builder: reqwest::ClientBuilder, seconds: u64) -> reqwest::ClientBuilder { + if seconds == 0 { + builder + } else { + builder.read_timeout(Duration::from_secs(seconds)) + } +} + impl AppState { pub fn new(config: Config, github_token: String) -> Self { // No global request timeout: SSE responses are long-lived streams, and @@ -179,18 +232,19 @@ impl AppState { // that window, and an idle connection is what load balancers, NATs and // corporate middleboxes reap -- which surfaces as a truncated body // partway through the answer. - let mut builder = reqwest::Client::builder() + let builder = reqwest::Client::builder() + .https_only(true) + // A credentialed request must not be replayed at a redirected origin. + .redirect(reqwest::redirect::Policy::none()) .connect_timeout(Duration::from_secs(30)) .pool_idle_timeout(Duration::from_secs(90)) .tcp_keepalive(UPSTREAM_KEEPALIVE_INTERVAL) .http2_keep_alive_interval(UPSTREAM_KEEPALIVE_INTERVAL) .http2_keep_alive_timeout(Duration::from_secs(20)) .http2_keep_alive_while_idle(true); - if config.upstream_read_timeout_seconds > 0 { - builder = - builder.read_timeout(Duration::from_secs(config.upstream_read_timeout_seconds)); - } - let http = builder.build().expect("failed to build HTTP client"); + let http = with_read_timeout(builder, config.upstream_read_timeout_seconds) + .build() + .expect("failed to build HTTP client"); AppState { http, config: StdRwLock::new(config), @@ -336,10 +390,14 @@ impl AppState { .cloned() } - pub fn copilot_base_url(&self) -> String { + pub fn copilot_base_url(&self) -> &'static str { self.config.read().unwrap().copilot_base_url() } + pub(crate) fn copilot_url(&self, endpoint: CopilotEndpoint) -> CopilotUrl { + CopilotUrl::new(self.config.read().unwrap().account_type, endpoint) + } + pub fn config_path(&self) -> String { config::config_path().display().to_string() } @@ -440,8 +498,8 @@ impl AppState { } /// Resolves the Copilot chat-completions URL and headers. - pub async fn chat_upstream(&self, vision: bool) -> (String, HeaderMap) { - let url = format!("{}/chat/completions", self.copilot_base_url()); + pub async fn chat_upstream(&self, vision: bool) -> (CopilotUrl, HeaderMap) { + let url = self.copilot_url(CopilotEndpoint::ChatCompletions); (url, self.copilot_headers(vision).await) } @@ -452,14 +510,12 @@ impl AppState { /// and `endpoints.api` is the only host involved. Discovered by probing; /// GitHub publishes no documentation for the inference API. pub async fn ws_responses_upstream(&self) -> (String, HeaderMap) { - let base = self.copilot_base_url(); - let ws = match base.split_once("://") { - Some(("https", rest)) => format!("wss://{rest}"), - Some(("http", rest)) => format!("ws://{rest}"), - _ => base.clone(), - }; + let host = self + .copilot_base_url() + .strip_prefix("https://") + .expect("Copilot endpoints are fixed HTTPS origins"); ( - format!("{}/responses", ws.trim_end_matches('/')), + format!("wss://{host}/responses"), self.copilot_headers(false).await, ) } @@ -499,11 +555,11 @@ impl AppState { /// Fetches the list of available models from upstream and caches it. pub async fn load_models(&self) -> Result<(), String> { self.ensure_copilot_token().await?; - let url = format!("{}/models", self.copilot_base_url()); + let url = self.copilot_url(CopilotEndpoint::Models); let headers = self.copilot_headers(false).await; let resp = self .http - .get(&url) + .get(url.0) .headers(headers) .send() .await @@ -974,13 +1030,10 @@ mod tests { #[tokio::test] async fn read_timeout_surfaces_a_stalled_upstream_as_an_error() { let url = stalling_upstream().await; - let cfg = Config { - upstream_read_timeout_seconds: 1, - ..Default::default() - }; - let state = AppState::new(cfg, "token".into()); - - let resp = state.http.get(&url).send().await.expect("headers arrive"); + let client = with_read_timeout(reqwest::Client::builder(), 1) + .build() + .unwrap(); + let resp = client.get(&url).send().await.expect("headers arrive"); assert!(resp.status().is_success()); let mut stream = resp.bytes_stream(); @@ -1001,18 +1054,60 @@ mod tests { #[tokio::test] async fn read_timeout_can_be_disabled() { let url = stalling_upstream().await; - let cfg = Config { - upstream_read_timeout_seconds: 0, - ..Default::default() - }; - let state = AppState::new(cfg, "token".into()); - let resp = state.http.get(&url).send().await.expect("headers arrive"); + let client = with_read_timeout(reqwest::Client::builder(), 0) + .build() + .unwrap(); + let resp = client.get(&url).send().await.expect("headers arrive"); let mut stream = resp.bytes_stream(); let _ = stream.next().await; let outcome = tokio::time::timeout(Duration::from_secs(3), stream.next()).await; assert!(outcome.is_err(), "expected the stream to still be hanging"); } + #[tokio::test] + async fn upstream_transport_rejects_plain_http_before_connecting() { + let state = AppState::new(Config::default(), "test-only".into()); + let err = state + .http + .get("http://127.0.0.1:1/") + .send() + .await + .unwrap_err(); + assert!(err.is_builder()); + } + + #[test] + fn credentialed_requests_only_use_the_public_origin_and_route() { + use config::AccountType::{Business, Enterprise, Individual}; + for tier in [Individual, Business, Enterprise] { + let cfg = Config { + account_type: tier, + api_key: Some("local-test-key".into()), + ..Config::default() + }; + let state = AppState::new(cfg, "github-test-key".into()); + for (endpoint, path) in [ + (CopilotEndpoint::Models, "/models"), + (CopilotEndpoint::ChatCompletions, "/chat/completions"), + (CopilotEndpoint::Responses, "/responses"), + (CopilotEndpoint::Messages, "/v1/messages"), + (CopilotEndpoint::CountTokens, "/v1/messages/count_tokens"), + (CopilotEndpoint::Embeddings, "/embeddings"), + ] { + let request = state + .copilot_url(endpoint) + .post(&state.http) + .bearer_auth("copilot-test-key") + .build() + .unwrap(); + assert_eq!( + request.url().as_str(), + format!("{}{path}", state.copilot_base_url()) + ); + } + } + } + #[test] fn premium_multiplier_reads_billing_from_the_catalog() { // Shape taken from a real `GET /models` response. diff --git a/src/util.rs b/src/util.rs index 92354f5..30a5710 100644 --- a/src/util.rs +++ b/src/util.rs @@ -1,7 +1,7 @@ //! Miscellaneous helpers: orphaned tool-result detection/removal, SSE line //! buffering, and an HTTP request retry wrapper with exponential backoff. -use crate::state::AppState; +use crate::state::{AppState, CopilotUrl}; use serde_json::Value; use std::time::Duration; @@ -297,13 +297,12 @@ pub fn is_retryable_error(status: u16) -> bool { /// fallback would have given immediately. pub async fn post_once( state: &AppState, - url: &str, + url: &CopilotUrl, headers: reqwest::header::HeaderMap, body: Vec, ) -> Option { - let resp = state - .http - .post(url) + let resp = url + .post(&state.http) .headers(headers) .body(body) .send() @@ -315,7 +314,7 @@ pub async fn post_once( pub async fn post_with_retry( state: &AppState, - url: &str, + url: &CopilotUrl, headers: reqwest::header::HeaderMap, body: Vec, endpoint: &str, @@ -323,9 +322,8 @@ pub async fn post_with_retry( let max = state.max_connection_retries(); let mut attempt = 0u32; loop { - let result = state - .http - .post(url) + let result = url + .post(&state.http) .headers(headers.clone()) .body(body.clone()) .send()