From d31cc4b2563e5de5e90fb2ce1a75c2e74e6257fc Mon Sep 17 00:00:00 2001 From: Shaurya Kesarwani Date: Sun, 25 Oct 2026 11:07:00 +0530 Subject: [PATCH 1/7] fix(providers): send custom headers, a product User-Agent and the OpenCode Go session to cloud providers Every chat request to OpenCode Go (`https://opencode.ai/zen/go/v1`) failed with HTTP 400 `MissingSessionID`: the endpoint requires a stable per-conversation `x-opencode-session` header and asks clients to send a product `User-Agent`, and OpenHuman sent neither. `[[cloud_providers]]` had no way to add a header either, so there was no configuration workaround. - `CloudProviderCreds` gains an optional `headers` table (`[cloud_providers.headers]` in `config.toml`, `headers` on the `config_update_model_settings` / `inference_update_model_settings` entries). The headers ride every request to that provider: chat completions, the context-window discovery listing and `list_models`. A settings save whose entries omit `headers` keeps the stored table, because the settings panel echoes every entry back and has no editor for it. - Header values may be secrets, so the client config snapshot shows only the header names, each value replaced by `[REDACTED]`. A save that echoes the placeholder back keeps the stored value, and a placeholder with nothing stored behind it is dropped rather than sent. - Header names and values are checked as HTTP headers when settings are saved and before a chat or listing request is built, so a typo fails with an error naming the provider and the header (never the value) instead of an opaque request-builder error. - Every OpenAI-compatible cloud route now carries `User-Agent: openhuman/` unless the route sets its own (Codex OAuth) or the entry configures one. The `/models` discovery requests carry it as a header, since the registry's discovery request ignores its separate `user_agent` option. - An entry whose endpoint is OpenCode Go gets `x-opencode-session` derived from the turn origin the client is built for: a hash of the web chat thread id, the channel conversation key, or the automation job id, with one id per process for origins that name no conversation (CLI). Title generation and summarization resolve the same origin as the thread's turns, so they share its session. A configured `x-opencode-session` wins. Closes #7865 --- .../src/channels/routes_provider_tests.rs | 2 + .../src/channels/tests/runtime_tool_calls.rs | 1 + .../src/config/ops/cloud_providers.rs | 52 +++- .../src/config/ops/cloud_providers_tests.rs | 32 +++ .../src/config/ops/loader/snapshot.rs | 3 + crates/openhuman-core/src/config/ops/model.rs | 5 +- .../src/config/ops/model_byok_route.rs | 1 + .../src/config/ops/model_byok_tests.rs | 1 + .../src/config/ops/primary_cloud_tests.rs | 1 + .../config/ops_model_and_local_ai_tests.rs | 5 + .../src/config/ops_provider_headers_tests.rs | 181 +++++++++++++ crates/openhuman-core/src/config/ops_tests.rs | 2 + .../config/schema/cli_overrides/ops_tests.rs | 1 + .../src/config/schema/cloud_providers.rs | 58 ++++ .../config/schema/cloud_providers_tests.rs | 116 ++++++++ .../src/config/schema/ephemeral_route.rs | 1 + .../schema/load_managed_provider_tests.rs | 1 + .../src/config/schema/load_migration_tests.rs | 1 + .../config/schemas/controllers/inference.rs | 1 + .../src/config/schemas/helpers.rs | 5 + .../config/schemas/schema_defs/inference.rs | 2 +- .../src/doctor/checks/inference_catalog.rs | 1 + .../src/doctor/checks/inference_live_tests.rs | 1 + .../src/doctor/checks/inference_tests.rs | 4 + .../src/doctor/inference_auth_error_tests.rs | 1 + .../doctor/inference_catalog_test_support.rs | 1 + .../src/doctor/inference_catalog_tests.rs | 4 + .../src/doctor/inference_config_tests.rs | 2 + .../doctor/inference_model_catalog_tests.rs | 1 + .../openhuman-core/src/doctor/tools_tests.rs | 2 + .../src/inference/context_window.rs | 15 ++ .../src/inference/provider/factory.rs | 5 + .../inference/provider/factory/chat_model.rs | 1 + .../inference/provider/factory/cloud_slug.rs | 41 +-- .../provider/factory/request_identity.rs | 184 +++++++++++++ .../factory/request_identity_tests.rs | 251 ++++++++++++++++++ .../provider/factory_explicit_ctx_tests.rs | 1 + .../provider/factory_request_headers_tests.rs | 176 ++++++++++++ .../src/inference/provider/factory_tests.rs | 5 + .../provider/model_listing_test_support.rs | 2 + .../provider/models/catalog_listing.rs | 8 + .../models/catalog_listing_error_tests.rs | 1 + .../provider/models/catalog_listing_tests.rs | 90 +++++++ .../provider/models/local_runtime.rs | 1 + .../inference/provider/models/mod_tests.rs | 1 + .../src/inference/turn_models_native_tests.rs | 1 + .../inference/turn_models_summarizer_tests.rs | 1 + .../src/triage/routing_tests.rs | 1 + .../src/inference/tiers.rs | 1 + docs/TEST-COVERAGE-MATRIX.md | 1 + .../model-routing/local-and-byok-models.md | 18 ++ scripts/ci/process-statics.json | 10 + tests/raw_coverage/host_inference_http_e2e.rs | 1 + 53 files changed, 1285 insertions(+), 20 deletions(-) create mode 100644 crates/openhuman-core/src/config/ops_provider_headers_tests.rs create mode 100644 crates/openhuman-core/src/inference/provider/factory/request_identity.rs create mode 100644 crates/openhuman-core/src/inference/provider/factory/request_identity_tests.rs create mode 100644 crates/openhuman-core/src/inference/provider/factory_request_headers_tests.rs diff --git a/crates/openhuman-core/src/channels/routes_provider_tests.rs b/crates/openhuman-core/src/channels/routes_provider_tests.rs index 263f779ef7a..e1fab006562 100644 --- a/crates/openhuman-core/src/channels/routes_provider_tests.rs +++ b/crates/openhuman-core/src/channels/routes_provider_tests.rs @@ -25,6 +25,7 @@ async fn handle_runtime_command_routes_configured_provider_slug_and_alias() { endpoint: "https://provider.example.test/v1".into(), auth_style: AuthStyle::Bearer, default_model: None, + headers: Default::default(), }, CloudProviderCreds { id: "p_managed_123".into(), @@ -33,6 +34,7 @@ async fn handle_runtime_command_routes_configured_provider_slug_and_alias() { endpoint: "https://api.openhuman.ai/v1".into(), auth_style: AuthStyle::OpenhumanJwt, default_model: None, + headers: Default::default(), }, ]; ctx.config = Some(Arc::new(config)); diff --git a/crates/openhuman-core/src/channels/tests/runtime_tool_calls.rs b/crates/openhuman-core/src/channels/tests/runtime_tool_calls.rs index 7021e083a11..6dd6a6c0597 100644 --- a/crates/openhuman-core/src/channels/tests/runtime_tool_calls.rs +++ b/crates/openhuman-core/src/channels/tests/runtime_tool_calls.rs @@ -139,6 +139,7 @@ async fn process_channel_message_handles_models_command_without_llm_call() { Arc::make_mut(config) .cloud_providers .push(crate::config::schema::CloudProviderCreds { + headers: Default::default(), id: "p_managed_models_test".to_string(), slug: "openhuman".to_string(), label: "Managed Backend".to_string(), diff --git a/crates/openhuman-core/src/config/ops/cloud_providers.rs b/crates/openhuman-core/src/config/ops/cloud_providers.rs index a5882463d3f..28518213629 100644 --- a/crates/openhuman-core/src/config/ops/cloud_providers.rs +++ b/crates/openhuman-core/src/config/ops/cloud_providers.rs @@ -1,7 +1,8 @@ //! RPC input conversion for cloud-provider settings. use crate::config::schema::cloud_providers::{ - builtin_cloud_provider, generate_provider_id, is_slug_reserved, AuthStyle, CloudProviderCreds, + builtin_cloud_provider, generate_provider_id, is_slug_reserved, validate_provider_headers, + AuthStyle, CloudProviderCreds, REDACTED_HEADER_VALUE, }; use serde::Deserialize; @@ -16,6 +17,10 @@ pub struct CloudProviderUpdate { pub(crate) auth_style: Option, #[serde(default)] pub(crate) ca_cert_pem: Option, + /// Extra request headers for this provider (`{name: value}`). Omitted + /// (or empty) keeps the headers already stored for the entry. + #[serde(default)] + pub(crate) headers: Option>, // keep until v0.66 (review after 2027-01-11): incoming RPC discriminator // remains accepted until shipped-client parameter coverage exists. #[serde(rename = "type", default)] @@ -84,6 +89,8 @@ pub fn build_cloud_provider_creds( .label .filter(|value| !value.trim().is_empty()) .unwrap_or_else(|| slug.clone()); + let headers = entry.headers.unwrap_or_default(); + validate_provider_headers(&slug, &headers)?; Ok(CloudProviderCreds { id, @@ -92,11 +99,54 @@ pub fn build_cloud_provider_creds( endpoint, auth_style, default_model: entry.default_model, + headers, }) }) .collect() } +/// Settings-save merge for provider `headers` (#7865). An entry arriving +/// without `headers` keeps the ones stored for it (matched by id, else slug): +/// the settings panel echoes every entry back on save and has no editor for +/// headers, so a table set in `config.toml` must survive an unrelated edit. +/// Sending a non-empty map replaces them. A value equal to the redaction +/// placeholder the client snapshot shows ([`REDACTED_HEADER_VALUE`]) is an +/// echo of a stored secret, not a new value, so it keeps the stored one; with +/// nothing stored behind it the header is dropped rather than sent. +pub(crate) fn carry_stored_headers( + incoming: Vec, + stored: &[CloudProviderCreds], +) -> Vec { + incoming + .into_iter() + .map(|mut entry| { + let previous = stored + .iter() + .find(|e| e.id == entry.id) + .or_else(|| stored.iter().find(|e| e.slug == entry.slug)); + if entry.headers.is_empty() { + if let Some(previous) = previous { + entry.headers = previous.headers.clone(); + } + return entry; + } + entry.headers.retain(|name, value| { + if value != REDACTED_HEADER_VALUE { + return true; + } + match previous.and_then(|p| p.headers.get(name)) { + Some(stored_value) => { + *value = stored_value.clone(); + true + } + None => false, + } + }); + entry + }) + .collect() +} + #[cfg(test)] #[path = "cloud_providers_tests.rs"] mod tests; diff --git a/crates/openhuman-core/src/config/ops/cloud_providers_tests.rs b/crates/openhuman-core/src/config/ops/cloud_providers_tests.rs index e685f98343a..d3310d5cd51 100644 --- a/crates/openhuman-core/src/config/ops/cloud_providers_tests.rs +++ b/crates/openhuman-core/src/config/ops/cloud_providers_tests.rs @@ -8,6 +8,7 @@ fn update(slug: &str) -> CloudProviderUpdate { endpoint: String::new(), auth_style: None, ca_cert_pem: None, + headers: None, legacy_type: None, default_model: None, } @@ -107,3 +108,34 @@ fn builder_rejects_empty_slug() { "cloud provider slug must not be empty" ); } + +#[test] +fn builder_carries_headers_and_rejects_malformed_ones_naming_the_provider() { + let mut entry = update("gateway"); + entry.endpoint = "https://gateway.example/v1".to_string(); + entry.headers = Some([("x-tenant".to_string(), "team-a".to_string())].into()); + let providers = build_cloud_provider_creds(vec![entry]).expect("valid headers build"); + assert_eq!( + providers[0].headers.get("x-tenant").map(String::as_str), + Some("team-a") + ); + + let mut bad_name = update("gateway"); + bad_name.endpoint = "https://gateway.example/v1".to_string(); + bad_name.headers = Some([("x tenant".to_string(), "team-a".to_string())].into()); + let error = build_cloud_provider_creds(vec![bad_name]).expect_err("space in a name"); + assert!( + error.contains("'gateway'") && error.contains("'x tenant'"), + "{error}" + ); + + let mut bad_value = update("gateway"); + bad_value.endpoint = "https://gateway.example/v1".to_string(); + bad_value.headers = Some([("x-tenant".to_string(), "secret\nInjected: 1".to_string())].into()); + let error = build_cloud_provider_creds(vec![bad_value]).expect_err("newline in a value"); + assert!(error.contains("'x-tenant'"), "{error}"); + assert!( + !error.contains("secret"), + "the value never reaches the error: {error}" + ); +} diff --git a/crates/openhuman-core/src/config/ops/loader/snapshot.rs b/crates/openhuman-core/src/config/ops/loader/snapshot.rs index 054d1eddf64..e5ffa127340 100644 --- a/crates/openhuman-core/src/config/ops/loader/snapshot.rs +++ b/crates/openhuman-core/src/config/ops/loader/snapshot.rs @@ -237,6 +237,9 @@ pub async fn client_config_json(config: &Config) -> serde_json::Value { "endpoint": c.endpoint, "auth_style": c.auth_style.as_str(), "ca_cert_pem": config.cloud_provider_ca_certs.get(&c.slug), + // Names only: header values may be secrets and this snapshot + // goes to the UI. + "headers": crate::config::schema::cloud_providers::redacted_headers(&c.headers), }) }) .collect(); diff --git a/crates/openhuman-core/src/config/ops/model.rs b/crates/openhuman-core/src/config/ops/model.rs index a155aa6570e..d0d5f4b4148 100644 --- a/crates/openhuman-core/src/config/ops/model.rs +++ b/crates/openhuman-core/src/config/ops/model.rs @@ -188,7 +188,10 @@ pub async fn apply_model_settings( "[config] apply_model_settings: preserving {} reserved cloud provider(s) before overwrite", preserved.len() ); - config.cloud_providers = providers; + // Entries echoed back without `headers` (or with redacted values) + // keep the stored ones (#7865). + let stored = std::mem::take(&mut config.cloud_providers); + config.cloud_providers = super::cloud_providers::carry_stored_headers(providers, &stored); let before_reinject = config.cloud_providers.len(); for entry in preserved { let preserved_slug = entry.slug.trim(); diff --git a/crates/openhuman-core/src/config/ops/model_byok_route.rs b/crates/openhuman-core/src/config/ops/model_byok_route.rs index 7c45897e2e9..b22b5e73def 100644 --- a/crates/openhuman-core/src/config/ops/model_byok_route.rs +++ b/crates/openhuman-core/src/config/ops/model_byok_route.rs @@ -112,6 +112,7 @@ pub(super) fn complete_byok_route(config: &mut Config, explicit: &ExplicitRolePi endpoint: endpoint.clone(), auth_style: AuthStyle::Bearer, default_model: Some(model.clone()), + headers: Default::default(), }); BYOK_INFERENCE_SLUG.to_string() } diff --git a/crates/openhuman-core/src/config/ops/model_byok_tests.rs b/crates/openhuman-core/src/config/ops/model_byok_tests.rs index 4b203836374..1bbbc941f75 100644 --- a/crates/openhuman-core/src/config/ops/model_byok_tests.rs +++ b/crates/openhuman-core/src/config/ops/model_byok_tests.rs @@ -35,6 +35,7 @@ fn entry(slug: &str, endpoint: &str) -> CloudProviderCreds { label: slug.to_string(), endpoint: endpoint.to_string(), auth_style: AuthStyle::Bearer, + headers: Default::default(), default_model: None, } } diff --git a/crates/openhuman-core/src/config/ops/primary_cloud_tests.rs b/crates/openhuman-core/src/config/ops/primary_cloud_tests.rs index e09b12796aa..c5ee9bef415 100644 --- a/crates/openhuman-core/src/config/ops/primary_cloud_tests.rs +++ b/crates/openhuman-core/src/config/ops/primary_cloud_tests.rs @@ -12,6 +12,7 @@ fn register_test_hosted_policy() { fn provider(id: &str, slug: &str, endpoint: &str, auth_style: AuthStyle) -> CloudProviderCreds { CloudProviderCreds { + headers: Default::default(), id: id.to_string(), slug: slug.to_string(), label: slug.to_string(), diff --git a/crates/openhuman-core/src/config/ops_model_and_local_ai_tests.rs b/crates/openhuman-core/src/config/ops_model_and_local_ai_tests.rs index 9f0b3b24dbc..bb5f616f40c 100644 --- a/crates/openhuman-core/src/config/ops_model_and_local_ai_tests.rs +++ b/crates/openhuman-core/src/config/ops_model_and_local_ai_tests.rs @@ -213,6 +213,7 @@ async fn apply_model_settings_preserves_existing_reserved_slug_cloud_providers() label: "OpenHuman".into(), endpoint: "https://api.tinyhumans.ai".into(), auth_style: AuthStyle::OpenhumanJwt, + headers: Default::default(), default_model: Some("reasoning-v1".into()), }, CloudProviderCreds { @@ -221,6 +222,7 @@ async fn apply_model_settings_preserves_existing_reserved_slug_cloud_providers() label: "My OpenAI".into(), endpoint: "https://api.openai.com".into(), auth_style: AuthStyle::Bearer, + headers: Default::default(), default_model: Some("gpt-4o".into()), }, ]; @@ -236,6 +238,7 @@ async fn apply_model_settings_preserves_existing_reserved_slug_cloud_providers() label: "My OpenAI (edited)".into(), endpoint: "https://api.openai.com/v1".into(), auth_style: AuthStyle::Bearer, + headers: Default::default(), default_model: Some("gpt-4o-mini".into()), }]), ..Default::default() @@ -277,6 +280,7 @@ async fn apply_model_settings_does_not_double_add_reserved_entries() { label: "OpenHuman (stored)".into(), endpoint: "https://api.tinyhumans.ai".into(), auth_style: AuthStyle::OpenhumanJwt, + headers: Default::default(), default_model: Some("reasoning-v1".into()), }]; @@ -287,6 +291,7 @@ async fn apply_model_settings_does_not_double_add_reserved_entries() { label: "OpenHuman (from patch)".into(), endpoint: "https://api.tinyhumans.ai".into(), auth_style: AuthStyle::OpenhumanJwt, + headers: Default::default(), default_model: Some("reasoning-v1".into()), }]), ..Default::default() diff --git a/crates/openhuman-core/src/config/ops_provider_headers_tests.rs b/crates/openhuman-core/src/config/ops_provider_headers_tests.rs new file mode 100644 index 00000000000..5da3c06793d --- /dev/null +++ b/crates/openhuman-core/src/config/ops_provider_headers_tests.rs @@ -0,0 +1,181 @@ +use super::*; + +#[tokio::test] +async fn apply_model_settings_keeps_stored_provider_headers_when_the_patch_has_none() { + // #7865: the settings panel echoes every entry back without `headers` + // (it has no editor for them), so a table set in config.toml must survive + // an unrelated edit; a patch that sends headers replaces them. + use crate::config::schema::cloud_providers::{AuthStyle, CloudProviderCreds}; + + let tmp = tempdir().unwrap(); + let mut cfg = tmp_config(&tmp); + let stored_headers: std::collections::BTreeMap = + [("x-tenant".to_string(), "team-a".to_string())].into(); + cfg.cloud_providers = vec![CloudProviderCreds { + id: "gw-1".into(), + slug: "gateway".into(), + label: "Gateway".into(), + endpoint: "https://gateway.example/v1".into(), + auth_style: AuthStyle::Bearer, + headers: stored_headers.clone(), + default_model: None, + }]; + + let without_headers = |label: &str| CloudProviderCreds { + id: "gw-1".into(), + slug: "gateway".into(), + label: label.into(), + endpoint: "https://gateway.example/v1".into(), + auth_style: AuthStyle::Bearer, + ..Default::default() + }; + + let _ = apply_model_settings( + &mut cfg, + ModelSettingsPatch { + cloud_providers: Some(vec![without_headers("Gateway (renamed)")]), + ..Default::default() + }, + ) + .await + .expect("apply"); + let entry = &cfg.cloud_providers[0]; + assert_eq!(entry.label, "Gateway (renamed)"); + assert_eq!( + entry.headers, stored_headers, + "stored headers survive a save" + ); + + // Matched by slug when the id changed. + let mut re_identified = without_headers("Gateway (new id)"); + re_identified.id = "gw-2".into(); + let _ = apply_model_settings( + &mut cfg, + ModelSettingsPatch { + cloud_providers: Some(vec![re_identified]), + ..Default::default() + }, + ) + .await + .expect("apply"); + assert_eq!(cfg.cloud_providers[0].headers, stored_headers); + + // An explicit map replaces the stored one. + let replacement: std::collections::BTreeMap = + [("x-tenant".to_string(), "team-b".to_string())].into(); + let mut with_headers = without_headers("Gateway"); + with_headers.headers = replacement.clone(); + let _ = apply_model_settings( + &mut cfg, + ModelSettingsPatch { + cloud_providers: Some(vec![with_headers]), + ..Default::default() + }, + ) + .await + .expect("apply"); + assert_eq!(cfg.cloud_providers[0].headers, replacement); + + // A brand-new entry with no stored counterpart gets nothing. + let mut fresh = without_headers("Other"); + fresh.id = "other-1".into(); + fresh.slug = "other".into(); + let _ = apply_model_settings( + &mut cfg, + ModelSettingsPatch { + cloud_providers: Some(vec![fresh]), + ..Default::default() + }, + ) + .await + .expect("apply"); + assert_eq!(cfg.cloud_providers.len(), 1); + assert!(cfg.cloud_providers[0].headers.is_empty()); +} + +#[tokio::test] +async fn client_config_snapshot_shows_header_names_but_not_values() { + use crate::config::schema::cloud_providers::{ + AuthStyle, CloudProviderCreds, REDACTED_HEADER_VALUE, + }; + + let tmp = tempdir().unwrap(); + let mut cfg = tmp_config(&tmp); + cfg.cloud_providers = vec![CloudProviderCreds { + id: "gw-1".into(), + slug: "gateway".into(), + label: "Gateway".into(), + endpoint: "https://gateway.example/v1".into(), + auth_style: AuthStyle::Bearer, + headers: [("x-api-secret".to_string(), "sk-live-123".to_string())].into(), + default_model: None, + }]; + + let snapshot = crate::config::ops::client_config_json(&cfg).await; + let rendered = snapshot.to_string(); + assert!(!rendered.contains("sk-live-123"), "{rendered}"); + let entry = snapshot["cloud_providers"] + .as_array() + .and_then(|entries| entries.iter().find(|e| e["slug"] == "gateway")) + .expect("gateway entry in the snapshot"); + assert_eq!(entry["headers"]["x-api-secret"], REDACTED_HEADER_VALUE); +} + +#[tokio::test] +async fn apply_model_settings_restores_stored_values_for_echoed_placeholders() { + use crate::config::schema::cloud_providers::{ + AuthStyle, CloudProviderCreds, REDACTED_HEADER_VALUE, + }; + + let tmp = tempdir().unwrap(); + let mut cfg = tmp_config(&tmp); + cfg.cloud_providers = vec![CloudProviderCreds { + id: "gw-1".into(), + slug: "gateway".into(), + label: "Gateway".into(), + endpoint: "https://gateway.example/v1".into(), + auth_style: AuthStyle::Bearer, + headers: [("x-api-secret".to_string(), "sk-live-123".to_string())].into(), + default_model: None, + }]; + + // A client that echoes the redacted snapshot back, adding one header and + // inventing a placeholder for a header that was never stored. + let echoed = CloudProviderCreds { + id: "gw-1".into(), + slug: "gateway".into(), + label: "Gateway".into(), + endpoint: "https://gateway.example/v1".into(), + auth_style: AuthStyle::Bearer, + headers: [ + ( + "x-api-secret".to_string(), + REDACTED_HEADER_VALUE.to_string(), + ), + ("x-tenant".to_string(), "team-a".to_string()), + ("x-unknown".to_string(), REDACTED_HEADER_VALUE.to_string()), + ] + .into(), + default_model: None, + }; + let _ = apply_model_settings( + &mut cfg, + ModelSettingsPatch { + cloud_providers: Some(vec![echoed]), + ..Default::default() + }, + ) + .await + .expect("apply"); + + let headers = &cfg.cloud_providers[0].headers; + assert_eq!( + headers.get("x-api-secret").map(String::as_str), + Some("sk-live-123") + ); + assert_eq!(headers.get("x-tenant").map(String::as_str), Some("team-a")); + assert!( + !headers.contains_key("x-unknown"), + "a placeholder with nothing stored is dropped, never sent" + ); +} diff --git a/crates/openhuman-core/src/config/ops_tests.rs b/crates/openhuman-core/src/config/ops_tests.rs index bf7a73285bb..9b1c98bb8b4 100644 --- a/crates/openhuman-core/src/config/ops_tests.rs +++ b/crates/openhuman-core/src/config/ops_tests.rs @@ -62,5 +62,7 @@ mod loader_and_search_tests; mod model_and_local_ai_tests; #[path = "ops_provider_ca_tests.rs"] mod provider_ca_tests; +#[path = "ops_provider_headers_tests.rs"] +mod provider_headers_tests; #[path = "ops_voice_and_autonomy_tests.rs"] mod voice_and_autonomy_tests; diff --git a/crates/openhuman-core/src/config/schema/cli_overrides/ops_tests.rs b/crates/openhuman-core/src/config/schema/cli_overrides/ops_tests.rs index 88bcc027946..3e43784a12b 100644 --- a/crates/openhuman-core/src/config/schema/cli_overrides/ops_tests.rs +++ b/crates/openhuman-core/src/config/schema/cli_overrides/ops_tests.rs @@ -9,6 +9,7 @@ fn provider() -> CloudProviderCreds { label: "OpenAI work".into(), endpoint: "https://api.openai.com/v1".into(), auth_style: AuthStyle::Bearer, + headers: Default::default(), default_model: Some("gpt-default".into()), } } diff --git a/crates/openhuman-core/src/config/schema/cloud_providers.rs b/crates/openhuman-core/src/config/schema/cloud_providers.rs index 4841f28f71f..b71cbd4e490 100644 --- a/crates/openhuman-core/src/config/schema/cloud_providers.rs +++ b/crates/openhuman-core/src/config/schema/cloud_providers.rs @@ -13,6 +13,7 @@ use serde::{Deserialize, Serialize}; use crate::config::Config; +use std::collections::BTreeMap; use std::sync::Arc; use crate::core::slots::HookSlot; @@ -69,6 +70,7 @@ fn seed_legacy_custom_provider(config: &mut Config, stats: &mut MigrationStats) endpoint: trimmed.to_string(), auth_style: AuthStyle::Bearer, default_model, + headers: Default::default(), }); stats.cloud_providers_seeded += 1; log::info!( @@ -341,6 +343,29 @@ pub struct CloudProviderCreds { // inference settings RPC depend on this field; replacement needs route migration. #[serde(default, skip_serializing_if = "Option::is_none")] pub default_model: Option, + + /// Extra HTTP headers sent on every request to this provider (chat, + /// completions and model listing), on top of the auth headers + /// [`auth_style`](Self::auth_style) adds. The way to satisfy a provider + /// that requires a header the auth style does not cover, without waiting + /// for a release: + /// + /// ```toml + /// [[cloud_providers]] + /// slug = "my-gateway" + /// endpoint = "https://gateway.example/v1" + /// auth_style = "bearer" + /// + /// [cloud_providers.headers] + /// x-tenant = "team-a" + /// ``` + /// + /// Names are matched case-insensitively against the headers OpenHuman adds + /// itself (`User-Agent`, `x-opencode-session`), and a configured value + /// replaces the built-in one. Values are sent verbatim and may be secrets, + /// so they never reach `info`-level logs. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub headers: BTreeMap, } impl Default for CloudProviderCreds { @@ -352,10 +377,43 @@ impl Default for CloudProviderCreds { endpoint: String::new(), auth_style: AuthStyle::Bearer, default_model: None, + headers: BTreeMap::new(), } } } +/// What a client-facing config snapshot shows in place of a configured +/// header value. Header values may be secrets, so only their names leave the +/// core; a settings save that echoes this placeholder back keeps the stored +/// value (see `config::ops::apply_model_settings`). +pub const REDACTED_HEADER_VALUE: &str = "[REDACTED]"; + +/// `headers` with every value replaced by [`REDACTED_HEADER_VALUE`]. +pub fn redacted_headers(headers: &BTreeMap) -> BTreeMap { + headers + .keys() + .map(|name| (name.clone(), REDACTED_HEADER_VALUE.to_string())) + .collect() +} + +/// Checks that every configured header on the provider `slug` is a valid +/// HTTP header name and value, so a typo in `config.toml` or a settings save +/// fails with an error that names the provider and the header instead of an +/// opaque request-builder error on every call. The value itself is never part +/// of the error: it may be a secret. +pub fn validate_provider_headers( + slug: &str, + headers: &BTreeMap, +) -> Result<(), String> { + for (name, value) in headers { + reqwest::header::HeaderName::from_bytes(name.as_bytes()) + .map_err(|_| format!("cloud provider '{slug}': invalid header name '{name}'"))?; + reqwest::header::HeaderValue::from_str(value) + .map_err(|_| format!("cloud provider '{slug}': invalid value for header '{name}'"))?; + } + Ok(()) +} + /// Reserved slugs that may not be used for user-configured providers. /// These are sentinels in the factory's routing grammar. /// diff --git a/crates/openhuman-core/src/config/schema/cloud_providers_tests.rs b/crates/openhuman-core/src/config/schema/cloud_providers_tests.rs index 346b4a76037..8db40796341 100644 --- a/crates/openhuman-core/src/config/schema/cloud_providers_tests.rs +++ b/crates/openhuman-core/src/config/schema/cloud_providers_tests.rs @@ -380,3 +380,119 @@ fn builtin_table_is_only_the_upstream_provider_catalog() { assert_eq!(mapped.auth_style, expected, "{}", mapped.slug); } } + +#[test] +fn cloud_provider_headers_table_round_trips_through_toml() { + use super::CloudProviderCreds; + + let entry: CloudProviderCreds = toml::from_str( + r#" +id = "p_opencode" +slug = "opencode-go" +label = "OpenCode Go" +endpoint = "https://opencode.ai/zen/go/v1" +auth_style = "bearer" + +[headers] +x-opencode-session = "ses_fixed" +X-Title = "openhuman" +"#, + ) + .expect("headers table parses"); + assert_eq!(entry.headers.len(), 2); + assert_eq!( + entry.headers.get("x-opencode-session").map(String::as_str), + Some("ses_fixed") + ); + assert_eq!( + entry.headers.get("X-Title").map(String::as_str), + Some("openhuman") + ); + + let rendered = toml::to_string(&entry).expect("serializes"); + assert!(rendered.contains("[headers]"), "{rendered}"); + let back: CloudProviderCreds = toml::from_str(&rendered).expect("re-parses"); + assert_eq!(back, entry); +} + +#[test] +fn cloud_provider_headers_default_to_empty_and_are_omitted_when_empty() { + use super::CloudProviderCreds; + + let entry: CloudProviderCreds = toml::from_str( + r#" +id = "p_plain" +slug = "plain" +label = "Plain" +endpoint = "https://api.example/v1" +auth_style = "bearer" +"#, + ) + .expect("entry without headers parses"); + assert!(entry.headers.is_empty()); + assert!(CloudProviderCreds::default().headers.is_empty()); + + let rendered = toml::to_string(&entry).expect("serializes"); + assert!( + !rendered.contains("headers"), + "an empty table must not be written: {rendered}" + ); + + let rejected = toml::from_str::( + r#" +slug = "bad" +endpoint = "https://api.example/v1" +headers = "not-a-table" +"#, + ); + assert!(rejected.is_err(), "a non-table `headers` value is rejected"); +} + +#[test] +fn validate_provider_headers_names_the_provider_and_header_but_not_the_value() { + use super::validate_provider_headers; + use std::collections::BTreeMap; + + let ok: BTreeMap = [ + ("x-tenant".to_string(), "team-a".to_string()), + ("User-Agent".to_string(), "my-agent/1.0".to_string()), + ] + .into(); + assert_eq!(validate_provider_headers("gw", &ok), Ok(())); + assert_eq!(validate_provider_headers("gw", &BTreeMap::new()), Ok(())); + + let bad_name: BTreeMap = [("x tenant".to_string(), "v".to_string())].into(); + assert_eq!( + validate_provider_headers("gw", &bad_name), + Err("cloud provider 'gw': invalid header name 'x tenant'".to_string()) + ); + + let bad_value: BTreeMap = + [("x-key".to_string(), "sk-secret\r\nx: y".to_string())].into(); + let error = validate_provider_headers("gw", &bad_value).expect_err("CRLF in a value"); + assert_eq!( + error, + "cloud provider 'gw': invalid value for header 'x-key'" + ); + assert!(!error.contains("sk-secret")); +} + +#[test] +fn redacted_headers_keep_names_and_hide_every_value() { + use super::{redacted_headers, REDACTED_HEADER_VALUE}; + use std::collections::BTreeMap; + + let headers: BTreeMap = [ + ("x-api-secret".to_string(), "sk-123".to_string()), + ("x-tenant".to_string(), "team-a".to_string()), + ] + .into(); + let redacted = redacted_headers(&headers); + assert_eq!( + redacted.keys().collect::>(), + headers.keys().collect::>() + ); + assert!(redacted + .values() + .all(|value| value == REDACTED_HEADER_VALUE)); +} diff --git a/crates/openhuman-core/src/config/schema/ephemeral_route.rs b/crates/openhuman-core/src/config/schema/ephemeral_route.rs index 21962090a01..fb80d7e36ad 100644 --- a/crates/openhuman-core/src/config/schema/ephemeral_route.rs +++ b/crates/openhuman-core/src/config/schema/ephemeral_route.rs @@ -201,6 +201,7 @@ pub fn apply(config: &mut crate::config::Config, route: EphemeralRoute) { label: "Per-call route".to_string(), endpoint: route.endpoint.clone(), auth_style: AuthStyle::Bearer, + headers: Default::default(), default_model: Some(model.clone()), }); diff --git a/crates/openhuman-core/src/config/schema/load_managed_provider_tests.rs b/crates/openhuman-core/src/config/schema/load_managed_provider_tests.rs index 80a1bda5c81..cc03fa2170d 100644 --- a/crates/openhuman-core/src/config/schema/load_managed_provider_tests.rs +++ b/crates/openhuman-core/src/config/schema/load_managed_provider_tests.rs @@ -15,6 +15,7 @@ async fn a_brand_new_workspace_persists_and_reopens_generic_config() { config .cloud_providers .push(crate::config::schema::CloudProviderCreds { + headers: Default::default(), id: "fixture-provider-id".to_string(), slug: "fixture-provider".to_string(), label: "Fixture Provider".to_string(), diff --git a/crates/openhuman-core/src/config/schema/load_migration_tests.rs b/crates/openhuman-core/src/config/schema/load_migration_tests.rs index 83a982d94b8..2a500fe0b87 100644 --- a/crates/openhuman-core/src/config/schema/load_migration_tests.rs +++ b/crates/openhuman-core/src/config/schema/load_migration_tests.rs @@ -385,6 +385,7 @@ fn migrate_cloud_provider_slugs_routes_cloud_to_legacy_custom_when_primary_is_op label: "Custom".into(), endpoint: "https://api.example.com/v1/".into(), auth_style: crate::config::schema::AuthStyle::Bearer, + headers: Default::default(), default_model: Some("gpt-4o-mini".into()), }, ]; diff --git a/crates/openhuman-core/src/config/schemas/controllers/inference.rs b/crates/openhuman-core/src/config/schemas/controllers/inference.rs index d94181acbc0..dc4964f923c 100644 --- a/crates/openhuman-core/src/config/schemas/controllers/inference.rs +++ b/crates/openhuman-core/src/config/schemas/controllers/inference.rs @@ -151,6 +151,7 @@ pub(super) fn handle_update_model_settings( label, endpoint, auth_style, + headers: e.headers.unwrap_or_default(), default_model: e.default_model, }; Ok(entry) diff --git a/crates/openhuman-core/src/config/schemas/helpers.rs b/crates/openhuman-core/src/config/schemas/helpers.rs index c8caa55c922..18e9c4a4833 100644 --- a/crates/openhuman-core/src/config/schemas/helpers.rs +++ b/crates/openhuman-core/src/config/schemas/helpers.rs @@ -28,6 +28,11 @@ pub(super) struct CloudProviderUpdate { /// Optional PEM CA bundle for this provider. Empty string removes it. #[serde(default)] pub(super) ca_cert_pem: Option, + /// Extra request headers for this provider (`{name: value}`). Omitted + /// (or empty) keeps the headers already stored for the entry, so a client + /// that does not know the field cannot drop them on save. + #[serde(default)] + pub(super) headers: Option>, /// Legacy field — tolerated on read for back-compat but not required. // keep until v0.66 (review after 2027-01-11): incoming RPC discriminator // remains accepted until shipped-client parameter coverage exists. diff --git a/crates/openhuman-core/src/config/schemas/schema_defs/inference.rs b/crates/openhuman-core/src/config/schemas/schema_defs/inference.rs index d12c8e4bc8b..736e83f1508 100644 --- a/crates/openhuman-core/src/config/schemas/schema_defs/inference.rs +++ b/crates/openhuman-core/src/config/schemas/schema_defs/inference.rs @@ -96,7 +96,7 @@ pub(super) fn lookup(function: &str) -> Option { FieldSchema { name: "cloud_providers", ty: TypeSchema::Option(Box::new(TypeSchema::Json)), - comment: "Optional list of cloud provider entries {id, slug, label, endpoint, auth_style, ca_cert_pem}. The optional PEM CA bundle is trusted only for this provider; an empty string clears it. API keys are stored separately via cloud_provider_set_key. Replaces config.cloud_providers wholesale.", + comment: "Optional list of cloud provider entries {id, slug, label, endpoint, auth_style, ca_cert_pem, headers}. The optional PEM CA bundle is trusted only for this provider; an empty string clears it. `headers` is an optional {name: value} map of extra request headers sent on every request to this provider; omitting it keeps the entry's stored headers. API keys are stored separately via cloud_provider_set_key. Replaces config.cloud_providers wholesale.", required: false, }, optional_string( diff --git a/crates/openhuman-core/src/doctor/checks/inference_catalog.rs b/crates/openhuman-core/src/doctor/checks/inference_catalog.rs index abe93ac581f..8c941a672ef 100644 --- a/crates/openhuman-core/src/doctor/checks/inference_catalog.rs +++ b/crates/openhuman-core/src/doctor/checks/inference_catalog.rs @@ -62,6 +62,7 @@ fn configured_entries(config: &crate::config::Config) -> Vec && !entries.iter().any(|entry| entry.slug == "openhuman") { entries.push(CloudProviderCreds { + headers: Default::default(), id: "openhuman".into(), slug: "openhuman".into(), label: "OpenHuman".into(), diff --git a/crates/openhuman-core/src/doctor/checks/inference_live_tests.rs b/crates/openhuman-core/src/doctor/checks/inference_live_tests.rs index a568c544937..43d699dcc28 100644 --- a/crates/openhuman-core/src/doctor/checks/inference_live_tests.rs +++ b/crates/openhuman-core/src/doctor/checks/inference_live_tests.rs @@ -63,6 +63,7 @@ fn config_for(server: &MockServer, model: &str) -> Fixture { fn add_cloud_provider(config: &mut Config, slug: &str, endpoint: &str, model: &str) { config.cloud_providers.push(CloudProviderCreds { + headers: Default::default(), id: format!("provider-id-{slug}"), slug: slug.to_string(), label: "Doctor test provider".to_string(), diff --git a/crates/openhuman-core/src/doctor/checks/inference_tests.rs b/crates/openhuman-core/src/doctor/checks/inference_tests.rs index 333153a25ae..43e81021088 100644 --- a/crates/openhuman-core/src/doctor/checks/inference_tests.rs +++ b/crates/openhuman-core/src/doctor/checks/inference_tests.rs @@ -197,6 +197,7 @@ async fn a_byok_cloud_fallback_without_a_key_reports_construction_failure() { config.chat_provider = Some("ollama:qwen2.5".to_owned()); config.primary_cloud = Some("provider-doctor-test".to_owned()); config.cloud_providers = vec![CloudProviderCreds { + headers: Default::default(), id: "provider-doctor-test".to_owned(), slug: "doctor-test".to_owned(), label: "Doctor test provider".to_owned(), @@ -321,6 +322,7 @@ async fn inspection_reports_refresh_required_without_refreshing_or_publishing_se config.vision_provider = Some("openai:gpt-4o".to_owned()); config.primary_cloud = Some("provider-openai".to_owned()); config.cloud_providers = vec![CloudProviderCreds { + headers: Default::default(), id: "provider-openai".to_owned(), slug: "openai".to_owned(), label: "OpenAI".to_owned(), @@ -503,6 +505,7 @@ async fn a_fully_configured_managed_default_constructs_cleanly() { config.api_key = Some("doctor-test-session-token".to_owned()); config.primary_cloud = Some("provider-openhuman".to_owned()); config.cloud_providers = vec![CloudProviderCreds { + headers: Default::default(), id: "provider-openhuman".to_owned(), slug: "openhuman".to_owned(), label: "OpenHuman".to_owned(), @@ -552,6 +555,7 @@ async fn missing_byok_model_is_reported_by_the_native_construct_check() { config.vision_provider = None; config.memory_provider = None; config.cloud_providers = vec![CloudProviderCreds { + headers: Default::default(), id: "doctor-empty-model-provider".to_owned(), slug: "doctor-empty-model".to_owned(), label: "Empty model fixture".to_owned(), diff --git a/crates/openhuman-core/src/doctor/inference_auth_error_tests.rs b/crates/openhuman-core/src/doctor/inference_auth_error_tests.rs index 77b218e0f71..7476befaccd 100644 --- a/crates/openhuman-core/src/doctor/inference_auth_error_tests.rs +++ b/crates/openhuman-core/src/doctor/inference_auth_error_tests.rs @@ -108,6 +108,7 @@ fn config_for_catalog( let (root, mut config) = temporary_config(); config.secrets.encrypt = false; config.cloud_providers = vec![CloudProviderCreds { + headers: Default::default(), id: provider_id.to_owned(), slug: slug.to_owned(), label: "Doctor catalog fixture".to_owned(), diff --git a/crates/openhuman-core/src/doctor/inference_catalog_test_support.rs b/crates/openhuman-core/src/doctor/inference_catalog_test_support.rs index 89b2fb998e7..a475ce69b6c 100644 --- a/crates/openhuman-core/src/doctor/inference_catalog_test_support.rs +++ b/crates/openhuman-core/src/doctor/inference_catalog_test_support.rs @@ -113,6 +113,7 @@ pub(super) fn config_for_catalog( let (root, mut config) = temporary_config(); config.secrets.encrypt = false; config.cloud_providers = vec![CloudProviderCreds { + headers: Default::default(), id: provider_id.to_owned(), slug: slug.to_owned(), label: "Doctor catalog fixture".to_owned(), diff --git a/crates/openhuman-core/src/doctor/inference_catalog_tests.rs b/crates/openhuman-core/src/doctor/inference_catalog_tests.rs index b18043fe8a9..cfd23a4c9ec 100644 --- a/crates/openhuman-core/src/doctor/inference_catalog_tests.rs +++ b/crates/openhuman-core/src/doctor/inference_catalog_tests.rs @@ -113,6 +113,7 @@ fn config_for_catalog( let (root, mut config) = temporary_config(); config.secrets.encrypt = false; config.cloud_providers = vec![CloudProviderCreds { + headers: Default::default(), id: provider_id.to_owned(), slug: slug.to_owned(), label: "Doctor catalog fixture".to_owned(), @@ -410,6 +411,7 @@ async fn prepared_catalog_identity_changes_when_managed_credential_rotates_in_pl let (_temp, mut config_a) = temporary_config(); config_a.api_key = Some("fixture-managed-credential-a".into()); config_a.cloud_providers = vec![CloudProviderCreds { + headers: Default::default(), id: "openhuman".into(), slug: "openhuman".into(), label: "Managed catalog fixture".into(), @@ -473,6 +475,7 @@ async fn a_slow_provider_times_out_without_blocking_the_other_catalog() { let (_temp, mut config) = temporary_config(); config.cloud_providers = vec![ CloudProviderCreds { + headers: Default::default(), id: "p_doctor_497_slow".into(), slug: "doctor-497-slow".into(), label: "Slow catalog fixture".into(), @@ -481,6 +484,7 @@ async fn a_slow_provider_times_out_without_blocking_the_other_catalog() { default_model: None, }, CloudProviderCreds { + headers: Default::default(), id: "p_doctor_497_fast".into(), slug: "doctor-497-fast".into(), label: "Fast catalog fixture".into(), diff --git a/crates/openhuman-core/src/doctor/inference_config_tests.rs b/crates/openhuman-core/src/doctor/inference_config_tests.rs index c8a41016e41..22736869f20 100644 --- a/crates/openhuman-core/src/doctor/inference_config_tests.rs +++ b/crates/openhuman-core/src/doctor/inference_config_tests.rs @@ -112,6 +112,7 @@ async fn a_byok_cloud_fallback_without_a_key_reports_construction_failure() { config.chat_provider = Some("ollama:qwen2.5".to_owned()); config.primary_cloud = Some("provider-doctor-test".to_owned()); config.cloud_providers = vec![CloudProviderCreds { + headers: Default::default(), id: "provider-doctor-test".to_owned(), slug: "doctor-test".to_owned(), label: "Doctor test provider".to_owned(), @@ -242,6 +243,7 @@ async fn a_fully_configured_managed_default_constructs_cleanly() { config.api_key = Some("doctor-test-session-token".to_owned()); config.primary_cloud = Some("provider-openhuman".to_owned()); config.cloud_providers = vec![CloudProviderCreds { + headers: Default::default(), id: "provider-openhuman".to_owned(), slug: "openhuman".to_owned(), label: "OpenHuman".to_owned(), diff --git a/crates/openhuman-core/src/doctor/inference_model_catalog_tests.rs b/crates/openhuman-core/src/doctor/inference_model_catalog_tests.rs index 01b41a718e2..3343d1819bb 100644 --- a/crates/openhuman-core/src/doctor/inference_model_catalog_tests.rs +++ b/crates/openhuman-core/src/doctor/inference_model_catalog_tests.rs @@ -114,6 +114,7 @@ fn config_for_catalog( let (root, mut config) = temporary_config(); config.secrets.encrypt = false; config.cloud_providers = vec![CloudProviderCreds { + headers: Default::default(), id: provider_id.to_owned(), slug: slug.to_owned(), label: "Doctor catalog fixture".to_owned(), diff --git a/crates/openhuman-core/src/doctor/tools_tests.rs b/crates/openhuman-core/src/doctor/tools_tests.rs index a761e4c28f1..8d7936ee38e 100644 --- a/crates/openhuman-core/src/doctor/tools_tests.rs +++ b/crates/openhuman-core/src/doctor/tools_tests.rs @@ -196,6 +196,7 @@ async fn models_tool_reports_each_configured_catalog_outcome() { config.model_routes.clear(); config.cloud_providers = vec![ crate::config::schema::cloud_providers::CloudProviderCreds { + headers: Default::default(), id: "p_doctor_tool_models_available".into(), slug: "doctor-tool-models-available".into(), label: "Available test provider".into(), @@ -204,6 +205,7 @@ async fn models_tool_reports_each_configured_catalog_outcome() { default_model: None, }, crate::config::schema::cloud_providers::CloudProviderCreds { + headers: Default::default(), id: "p_doctor_tool_models_missing".into(), slug: "doctor-tool-models-missing".into(), label: "Missing test provider".into(), diff --git a/crates/openhuman-core/src/inference/context_window.rs b/crates/openhuman-core/src/inference/context_window.rs index cb21efdf945..f47096b36f3 100644 --- a/crates/openhuman-core/src/inference/context_window.rs +++ b/crates/openhuman-core/src/inference/context_window.rs @@ -308,8 +308,23 @@ pub(crate) async fn model_limits_request_for( resolution.entry, &resolution.effective_model, ); + // The entry's configured headers (#7865) and the product `User-Agent` + // ride the `/models` lookup too: a gateway that requires them on chat + // usually requires them on the listing as well. + let extra_headers = + match crate::inference::provider::factory::request_identity::catalog_request_headers( + resolution.entry, + None, + ) { + Ok(headers) => headers, + Err(error) => { + log::warn!("[model_limits] skipping window discovery: {error}"); + return None; + } + }; let options = ProviderBuildOptions { auth_style: Some(resolution.entry.auth_style.into()), + extra_headers: &extra_headers, codex: Some(&resolution.codex), ..ProviderBuildOptions::default() }; diff --git a/crates/openhuman-core/src/inference/provider/factory.rs b/crates/openhuman-core/src/inference/provider/factory.rs index 5745824cbd9..057b5d06a7e 100644 --- a/crates/openhuman-core/src/inference/provider/factory.rs +++ b/crates/openhuman-core/src/inference/provider/factory.rs @@ -19,6 +19,7 @@ mod credentials; mod inspection; mod local_runtime; mod managed_backend; +pub(crate) mod request_identity; mod routing; mod subprocess_providers; @@ -68,6 +69,10 @@ pub mod test_provider_override; #[path = "factory_tests.rs"] mod factory_tests; +#[cfg(test)] +#[path = "factory_request_headers_tests.rs"] +mod factory_request_headers_tests; + use crate::config::schema::cloud_providers::AuthStyle; use crate::config::Config; use crate::security::egress::EgressLedger; diff --git a/crates/openhuman-core/src/inference/provider/factory/chat_model.rs b/crates/openhuman-core/src/inference/provider/factory/chat_model.rs index 1467780ac10..95ca9f71156 100644 --- a/crates/openhuman-core/src/inference/provider/factory/chat_model.rs +++ b/crates/openhuman-core/src/inference/provider/factory/chat_model.rs @@ -285,6 +285,7 @@ impl OpenHumanModelFactory<'_> { request.opts.native_tools, self.egress, context_extensions, + self.ctx.turn_origin_or_scoped().as_ref(), CredentialAccess::Runtime(&self.credentials), None, None, diff --git a/crates/openhuman-core/src/inference/provider/factory/cloud_slug.rs b/crates/openhuman-core/src/inference/provider/factory/cloud_slug.rs index 9d9700e1af8..2d08e3ab9e1 100644 --- a/crates/openhuman-core/src/inference/provider/factory/cloud_slug.rs +++ b/crates/openhuman-core/src/inference/provider/factory/cloud_slug.rs @@ -1,6 +1,7 @@ //! `:` BYOK cloud providers: shared slug resolution (model fallback, //! abstract-tier remapping, credentials, codex routing) and the crate-native builders. +use super::request_identity::{apply_request_identity, route_headers}; use super::{ access_gates::enforce_local_only_inference, cloud_spec, @@ -14,6 +15,7 @@ use super::{ use crate::config::ops::resolve_primary_cloud_provider_string; use crate::config::schema::cloud_providers::AuthStyle; use crate::config::Config; +use crate::core::runtime::turn_origin::AgentTurnOrigin; use crate::inference::provider::fallback_diagnostics; use crate::inference::provider::openai_codex::resolve_openai_codex_routing_for_inspection; use crate::security::egress::EgressLedger; @@ -379,6 +381,7 @@ pub(super) async fn try_create_cloud_slug_chat_model_for_inspection_with_identit true, &EgressLedger::none(), extensions, + None, CredentialAccess::Inspection, inspection_credential.as_ref(), Some(&mut identity), @@ -420,6 +423,7 @@ pub(super) async fn try_create_cloud_slug_chat_model_with_native_tools_and_acces native_tool_calling, egress, extensions, + crate::core::runtime::CoreContext::current_turn_origin().as_ref(), credential_access, inspection_credential, inspection_identity, @@ -454,6 +458,7 @@ pub(super) async fn try_create_cloud_slug_chat_model_from_string_with_native_too native_tool_calling, egress, extensions.as_ref(), + crate::core::runtime::CoreContext::current_turn_origin().as_ref(), CredentialAccess::Runtime(&RuntimeCredentialSnapshot::default()), None, None, @@ -476,6 +481,7 @@ pub(super) async fn try_create_cloud_slug_chat_model_from_string_with_native_too native_tool_calling, egress, extensions, + None, CredentialAccess::Runtime(&RuntimeCredentialSnapshot::default()), None, None, @@ -490,6 +496,7 @@ pub(super) async fn try_create_cloud_slug_chat_model_from_string_with_native_too native_tool_calling: bool, egress: &EgressLedger, extensions: Option<&crate::core::slots::Extensions>, + turn_origin: Option<&AgentTurnOrigin>, credential_access: CredentialAccess<'_>, inspection_credential: Option<&super::credentials::ReadOnlyCloudCredential>, mut inspection_identity: Option< @@ -555,23 +562,15 @@ pub(super) async fn try_create_cloud_slug_chat_model_from_string_with_native_too // model; Codex OAuth routes to the Responses API with its headers / UA / // query; every other Bearer/Anthropic/None slug uses Chat Completions (or // the Anthropic Messages adapter for a first-party native-tools endpoint). - let mut extra_headers: Vec<(String, String)> = config - .ephemeral_route - .as_ref() - .filter(|route| { - slug == crate::config::schema::ephemeral_route::EPHEMERAL_ROUTE_SLUG - && route.endpoint == entry.endpoint - }) - .map(|route| route.headers.clone()) - .unwrap_or_default(); - let default_provider_options = config - .ephemeral_route - .as_ref() - .filter(|route| { - slug == crate::config::schema::ephemeral_route::EPHEMERAL_ROUTE_SLUG - && route.endpoint == entry.endpoint - }) - .and_then(|route| route.provider_options.clone()); + let ephemeral_route = config.ephemeral_route.as_ref().filter(|route| { + slug == crate::config::schema::ephemeral_route::EPHEMERAL_ROUTE_SLUG + && route.endpoint == entry.endpoint + }); + let mut extra_headers = match route_headers(entry, ephemeral_route) { + Ok(headers) => headers, + Err(error) => return Some(Err(anyhow::anyhow!(error))), + }; + let default_provider_options = ephemeral_route.and_then(|route| route.provider_options.clone()); let mut extra_query_params: Vec<(String, String)> = Vec::new(); let mut user_agent: Option = None; let mut codex_route: Option<&tinyinference_llm::providers::openai::codex::OpenAiCodexRouting> = @@ -673,6 +672,14 @@ pub(super) async fn try_create_cloud_slug_chat_model_from_string_with_native_too } } + // `User-Agent` and the OpenCode Go session (#7865); configured headers win. + apply_request_identity( + &entry.endpoint, + turn_origin, + &mut extra_headers, + &mut user_agent, + ); + // Egress spine (privacy epic S2, #4436): committed to a BYOK cloud slug here // — past the managed/bespoke returns and the access // gates, so this constructs. Disclose as external. Single cloud chokepoint diff --git a/crates/openhuman-core/src/inference/provider/factory/request_identity.rs b/crates/openhuman-core/src/inference/provider/factory/request_identity.rs new file mode 100644 index 00000000000..107e2fe1cfa --- /dev/null +++ b/crates/openhuman-core/src/inference/provider/factory/request_identity.rs @@ -0,0 +1,184 @@ +//! What a BYOK cloud request says about who is calling: the product +//! `User-Agent` every OpenAI-compatible route carries, and the per-conversation +//! session id that OpenCode Go requires (#7865). +//! +//! OpenCode Go (`https://opencode.ai/zen/go/v1`) rejects every chat request +//! that lacks an `x-opencode-session` header with HTTP 400 `MissingSessionID`, +//! and asks clients to identify themselves with a product user agent rather +//! than an HTTP library's. The id only has to be opaque and stable for one +//! conversation — it drives prompt-cache routing on their side — so it is +//! derived from the turn origin the factory already runs under: the chat +//! thread, the channel conversation, or the automation job. Auxiliary calls +//! made for the same thread (title generation, summarization) resolve the same +//! origin and therefore the same id. + +use std::sync::LazyLock; + +use sha2::{Digest, Sha256}; + +use crate::core::runtime::turn_origin::AgentTurnOrigin; +use tinyinference_providers::builtin::endpoint_host; + +/// The header OpenCode Go routes conversations by. +pub const OPENCODE_SESSION_HEADER: &str = "x-opencode-session"; + +/// The `User-Agent` OpenHuman presents to OpenAI-compatible cloud providers +/// (`openhuman/`), unless a route sets its own (Codex OAuth) or +/// the provider entry configures one. +pub fn product_user_agent() -> String { + format!("openhuman/{}", env!("CARGO_PKG_VERSION")) +} + +/// Whether `endpoint` is an OpenCode Go base URL, i.e. one that refuses +/// requests without [`OPENCODE_SESSION_HEADER`]. Matched on the `opencode.ai` +/// host and the `/zen/go` path prefix so the regular Zen endpoint, which has +/// no such requirement, is left alone. +pub fn endpoint_requires_opencode_session(endpoint: &str) -> bool { + if endpoint_host(endpoint).as_deref() != Some("opencode.ai") { + return false; + } + let trimmed = endpoint.trim(); + let after_scheme = trimmed + .split_once("://") + .map(|(_, rest)| rest) + .unwrap_or(trimmed); + let path = after_scheme + .find('/') + .map(|i| &after_scheme[i..]) + .unwrap_or(""); + let path = path.to_ascii_lowercase(); + path == "/zen/go" || path.starts_with("/zen/go/") +} + +/// The conversation a turn origin belongs to, as a key that is the same for +/// every request made on behalf of that conversation and different across +/// conversations. `None` for origins that carry no conversation (CLI, direct +/// chat, unknown), which fall back to one id per process. +pub fn conversation_key(origin: Option<&AgentTurnOrigin>) -> Option { + match origin? { + AgentTurnOrigin::WebChat { thread_id, .. } => Some(format!("thread:{thread_id}")), + AgentTurnOrigin::ExternalChannel { + channel, + history_key, + reply_target, + .. + } => Some(format!( + "channel:{channel}:{}", + history_key.as_deref().unwrap_or(reply_target) + )), + AgentTurnOrigin::TrustedAutomation { job_id, .. } => Some(format!("job:{job_id}")), + _ => None, + } +} + +/// A stable id for the process, used when the origin names no conversation +/// so the requests of one CLI run still share a session. +static PROCESS_CONVERSATION_KEY: LazyLock = + LazyLock::new(|| format!("process:{}", uuid::Uuid::new_v4())); + +/// The `x-opencode-session` value for `origin`: a 32-hex-character digest of +/// the conversation key, so a thread id never leaves the machine verbatim. +pub fn opencode_session_id(origin: Option<&AgentTurnOrigin>) -> String { + let key = conversation_key(origin).unwrap_or_else(|| PROCESS_CONVERSATION_KEY.clone()); + let mut hasher = Sha256::new(); + hasher.update(b"openhuman-opencode-session-v1:"); + hasher.update(key.as_bytes()); + let digest = hasher.finalize(); + digest[..16] + .iter() + .map(|byte| format!("{byte:02x}")) + .collect() +} + +/// Whether `headers` already carries `name` (case-insensitive), so a value the +/// user configured on the provider entry wins over the built-in one. +pub fn has_header(headers: &[(String, String)], name: &str) -> bool { + headers + .iter() + .any(|(existing, _)| existing.eq_ignore_ascii_case(name)) +} + +/// Completes a cloud route's request identity in place: the product +/// `User-Agent` when the route set none and the entry configured none, and the +/// OpenCode Go session header when `endpoint` requires it and the entry did +/// not configure one. `origin` is the turn the client is built for. +pub fn apply_request_identity( + endpoint: &str, + origin: Option<&AgentTurnOrigin>, + headers: &mut Vec<(String, String)>, + user_agent: &mut Option, +) { + log::debug!( + "[providers][request-identity] origin={} configured_headers={} route_user_agent={}", + origin + .map(|origin| origin.class()) + .unwrap_or_else(|| "none".to_string()), + headers.len(), + user_agent.is_some() + ); + if user_agent.is_none() && !has_header(headers, "user-agent") { + *user_agent = Some(product_user_agent()); + } + if endpoint_requires_opencode_session(endpoint) && !has_header(headers, OPENCODE_SESSION_HEADER) + { + headers.push(( + OPENCODE_SESSION_HEADER.to_string(), + opencode_session_id(origin), + )); + } +} + +/// The entry's configured `headers` table as request headers, after checking +/// each is a valid HTTP header. Fails, naming the provider and header (never +/// the value), so a typo surfaces before a request is built. +pub fn configured_headers( + entry: &crate::config::schema::cloud_providers::CloudProviderCreds, +) -> Result, String> { + crate::config::schema::cloud_providers::validate_provider_headers(&entry.slug, &entry.headers)?; + Ok(entry + .headers + .iter() + .map(|(name, value)| (name.clone(), value.clone())) + .collect()) +} + +/// The headers a chat request to `entry` starts from: those of the ephemeral +/// route in effect for it, if any, then the entry's own `headers` table. Fails +/// like [`configured_headers`] on a malformed one. +pub fn route_headers( + entry: &crate::config::schema::cloud_providers::CloudProviderCreds, + ephemeral_route: Option<&crate::config::schema::ephemeral_route::EphemeralRoute>, +) -> Result, String> { + let mut headers = ephemeral_route + .map(|route| route.headers.clone()) + .unwrap_or_default(); + headers.extend(configured_headers(entry)?); + Ok(headers) +} + +/// The headers a model-catalog (`/models`) request to a cloud provider +/// carries: the entry's configured headers, plus a `User-Agent` when none of +/// them sets one: `route_user_agent` (the Codex OAuth identity) if the route +/// has its own, else [`product_user_agent`]. The registry's discovery request +/// reads its separate `user_agent` option for Codex OAuth only, and lets +/// `extra_headers` replace it, so the identity travels as a header. +/// +/// Fails, naming the provider and header, when a configured header is not a +/// valid HTTP header. +pub fn catalog_request_headers( + entry: &crate::config::schema::cloud_providers::CloudProviderCreds, + route_user_agent: Option<&str>, +) -> Result, String> { + let mut headers = configured_headers(entry)?; + if !has_header(&headers, "user-agent") { + let user_agent = route_user_agent + .map(str::to_string) + .unwrap_or_else(product_user_agent); + headers.push(("User-Agent".to_string(), user_agent)); + } + Ok(headers) +} + +#[cfg(test)] +#[path = "request_identity_tests.rs"] +mod tests; diff --git a/crates/openhuman-core/src/inference/provider/factory/request_identity_tests.rs b/crates/openhuman-core/src/inference/provider/factory/request_identity_tests.rs new file mode 100644 index 00000000000..5f29c5b86ef --- /dev/null +++ b/crates/openhuman-core/src/inference/provider/factory/request_identity_tests.rs @@ -0,0 +1,251 @@ +use super::*; +use crate::core::runtime::turn_origin::TrustedAutomationSource; + +fn web_chat(thread_id: &str) -> AgentTurnOrigin { + AgentTurnOrigin::WebChat { + thread_id: thread_id.to_string(), + client_id: "client-1".to_string(), + request_id: Some("req-1".to_string()), + } +} + +fn channel(history_key: Option<&str>, reply_target: &str) -> AgentTurnOrigin { + AgentTurnOrigin::ExternalChannel { + channel: "telegram".to_string(), + sender: Some("user-7".to_string()), + sender_name: None, + reply_target: reply_target.to_string(), + message_id: "m-1".to_string(), + history_key: history_key.map(str::to_string), + channel_session: None, + } +} + +#[test] +fn product_user_agent_names_openhuman_and_the_core_version() { + assert_eq!( + product_user_agent(), + format!("openhuman/{}", env!("CARGO_PKG_VERSION")) + ); +} + +#[test] +fn only_opencode_go_endpoints_require_the_session_header() { + for endpoint in [ + "https://opencode.ai/zen/go/v1", + "https://opencode.ai/zen/go/v1/", + "HTTPS://OPENCODE.AI/ZEN/GO/v1", + "https://opencode.ai/zen/go", + "opencode.ai/zen/go/v1", + ] { + assert!( + endpoint_requires_opencode_session(endpoint), + "{endpoint} is OpenCode Go" + ); + } + for endpoint in [ + "https://opencode.ai/zen/v1", + "https://opencode.ai/zen/gopher/v1", + "https://api.openai.com/v1", + "https://evil.example/opencode.ai/zen/go/v1", + "https://opencode.ai.example/zen/go/v1", + "", + ] { + assert!( + !endpoint_requires_opencode_session(endpoint), + "{endpoint} is not OpenCode Go" + ); + } +} + +#[test] +fn session_id_is_stable_within_a_conversation_and_distinct_across_them() { + let thread_a = web_chat("thread-a"); + let thread_b = web_chat("thread-b"); + + let first = opencode_session_id(Some(&thread_a)); + assert_eq!(first, opencode_session_id(Some(&thread_a))); + assert_eq!(first.len(), 32, "{first}"); + assert!(first.chars().all(|c| c.is_ascii_hexdigit()), "{first}"); + assert!( + !first.contains("thread-a"), + "the thread id must not be sent verbatim" + ); + assert_ne!(first, opencode_session_id(Some(&thread_b))); + + // Auxiliary calls on the same thread differ in request / client ids only + // and still share the session. + let same_thread_other_request = AgentTurnOrigin::WebChat { + thread_id: "thread-a".to_string(), + client_id: "client-2".to_string(), + request_id: None, + }; + assert_eq!(first, opencode_session_id(Some(&same_thread_other_request))); +} + +#[test] +fn conversation_key_follows_the_origin_kind() { + assert_eq!( + conversation_key(Some(&web_chat("t1"))).as_deref(), + Some("thread:t1") + ); + assert_eq!( + conversation_key(Some(&channel(Some("chat-42"), "chat-42-target"))).as_deref(), + Some("channel:telegram:chat-42") + ); + assert_eq!( + conversation_key(Some(&channel(None, "chat-42-target"))).as_deref(), + Some("channel:telegram:chat-42-target") + ); + assert_eq!( + conversation_key(Some(&AgentTurnOrigin::TrustedAutomation { + job_id: "cron-9".to_string(), + source: TrustedAutomationSource::Cron, + })) + .as_deref(), + Some("job:cron-9") + ); + for origin in [ + AgentTurnOrigin::Cli, + AgentTurnOrigin::DirectChat, + AgentTurnOrigin::Unknown, + ] { + assert_eq!(conversation_key(Some(&origin)), None, "{origin:?}"); + } + assert_eq!(conversation_key(None), None); +} + +#[test] +fn origins_without_a_conversation_share_one_process_session() { + let unscoped = opencode_session_id(None); + assert_eq!(unscoped, opencode_session_id(None)); + assert_eq!(unscoped, opencode_session_id(Some(&AgentTurnOrigin::Cli))); + assert_ne!(unscoped, opencode_session_id(Some(&web_chat("thread-a")))); +} + +#[test] +fn has_header_ignores_case() { + let headers = vec![("X-OpenCode-Session".to_string(), "abc".to_string())]; + assert!(has_header(&headers, OPENCODE_SESSION_HEADER)); + assert!(has_header(&headers, "x-opencode-session")); + assert!(!has_header(&headers, "user-agent")); + assert!(!has_header(&[], OPENCODE_SESSION_HEADER)); +} + +#[test] +fn request_identity_adds_the_product_user_agent_and_nothing_else_off_opencode() { + let mut headers = Vec::new(); + let mut user_agent = None; + apply_request_identity( + "https://api.openai.com/v1", + Some(&web_chat("t1")), + &mut headers, + &mut user_agent, + ); + assert_eq!(user_agent.as_deref(), Some(product_user_agent().as_str())); + assert!(headers.is_empty(), "{headers:?}"); +} + +#[test] +fn request_identity_attaches_the_conversation_session_for_opencode_go() { + let origin = web_chat("t1"); + let mut headers = vec![("x-custom".to_string(), "1".to_string())]; + let mut user_agent = None; + apply_request_identity( + "https://opencode.ai/zen/go/v1", + Some(&origin), + &mut headers, + &mut user_agent, + ); + assert_eq!(user_agent.as_deref(), Some(product_user_agent().as_str())); + assert_eq!( + headers, + vec![ + ("x-custom".to_string(), "1".to_string()), + ( + OPENCODE_SESSION_HEADER.to_string(), + opencode_session_id(Some(&origin)) + ), + ] + ); +} + +#[test] +fn request_identity_defers_to_configured_headers_and_a_route_user_agent() { + let configured = vec![ + ("User-Agent".to_string(), "my-agent/1.0".to_string()), + ("X-OpenCode-Session".to_string(), "ses_fixed".to_string()), + ]; + let mut headers = configured.clone(); + let mut user_agent = None; + apply_request_identity( + "https://opencode.ai/zen/go/v1", + Some(&web_chat("t1")), + &mut headers, + &mut user_agent, + ); + assert_eq!(headers, configured, "configured values are not duplicated"); + assert_eq!(user_agent, None, "the configured User-Agent header stands"); + + let mut headers = Vec::new(); + let mut user_agent = Some("codex_cli_rs/1.0".to_string()); + apply_request_identity( + "https://api.openai.com/v1", + None, + &mut headers, + &mut user_agent, + ); + assert_eq!(user_agent.as_deref(), Some("codex_cli_rs/1.0")); +} + +fn catalog_entry( + headers: &[(&str, &str)], +) -> crate::config::schema::cloud_providers::CloudProviderCreds { + crate::config::schema::cloud_providers::CloudProviderCreds { + slug: "gateway".to_string(), + endpoint: "https://gateway.example/v1".to_string(), + headers: headers + .iter() + .map(|(name, value)| (name.to_string(), value.to_string())) + .collect(), + ..Default::default() + } +} + +#[test] +fn catalog_request_headers_add_the_product_user_agent_to_configured_headers() { + let headers = catalog_request_headers(&catalog_entry(&[("x-tenant", "team-a")]), None) + .expect("valid headers"); + assert!(headers.contains(&("x-tenant".to_string(), "team-a".to_string()))); + assert!(headers.contains(&("User-Agent".to_string(), product_user_agent()))); +} + +#[test] +fn catalog_request_headers_prefer_a_route_user_agent_and_keep_a_configured_one() { + let routed = + catalog_request_headers(&catalog_entry(&[]), Some("codex-ua/1")).expect("valid headers"); + assert_eq!( + routed, + vec![("User-Agent".to_string(), "codex-ua/1".to_string())] + ); + + let configured = catalog_request_headers( + &catalog_entry(&[("user-agent", "mine/2")]), + Some("codex-ua/1"), + ) + .expect("valid headers"); + assert_eq!( + configured, + vec![("user-agent".to_string(), "mine/2".to_string())] + ); +} + +#[test] +fn catalog_request_headers_reject_a_malformed_header() { + let error = catalog_request_headers(&catalog_entry(&[("x tenant", "a")]), None) + .expect_err("space in a header name"); + assert!( + error.contains("'gateway'") && error.contains("'x tenant'"), + "{error}" + ); +} diff --git a/crates/openhuman-core/src/inference/provider/factory_explicit_ctx_tests.rs b/crates/openhuman-core/src/inference/provider/factory_explicit_ctx_tests.rs index 6213884e7c2..3381de859a6 100644 --- a/crates/openhuman-core/src/inference/provider/factory_explicit_ctx_tests.rs +++ b/crates/openhuman-core/src/inference/provider/factory_explicit_ctx_tests.rs @@ -265,6 +265,7 @@ async fn hosted_cloud_slug_uses_explicit_auth_policy_and_model_entry() { .expect("store isolated fixture session"); config.chat_provider = Some("p_hosted:fixture/model-v1".to_string()); config.cloud_providers.push(CloudProviderCreds { + headers: Default::default(), id: "p_hosted_fixture".to_string(), slug: "p_hosted".to_string(), label: "Hosted fixture".to_string(), diff --git a/crates/openhuman-core/src/inference/provider/factory_request_headers_tests.rs b/crates/openhuman-core/src/inference/provider/factory_request_headers_tests.rs new file mode 100644 index 00000000000..f64fe49cc6d --- /dev/null +++ b/crates/openhuman-core/src/inference/provider/factory_request_headers_tests.rs @@ -0,0 +1,176 @@ +//! Wire-level coverage for #7865: a `[[cloud_providers]]` entry's `headers` +//! table and the product `User-Agent` reach the provider on a chat request, +//! and the request identity does not leak onto a provider that configured +//! its own values. + +use super::cloud_slug::try_create_cloud_slug_chat_model_from_string_with_native_tools; +use super::request_identity::{product_user_agent, OPENCODE_SESSION_HEADER}; +use super::*; +use crate::config::schema::cloud_providers::CloudProviderCreds; +use tinyinference_llm::message::Message; +use wiremock::matchers::{method, path}; +use wiremock::{Mock, MockServer, ResponseTemplate}; + +fn entry_for(server: &MockServer, headers: &[(&str, &str)]) -> CloudProviderCreds { + CloudProviderCreds { + id: "p_gateway".to_string(), + slug: "gateway".to_string(), + label: "Gateway".to_string(), + endpoint: format!("{}/v1", server.uri()), + auth_style: AuthStyle::None, + headers: headers + .iter() + .map(|(name, value)| (name.to_string(), value.to_string())) + .collect(), + ..Default::default() + } +} + +async fn mount_completion(server: &MockServer) { + Mock::given(method("POST")) + .and(path("/v1/chat/completions")) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "id": "gen-1", + "model": "m", + "choices": [{ + "index": 0, + "message": {"role": "assistant", "content": "ok"}, + "finish_reason": "stop" + }], + "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2} + }))) + .mount(server) + .await; +} + +async fn one_request(server: &MockServer) -> wiremock::Request { + let mut requests = server.received_requests().await.expect("recording on"); + assert_eq!(requests.len(), 1, "exactly one provider call"); + requests.remove(0) +} + +fn header<'a>(request: &'a wiremock::Request, name: &str) -> Option<&'a str> { + request + .headers + .get(name) + .and_then(|value| value.to_str().ok()) +} + +async fn invoke(config: &Config) { + let (model, model_id) = try_create_cloud_slug_chat_model_from_string_with_native_tools( + "chat", + "gateway:m", + config, + true, + &EgressLedger::none(), + ) + .await + .expect("configured slug") + .expect("model builds"); + assert_eq!(model_id, "m"); + let request = tinyinference_llm::model::ModelRequest::new(vec![Message::user("hi")]); + let response = model.invoke(&(), request).await.expect("completion"); + assert_eq!(response.text(), "ok"); +} + +#[tokio::test] +async fn configured_headers_and_the_product_user_agent_reach_the_provider() { + let _guard = crate::inference::inference_test_guard_async().await; + let server = MockServer::start().await; + mount_completion(&server).await; + let mut config = Config::default(); + config + .cloud_providers + .push(entry_for(&server, &[("x-tenant", "team-a")])); + + invoke(&config).await; + + let request = one_request(&server).await; + assert_eq!(header(&request, "x-tenant"), Some("team-a")); + assert_eq!( + header(&request, "user-agent"), + Some(product_user_agent().as_str()) + ); + assert_eq!( + header(&request, OPENCODE_SESSION_HEADER), + None, + "a non-OpenCode endpoint gets no session header" + ); +} + +#[tokio::test] +async fn configured_user_agent_and_session_headers_are_sent_verbatim() { + let _guard = crate::inference::inference_test_guard_async().await; + let server = MockServer::start().await; + mount_completion(&server).await; + let mut config = Config::default(); + config.cloud_providers.push(entry_for( + &server, + &[ + ("User-Agent", "my-agent/1.0"), + (OPENCODE_SESSION_HEADER, "ses_fixed"), + ], + )); + + invoke(&config).await; + + let request = one_request(&server).await; + assert_eq!( + request.headers.get_all("user-agent").iter().count(), + 1, + "the configured User-Agent replaces the product one" + ); + assert_eq!(header(&request, "user-agent"), Some("my-agent/1.0")); + assert_eq!(header(&request, OPENCODE_SESSION_HEADER), Some("ses_fixed")); +} + +#[tokio::test] +async fn an_entry_without_headers_sends_only_the_product_user_agent() { + let _guard = crate::inference::inference_test_guard_async().await; + let server = MockServer::start().await; + mount_completion(&server).await; + let mut config = Config::default(); + config.cloud_providers.push(entry_for(&server, &[])); + + invoke(&config).await; + + let request = one_request(&server).await; + assert_eq!( + header(&request, "user-agent"), + Some(product_user_agent().as_str()) + ); + assert_eq!(header(&request, "x-tenant"), None); +} + +#[tokio::test] +async fn a_malformed_configured_header_fails_the_build_naming_provider_and_header() { + let _guard = crate::inference::inference_test_guard_async().await; + let mut config = Config::default(); + config.cloud_providers.push(CloudProviderCreds { + id: "p_gateway".to_string(), + slug: "gateway".to_string(), + label: "Gateway".to_string(), + endpoint: "https://gateway.example/v1".to_string(), + auth_style: AuthStyle::None, + headers: [("x tenant".to_string(), "team-a".to_string())].into(), + ..Default::default() + }); + + let result = try_create_cloud_slug_chat_model_from_string_with_native_tools( + "chat", + "gateway:m", + &config, + true, + &EgressLedger::none(), + ) + .await + .expect("configured slug"); + let error = match result { + Ok(_) => panic!("a malformed header must not build"), + Err(error) => error.to_string(), + }; + assert!( + error.contains("'gateway'") && error.contains("'x tenant'"), + "{error}" + ); +} diff --git a/crates/openhuman-core/src/inference/provider/factory_tests.rs b/crates/openhuman-core/src/inference/provider/factory_tests.rs index 03a8069daed..63a5f92f8eb 100644 --- a/crates/openhuman-core/src/inference/provider/factory_tests.rs +++ b/crates/openhuman-core/src/inference/provider/factory_tests.rs @@ -106,6 +106,7 @@ fn install_test_managed_provider() -> Arc>> { fn fixture_managed_entry(id: &str) -> CloudProviderCreds { CloudProviderCreds { + headers: Default::default(), id: id.to_string(), slug: "fixture-managed".to_string(), label: "Managed fixture".to_string(), @@ -262,6 +263,7 @@ fn openai_entry(id: &str, slug: &str) -> CloudProviderCreds { label: "OpenAI".to_string(), endpoint: "https://api.openai.com/v1".to_string(), auth_style: AuthStyle::Bearer, + headers: Default::default(), default_model: Some("gpt-4o".to_string()), } } @@ -273,6 +275,7 @@ fn anthropic_entry(id: &str, slug: &str) -> CloudProviderCreds { label: "Anthropic".to_string(), endpoint: "https://api.anthropic.com/v1".to_string(), auth_style: AuthStyle::Anthropic, + headers: Default::default(), default_model: Some("claude-sonnet-4-6".to_string()), } } @@ -284,6 +287,7 @@ fn nvidia_nim_entry(id: &str, default_model: Option<&str>) -> CloudProviderCreds label: "NVIDIA NIM".to_string(), endpoint: "https://integrate.api.nvidia.com/v1".to_string(), auth_style: AuthStyle::Bearer, + headers: Default::default(), default_model: default_model.map(ToString::to_string), } } @@ -593,6 +597,7 @@ fn deepseek_entry(id: &str) -> CloudProviderCreds { label: "DeepSeek".to_string(), endpoint: "https://api.deepseek.com/v1".to_string(), auth_style: AuthStyle::Bearer, + headers: Default::default(), default_model: Some("deepseek-chat".to_string()), } } diff --git a/crates/openhuman-core/src/inference/provider/model_listing_test_support.rs b/crates/openhuman-core/src/inference/provider/model_listing_test_support.rs index e091212f5a5..dc853882ed7 100644 --- a/crates/openhuman-core/src/inference/provider/model_listing_test_support.rs +++ b/crates/openhuman-core/src/inference/provider/model_listing_test_support.rs @@ -121,6 +121,7 @@ pub(crate) async fn configure_openrouter_workspace( label: "OpenRouter".to_string(), endpoint, auth_style: AuthStyle::Bearer, + headers: Default::default(), default_model: None, }); config.save().await.expect("save config"); @@ -187,6 +188,7 @@ pub(crate) async fn configure_generic_workspace(tmp: &TempDir, endpoint: String) label: "Generic".to_string(), endpoint, auth_style: AuthStyle::None, + headers: Default::default(), default_model: None, }); config.save().await.expect("save config"); diff --git a/crates/openhuman-core/src/inference/provider/models/catalog_listing.rs b/crates/openhuman-core/src/inference/provider/models/catalog_listing.rs index a09b2591f15..277497d7ac5 100644 --- a/crates/openhuman-core/src/inference/provider/models/catalog_listing.rs +++ b/crates/openhuman-core/src/inference/provider/models/catalog_listing.rs @@ -101,8 +101,16 @@ fn discovery_request( let user_agent = routing .using_oauth .then(|| openai_codex_user_agent("OpenHuman", env!("CARGO_PKG_VERSION"))); + // The entry's configured headers (#7865) and the product `User-Agent` ride + // the listing like every other request to this provider. + let extra_headers = + crate::inference::provider::factory::request_identity::catalog_request_headers( + entry, + user_agent.as_deref(), + )?; let options = ProviderBuildOptions { auth_style: Some(entry.auth_style.into()), + extra_headers: &extra_headers, extra_query_params: &query_params, user_agent: user_agent.as_deref(), codex: Some(routing), diff --git a/crates/openhuman-core/src/inference/provider/models/catalog_listing_error_tests.rs b/crates/openhuman-core/src/inference/provider/models/catalog_listing_error_tests.rs index 138f9c5e8d5..8fe1dbc263a 100644 --- a/crates/openhuman-core/src/inference/provider/models/catalog_listing_error_tests.rs +++ b/crates/openhuman-core/src/inference/provider/models/catalog_listing_error_tests.rs @@ -19,6 +19,7 @@ fn list_configured_models_accepts_slug() { let mut config = Config::default(); config.cloud_providers.push(CloudProviderCreds { + headers: Default::default(), id: "p_openai_xyz99".to_string(), slug: "openai".to_string(), label: "OpenAI".to_string(), diff --git a/crates/openhuman-core/src/inference/provider/models/catalog_listing_tests.rs b/crates/openhuman-core/src/inference/provider/models/catalog_listing_tests.rs index 05754fc6694..666b736b728 100644 --- a/crates/openhuman-core/src/inference/provider/models/catalog_listing_tests.rs +++ b/crates/openhuman-core/src/inference/provider/models/catalog_listing_tests.rs @@ -180,6 +180,7 @@ fn cloud_providers_entry_takes_precedence_over_local_runtime_synthesis() { label: "Remote Ollama".to_string(), endpoint: "https://ollama.example.com/v1".to_string(), auth_style: AuthStyle::Bearer, + headers: Default::default(), default_model: None, }); @@ -242,3 +243,92 @@ fn missing_cloud_providers_entry_for_unknown_slug_still_errors() { "unknown slug with no cloud_providers entry must NOT synthesize", ); } + +// ── configured headers on the listing (#7865) ─────────────────────────── + +use axum::{ + extract::State, + http::HeaderMap, + response::{IntoResponse, Response}, + routing::get, + Router, +}; +use std::sync::{Arc, Mutex}; + +#[derive(Clone)] +struct RecordedListing { + body: &'static str, + headers: Arc>>, +} + +async fn recording_models_handler( + State(state): State, + headers: HeaderMap, +) -> Response { + state.headers.lock().expect("lock").push(headers); + (StatusCode::OK, state.body).into_response() +} + +async fn spawn_recording_models_server(body: &'static str) -> (String, RecordedListing) { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind"); + let addr = listener.local_addr().expect("local_addr"); + let state = RecordedListing { + body, + headers: Arc::new(Mutex::new(Vec::new())), + }; + let app = Router::new() + .route("/models", get(recording_models_handler)) + .with_state(state.clone()); + tokio::spawn(async move { + axum::serve(listener, app).await.expect("serve"); + }); + (format!("http://{addr}"), state) +} + +#[tokio::test] +async fn list_models_sends_the_entry_headers_and_the_product_user_agent() { + let tmp = tempfile::tempdir().expect("tempdir"); + let (endpoint, recorded) = + spawn_recording_models_server(r#"{"data":[{"id":"gated-model","owned_by":"team"}]}"#).await; + let mut config = configure_generic_workspace(&tmp, endpoint).await; + config.cloud_providers[0].headers = [("x-tenant".to_string(), "team-a".to_string())].into(); + + let outcome = catalog_listing::list_configured_models_from_config("generic-test", &config) + .await + .expect("listing succeeds"); + assert_eq!(outcome.value["models"][0]["id"], "gated-model"); + + let seen = recorded.headers.lock().expect("lock"); + assert_eq!(seen.len(), 1, "one listing request"); + assert_eq!( + seen[0].get("x-tenant").and_then(|v| v.to_str().ok()), + Some("team-a") + ); + assert_eq!( + seen[0].get("user-agent").and_then(|v| v.to_str().ok()), + Some(crate::inference::provider::factory::request_identity::product_user_agent().as_str()) + ); +} + +#[tokio::test] +async fn list_models_lets_a_configured_user_agent_replace_the_product_one() { + let tmp = tempfile::tempdir().expect("tempdir"); + let (endpoint, recorded) = spawn_recording_models_server(r#"{"data":[]}"#).await; + let mut config = configure_generic_workspace(&tmp, endpoint).await; + config.cloud_providers[0].headers = + [("User-Agent".to_string(), "my-agent/1.0".to_string())].into(); + + catalog_listing::list_configured_models_from_config("generic-test", &config) + .await + .expect("listing succeeds"); + + let seen = recorded.headers.lock().expect("lock"); + let agents: Vec<_> = seen[0] + .get_all("user-agent") + .iter() + .filter_map(|v| v.to_str().ok()) + .collect(); + assert_eq!(agents, vec!["my-agent/1.0"]); +} diff --git a/crates/openhuman-core/src/inference/provider/models/local_runtime.rs b/crates/openhuman-core/src/inference/provider/models/local_runtime.rs index b4f64acfb8c..6b4b9a47db1 100644 --- a/crates/openhuman-core/src/inference/provider/models/local_runtime.rs +++ b/crates/openhuman-core/src/inference/provider/models/local_runtime.rs @@ -50,6 +50,7 @@ pub fn synthesize_local_runtime_entry( // header — `lookup_key_for_slug` may still return a key, but // `AuthStyle::None` ignores it (see auth-style match below). auth_style: AuthStyle::None, + headers: Default::default(), default_model: None, }) } diff --git a/crates/openhuman-core/src/inference/provider/models/mod_tests.rs b/crates/openhuman-core/src/inference/provider/models/mod_tests.rs index dd8cb25424c..dab88de166e 100644 --- a/crates/openhuman-core/src/inference/provider/models/mod_tests.rs +++ b/crates/openhuman-core/src/inference/provider/models/mod_tests.rs @@ -48,6 +48,7 @@ fn workspace_with_provider( }; config.secrets.encrypt = false; config.cloud_providers.push(CloudProviderCreds { + headers: Default::default(), id: format!("p_{slug}"), slug: slug.to_string(), label: slug.to_string(), diff --git a/crates/openhuman-core/src/inference/turn_models_native_tests.rs b/crates/openhuman-core/src/inference/turn_models_native_tests.rs index 97052a5d59d..ca12c993f62 100644 --- a/crates/openhuman-core/src/inference/turn_models_native_tests.rs +++ b/crates/openhuman-core/src/inference/turn_models_native_tests.rs @@ -195,6 +195,7 @@ async fn native_turn_preserves_deepseek_route_metadata_after_cloud_resolution() workspace_dir: tmp.path().join("workspace"), chat_provider: Some("deepseek:hint:chat".into()), cloud_providers: vec![CloudProviderCreds { + headers: Default::default(), id: "deepseek-fixture".into(), slug: "deepseek".into(), label: "DeepSeek fixture".into(), diff --git a/crates/openhuman-core/src/inference/turn_models_summarizer_tests.rs b/crates/openhuman-core/src/inference/turn_models_summarizer_tests.rs index 750a71b406f..fee74dba055 100644 --- a/crates/openhuman-core/src/inference/turn_models_summarizer_tests.rs +++ b/crates/openhuman-core/src/inference/turn_models_summarizer_tests.rs @@ -58,6 +58,7 @@ async fn wire_models(summarizer_model: Option<&str>) -> WireModels { endpoint: format!("{}/api/v1", server.uri()), auth_style: AuthStyle::Bearer, default_model: Some(TURN_MODEL.into()), + headers: Default::default(), }); config.chat_provider = Some(format!("openrouter:{TURN_MODEL}")); config.context.summarizer_model = summarizer_model.map(str::to_owned); diff --git a/crates/openhuman-core/src/triage/routing_tests.rs b/crates/openhuman-core/src/triage/routing_tests.rs index 5a483158d3b..74e8567e2e5 100644 --- a/crates/openhuman-core/src/triage/routing_tests.rs +++ b/crates/openhuman-core/src/triage/routing_tests.rs @@ -17,6 +17,7 @@ fn openai_entry(id: &str, slug: &str) -> CloudProviderCreds { label: "OpenAI".to_string(), endpoint: "https://api.openai.com/v1".to_string(), auth_style: AuthStyle::Bearer, + headers: Default::default(), default_model: Some("gpt-4o".to_string()), } } diff --git a/crates/openhuman-tinyhumans/src/inference/tiers.rs b/crates/openhuman-tinyhumans/src/inference/tiers.rs index 781accba666..db8784fe962 100644 --- a/crates/openhuman-tinyhumans/src/inference/tiers.rs +++ b/crates/openhuman-tinyhumans/src/inference/tiers.rs @@ -149,6 +149,7 @@ pub(crate) fn normalize_config(config: &mut Config) -> bool { ); config.cloud_providers.push( openhuman_embed::__host::config::schema::cloud_providers::CloudProviderCreds { + headers: Default::default(), id: id.clone(), slug: preset.slug.to_string(), label: preset.label.to_string(), diff --git a/docs/TEST-COVERAGE-MATRIX.md b/docs/TEST-COVERAGE-MATRIX.md index 5ce5482d1a9..82e5938d081 100644 --- a/docs/TEST-COVERAGE-MATRIX.md +++ b/docs/TEST-COVERAGE-MATRIX.md @@ -130,6 +130,7 @@ Local inference runs against a runtime the user installs, starts, and pulls mode | 3.1.3 | Model Version Handling | RU | `crates/openhuman-core/src/config/schema/types/model_ids.rs` | ✅ | **Path corrected** (was `crates/openhuman-core/src/inference/model_ids.rs`). | | 3.1.4 | LM Studio Model Discovery | RU+RI | `vendor/tinyagents/vendor/tinyinference/crates/tinyinference-local/src/service/ollama_admin_tests.rs` (LM Studio cases), `tests/json_rpc_e2e.rs` | ✅ | Uses LM Studio's OpenAI-compatible `/v1/models` surface. **Path corrected** (was `crates/openhuman-core/src/inference/local/service/ollama_admin_tests.rs`, which moved upstream with the runtime). ⚠️ **`tinyinference-local` is not built by any OpenHuman lane** — `vendor` is in the root `[workspace] exclude` and no CI step names the package, so its unit tests are cited history, not executed coverage. | | 3.1.5 | Model Context-Window Requirement Gate | RU | `vendor/tinyagents/vendor/tinyinference/crates/tinyinference-local/src/model_requirements.rs`, `vendor/tinyagents/vendor/tinyinference/crates/tinyinference-local/src/ollama.rs` | 🟡 | Rejects Ollama models whose native context window is below the memory-layer minimum (`local_ai.model_context_check`). The model is one the user pulled; OpenHuman no longer suggests or pulls a replacement. ⚠️ **`tinyinference-local` is not built by any OpenHuman lane** — `vendor` is in the root `[workspace] exclude` and no CI step names the package, so its unit tests are cited history, not executed coverage. | +| 3.1.6 | Cloud provider request identity (`[[cloud_providers]].headers`, product `User-Agent`, OpenCode Go `x-opencode-session`) | RU | `crates/openhuman-core/src/inference/provider/factory/request_identity_tests.rs`, `crates/openhuman-core/src/inference/provider/factory_request_headers_tests.rs`, `crates/openhuman-core/src/config/schema/cloud_providers_tests.rs`, `crates/openhuman-core/src/config/ops_provider_headers_tests.rs` | ✅ | A `headers` table on the entry and `openhuman/` reach the provider on a chat request (wiremock); an OpenCode Go endpoint gets a session id derived from the turn origin (thread / channel conversation / job), stable within a conversation and distinct across them; configured `User-Agent` / `x-opencode-session` values win; the table round-trips through TOML and survives a settings save that omits it (#7865) | ### 3.2 Runtime Execution diff --git a/docs/gitbooks/en/features/model-routing/local-and-byok-models.md b/docs/gitbooks/en/features/model-routing/local-and-byok-models.md index 5bcecc92143..1245c8d42d6 100644 --- a/docs/gitbooks/en/features/model-routing/local-and-byok-models.md +++ b/docs/gitbooks/en/features/model-routing/local-and-byok-models.md @@ -132,6 +132,24 @@ Anything else that speaks the OpenAI-compatible API also works. Register it with For an HTTPS endpoint signed by a private or corporate CA, upload its PEM CA certificate in the custom provider editor. OpenHuman trusts that certificate for this provider's model listing and inference requests. You can also install the CA in the operating system's trust store; on macOS and Linux, `SSL_CERT_FILE` supplies a PEM bundle to the core process. +Every request to an OpenAI-compatible provider identifies the client as `openhuman/` in its `User-Agent`. A provider that needs a header the auth style does not cover takes it from a `headers` table on its `[[cloud_providers]]` entry in `config.toml`; the headers are sent on every request to that provider, chat and model listing alike, and a configured `User-Agent` or `x-opencode-session` replaces the value OpenHuman would add: + +```toml +[[cloud_providers]] +id = "p_gateway_1" +slug = "my-gateway" +label = "Team gateway" +endpoint = "https://gateway.example/v1" +auth_style = "bearer" + +[cloud_providers.headers] +x-tenant = "team-a" +``` + +Header names and values must be valid HTTP headers; a malformed one makes requests to that provider fail with an error naming the provider and the header. Header values may be secrets, so the settings UI only ever sees their names. + +OpenCode Go (`https://opencode.ai/zen/go/v1`) needs no such table: it requires a stable per-conversation `x-opencode-session`, and OpenHuman derives one from the chat thread, channel conversation or automation job each request belongs to, so a thread's turns and its title and summary calls share a session. + On a headless core (`openhuman-core serve`), custom cloud providers are built only when a backend session or TinyHumans API key is present. If you run the core with no account, set the endpoint up as the `local-openai` runtime instead: set `LOCAL_OPENAI_URL`, put the key in `local_ai.api_key`, and pin workloads to `local-openai:`. See [Headless without a TinyHumans account](../cloud-deploy.md#headless-without-a-tinyhumans-account). ### 2. Route workloads to it diff --git a/scripts/ci/process-statics.json b/scripts/ci/process-statics.json index 1f9620ceade..3b6b18c60d1 100644 --- a/scripts/ci/process-statics.json +++ b/scripts/ci/process-statics.json @@ -269,6 +269,16 @@ "reason": "Immutable provider-neutral routing policy parsed once from the built-in hint routes; per-request route facts and user configuration are passed through ConfigRouteSource.", "verification": "inference/provider/factory_egress_fallback_tests.rs: cloud_fallback_roles_match_the_roles_provider_for_role_actually_falls_back" }, + { + "file": "crates/openhuman-core/src/inference/provider/factory/request_identity.rs", + "scope": "", + "name": "PROCESS_CONVERSATION_KEY", + "type": "LazyLock", + "count": 1, + "category": "A", + "reason": "A random per-process id generated once and never written again; it is only the fallback OpenCode Go session key for turn origins that name no conversation (CLI, direct chat), so it carries no tenant data. Origins with a thread, channel conversation or job derive their key from that origin instead.", + "verification": "inference/provider/factory/request_identity_tests.rs: origins_without_a_conversation_share_one_process_session" + }, { "file": "crates/openhuman-core/src/inference/registry.rs", "scope": "", diff --git a/tests/raw_coverage/host_inference_http_e2e.rs b/tests/raw_coverage/host_inference_http_e2e.rs index b756a047a4d..5d03f99d3dd 100644 --- a/tests/raw_coverage/host_inference_http_e2e.rs +++ b/tests/raw_coverage/host_inference_http_e2e.rs @@ -98,6 +98,7 @@ async fn http_models_and_chat_use_mocked_ollama_without_real_runtime() { label: "Round 23".to_string(), endpoint: format!("{base}/cloud"), auth_style: CloudAuthStyle::None, + headers: Default::default(), default_model: Some("cloud-default@0.5".to_string()), }]; config.save().await.expect("save config"); From fca4e39e534103cec55e27f26d7dc60202d59041 Mon Sep 17 00:00:00 2001 From: Shaurya Kesarwani Date: Thu, 3 Dec 2026 17:49:31 +0530 Subject: [PATCH 2/7] fix(config): drop stored provider headers when the endpoint changes A stored header may be a credential for the host it was set for. A save that changes a provider's endpoint now keeps none of them, whether the save omits the headers or echoes the redaction placeholder. Headers are kept only when the endpoint is unchanged apart from trailing slashes. --- .../src/config/ops/cloud_providers.rs | 25 +++++- crates/openhuman-core/src/config/ops/model.rs | 2 +- .../src/config/ops/model_byok_route.rs | 2 +- .../src/config/ops_provider_headers_tests.rs | 84 +++++++++++++++++++ .../src/config/schemas/helpers.rs | 3 +- .../config/schemas/schema_defs/inference.rs | 2 +- docs/TEST-COVERAGE-MATRIX.md | 2 +- .../model-routing/local-and-byok-models.md | 2 +- 8 files changed, 113 insertions(+), 9 deletions(-) diff --git a/crates/openhuman-core/src/config/ops/cloud_providers.rs b/crates/openhuman-core/src/config/ops/cloud_providers.rs index 28518213629..411555eb97b 100644 --- a/crates/openhuman-core/src/config/ops/cloud_providers.rs +++ b/crates/openhuman-core/src/config/ops/cloud_providers.rs @@ -6,6 +6,8 @@ use crate::config::schema::cloud_providers::{ }; use serde::Deserialize; +use super::model::model_byok_route::same_endpoint; + #[derive(Debug, Deserialize)] pub struct CloudProviderUpdate { pub(crate) id: Option, @@ -18,7 +20,8 @@ pub struct CloudProviderUpdate { #[serde(default)] pub(crate) ca_cert_pem: Option, /// Extra request headers for this provider (`{name: value}`). Omitted - /// (or empty) keeps the headers already stored for the entry. + /// (or empty) keeps the headers already stored for the entry, unless its + /// endpoint changes. #[serde(default)] pub(crate) headers: Option>, // keep until v0.66 (review after 2027-01-11): incoming RPC discriminator @@ -109,7 +112,11 @@ pub fn build_cloud_provider_creds( /// without `headers` keeps the ones stored for it (matched by id, else slug): /// the settings panel echoes every entry back on save and has no editor for /// headers, so a table set in `config.toml` must survive an unrelated edit. -/// Sending a non-empty map replaces them. A value equal to the redaction +/// Sending a non-empty map replaces them. +/// +/// Stored headers belong to the endpoint they were set for, because a value +/// may be a credential: an entry whose endpoint changed inherits nothing, so +/// the new host only receives what the save itself supplies. A value equal to the redaction /// placeholder the client snapshot shows ([`REDACTED_HEADER_VALUE`]) is an /// echo of a stored secret, not a new value, so it keeps the stored one; with /// nothing stored behind it the header is dropped rather than sent. @@ -123,7 +130,19 @@ pub(crate) fn carry_stored_headers( let previous = stored .iter() .find(|e| e.id == entry.id) - .or_else(|| stored.iter().find(|e| e.slug == entry.slug)); + .or_else(|| stored.iter().find(|e| e.slug == entry.slug)) + .filter(|previous| { + let unchanged = same_endpoint(&previous.endpoint, &entry.endpoint); + if !unchanged && !previous.headers.is_empty() { + log::debug!( + "[config] cloud provider '{}': endpoint changed, not carrying {} \ + stored header(s) over", + entry.slug, + previous.headers.len() + ); + } + unchanged + }); if entry.headers.is_empty() { if let Some(previous) = previous { entry.headers = previous.headers.clone(); diff --git a/crates/openhuman-core/src/config/ops/model.rs b/crates/openhuman-core/src/config/ops/model.rs index d0d5f4b4148..f3eeb30e752 100644 --- a/crates/openhuman-core/src/config/ops/model.rs +++ b/crates/openhuman-core/src/config/ops/model.rs @@ -7,7 +7,7 @@ use crate::core::Outcome; use super::loader::snapshot_config_json; #[path = "model_byok_route.rs"] -mod model_byok_route; +pub(super) mod model_byok_route; #[cfg(test)] use model_byok_route::BYOK_INFERENCE_SLUG; use model_byok_route::{complete_byok_route, ExplicitRolePins}; diff --git a/crates/openhuman-core/src/config/ops/model_byok_route.rs b/crates/openhuman-core/src/config/ops/model_byok_route.rs index b22b5e73def..f1dd4d96767 100644 --- a/crates/openhuman-core/src/config/ops/model_byok_route.rs +++ b/crates/openhuman-core/src/config/ops/model_byok_route.rs @@ -17,7 +17,7 @@ pub(super) struct ExplicitRolePins { pub(super) const BYOK_INFERENCE_SLUG: &str = "byok-inference"; /// Two endpoints are the same route if they differ only by trailing slashes. -fn same_endpoint(a: &str, b: &str) -> bool { +pub(in crate::config::ops) fn same_endpoint(a: &str, b: &str) -> bool { a.trim().trim_end_matches('/') == b.trim().trim_end_matches('/') } diff --git a/crates/openhuman-core/src/config/ops_provider_headers_tests.rs b/crates/openhuman-core/src/config/ops_provider_headers_tests.rs index 5da3c06793d..29893c1f20a 100644 --- a/crates/openhuman-core/src/config/ops_provider_headers_tests.rs +++ b/crates/openhuman-core/src/config/ops_provider_headers_tests.rs @@ -179,3 +179,87 @@ async fn apply_model_settings_restores_stored_values_for_echoed_placeholders() { "a placeholder with nothing stored is dropped, never sent" ); } + +#[tokio::test] +async fn apply_model_settings_drops_stored_headers_when_the_endpoint_changes() { + // A stored header may be a credential for the host it was set for, so it + // must not follow the entry to another one, neither through an omitted + // map nor through an echoed placeholder. + use crate::config::schema::cloud_providers::{ + AuthStyle, CloudProviderCreds, REDACTED_HEADER_VALUE, + }; + + let provider = |id: &str, endpoint: &str, headers: &[(&str, &str)]| CloudProviderCreds { + id: id.into(), + slug: "gateway".into(), + label: "Gateway".into(), + endpoint: endpoint.into(), + auth_style: AuthStyle::Bearer, + headers: headers + .iter() + .map(|(name, value)| (name.to_string(), value.to_string())) + .collect(), + default_model: None, + }; + let secret = [("x-api-secret", "sk-live-123")]; + let placeholder = [("x-api-secret", REDACTED_HEADER_VALUE)]; + let old = "https://gateway.example/v1"; + + for (case, incoming, expected) in [ + ( + "omitted headers, same id", + provider("gw-1", "https://other.example/v1", &[]), + None, + ), + ( + "omitted headers, matched by slug", + provider("gw-2", "https://other.example/v1", &[]), + None, + ), + ( + "echoed placeholder", + provider("gw-1", "https://other.example/v1", &placeholder), + None, + ), + ( + "same host over plain http", + provider("gw-1", "http://gateway.example/v1", &[]), + None, + ), + ( + "value supplied for the new endpoint", + provider( + "gw-1", + "https://other.example/v1", + &[("x-api-secret", "sk-new")], + ), + Some("sk-new"), + ), + ( + "trailing slash only", + provider("gw-1", "https://gateway.example/v1/", &[]), + Some("sk-live-123"), + ), + ] { + let tmp = tempdir().unwrap(); + let mut cfg = tmp_config(&tmp); + cfg.cloud_providers = vec![provider("gw-1", old, &secret)]; + let _ = apply_model_settings( + &mut cfg, + ModelSettingsPatch { + cloud_providers: Some(vec![incoming]), + ..Default::default() + }, + ) + .await + .expect("apply"); + assert_eq!( + cfg.cloud_providers[0] + .headers + .get("x-api-secret") + .map(String::as_str), + expected, + "{case}" + ); + } +} diff --git a/crates/openhuman-core/src/config/schemas/helpers.rs b/crates/openhuman-core/src/config/schemas/helpers.rs index 18e9c4a4833..cd24fb51784 100644 --- a/crates/openhuman-core/src/config/schemas/helpers.rs +++ b/crates/openhuman-core/src/config/schemas/helpers.rs @@ -30,7 +30,8 @@ pub(super) struct CloudProviderUpdate { pub(super) ca_cert_pem: Option, /// Extra request headers for this provider (`{name: value}`). Omitted /// (or empty) keeps the headers already stored for the entry, so a client - /// that does not know the field cannot drop them on save. + /// that does not know the field cannot drop them on save. An entry whose + /// endpoint changes keeps none. #[serde(default)] pub(super) headers: Option>, /// Legacy field — tolerated on read for back-compat but not required. diff --git a/crates/openhuman-core/src/config/schemas/schema_defs/inference.rs b/crates/openhuman-core/src/config/schemas/schema_defs/inference.rs index 736e83f1508..719a40eed76 100644 --- a/crates/openhuman-core/src/config/schemas/schema_defs/inference.rs +++ b/crates/openhuman-core/src/config/schemas/schema_defs/inference.rs @@ -96,7 +96,7 @@ pub(super) fn lookup(function: &str) -> Option { FieldSchema { name: "cloud_providers", ty: TypeSchema::Option(Box::new(TypeSchema::Json)), - comment: "Optional list of cloud provider entries {id, slug, label, endpoint, auth_style, ca_cert_pem, headers}. The optional PEM CA bundle is trusted only for this provider; an empty string clears it. `headers` is an optional {name: value} map of extra request headers sent on every request to this provider; omitting it keeps the entry's stored headers. API keys are stored separately via cloud_provider_set_key. Replaces config.cloud_providers wholesale.", + comment: "Optional list of cloud provider entries {id, slug, label, endpoint, auth_style, ca_cert_pem, headers}. The optional PEM CA bundle is trusted only for this provider; an empty string clears it. `headers` is an optional {name: value} map of extra request headers sent on every request to this provider; omitting it keeps the entry's stored headers while its endpoint is unchanged. API keys are stored separately via cloud_provider_set_key. Replaces config.cloud_providers wholesale.", required: false, }, optional_string( diff --git a/docs/TEST-COVERAGE-MATRIX.md b/docs/TEST-COVERAGE-MATRIX.md index 82e5938d081..a50edfd6dc2 100644 --- a/docs/TEST-COVERAGE-MATRIX.md +++ b/docs/TEST-COVERAGE-MATRIX.md @@ -130,7 +130,7 @@ Local inference runs against a runtime the user installs, starts, and pulls mode | 3.1.3 | Model Version Handling | RU | `crates/openhuman-core/src/config/schema/types/model_ids.rs` | ✅ | **Path corrected** (was `crates/openhuman-core/src/inference/model_ids.rs`). | | 3.1.4 | LM Studio Model Discovery | RU+RI | `vendor/tinyagents/vendor/tinyinference/crates/tinyinference-local/src/service/ollama_admin_tests.rs` (LM Studio cases), `tests/json_rpc_e2e.rs` | ✅ | Uses LM Studio's OpenAI-compatible `/v1/models` surface. **Path corrected** (was `crates/openhuman-core/src/inference/local/service/ollama_admin_tests.rs`, which moved upstream with the runtime). ⚠️ **`tinyinference-local` is not built by any OpenHuman lane** — `vendor` is in the root `[workspace] exclude` and no CI step names the package, so its unit tests are cited history, not executed coverage. | | 3.1.5 | Model Context-Window Requirement Gate | RU | `vendor/tinyagents/vendor/tinyinference/crates/tinyinference-local/src/model_requirements.rs`, `vendor/tinyagents/vendor/tinyinference/crates/tinyinference-local/src/ollama.rs` | 🟡 | Rejects Ollama models whose native context window is below the memory-layer minimum (`local_ai.model_context_check`). The model is one the user pulled; OpenHuman no longer suggests or pulls a replacement. ⚠️ **`tinyinference-local` is not built by any OpenHuman lane** — `vendor` is in the root `[workspace] exclude` and no CI step names the package, so its unit tests are cited history, not executed coverage. | -| 3.1.6 | Cloud provider request identity (`[[cloud_providers]].headers`, product `User-Agent`, OpenCode Go `x-opencode-session`) | RU | `crates/openhuman-core/src/inference/provider/factory/request_identity_tests.rs`, `crates/openhuman-core/src/inference/provider/factory_request_headers_tests.rs`, `crates/openhuman-core/src/config/schema/cloud_providers_tests.rs`, `crates/openhuman-core/src/config/ops_provider_headers_tests.rs` | ✅ | A `headers` table on the entry and `openhuman/` reach the provider on a chat request (wiremock); an OpenCode Go endpoint gets a session id derived from the turn origin (thread / channel conversation / job), stable within a conversation and distinct across them; configured `User-Agent` / `x-opencode-session` values win; the table round-trips through TOML and survives a settings save that omits it (#7865) | +| 3.1.6 | Cloud provider request identity (`[[cloud_providers]].headers`, product `User-Agent`, OpenCode Go `x-opencode-session`) | RU | `crates/openhuman-core/src/inference/provider/factory/request_identity_tests.rs`, `crates/openhuman-core/src/inference/provider/factory_request_headers_tests.rs`, `crates/openhuman-core/src/config/schema/cloud_providers_tests.rs`, `crates/openhuman-core/src/config/ops_provider_headers_tests.rs` | ✅ | A `headers` table on the entry and `openhuman/` reach the provider on a chat request (wiremock); an OpenCode Go endpoint gets a session id derived from the turn origin (thread / channel conversation / job), stable within a conversation and distinct across them; configured `User-Agent` / `x-opencode-session` values win; the table round-trips through TOML, survives a settings save that omits it, and is dropped when the save changes the endpoint (#7865) | ### 3.2 Runtime Execution diff --git a/docs/gitbooks/en/features/model-routing/local-and-byok-models.md b/docs/gitbooks/en/features/model-routing/local-and-byok-models.md index 1245c8d42d6..6cfe635094f 100644 --- a/docs/gitbooks/en/features/model-routing/local-and-byok-models.md +++ b/docs/gitbooks/en/features/model-routing/local-and-byok-models.md @@ -146,7 +146,7 @@ auth_style = "bearer" x-tenant = "team-a" ``` -Header names and values must be valid HTTP headers; a malformed one makes requests to that provider fail with an error naming the provider and the header. Header values may be secrets, so the settings UI only ever sees their names. +Header names and values must be valid HTTP headers, and two names may not differ only by case; a malformed or duplicate one makes requests to that provider fail with an error naming the provider and the header. Header values may be secrets, so the settings UI only ever sees their names. Saving settings keeps the stored headers as long as the endpoint is unchanged. When a save changes the endpoint, the stored headers are dropped, so a credential never follows the entry to another host; set them again for the new endpoint. OpenCode Go (`https://opencode.ai/zen/go/v1`) needs no such table: it requires a stable per-conversation `x-opencode-session`, and OpenHuman derives one from the chat thread, channel conversation or automation job each request belongs to, so a thread's turns and its title and summary calls share a session. From cf1b0a80cfc8f6fae228fee35313216770c1c471 Mon Sep 17 00:00:00 2001 From: Shaurya Kesarwani Date: Thu, 3 Dec 2026 17:49:31 +0530 Subject: [PATCH 3/7] fix(config): reject provider header names that differ only by case HTTP header names are case-insensitive, so both would be sent with no defined winner. The config-domain save path now validates headers like the inference-domain one. --- .../src/config/schema/cloud_providers.rs | 13 +++++++++++-- .../src/config/schema/cloud_providers_tests.rs | 16 ++++++++++++++++ .../src/config/schemas/controllers/inference.rs | 8 +++++--- 3 files changed, 32 insertions(+), 5 deletions(-) diff --git a/crates/openhuman-core/src/config/schema/cloud_providers.rs b/crates/openhuman-core/src/config/schema/cloud_providers.rs index b71cbd4e490..28256eb9fea 100644 --- a/crates/openhuman-core/src/config/schema/cloud_providers.rs +++ b/crates/openhuman-core/src/config/schema/cloud_providers.rs @@ -397,7 +397,7 @@ pub fn redacted_headers(headers: &BTreeMap) -> BTreeMap, ) -> Result<(), String> { + let mut seen = std::collections::HashSet::new(); for (name, value) in headers { - reqwest::header::HeaderName::from_bytes(name.as_bytes()) + // `HeaderName` is lowercase-normalized, so it equates names that differ + // only by case. Both would be sent, with no defined winner. + let parsed = reqwest::header::HeaderName::from_bytes(name.as_bytes()) .map_err(|_| format!("cloud provider '{slug}': invalid header name '{name}'"))?; + if !seen.insert(parsed) { + return Err(format!( + "cloud provider '{slug}': duplicate header name '{name}' (names are \ + case-insensitive)" + )); + } reqwest::header::HeaderValue::from_str(value) .map_err(|_| format!("cloud provider '{slug}': invalid value for header '{name}'"))?; } diff --git a/crates/openhuman-core/src/config/schema/cloud_providers_tests.rs b/crates/openhuman-core/src/config/schema/cloud_providers_tests.rs index 8db40796341..6bba0038257 100644 --- a/crates/openhuman-core/src/config/schema/cloud_providers_tests.rs +++ b/crates/openhuman-core/src/config/schema/cloud_providers_tests.rs @@ -477,6 +477,22 @@ fn validate_provider_headers_names_the_provider_and_header_but_not_the_value() { assert!(!error.contains("sk-secret")); } +#[test] +fn validate_provider_headers_rejects_names_that_differ_only_by_case() { + use super::validate_provider_headers; + + let headers = [ + ("User-Agent".to_string(), "agent/1".to_string()), + ("user-agent".to_string(), "agent/2".to_string()), + ] + .into(); + let error = validate_provider_headers("gw", &headers).expect_err("case-variant duplicate"); + assert_eq!( + error, + "cloud provider 'gw': duplicate header name 'user-agent' (names are case-insensitive)" + ); +} + #[test] fn redacted_headers_keep_names_and_hide_every_value() { use super::{redacted_headers, REDACTED_HEADER_VALUE}; diff --git a/crates/openhuman-core/src/config/schemas/controllers/inference.rs b/crates/openhuman-core/src/config/schemas/controllers/inference.rs index dc4964f923c..da5a0299e5c 100644 --- a/crates/openhuman-core/src/config/schemas/controllers/inference.rs +++ b/crates/openhuman-core/src/config/schemas/controllers/inference.rs @@ -69,8 +69,8 @@ pub(super) fn handle_update_model_settings( .cloud_providers .map(|entries| { use crate::config::schema::cloud_providers::{ - generate_provider_id, is_slug_reserved, builtin_cloud_provider, AuthStyle, - CloudProviderCreds, + generate_provider_id, is_slug_reserved, builtin_cloud_provider, + validate_provider_headers, AuthStyle, CloudProviderCreds, }; let reserved_count = entries .iter() @@ -145,13 +145,15 @@ pub(super) fn handle_update_model_settings( .label .filter(|s| !s.trim().is_empty()) .unwrap_or_else(|| slug.clone()); + let headers = e.headers.unwrap_or_default(); + validate_provider_headers(&slug, &headers)?; let entry = CloudProviderCreds { id, slug, label, endpoint, auth_style, - headers: e.headers.unwrap_or_default(), + headers, default_model: e.default_model, }; Ok(entry) From a8b17646ce14fd27175fcf8a1c17fc63b216ffb9 Mon Sep 17 00:00:00 2001 From: Shaurya Kesarwani Date: Thu, 3 Dec 2026 17:49:31 +0530 Subject: [PATCH 4/7] fix(providers): let a configured User-Agent replace the Codex one The transport appends the route's user agent next to the extra headers, so a Codex OAuth request carried both values. --- .../provider/factory/request_identity.rs | 15 +++-- .../factory/request_identity_tests.rs | 15 +++++ .../provider/factory_request_headers_tests.rs | 57 +++++++++++++++++++ 3 files changed, 82 insertions(+), 5 deletions(-) diff --git a/crates/openhuman-core/src/inference/provider/factory/request_identity.rs b/crates/openhuman-core/src/inference/provider/factory/request_identity.rs index 107e2fe1cfa..8f75fb93f33 100644 --- a/crates/openhuman-core/src/inference/provider/factory/request_identity.rs +++ b/crates/openhuman-core/src/inference/provider/factory/request_identity.rs @@ -23,8 +23,8 @@ use tinyinference_providers::builtin::endpoint_host; pub const OPENCODE_SESSION_HEADER: &str = "x-opencode-session"; /// The `User-Agent` OpenHuman presents to OpenAI-compatible cloud providers -/// (`openhuman/`), unless a route sets its own (Codex OAuth) or -/// the provider entry configures one. +/// (`openhuman/`), unless the provider entry configures one or a +/// route sets its own (Codex OAuth); the configured one wins over both. pub fn product_user_agent() -> String { format!("openhuman/{}", env!("CARGO_PKG_VERSION")) } @@ -98,8 +98,9 @@ pub fn has_header(headers: &[(String, String)], name: &str) -> bool { .any(|(existing, _)| existing.eq_ignore_ascii_case(name)) } -/// Completes a cloud route's request identity in place: the product -/// `User-Agent` when the route set none and the entry configured none, and the +/// Completes a cloud route's request identity in place: exactly one +/// `User-Agent` (the configured header if there is one, else the route's own, +/// else the product one), and the /// OpenCode Go session header when `endpoint` requires it and the entry did /// not configure one. `origin` is the turn the client is built for. pub fn apply_request_identity( @@ -116,7 +117,11 @@ pub fn apply_request_identity( headers.len(), user_agent.is_some() ); - if user_agent.is_none() && !has_header(headers, "user-agent") { + if has_header(headers, "user-agent") { + // The transport appends `user_agent` next to `headers`, so a route's + // own value (Codex OAuth) has to go for the configured one to stand. + *user_agent = None; + } else if user_agent.is_none() { *user_agent = Some(product_user_agent()); } if endpoint_requires_opencode_session(endpoint) && !has_header(headers, OPENCODE_SESSION_HEADER) diff --git a/crates/openhuman-core/src/inference/provider/factory/request_identity_tests.rs b/crates/openhuman-core/src/inference/provider/factory/request_identity_tests.rs index 5f29c5b86ef..34e0cb79333 100644 --- a/crates/openhuman-core/src/inference/provider/factory/request_identity_tests.rs +++ b/crates/openhuman-core/src/inference/provider/factory/request_identity_tests.rs @@ -198,6 +198,21 @@ fn request_identity_defers_to_configured_headers_and_a_route_user_agent() { assert_eq!(user_agent.as_deref(), Some("codex_cli_rs/1.0")); } +#[test] +fn a_configured_user_agent_replaces_the_route_user_agent() { + let configured = vec![("user-agent".to_string(), "my-agent/1.0".to_string())]; + let mut headers = configured.clone(); + let mut user_agent = Some("codex_cli_rs/1.0".to_string()); + apply_request_identity( + "https://api.openai.com/v1", + None, + &mut headers, + &mut user_agent, + ); + assert_eq!(headers, configured); + assert_eq!(user_agent, None, "the route value must not be sent as well"); +} + fn catalog_entry( headers: &[(&str, &str)], ) -> crate::config::schema::cloud_providers::CloudProviderCreds { diff --git a/crates/openhuman-core/src/inference/provider/factory_request_headers_tests.rs b/crates/openhuman-core/src/inference/provider/factory_request_headers_tests.rs index f64fe49cc6d..871554895f5 100644 --- a/crates/openhuman-core/src/inference/provider/factory_request_headers_tests.rs +++ b/crates/openhuman-core/src/inference/provider/factory_request_headers_tests.rs @@ -174,3 +174,60 @@ async fn a_malformed_configured_header_fails_the_build_naming_provider_and_heade "{error}" ); } + +/// Codex OAuth always targets the fixed ChatGPT backend, so this builds the +/// route the way `cloud_slug` does, with the endpoint pointed at the mock. +#[tokio::test] +async fn a_configured_user_agent_is_the_only_one_on_a_codex_oauth_request() { + use super::cloud_spec::{build_cloud_model, cloud_provider_spec, CloudBuild}; + use super::request_identity::{apply_request_identity, configured_headers}; + use tinyinference_llm::providers::openai::codex::OpenAiCodexRouting; + use tinyinference_llm::providers::openai::AuthStyle as CompatAuthStyle; + + let _guard = crate::inference::inference_test_guard_async().await; + let server = MockServer::start().await; + // The reply is irrelevant; the test reads the recorded request. + Mock::given(method("POST")) + .respond_with(ResponseTemplate::new(400)) + .mount(&server) + .await; + let entry = entry_for(&server, &[("User-Agent", "my-agent/1.0")]); + let codex = OpenAiCodexRouting { + endpoint: format!("{}/backend-api/codex", server.uri()), + using_oauth: true, + account_id: Some("acct-1".to_string()), + }; + let mut headers = configured_headers(&entry).expect("valid headers"); + let mut user_agent = Some("codex_cli_rs/1.0".to_string()); + apply_request_identity(&entry.endpoint, None, &mut headers, &mut user_agent); + + let model = build_cloud_model(CloudBuild { + spec: cloud_provider_spec(&entry, "m"), + auth_style: CompatAuthStyle::Bearer, + key: "oauth-bearer", + temperature_override: None, + temperature_unsupported_models: &[], + native_tool_calling: true, + default_provider_options: None, + extra_headers: &headers, + extra_query_params: &[], + user_agent: user_agent.as_deref(), + codex: Some(&codex), + http: None, + }) + .expect("codex model builds"); + let request = tinyinference_llm::model::ModelRequest::new(vec![Message::user("hi")]); + let _ = model.invoke(&(), request).await; + + let requests = server.received_requests().await.expect("recording on"); + assert!(!requests.is_empty(), "the codex route was called"); + for request in &requests { + assert!( + request.url.path().ends_with("/responses"), + "{}", + request.url + ); + let sent: Vec<_> = request.headers.get_all("user-agent").iter().collect(); + assert_eq!(sent, ["my-agent/1.0"]); + } +} From 7db98005d81b01a77803094d7f3aa25600fcd1f0 Mon Sep 17 00:00:00 2001 From: Shaurya Kesarwani Date: Thu, 3 Dec 2026 17:49:31 +0530 Subject: [PATCH 5/7] fix(threads): generate titles under the thread's own origin The title request arrives on a transport context that names no turn, so its OpenCode Go session was the process-wide one. Bind the thread's origin so it shares the conversation's session. --- .../src/threads/ops/title_generation.rs | 16 ++++++++++++- .../src/threads/ops/title_generation_tests.rs | 24 +++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/crates/openhuman-core/src/threads/ops/title_generation.rs b/crates/openhuman-core/src/threads/ops/title_generation.rs index 8709fcdcbce..e2649864c8b 100644 --- a/crates/openhuman-core/src/threads/ops/title_generation.rs +++ b/crates/openhuman-core/src/threads/ops/title_generation.rs @@ -6,6 +6,7 @@ use super::support::{ update_title_unless_renamed, }; use crate::config::Config; +use crate::core::runtime::turn_origin::AgentTurnOrigin; use crate::core::runtime::DispatchCtx; use crate::core::Outcome; use crate::inference::provider; @@ -46,6 +47,18 @@ pub(crate) fn is_replaceable_title( .is_some_and(|interim| interim == title.trim()) } +/// `ctx` with the thread's own origin bound. The request arrives on a transport +/// context that names no turn; binding the origin makes the title call part of +/// its conversation, so a provider that routes by session (OpenCode Go) sees +/// one session for the title and the thread's turns. +fn title_dispatch(ctx: &DispatchCtx, thread_id: &str) -> DispatchCtx { + ctx.with_turn_origin(AgentTurnOrigin::WebChat { + thread_id: thread_id.to_string(), + client_id: String::new(), + request_id: None, + }) +} + /// Generates a durable thread title from the first user message and assistant reply. pub async fn thread_generate_title( ctx: &DispatchCtx, @@ -131,8 +144,9 @@ pub async fn thread_generate_title( // `_with_model_id` rather than the plain constructor: the debug line below // reports the model this call actually dispatches on, and only the factory // knows what the `summarization` role resolved to for this configuration. + let title_ctx = title_dispatch(ctx, &request.thread_id); let (chat_model, resolved_model) = match provider::create_chat_model_with_model_id_in( - ctx, + &title_ctx, "summarization", &config, 0.2, diff --git a/crates/openhuman-core/src/threads/ops/title_generation_tests.rs b/crates/openhuman-core/src/threads/ops/title_generation_tests.rs index cced55e131d..a5387dbfcec 100644 --- a/crates/openhuman-core/src/threads/ops/title_generation_tests.rs +++ b/crates/openhuman-core/src/threads/ops/title_generation_tests.rs @@ -27,3 +27,27 @@ fn user_chosen_title_is_never_replaced() { assert!(!is_replaceable_title("Inbox triage", Some(message), 0)); assert!(!is_replaceable_title("Inbox triage", None, 0)); } + +#[test] +fn a_title_call_shares_the_session_of_its_threads_turns() { + use crate::inference::provider::factory::request_identity::opencode_session_id; + + let turn = |thread_id: &str| AgentTurnOrigin::WebChat { + thread_id: thread_id.to_string(), + client_id: "client-1".to_string(), + request_id: Some("req-1".to_string()), + }; + let title_session = |ctx: &DispatchCtx| { + let origin = title_dispatch(ctx, "thread-a").turn_origin_or_scoped(); + opencode_session_id(origin.as_ref()) + }; + let expected = opencode_session_id(Some(&turn("thread-a"))); + + let transport = DispatchCtx::ambient(); + assert_eq!(title_session(&transport), expected); + // A title requested from another conversation's turn still belongs to the + // thread it names. + let other_turn = transport.with_turn_origin(turn("thread-b")); + assert_eq!(title_session(&other_turn), expected); + assert_ne!(expected, opencode_session_id(Some(&turn("thread-b")))); +} From 71d41a4aee9a20dc828da410a4bd1bdbed0d3a0f Mon Sep 17 00:00:00 2001 From: Shaurya Kesarwani Date: Thu, 3 Dec 2026 17:49:31 +0530 Subject: [PATCH 6/7] fix(config): hide provider header values in the full config snapshot main now masks every credential in that snapshot; the new headers table has to follow the same rule. --- .../src/config/ops/loader/snapshot.rs | 9 ++++++++- .../config/ops/loader_snapshot_secrets_tests.rs | 17 +++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/crates/openhuman-core/src/config/ops/loader/snapshot.rs b/crates/openhuman-core/src/config/ops/loader/snapshot.rs index e5ffa127340..8beeac618ed 100644 --- a/crates/openhuman-core/src/config/ops/loader/snapshot.rs +++ b/crates/openhuman-core/src/config/ops/loader/snapshot.rs @@ -45,7 +45,8 @@ pub async fn snapshot_config_json(config: &Config) -> Result server.auth = McpAuthConfig::None, } } + // Any provider header can hold a key (`Authorization`, `x-tenant`), so + // every value goes; the names stay. + for provider in &mut config.cloud_providers { + provider.headers = + crate::config::schema::cloud_providers::redacted_headers(&provider.headers); + } // Client-declared metadata with free-form keys (an `Authorization` entry // has no credential-shaped name), and nothing displays it. blank_strings(&mut config.mcp_client.client_identity.capabilities); diff --git a/crates/openhuman-core/src/config/ops/loader_snapshot_secrets_tests.rs b/crates/openhuman-core/src/config/ops/loader_snapshot_secrets_tests.rs index 91efd688c9a..adfb886cab1 100644 --- a/crates/openhuman-core/src/config/ops/loader_snapshot_secrets_tests.rs +++ b/crates/openhuman-core/src/config/ops/loader_snapshot_secrets_tests.rs @@ -67,6 +67,16 @@ fn config_with_every_secret() -> Config { })) }) .collect(); + config.cloud_providers = vec![crate::config::schema::cloud_providers::CloudProviderCreds { + slug: "gateway".into(), + endpoint: "https://gateway.example/v1".into(), + headers: [ + ("Authorization".to_string(), format!("Bearer {SENTINEL}")), + ("x-tenant".to_string(), SENTINEL.to_string()), + ] + .into(), + ..Default::default() + }]; config.mcp_client.registry_auth.smithery_api_key = Some(SENTINEL.into()); config.mcp_client.registry_auth.mcp_official_token = Some(SENTINEL.into()); config.mcp_client.client_identity.capabilities = json!({ @@ -130,6 +140,13 @@ async fn snapshot_carries_no_credential() { assert_eq!(server["env"]["AWS_SECRET_ACCESS_KEY"], ""); assert_eq!(server["args"], json!(["", "", ""])); assert_eq!(server["endpoint"], "https://***@mcp.example/rpc?***"); + // Provider headers keep their names. + let headers = &snapshot["config"]["cloud_providers"][0]["headers"]; + assert_eq!( + headers["x-tenant"], + crate::config::schema::cloud_providers::REDACTED_HEADER_VALUE + ); + assert!(headers.get("Authorization").is_some()); assert_eq!( snapshot["config"]["proxy"]["http_proxy"], "http://***@proxy.example:8080" From 93499cc855fd56df1a8e71e7c3fe794dc0288874 Mon Sep 17 00:00:00 2001 From: Shaurya Kesarwani Date: Fri, 4 Dec 2026 14:23:07 +0530 Subject: [PATCH 7/7] fix(config): keep provider header placeholders intact and match echoed names case-insensitively The full snapshot's generic secret masker blanked provider headers whose name ends in token or secret, so a client echoing the snapshot back would have overwritten the stored value with an empty string. Restore the placeholder after that pass. Restoring an echoed placeholder on save now finds the stored header regardless of name case. --- .../src/config/ops/cloud_providers.rs | 12 +++++- .../src/config/ops/loader/snapshot.rs | 20 ++++++++++ .../ops/loader_snapshot_secrets_tests.rs | 18 +++++++++ .../src/config/ops_provider_headers_tests.rs | 40 +++++++++++++++++++ 4 files changed, 89 insertions(+), 1 deletion(-) diff --git a/crates/openhuman-core/src/config/ops/cloud_providers.rs b/crates/openhuman-core/src/config/ops/cloud_providers.rs index 411555eb97b..39f48dc01df 100644 --- a/crates/openhuman-core/src/config/ops/cloud_providers.rs +++ b/crates/openhuman-core/src/config/ops/cloud_providers.rs @@ -153,7 +153,17 @@ pub(crate) fn carry_stored_headers( if value != REDACTED_HEADER_VALUE { return true; } - match previous.and_then(|p| p.headers.get(name)) { + // Header names are case-insensitive on the wire, so a client + // that re-cases one still names the stored header. + let stored_value = previous.and_then(|p| { + p.headers.get(name).or_else(|| { + p.headers + .iter() + .find(|(stored, _)| stored.eq_ignore_ascii_case(name)) + .map(|(_, v)| v) + }) + }); + match stored_value { Some(stored_value) => { *value = stored_value.clone(); true diff --git a/crates/openhuman-core/src/config/ops/loader/snapshot.rs b/crates/openhuman-core/src/config/ops/loader/snapshot.rs index 8beeac618ed..9a385b64fdc 100644 --- a/crates/openhuman-core/src/config/ops/loader/snapshot.rs +++ b/crates/openhuman-core/src/config/ops/loader/snapshot.rs @@ -22,6 +22,11 @@ pub async fn snapshot_config_json(config: &Config) -> Result