use super::*;
use crate::wire::secret::tests::a_config_reloads_without_its_credential;
pub(super) fn recorded(section: &str, relative: &str) -> String {
let root = concat!(
env!("CARGO_MANIFEST_DIR"),
"/../rig-cassette/fixtures/cassettes/openai/"
);
let text = std::fs::read_to_string(format!("{root}{relative}"))
.unwrap_or_else(|error| panic!("cassette {relative} is readable: {error}"));
let (when, then) = text
.split_once("\nthen:\n")
.unwrap_or_else(|| panic!("cassette {relative} has a `then:` section"));
let scope = if section == "when" { when } else { then };
let mut lines = scope.lines();
let body = lines
.by_ref()
.find(|line| line.trim_start().starts_with("body:"))
.and_then(|line| line.split_once("body:"))
.map(|(_, rest)| rest.trim())
.unwrap_or_else(|| panic!("cassette {relative} names a {section} body"));
if let Some(quoted) = body.strip_prefix('\'').and_then(|b| b.strip_suffix('\'')) {
return quoted.replace("''", "'");
}
let mut block = String::new();
for line in lines {
if !line.is_empty() && !line.starts_with(" ") {
break;
}
block.push_str(line.get(4..).unwrap_or_default());
block.push('\n');
}
block
}
pub(super) fn recorded_json(section: &str, relative: &str) -> serde_json::Value {
serde_json::from_str(&recorded(section, relative))
.unwrap_or_else(|error| panic!("cassette {relative} {section} body is JSON: {error}"))
}
#[test]
fn a_serialized_configuration_carries_no_key_material() {
a_config_reloads_without_its_credential(
&OpenAIConfig::new("sk-secret"),
"sk-secret",
|openai| &openai.api_key,
);
for wire in [
serde_json::to_string(&OpenAIConfig::new("sk-secret").chat("gpt-5.2")),
serde_json::to_string(&OpenAIConfig::new("sk-secret").responses("gpt-5.2")),
] {
let json = wire.expect("the wire serializes");
assert!(!json.contains("sk-secret"), "the key leaked: {json}");
}
}
#[test]
fn a_gateway_configuration_round_trips_without_its_credential() {
let chatgpt = crate::providers::chatgpt::DIALECT;
let config = OpenAIConfig::with_key(&chatgpt, "tok-secret").with_account_id("acct-1");
assert_eq!(
config.instructions.as_deref(),
chatgpt.quirks.default_instructions
);
assert!(config.identity.is_some());
let json = serde_json::to_string(&config).expect("serializes");
assert!(!json.contains("tok-secret"), "the token leaked: {json}");
let restored: OpenAIConfig = serde_json::from_str(&json).expect("deserializes");
assert_eq!(restored.dialect, chatgpt);
assert_eq!(restored.account_id.as_deref(), Some("acct-1"));
assert_eq!(restored.instructions, config.instructions);
assert_eq!(restored.identity, config.identity);
assert!(restored.api_key.is_empty());
let wire = config.responses("gpt-5.4");
let restored: super::super::responses_api::wire::Responses =
serde_json::from_str(&serde_json::to_string(&wire).expect("serializes"))
.expect("deserializes");
assert_eq!(restored.system_instructions, wire.system_instructions);
assert_eq!(restored.provider.dialect, chatgpt);
}
fn route_of(wire: &OpenAiWire) -> Option<&'static str> {
use crate::wire::Wire as _;
let request = crate::completion::CompletionRequest::new("hi");
let encoded = wire
.encode(request, crate::wire::Mode::Unary)
.expect("the request encodes");
let path = encoded.request.uri().path();
["/responses", "/chat/completions"]
.into_iter()
.find(|endpoint| path.ends_with(endpoint))
}
#[test]
fn the_default_completion_wire_is_the_dialects_route_and_round_trips() {
use crate::wire::Wire as _;
let openai = OpenAIConfig::new("sk-secret").completion("gpt-5.2");
let groq = OpenAIConfig::with_key(&GROQ, "gsk-secret").completion("llama-3.3-70b-versatile");
assert!(matches!(openai, OpenAiWire::Responses(_)), "{openai:?}");
assert!(matches!(groq, OpenAiWire::Chat(_)), "{groq:?}");
assert_eq!(route_of(&openai), Some("/responses"));
assert_eq!(route_of(&groq), Some("/chat/completions"));
for (wire, secret) in [(openai, "sk-secret"), (groq, "gsk-secret")] {
let json = serde_json::to_string(&wire).expect("the wire serializes");
assert!(!json.contains(secret), "the key leaked: {json}");
let restored: OpenAiWire = serde_json::from_str(&json).expect("the wire deserializes");
assert_eq!(restored.describe().model, wire.describe().model);
assert_eq!(restored.provider().dialect, wire.provider().dialect);
assert_eq!(
std::mem::discriminant(&restored),
std::mem::discriminant(&wire)
);
}
}
#[test]
fn a_configured_route_overrides_the_dialects_and_round_trips() {
let on_chat = OpenAIConfig::new("sk-secret").with_route(Route::Chat);
let on_responses = OpenAIConfig::with_key(&GROQ, "gsk-secret").with_route(Route::Responses);
assert_eq!(on_chat.completion_route(), Route::Chat);
assert_eq!(on_responses.completion_route(), Route::Responses);
assert_eq!(
route_of(&on_chat.completion("gpt-5.2")),
Some("/chat/completions")
);
assert_eq!(
route_of(&on_responses.completion("llama")),
Some("/responses")
);
let restored: OpenAIConfig =
serde_json::from_str(&serde_json::to_string(&on_chat).expect("serializes"))
.expect("deserializes");
assert_eq!(restored.completion_route(), Route::Chat);
assert!(
matches!(restored.completion("gpt-5.2"), OpenAiWire::Chat(_)),
"the configured route survives storage"
);
let json = serde_json::to_string(&OpenAIConfig::new("sk-secret")).expect("serializes");
assert!(!json.contains("route"), "{json}");
}
#[test]
fn a_dialect_round_trips_through_its_name() {
let json = serde_json::to_string(&GROQ).expect("a dialect serializes");
assert_eq!(json, "\"groq\"");
assert_eq!(
serde_json::from_str::<Dialect>(&json).expect("a dialect deserializes"),
GROQ
);
let config = OpenAIConfig::new("k").with_dialect(&MISTRAL);
let restored: OpenAIConfig =
serde_json::from_str(&serde_json::to_string(&config).expect("serializes"))
.expect("deserializes");
assert_eq!(restored.dialect, MISTRAL);
assert_eq!(restored.base_url, MISTRAL.base_url);
}
#[test]
fn an_unknown_dialect_name_is_rejected() {
let error = serde_json::from_str::<Dialect>("\"not-a-provider\"")
.expect_err("an unknown dialect is rejected");
assert!(
error.to_string().contains("not-a-provider"),
"the error names the dialect: {error}"
);
}
#[test]
fn the_dialect_decides_the_credential_header() {
fn headers(provider: &OpenAIConfig) -> http::HeaderMap {
provider
.authenticate(http::Request::get("https://example.invalid/"))
.body(())
.expect("builds")
.headers()
.clone()
}
let openai = headers(&OpenAIConfig::new("sk-test"));
assert_eq!(openai["authorization"], "Bearer sk-test");
let azure = headers(&OpenAIConfig::with_key(&AZURE, "azure-key"));
assert_eq!(azure["api-key"], "azure-key");
assert!(!azure.contains_key("authorization"));
let keyless = headers(&OpenAIConfig::with_key(&LLAMACPP, ""));
assert!(
!keyless.contains_key("authorization"),
"`llama-server` rejects a request carrying a key it was not started with"
);
let keyed = headers(&OpenAIConfig::with_key(&LLAMACPP, "local"));
assert_eq!(keyed["authorization"], "Bearer local");
}
#[test]
fn the_chatgpt_session_id_is_the_cache_key() {
let config = OpenAIConfig::with_key(&crate::providers::chatgpt::DIALECT, "tok");
let session = |key: Option<&str>| {
let request = config
.headers_in_session(http::Request::get("https://example.invalid/"), key)
.body(())
.expect("builds");
assert!(
!request.headers().contains_key("session_id"),
"the backend ignores the underscored spelling"
);
request
.headers()
.get("session-id")
.and_then(|value| value.to_str().ok())
.map(str::to_owned)
};
assert_eq!(session(Some("agent-1")).as_deref(), Some("agent-1"));
assert_eq!(session(Some("agent-1")), session(Some("agent-1")));
let fresh = session(None).expect("a fresh id");
assert_ne!(Some(fresh), session(None));
}
#[test]
fn a_dialect_without_a_verify_endpoint_refuses_to_invent_one() {
use crate::wire::{Mode, Wire};
assert!(
OpenAIConfig::with_key(&PERPLEXITY, "k")
.verify()
.encode((), Mode::Unary)
.is_err()
);
assert!(
OpenAIConfig::new("k")
.verify()
.encode((), Mode::Unary)
.is_ok()
);
}
#[test]
fn azure_accepts_either_credential_under_its_own_header() {
fn headers(provider: &OpenAIConfig) -> http::HeaderMap {
provider
.authenticate(http::Request::get("https://example.invalid/"))
.body(())
.expect("builds")
.headers()
.clone()
}
let alternative = AZURE
.alternate_auth
.expect("azure accepts a second credential");
assert_eq!(alternative.api_key_env, "AZURE_TOKEN");
assert_eq!(alternative.auth, Auth::Bearer);
assert_eq!(AZURE.api_key_env, "AZURE_API_KEY");
let keyed = headers(&OpenAIConfig::with_key(&AZURE, "account-key"));
assert_eq!(keyed["api-key"], "account-key");
assert!(!keyed.contains_key("authorization"));
let token = headers(&OpenAIConfig::with_key(&AZURE, "entra-token").with_auth(alternative.auth));
assert_eq!(token["authorization"], "Bearer entra-token");
assert!(
!token.contains_key("api-key"),
"an Entra token is not an account key"
);
}
#[test]
fn the_huggingface_sub_route_decides_the_model_and_the_routes() {
assert_eq!(
SubRoute::Fireworks.model_identifier("llama-3.3-70b"),
"llama-3.3-70b:fireworks"
);
assert_eq!(
SubRoute::Fireworks.model_identifier("llama-3.3-70b:fireworks"),
"llama-3.3-70b:fireworks"
);
assert_eq!(
SubRoute::Together.model_identifier("llama-3.3-70b"),
"llama-3.3-70b:together"
);
assert_eq!(SubRoute::HFInference.slug(), "hf-inference");
assert_eq!(SubRoute::Fireworks.slug(), "fireworks");
assert_eq!(SubRoute::from("my-route").slug(), "my-route");
let default = OpenAIConfig::with_key(&HUGGINGFACE, "hf");
assert_eq!(
default
.modality_uri(
"transcription",
"/audio/transcriptions",
"openai/whisper-large-v3"
)
.expect("hf-inference serves transcription"),
"https://router.huggingface.co/hf-inference/models/openai/whisper-large-v3"
);
let routed = default.clone().with_sub_route(SubRoute::Together);
let error = routed
.modality_uri("transcription", "/audio/transcriptions", "whisper")
.expect_err("only hf-inference serves transcription");
assert_eq!(
error,
"transcription endpoint is not supported yet for together"
);
assert!(
routed
.modality_uri("image generation", "/images/generations", "sd")
.is_err()
);
assert_eq!(
OpenAIConfig::new("k")
.modality_uri("transcription", "/audio/transcriptions", "whisper-1")
.expect("openai serves transcription"),
"https://api.openai.com/v1/audio/transcriptions"
);
}
#[test]
fn every_dialects_listing_and_verify_urls_match_the_recorded_paths() {
let expected: &[(&Dialect, &str, Option<&str>)] = &[
(
&OPENAI,
"https://api.openai.com/v1/models",
Some("https://api.openai.com/v1/models"),
),
(
&DEEPSEEK,
"https://api.deepseek.com/models",
Some("https://api.deepseek.com/user/balance"),
),
(
&GROQ,
"https://api.groq.com/openai/v1/models",
Some("https://api.groq.com/openai/v1/models"),
),
(
&MISTRAL,
"https://api.mistral.ai/v1/models",
Some("https://api.mistral.ai/v1/models"),
),
(
&OPENROUTER,
"https://openrouter.ai/api/v1/models",
Some("https://openrouter.ai/api/v1/key"),
),
(
&VENICE,
"https://api.venice.ai/api/v1/models",
Some("https://api.venice.ai/api/v1/models"),
),
(
&LLAMACPP,
"http://localhost:8080/v1/models",
Some("http://localhost:8080/props"),
),
(
&MIRA,
"https://api.mira.network/v1/models",
Some("https://api.mira.network/user-credits"),
),
(
&HUGGINGFACE,
"https://router.huggingface.co/models",
Some("https://router.huggingface.co/api/whoami-v2"),
),
(
&TOGETHER,
"https://api.together.xyz/v1/models",
Some("https://api.together.xyz/models"),
),
(&PERPLEXITY, "https://api.perplexity.ai/models", None),
(
&crate::providers::xai::DIALECT,
"https://api.x.ai/v1/models",
Some("https://api.x.ai/v1/api-key"),
),
];
for (dialect, models, verify) in expected {
let provider = OpenAIConfig::with_key(dialect, "k");
assert_eq!(
provider.uri(dialect.quirks.models_path, None),
*models,
"{} model-listing URL",
dialect.name
);
match verify {
Some(verify) => assert_eq!(
provider.uri(dialect.quirks.verify_path, None),
*verify,
"{} verify URL",
dialect.name
),
None => assert!(
dialect.quirks.verify_path.is_empty(),
"{} has no token-free credential check",
dialect.name
),
}
}
}
#[test]
fn llamacpp_serves_its_operational_routes_unversioned() {
let provider = OpenAIConfig::with_key(&LLAMACPP, "");
for route in LLAMACPP.quirks.root_relative_routes {
assert_eq!(
provider.uri(route, None),
format!("http://localhost:8080{route}"),
"{route} is a root route"
);
}
assert_eq!(
provider.uri("/chat/completions", None),
"http://localhost:8080/v1/chat/completions"
);
assert_eq!(
provider.uri("/rerank", None),
"http://localhost:8080/v1/rerank"
);
for dialect in all() {
if !["llamacpp", "deepseek"].contains(&dialect.name) {
assert!(
dialect.quirks.root_relative_routes.is_empty(),
"{} declares root routes it never had",
dialect.name
);
}
}
}
#[test]
fn a_debug_printed_request_hides_the_key_it_sends() {
use crate::completion::CompletionRequest;
use crate::providers::anthropic::wire::{AnthropicConfig, OLLAMA as ANTHROPIC_OLLAMA};
use crate::providers::{cohere, copilot, gemini, ollama, voyageai};
use crate::wire::{Mode, Wire};
const KEY: &str = "sk-NOTAREALKEY-0123456789";
let bearer = format!("Bearer {KEY}");
let probe = || CompletionRequest::new("probe").max_tokens(16);
let texts = || vec!["probe".to_owned()];
let openai = |config: OpenAIConfig| config.completion("gpt-5").encode(probe(), Mode::Unary);
let anthropic = |config: AnthropicConfig| {
config
.completion("claude-haiku-4-5")
.encode(probe(), Mode::Unary)
};
let gemini = gemini::GeminiConfig::new(KEY);
let built = [
(
openai(OpenAIConfig::new(KEY)).map(|e| e.request),
"authorization",
bearer.as_str(),
),
(
openai(OpenAIConfig::with_key(&AZURE, KEY)).map(|e| e.request),
"api-key",
KEY,
),
(
openai(OpenAIConfig::with_key(&LLAMACPP, KEY)).map(|e| e.request),
"authorization",
bearer.as_str(),
),
(
anthropic(AnthropicConfig::new(KEY)).map(|e| e.request),
"x-api-key",
KEY,
),
(
anthropic(AnthropicConfig::with_key(&ANTHROPIC_OLLAMA, KEY)).map(|e| e.request),
"authorization",
bearer.as_str(),
),
(
gemini
.completion("gemini-3.8-flash")
.encode(probe(), Mode::Unary)
.map(|e| e.request),
"x-goog-api-key",
KEY,
),
(
gemini
.interactions("gemini-3.8-flash")
.encode(probe(), Mode::Unary)
.map(|e| e.request),
"x-goog-api-key",
KEY,
),
(
OpenAIConfig::with_key(&copilot::DIALECT, KEY)
.completion(copilot::GPT_4O)
.encode(probe(), Mode::Unary)
.map(|e| e.request),
"authorization",
bearer.as_str(),
),
(
OpenAIConfig::with_key(&copilot::DIALECT, KEY)
.embedding(copilot::TEXT_EMBEDDING_3_SMALL, None)
.encode(texts(), Mode::Unary)
.map(|e| e.request),
"authorization",
bearer.as_str(),
),
(
cohere::CohereConfig::new(KEY)
.embedding(cohere::EMBED_V4, None)
.encode(texts(), Mode::Unary)
.map(|e| e.request),
"authorization",
bearer.as_str(),
),
(
ollama::OllamaConfig::new()
.with_api_key(KEY)
.native_completion("qwen3:4b")
.encode(probe(), Mode::Unary)
.map(|e| e.request),
"authorization",
bearer.as_str(),
),
(
voyageai::VoyageAiConfig::new(KEY)
.embedding("voyage-3.5", None)
.encode(texts(), Mode::Unary)
.map(|e| e.request),
"authorization",
bearer.as_str(),
),
];
for (request, header, value) in built {
let request = request.unwrap_or_else(|error| panic!("{error}"));
assert_eq!(
request.headers().get(header).map(|v| v.as_bytes()),
Some(value.as_bytes()),
"{} lost the key in {header}",
request.uri()
);
assert!(
!format!("{request:?}").contains(KEY),
"the debug-printed request to {} leaked the key in {header}",
request.uri()
);
}
}
#[test]
fn the_huggingface_sub_route_selects_the_provider_by_model_suffix() {
use crate::completion::CompletionRequest;
use crate::test_utils::json_body;
use crate::wire::{Mode, Wire};
use serde_json::json;
const MODEL: &str = "meta-llama/Llama-3.3-70B-Instruct";
let router = OpenAIConfig::with_key(&HUGGINGFACE, "hf");
let sent = |config: &OpenAIConfig, request: CompletionRequest| {
config
.chat(MODEL)
.encode(request, Mode::Unary)
.map(|encoded| {
(
encoded.request.uri().to_string(),
json_body(&encoded.request),
)
})
};
let probe = || CompletionRequest::new("probe");
let model_sent = |config: &OpenAIConfig, request: CompletionRequest| {
sent(config, request)
.expect("the request encodes")
.1
.get("model")
.cloned()
};
for (route, suffix) in [
(SubRoute::Together, "together"),
(SubRoute::Nebius, "nebius"),
(SubRoute::Fireworks, "fireworks"),
(SubRoute::HFInference, "hf-inference"),
] {
let routed = router.clone().with_sub_route(route);
let (uri, body) = sent(&routed, probe()).expect("the request encodes");
assert_eq!(uri, "https://router.huggingface.co/v1/chat/completions");
assert_eq!(body.get("model"), Some(&json!(format!("{MODEL}:{suffix}"))));
}
assert_eq!(model_sent(&router, probe()), Some(json!(MODEL)));
let together = router.clone().with_sub_route(SubRoute::Together);
let mut overridden = probe();
overridden.model = Some("org/request-model".to_owned());
overridden.additional_params = Some(json!({ "model": "org/raw-model" }));
assert_eq!(
model_sent(&together, overridden),
Some(json!("org/raw-model:together"))
);
let mut already = probe();
already.model = Some(format!("{MODEL}:together"));
assert_eq!(
model_sent(&together, already),
Some(json!(format!("{MODEL}:together")))
);
let fireworks = router.clone().with_sub_route(SubRoute::Fireworks);
let mut already = probe();
already.model = Some(format!("{MODEL}:fireworks"));
assert_eq!(
model_sent(&fireworks, already),
Some(json!(format!("{MODEL}:fireworks")))
);
let mut conflicting = probe();
conflicting.model = Some(format!("{MODEL}:novita"));
assert!(
sent(&together, conflicting).is_err(),
"a model selecting another provider is refused, not sent with two suffixes"
);
let mut raw_conflict = probe();
raw_conflict.additional_params = Some(json!({ "model": format!("{MODEL}:fastest") }));
assert!(
sent(&together, raw_conflict).is_err(),
"a raw override selecting a policy is refused too"
);
}