mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-11-30 00:00:48 +00:00
Route native requests only to providers that support their wire protocol. Convert Chat Completions directly to Responses, Messages or GenAI while preserving the shared request lifecycle and native continuation ownership. Remove provider-side cross-protocol adaptation outside compat modules and update protocol, provider, routing and delivery regression coverage. Validation: workspace fmt and strict Clippy; 4,741 tests passed, none skipped. Live-tested native Codex, AGY and Grok harnesses plus Chat JSON/SSE and tools. BREAKING CHANGE: Built-in cross-protocol conversion is available only through Chat Completions. Native callers must use a matching provider protocol. Co-authored-by: Codex <noreply@openai.com>
1096 lines
35 KiB
Rust
1096 lines
35 KiB
Rust
//! 路由领域测试入口,以及版本、账号范围与 Key 策略约束测试
|
|
|
|
use std::collections::{BTreeMap, BTreeSet};
|
|
use std::sync::Arc;
|
|
|
|
use bytes::Bytes;
|
|
use gateway_core::account::ProviderAccountId;
|
|
use gateway_core::operation::{
|
|
CapabilityRequirements, Feature, GenerateRequest, ImageRequest, ImageRequestKind, Operation,
|
|
OperationKind, ProtocolPayload, ProviderHttpMethod, ProviderHttpRequest, RawHttpPayload,
|
|
RawJsonPayload, TokenCountRequest,
|
|
};
|
|
use gateway_core::policy::{ClientApiKeyId, ClientPolicy, PlaintextClientApiKey, RateLimits};
|
|
use gateway_core::routing::{
|
|
AccountGroupId, AccountRoutingScopeKind, ClientRoutingScope, ConfigRevision,
|
|
FrozenAccountScope, ModelCapabilities, ProviderKind, ProviderModel, PublicModelId,
|
|
RoutingContext, RoutingGroupSnapshot, RuntimeAccount, RuntimeAccountDirectory, RuntimeSnapshot,
|
|
UpstreamModelId,
|
|
};
|
|
|
|
mod privacy;
|
|
mod request_settings;
|
|
mod snapshot;
|
|
|
|
fn settings() -> gateway_core::settings::SettingsValues {
|
|
gateway_core::settings::SettingsValues::new(3, "smart", BTreeMap::new(), None, None)
|
|
}
|
|
|
|
fn capabilities() -> ModelCapabilities {
|
|
ModelCapabilities::new(BTreeSet::from([OperationKind::Generate]), Some(16_000))
|
|
}
|
|
|
|
fn model(provider: &str, name: &str, capabilities: ModelCapabilities) -> ProviderModel {
|
|
ProviderModel::new(
|
|
ProviderKind::new(provider).expect("valid provider"),
|
|
UpstreamModelId::new(name).expect("valid model"),
|
|
capabilities,
|
|
)
|
|
}
|
|
|
|
fn operation() -> Operation {
|
|
let body = serde_json::json!({
|
|
"model": "gpt-5.5",
|
|
"input": [{"type": "message", "role": "user", "content": "hello"}],
|
|
});
|
|
Operation::Generate(GenerateRequest::from_protocol_payload(
|
|
ProtocolPayload::json_object("openai", body.as_object().expect("request object").clone())
|
|
.expect("OpenAI payload"),
|
|
))
|
|
}
|
|
|
|
fn image_operation() -> Operation {
|
|
let body = serde_json::json!({
|
|
"model": "gpt-image-2",
|
|
"prompt": "draw",
|
|
});
|
|
Operation::GenerateImage(ImageRequest::from_raw_json(
|
|
ImageRequestKind::Generation,
|
|
RawJsonPayload::new(
|
|
"openai",
|
|
Bytes::from(serde_json::to_vec(&body).expect("image JSON")),
|
|
)
|
|
.expect("OpenAI payload"),
|
|
))
|
|
}
|
|
|
|
fn account_directory() -> Arc<RuntimeAccountDirectory> {
|
|
Arc::new(RuntimeAccountDirectory::new(BTreeMap::from([
|
|
(
|
|
ProviderAccountId::new("acct_openai").expect("account"),
|
|
RuntimeAccount::new(
|
|
ProviderKind::new("openai").expect("provider"),
|
|
BTreeSet::new(),
|
|
),
|
|
),
|
|
(
|
|
ProviderAccountId::new("acct_xai").expect("account"),
|
|
RuntimeAccount::new(ProviderKind::new("xai").expect("provider"), BTreeSet::new()),
|
|
),
|
|
])))
|
|
}
|
|
|
|
fn account_scope() -> Arc<FrozenAccountScope> {
|
|
Arc::new(FrozenAccountScope::new(
|
|
account_directory(),
|
|
ClientRoutingScope::all_accounts(),
|
|
))
|
|
}
|
|
|
|
fn client_policy(id: &str, plaintext: &str, enabled: bool) -> ClientPolicy {
|
|
ClientPolicy::new(
|
|
ClientApiKeyId::new(id).expect("client key ID"),
|
|
PlaintextClientApiKey::new(plaintext).expect("plaintext client key"),
|
|
account_scope(),
|
|
enabled,
|
|
RateLimits::unlimited(),
|
|
)
|
|
}
|
|
|
|
fn snapshot() -> RuntimeSnapshot {
|
|
let snapshot = RuntimeSnapshot::new(
|
|
ConfigRevision::new(1).expect("revision"),
|
|
settings(),
|
|
vec![
|
|
ProviderKind::new("openai").expect("provider"),
|
|
ProviderKind::new("xai").expect("provider"),
|
|
],
|
|
vec![
|
|
model("openai", "gpt-5.5", capabilities()),
|
|
model("xai", "grok-4.5", capabilities()),
|
|
],
|
|
Vec::new(),
|
|
)
|
|
.expect("snapshot")
|
|
.with_account_directory(account_directory());
|
|
let settings = snapshot
|
|
.settings()
|
|
.clone()
|
|
.with_model_mappings(BTreeMap::from([
|
|
("gpt-5.4".to_owned(), "gpt-5.5".to_owned()),
|
|
("grok-latest".to_owned(), "grok-4.5".to_owned()),
|
|
]));
|
|
snapshot.with_settings(&settings).unwrap()
|
|
}
|
|
|
|
#[test]
|
|
fn config_revision_should_reject_zero() {
|
|
assert!(ConfigRevision::new(0).is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn account_group_id_should_match_the_database_contract_exactly() {
|
|
let valid = "grp_0123456789abcdef0123456789abcdef";
|
|
assert_eq!(
|
|
AccountGroupId::new(valid).expect("valid group ID").as_str(),
|
|
valid
|
|
);
|
|
for invalid in [
|
|
"0123456789abcdef0123456789abcdef",
|
|
"grp_0123456789abcdef0123456789abcde",
|
|
"grp_0123456789abcdef0123456789abcdef0",
|
|
"grp_0123456789abcdef0123456789abcdeF",
|
|
"grp_0123456789abcdef0123456789abcdeg",
|
|
] {
|
|
assert!(
|
|
AccountGroupId::new(invalid).is_err(),
|
|
"invalid group ID was accepted: {invalid}"
|
|
);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn restricted_scope_should_use_enabled_group_union_and_preserve_all_bindings_for_history() {
|
|
let enabled =
|
|
AccountGroupId::new("grp_11111111111111111111111111111111").expect("enabled group");
|
|
let disabled =
|
|
AccountGroupId::new("grp_22222222222222222222222222222222").expect("disabled group");
|
|
let provider = ProviderKind::new("openai").expect("provider");
|
|
let allowed_account = ProviderAccountId::new("acct_allowed").expect("account");
|
|
let disabled_only_account = ProviderAccountId::new("acct_disabled").expect("account");
|
|
let directory = Arc::new(RuntimeAccountDirectory::new(BTreeMap::from([
|
|
(
|
|
allowed_account.clone(),
|
|
RuntimeAccount::new(provider.clone(), BTreeSet::from([enabled.clone()])),
|
|
),
|
|
(
|
|
disabled_only_account.clone(),
|
|
RuntimeAccount::new(provider.clone(), BTreeSet::from([disabled.clone()])),
|
|
),
|
|
])));
|
|
let scope = FrozenAccountScope::new(
|
|
directory,
|
|
ClientRoutingScope::restricted(
|
|
vec![
|
|
RoutingGroupSnapshot::new(enabled.clone(), "Enabled".to_owned()),
|
|
RoutingGroupSnapshot::new(disabled, "Disabled".to_owned()),
|
|
],
|
|
BTreeSet::from([enabled]),
|
|
BTreeSet::from([provider]),
|
|
)
|
|
.expect("restricted scope"),
|
|
);
|
|
|
|
assert!(scope.allows(&allowed_account));
|
|
assert!(!scope.allows(&disabled_only_account));
|
|
let history = scope.routing_snapshot();
|
|
assert_eq!(history.kind(), AccountRoutingScopeKind::Groups);
|
|
assert_eq!(history.groups_snapshot().len(), 2);
|
|
assert_eq!(history.groups_snapshot()[1].name(), "Disabled");
|
|
}
|
|
|
|
#[test]
|
|
fn restricted_scope_with_no_enabled_group_should_fail_closed() {
|
|
let group = AccountGroupId::new("grp_33333333333333333333333333333333").expect("group");
|
|
let account = ProviderAccountId::new("acct_group_member").expect("account");
|
|
let directory = Arc::new(RuntimeAccountDirectory::new(BTreeMap::from([(
|
|
account.clone(),
|
|
RuntimeAccount::new(
|
|
ProviderKind::new("openai").expect("provider"),
|
|
BTreeSet::from([group.clone()]),
|
|
),
|
|
)])));
|
|
let scope = FrozenAccountScope::new(
|
|
directory,
|
|
ClientRoutingScope::restricted(
|
|
vec![RoutingGroupSnapshot::new(group, "Disabled".to_owned())],
|
|
BTreeSet::new(),
|
|
BTreeSet::new(),
|
|
)
|
|
.expect("restricted scope"),
|
|
);
|
|
|
|
assert!(scope.provider_kinds().is_empty());
|
|
assert!(!scope.allows(&account));
|
|
}
|
|
|
|
#[test]
|
|
fn snapshot_should_publish_only_enabled_plaintext_client_policies() {
|
|
let snapshot = RuntimeSnapshot::new(
|
|
ConfigRevision::new(1).expect("revision"),
|
|
settings(),
|
|
vec![ProviderKind::new("openai").expect("provider")],
|
|
Vec::new(),
|
|
vec![
|
|
client_policy("key_enabled", "sk_enabled", true),
|
|
client_policy("key_disabled", "sk_disabled", false),
|
|
],
|
|
)
|
|
.expect("snapshot");
|
|
|
|
let policies = snapshot.client_policies().collect::<Vec<_>>();
|
|
assert_eq!(policies.len(), 1);
|
|
assert_eq!(policies[0].key_id().as_str(), "key_enabled");
|
|
assert!(
|
|
policies[0]
|
|
.account_scope()
|
|
.provider_kinds()
|
|
.contains(&ProviderKind::new("openai").expect("provider"))
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn snapshot_should_reject_model_for_missing_provider() {
|
|
let result = RuntimeSnapshot::new(
|
|
ConfigRevision::new(1).expect("revision"),
|
|
settings(),
|
|
Vec::new(),
|
|
vec![model("missing", "gpt-5.5", capabilities())],
|
|
Vec::new(),
|
|
);
|
|
|
|
assert!(result.is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn snapshot_should_reject_duplicate_provider_model() {
|
|
let result = RuntimeSnapshot::new(
|
|
ConfigRevision::new(1).expect("revision"),
|
|
settings(),
|
|
vec![ProviderKind::new("openai").expect("provider")],
|
|
vec![
|
|
model("openai", "gpt-5.5", capabilities()),
|
|
model("openai", "gpt-5.5", capabilities()),
|
|
],
|
|
Vec::new(),
|
|
);
|
|
|
|
assert!(result.is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn selected_provider_should_use_global_model_mapping() {
|
|
let snapshot = snapshot();
|
|
let plan = snapshot
|
|
.plan(
|
|
&PublicModelId::new("gpt-5.4").expect("model"),
|
|
&operation(),
|
|
snapshot.all_account_scope(),
|
|
&RoutingContext {
|
|
required_provider: Some(ProviderKind::new("openai").expect("provider")),
|
|
..RoutingContext::default()
|
|
},
|
|
)
|
|
.expect("plan");
|
|
|
|
assert_eq!(plan.candidates().len(), 1);
|
|
assert_eq!(plan.candidates()[0].provider().as_str(), "openai");
|
|
assert_eq!(
|
|
plan.candidates()[0]
|
|
.upstream_model()
|
|
.expect("model route candidate")
|
|
.as_str(),
|
|
"gpt-5.5"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn model_mapping_should_follow_a_bounded_alias_chain() {
|
|
let snapshot = snapshot();
|
|
let settings = snapshot
|
|
.settings()
|
|
.clone()
|
|
.with_model_mappings(BTreeMap::from([
|
|
("public-model".to_owned(), "compat-model".to_owned()),
|
|
("compat-model".to_owned(), "gpt-5.5".to_owned()),
|
|
]));
|
|
let snapshot = snapshot.with_settings(&settings).unwrap();
|
|
|
|
assert_eq!(snapshot.mapped_model("public-model"), "gpt-5.5");
|
|
}
|
|
|
|
#[test]
|
|
fn cyclic_model_mapping_should_fall_back_to_the_original_name() {
|
|
let snapshot = snapshot();
|
|
let settings = snapshot
|
|
.settings()
|
|
.clone()
|
|
.with_model_mappings(BTreeMap::from([
|
|
("first".to_owned(), "second".to_owned()),
|
|
("second".to_owned(), "first".to_owned()),
|
|
]));
|
|
let snapshot = snapshot.with_settings(&settings).unwrap();
|
|
|
|
assert_eq!(snapshot.mapped_model("first"), "first");
|
|
}
|
|
|
|
#[test]
|
|
fn known_provider_catalog_missing_mapped_model_should_be_filtered() {
|
|
let snapshot = snapshot();
|
|
let error = snapshot
|
|
.plan(
|
|
&PublicModelId::new("gpt-5.4").expect("model"),
|
|
&operation(),
|
|
snapshot.all_account_scope(),
|
|
&RoutingContext {
|
|
required_provider: Some(ProviderKind::new("xai").expect("provider")),
|
|
..RoutingContext::default()
|
|
},
|
|
)
|
|
.expect_err("known xAI catalog does not contain the mapped OpenAI model");
|
|
|
|
assert_eq!(
|
|
error,
|
|
gateway_core::error::RoutingError::ModelNotFound {
|
|
model: "gpt-5.4".to_owned(),
|
|
mapped_model: "gpt-5.5".to_owned(),
|
|
}
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn missing_model_should_be_reported_when_all_scoped_catalogs_are_known() {
|
|
let snapshot = snapshot();
|
|
let error = snapshot
|
|
.plan(
|
|
&PublicModelId::new("missing-model").expect("model"),
|
|
&operation(),
|
|
snapshot.all_account_scope(),
|
|
&RoutingContext::default(),
|
|
)
|
|
.expect_err("neither provider publishes the requested model");
|
|
|
|
assert_eq!(
|
|
error,
|
|
gateway_core::error::RoutingError::ModelNotFound {
|
|
model: "missing-model".to_owned(),
|
|
mapped_model: "missing-model".to_owned(),
|
|
}
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn missing_model_in_one_provider_should_still_route_to_another() {
|
|
let snapshot = snapshot();
|
|
let plan = snapshot
|
|
.plan(
|
|
&PublicModelId::new("grok-4.5").expect("model"),
|
|
&operation(),
|
|
snapshot.all_account_scope(),
|
|
&RoutingContext::default(),
|
|
)
|
|
.expect("xAI publishes the model missing from OpenAI");
|
|
|
|
assert_eq!(plan.candidates()[0].provider().as_str(), "xai");
|
|
}
|
|
|
|
#[test]
|
|
fn blocked_model_provider_should_not_be_misreported_as_model_not_found() {
|
|
let snapshot = snapshot();
|
|
let error = snapshot
|
|
.plan(
|
|
&PublicModelId::new("gpt-5.5").expect("model"),
|
|
&operation(),
|
|
snapshot.all_account_scope(),
|
|
&RoutingContext {
|
|
blocked_providers: BTreeSet::from([ProviderKind::new("openai").expect("provider")]),
|
|
..RoutingContext::default()
|
|
},
|
|
)
|
|
.expect_err("OpenAI is blocked and xAI does not publish this model");
|
|
|
|
assert!(matches!(
|
|
error,
|
|
gateway_core::error::RoutingError::NoCapableProvider { .. }
|
|
));
|
|
}
|
|
|
|
#[test]
|
|
fn blocked_unknown_catalog_should_not_prove_model_absence() {
|
|
let snapshot = RuntimeSnapshot::new(
|
|
ConfigRevision::new(1).expect("revision"),
|
|
settings(),
|
|
vec![
|
|
ProviderKind::new("openai").expect("provider"),
|
|
ProviderKind::new("xai").expect("provider"),
|
|
],
|
|
vec![model("xai", "grok-4.5", capabilities())],
|
|
Vec::new(),
|
|
)
|
|
.expect("snapshot")
|
|
.with_account_directory(account_directory());
|
|
let error = snapshot
|
|
.plan(
|
|
&PublicModelId::new("missing-model").expect("model"),
|
|
&operation(),
|
|
snapshot.all_account_scope(),
|
|
&RoutingContext {
|
|
blocked_providers: BTreeSet::from([ProviderKind::new("openai").expect("provider")]),
|
|
..RoutingContext::default()
|
|
},
|
|
)
|
|
.expect_err("the blocked provider's catalog cannot establish model absence");
|
|
|
|
assert!(matches!(
|
|
error,
|
|
gateway_core::error::RoutingError::NoCapableProvider { .. }
|
|
));
|
|
}
|
|
|
|
#[test]
|
|
fn empty_account_scope_should_not_be_misreported_as_model_not_found() {
|
|
let snapshot = snapshot();
|
|
let empty_scope = Arc::new(FrozenAccountScope::new(
|
|
Arc::new(RuntimeAccountDirectory::default()),
|
|
ClientRoutingScope::all_accounts(),
|
|
));
|
|
let error = snapshot
|
|
.plan(
|
|
&PublicModelId::new("missing-model").expect("model"),
|
|
&operation(),
|
|
empty_scope,
|
|
&RoutingContext::default(),
|
|
)
|
|
.expect_err("the API key has no accounts");
|
|
|
|
assert_eq!(error, gateway_core::error::RoutingError::EmptyAccountScope);
|
|
}
|
|
|
|
#[test]
|
|
fn forced_provider_does_not_bypass_an_empty_key_account_scope() {
|
|
let snapshot = snapshot();
|
|
let empty_scope = Arc::new(FrozenAccountScope::new(
|
|
Arc::new(RuntimeAccountDirectory::default()),
|
|
ClientRoutingScope::all_accounts(),
|
|
));
|
|
let error = snapshot
|
|
.plan(
|
|
&PublicModelId::new("gpt-5.5").expect("model"),
|
|
&operation(),
|
|
empty_scope,
|
|
&RoutingContext {
|
|
required_provider: Some(ProviderKind::new("openai").expect("provider")),
|
|
..RoutingContext::default()
|
|
},
|
|
)
|
|
.expect_err("a forced Provider is not an account authorization");
|
|
|
|
assert!(matches!(
|
|
error,
|
|
gateway_core::error::RoutingError::NoCapableProvider { .. }
|
|
));
|
|
}
|
|
|
|
#[test]
|
|
fn provider_endpoint_plan_should_not_consult_or_publish_the_text_model_catalog() {
|
|
let snapshot = snapshot();
|
|
let provider = ProviderKind::new("openai").expect("provider");
|
|
let public_model = PublicModelId::new("gpt-image-2").expect("model");
|
|
|
|
assert!(!snapshot.contains_public_model_for_provider(&public_model, &provider));
|
|
let plan = snapshot
|
|
.plan_provider_endpoint(
|
|
&provider,
|
|
None,
|
|
&image_operation(),
|
|
snapshot.all_account_scope(),
|
|
&RoutingContext::default(),
|
|
)
|
|
.expect("provider-owned endpoint remains routable");
|
|
|
|
assert_eq!(plan.operation(), OperationKind::GenerateImage);
|
|
assert_eq!(plan.candidates().len(), 1);
|
|
assert_eq!(plan.candidates()[0].provider(), &provider);
|
|
assert_eq!(plan.candidates()[0].upstream_model(), None);
|
|
assert!(!snapshot.contains_public_model_for_provider(&public_model, &provider));
|
|
}
|
|
|
|
#[test]
|
|
fn provider_endpoint_plan_should_still_respect_circuit_filtering() {
|
|
let snapshot = snapshot();
|
|
let provider = ProviderKind::new("openai").expect("provider");
|
|
let error = snapshot
|
|
.plan_provider_endpoint(
|
|
&provider,
|
|
None,
|
|
&image_operation(),
|
|
snapshot.all_account_scope(),
|
|
&RoutingContext {
|
|
blocked_providers: BTreeSet::from([provider.clone()]),
|
|
..RoutingContext::default()
|
|
},
|
|
)
|
|
.expect_err("blocked provider has no endpoint candidate");
|
|
|
|
assert!(matches!(
|
|
error,
|
|
gateway_core::error::RoutingError::NoCapableProviderEndpoint { .. }
|
|
));
|
|
}
|
|
|
|
#[test]
|
|
fn token_count_endpoint_should_require_exact_model_capability_and_scope() {
|
|
let provider = ProviderKind::new("openai").expect("provider");
|
|
let model = UpstreamModelId::new("gpt-5.5").expect("model");
|
|
let operation = Operation::CountTokens(TokenCountRequest::from_raw_json(
|
|
RawJsonPayload::new("token-count", Bytes::from_static(br#"{"input":"hello"}"#))
|
|
.expect("token count payload"),
|
|
));
|
|
let unsupported = snapshot()
|
|
.plan_provider_endpoint(
|
|
&provider,
|
|
Some(&model),
|
|
&operation,
|
|
account_scope(),
|
|
&RoutingContext::default(),
|
|
)
|
|
.expect_err("generate-only model cannot count tokens");
|
|
assert!(matches!(
|
|
unsupported,
|
|
gateway_core::error::RoutingError::UnsupportedProviderEndpoint { .. }
|
|
));
|
|
|
|
let capabilities = ModelCapabilities::new(
|
|
BTreeSet::from([OperationKind::Generate, OperationKind::CountTokens]),
|
|
Some(16_000),
|
|
);
|
|
let capable = RuntimeSnapshot::new(
|
|
ConfigRevision::new(1).expect("revision"),
|
|
settings(),
|
|
vec![provider.clone()],
|
|
vec![ProviderModel::new(
|
|
provider.clone(),
|
|
model.clone(),
|
|
capabilities,
|
|
)],
|
|
Vec::new(),
|
|
)
|
|
.expect("snapshot")
|
|
.with_account_directory(account_directory());
|
|
let plan = capable
|
|
.plan_provider_endpoint(
|
|
&provider,
|
|
Some(&model),
|
|
&operation,
|
|
capable.all_account_scope(),
|
|
&RoutingContext::default(),
|
|
)
|
|
.expect("declared token counter");
|
|
assert_eq!(plan.operation(), OperationKind::CountTokens);
|
|
assert_eq!(plan.candidates()[0].upstream_model(), Some(&model));
|
|
assert!(
|
|
capable
|
|
.plan_provider_endpoint(
|
|
&provider,
|
|
None,
|
|
&operation,
|
|
capable.all_account_scope(),
|
|
&RoutingContext::default(),
|
|
)
|
|
.is_err(),
|
|
"token counting cannot drop the model binding"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn provider_http_endpoint_should_carry_the_model_into_account_permissions() {
|
|
use gateway_core::account::{AccountModelAccess, AccountModelAccessMode};
|
|
use gateway_core::error::RoutingError;
|
|
|
|
let provider = ProviderKind::new("openai").expect("provider");
|
|
let operation = Operation::ProviderHttp(
|
|
ProviderHttpRequest::new(
|
|
"models",
|
|
ProviderHttpMethod::Get,
|
|
None,
|
|
Vec::new(),
|
|
RawHttpPayload::new("provider-http", Bytes::new()).expect("HTTP payload"),
|
|
)
|
|
.expect("provider HTTP operation"),
|
|
);
|
|
let snapshot = RuntimeSnapshot::new(
|
|
ConfigRevision::new(1).expect("revision"),
|
|
settings(),
|
|
vec![provider.clone()],
|
|
Vec::new(),
|
|
Vec::new(),
|
|
)
|
|
.expect("snapshot")
|
|
.with_account_directory(account_directory());
|
|
let model = UpstreamModelId::new("gpt-live-1-codex").expect("model");
|
|
let plan = snapshot
|
|
.plan_provider_endpoint(
|
|
&provider,
|
|
Some(&model),
|
|
&operation,
|
|
snapshot.all_account_scope(),
|
|
&RoutingContext::default(),
|
|
)
|
|
.expect("provider endpoint with a permitted model");
|
|
assert_eq!(plan.candidates()[0].provider(), &provider);
|
|
assert_eq!(plan.candidates()[0].upstream_model(), Some(&model));
|
|
// 账号范围整体禁止该模型时在路由层拒绝,而不是交给未授权账号服务。
|
|
let denied_directory = Arc::new(RuntimeAccountDirectory::new(BTreeMap::from([(
|
|
ProviderAccountId::new("acct_openai").expect("account"),
|
|
RuntimeAccount::new(provider.clone(), BTreeSet::new()).with_model_access(
|
|
AccountModelAccess::new(
|
|
AccountModelAccessMode::Denylist,
|
|
vec!["gpt-live-1-codex".to_owned()],
|
|
)
|
|
.expect("model access"),
|
|
),
|
|
)])));
|
|
let denied_scope = Arc::new(FrozenAccountScope::new(
|
|
denied_directory,
|
|
ClientRoutingScope::all_accounts(),
|
|
));
|
|
assert!(matches!(
|
|
snapshot.plan_provider_endpoint(
|
|
&provider,
|
|
Some(&model),
|
|
&operation,
|
|
denied_scope,
|
|
&RoutingContext::default(),
|
|
),
|
|
Err(RoutingError::NoCapableProviderEndpoint { .. })
|
|
));
|
|
}
|
|
|
|
#[test]
|
|
fn unmapped_model_should_pass_through_unchanged() {
|
|
let snapshot = RuntimeSnapshot::new(
|
|
ConfigRevision::new(1).expect("revision"),
|
|
settings(),
|
|
vec![ProviderKind::new("openai").expect("provider")],
|
|
Vec::new(),
|
|
Vec::new(),
|
|
)
|
|
.expect("snapshot")
|
|
.with_account_directory(account_directory());
|
|
for requested in [
|
|
"future-openai-model".to_owned(),
|
|
format!("future-{}", "x".repeat(512)),
|
|
"future\0model".to_owned(),
|
|
" future-openai-model ".to_owned(),
|
|
] {
|
|
let plan = snapshot
|
|
.plan(
|
|
&PublicModelId::from_client_wire(requested.clone()).expect("client model"),
|
|
&operation(),
|
|
snapshot.all_account_scope(),
|
|
&RoutingContext {
|
|
required_provider: Some(ProviderKind::new("openai").expect("provider")),
|
|
..RoutingContext::default()
|
|
},
|
|
)
|
|
.expect("unknown model remains transparent");
|
|
|
|
assert_eq!(
|
|
plan.candidates()[0]
|
|
.upstream_model()
|
|
.expect("model route candidate")
|
|
.as_str(),
|
|
requested
|
|
);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn model_mapping_should_use_exact_client_keys() {
|
|
let snapshot = snapshot();
|
|
let settings = snapshot
|
|
.settings()
|
|
.clone()
|
|
.with_model_mappings(BTreeMap::from([(
|
|
" exact-alias ".to_owned(),
|
|
"gpt-5.5".to_owned(),
|
|
)]));
|
|
let snapshot = snapshot.with_settings(&settings).unwrap();
|
|
|
|
assert_eq!(snapshot.mapped_model(" exact-alias "), "gpt-5.5");
|
|
assert_eq!(snapshot.mapped_model("exact-alias"), "exact-alias");
|
|
}
|
|
|
|
#[test]
|
|
fn blocked_provider_should_be_filtered() {
|
|
let snapshot = snapshot();
|
|
let error = snapshot
|
|
.plan(
|
|
&PublicModelId::new("gpt-5.5").expect("model"),
|
|
&operation(),
|
|
snapshot.all_account_scope(),
|
|
&RoutingContext {
|
|
required_provider: Some(ProviderKind::new("openai").expect("provider")),
|
|
blocked_providers: BTreeSet::from([ProviderKind::new("openai").expect("provider")]),
|
|
},
|
|
)
|
|
.expect_err("blocked platform has no candidate");
|
|
|
|
assert!(matches!(
|
|
error,
|
|
gateway_core::error::RoutingError::NoCapableProvider { .. }
|
|
));
|
|
}
|
|
|
|
#[test]
|
|
fn known_unsupported_operation_should_not_be_bypassed() {
|
|
let snapshot = RuntimeSnapshot::new(
|
|
ConfigRevision::new(1).expect("revision"),
|
|
settings(),
|
|
vec![ProviderKind::new("openai").expect("provider")],
|
|
vec![model(
|
|
"openai",
|
|
"gpt-known-unsupported",
|
|
ModelCapabilities::new(BTreeSet::new(), None),
|
|
)],
|
|
Vec::new(),
|
|
)
|
|
.expect("snapshot");
|
|
|
|
let error = snapshot
|
|
.plan(
|
|
&PublicModelId::new("gpt-known-unsupported").expect("model"),
|
|
&operation(),
|
|
snapshot.all_account_scope(),
|
|
&RoutingContext {
|
|
required_provider: Some(ProviderKind::new("openai").expect("provider")),
|
|
..RoutingContext::default()
|
|
},
|
|
)
|
|
.expect_err("the model exists but cannot perform this operation");
|
|
|
|
assert!(matches!(
|
|
error,
|
|
gateway_core::error::RoutingError::NoCapableProvider { .. }
|
|
));
|
|
}
|
|
|
|
#[test]
|
|
fn upstream_feature_validation_should_preserve_operation_and_limit_gates() {
|
|
let capabilities =
|
|
ModelCapabilities::new(BTreeSet::from([OperationKind::Generate]), Some(16_000))
|
|
.with_feature(
|
|
Feature::Tools,
|
|
gateway_core::routing::SupportLevel::Unsupported,
|
|
)
|
|
.with_upstream_feature_validation();
|
|
let wire_features = CapabilityRequirements::new(OperationKind::Generate)
|
|
.require(Feature::Tools)
|
|
.require(Feature::JsonSchema);
|
|
let oversized_output = CapabilityRequirements::new(OperationKind::Generate)
|
|
.with_requested_output_tokens(Some(16_001));
|
|
let unsupported_operation = CapabilityRequirements::new(OperationKind::GenerateImage);
|
|
|
|
assert_eq!(
|
|
(
|
|
capabilities.match_requirements(&wire_features),
|
|
capabilities.match_requirements(&oversized_output),
|
|
capabilities.match_requirements(&unsupported_operation),
|
|
),
|
|
(Some(BTreeSet::new()), None, None)
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn public_catalog_should_include_discovered_models_and_aliases() {
|
|
let models =
|
|
snapshot().public_models_for_provider(&ProviderKind::new("openai").expect("provider"));
|
|
let names = models
|
|
.iter()
|
|
.map(PublicModelId::as_str)
|
|
.collect::<BTreeSet<_>>();
|
|
|
|
assert_eq!(names, BTreeSet::from(["gpt-5.4", "gpt-5.5", "grok-latest"]));
|
|
}
|
|
|
|
#[test]
|
|
fn unknown_model_should_be_hidden_when_provider_catalog_is_available() {
|
|
assert!(!snapshot().contains_public_model_for_provider(
|
|
&PublicModelId::new("future-model").expect("model"),
|
|
&ProviderKind::new("openai").expect("provider"),
|
|
));
|
|
}
|
|
|
|
#[test]
|
|
fn alias_should_only_be_available_from_a_provider_with_its_mapped_model() {
|
|
let snapshot = snapshot();
|
|
let alias = PublicModelId::new("grok-latest").expect("model");
|
|
|
|
assert!(!snapshot.contains_public_model_for_provider(
|
|
&alias,
|
|
&ProviderKind::new("openai").expect("provider"),
|
|
));
|
|
assert!(
|
|
snapshot.contains_public_model_for_provider(
|
|
&alias,
|
|
&ProviderKind::new("xai").expect("provider"),
|
|
)
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn account_model_access_filters_catalog_and_aliases_using_the_whole_frozen_pool() {
|
|
use gateway_core::{
|
|
account::{AccountModelAccess, AccountModelAccessMode},
|
|
error::RoutingError,
|
|
};
|
|
let provider = ProviderKind::new("openai").expect("provider");
|
|
let restricted =
|
|
AccountModelAccess::new(AccountModelAccessMode::Denylist, vec!["gpt-5.5".to_owned()])
|
|
.expect("policy");
|
|
let directory = Arc::new(RuntimeAccountDirectory::new(BTreeMap::from([(
|
|
ProviderAccountId::new("acct_restricted").expect("id"),
|
|
RuntimeAccount::new(provider.clone(), BTreeSet::new())
|
|
.with_model_access(restricted.clone()),
|
|
)])));
|
|
let old_scope = Arc::new(FrozenAccountScope::new(
|
|
directory,
|
|
ClientRoutingScope::all_accounts(),
|
|
));
|
|
let snapshot = snapshot();
|
|
assert_eq!(
|
|
snapshot
|
|
.public_models_for_scope(&old_scope)
|
|
.iter()
|
|
.map(PublicModelId::as_str)
|
|
.collect::<Vec<_>>(),
|
|
vec!["grok-latest"]
|
|
);
|
|
assert!(!snapshot.contains_public_model_for_scope(
|
|
&PublicModelId::new("gpt-5.4").expect("alias"),
|
|
&old_scope
|
|
));
|
|
assert!(matches!(
|
|
snapshot.plan(
|
|
&PublicModelId::new("gpt-5.4").expect("alias"),
|
|
&operation(),
|
|
old_scope.clone(),
|
|
&RoutingContext::default(),
|
|
),
|
|
Err(RoutingError::NoCapableProvider { .. })
|
|
));
|
|
let new_scope = FrozenAccountScope::new(
|
|
Arc::new(RuntimeAccountDirectory::new(BTreeMap::from([
|
|
(
|
|
ProviderAccountId::new("acct_restricted").expect("id"),
|
|
RuntimeAccount::new(provider.clone(), BTreeSet::new())
|
|
.with_model_access(restricted),
|
|
),
|
|
(
|
|
ProviderAccountId::new("acct_unrestricted").expect("id"),
|
|
RuntimeAccount::new(provider, BTreeSet::new()),
|
|
),
|
|
]))),
|
|
ClientRoutingScope::all_accounts(),
|
|
);
|
|
assert_eq!(
|
|
snapshot
|
|
.public_models_for_scope(&new_scope)
|
|
.iter()
|
|
.map(PublicModelId::as_str)
|
|
.collect::<Vec<_>>(),
|
|
vec!["gpt-5.4", "gpt-5.5", "grok-latest"]
|
|
);
|
|
assert!(
|
|
!snapshot.contains_public_model_for_scope(
|
|
&PublicModelId::new("gpt-5.5").expect("model"),
|
|
&old_scope
|
|
),
|
|
"a new policy must not alter an existing request scope"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn generation_routes_only_to_models_that_accept_the_wire_and_the_key() {
|
|
for translated in [false, true] {
|
|
let provider = |name| ProviderKind::new(name).unwrap();
|
|
let snapshot = RuntimeSnapshot::new(
|
|
ConfigRevision::new(1).unwrap(),
|
|
settings(),
|
|
vec![provider("openai"), provider("xai")],
|
|
vec![
|
|
model("openai", "shared", capabilities()),
|
|
model(
|
|
"xai",
|
|
"shared",
|
|
capabilities()
|
|
.with_generation_protocol("native-test")
|
|
.with_translated_generation_protocols(if translated {
|
|
vec!["openai"]
|
|
} else {
|
|
Vec::new()
|
|
}),
|
|
),
|
|
],
|
|
vec![],
|
|
)
|
|
.unwrap()
|
|
.with_account_directory(account_directory());
|
|
let public = PublicModelId::new("shared").unwrap();
|
|
let native = Operation::Generate(
|
|
GenerateRequest::from_protocol_payload(
|
|
ProtocolPayload::json_object("native-test", Default::default()).unwrap(),
|
|
)
|
|
.requiring_native_protocol(),
|
|
);
|
|
for (request, expected) in [
|
|
(
|
|
operation(),
|
|
if translated {
|
|
vec!["openai", "xai"]
|
|
} else {
|
|
vec!["openai"]
|
|
},
|
|
),
|
|
(native.clone(), vec!["xai"]),
|
|
] {
|
|
let plan = snapshot
|
|
.plan(
|
|
&public,
|
|
&request,
|
|
account_scope(),
|
|
&RoutingContext::default(),
|
|
)
|
|
.unwrap();
|
|
let actual: Vec<_> = plan
|
|
.candidates()
|
|
.iter()
|
|
.map(|c| c.provider().as_str())
|
|
.collect();
|
|
assert_eq!(actual, expected);
|
|
}
|
|
let restricted = Arc::new(
|
|
account_scope().restricted_to(&[provider("openai")].into(), &Default::default()),
|
|
);
|
|
assert!(
|
|
snapshot
|
|
.plan(&public, &native, restricted, &RoutingContext::default())
|
|
.is_err()
|
|
);
|
|
assert!(
|
|
snapshot
|
|
.plan(
|
|
&PublicModelId::new("unknown").unwrap(),
|
|
&native,
|
|
account_scope(),
|
|
&RoutingContext::default()
|
|
)
|
|
.is_err()
|
|
);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn native_count_catalog_and_execution_do_not_fall_back_to_another_protocol() {
|
|
let caps = ModelCapabilities::new(
|
|
BTreeSet::from([OperationKind::Generate, OperationKind::CountTokens]),
|
|
None,
|
|
);
|
|
let snapshot = RuntimeSnapshot::new(
|
|
ConfigRevision::new(1).unwrap(),
|
|
settings(),
|
|
vec![
|
|
ProviderKind::new("openai").unwrap(),
|
|
ProviderKind::new("xai").unwrap(),
|
|
],
|
|
vec![
|
|
model("openai", "shared", caps.clone()),
|
|
model("xai", "shared", caps.with_generation_protocol("genai")),
|
|
],
|
|
vec![],
|
|
)
|
|
.unwrap()
|
|
.with_account_directory(account_directory());
|
|
let original = Operation::CountTokens(
|
|
TokenCountRequest::from_raw_json(
|
|
RawJsonPayload::new("genai", Bytes::from_static(b"{}")).unwrap(),
|
|
)
|
|
.requiring_native_protocol(),
|
|
);
|
|
let operation = original
|
|
.replace_protocol_wire(
|
|
Some(Bytes::from_static(b"{\"contents\":[]}")),
|
|
Default::default(),
|
|
)
|
|
.unwrap();
|
|
assert!(matches!(&operation,Operation::CountTokens(count) if count.requires_native_protocol()));
|
|
let public = PublicModelId::new("shared").unwrap();
|
|
let plan = snapshot
|
|
.plan(
|
|
&public,
|
|
&operation,
|
|
account_scope(),
|
|
&RoutingContext::default(),
|
|
)
|
|
.unwrap();
|
|
assert_eq!(plan.candidates().len(), 1);
|
|
assert_eq!(plan.candidates()[0].provider().as_str(), "xai");
|
|
assert_eq!(
|
|
snapshot.public_models_for_operation(&account_scope(), &operation),
|
|
vec![public]
|
|
);
|
|
let restricted = Arc::new(account_scope().restricted_to(
|
|
&[ProviderKind::new("openai").unwrap()].into(),
|
|
&Default::default(),
|
|
));
|
|
assert!(
|
|
snapshot
|
|
.public_models_for_operation(&restricted, &operation)
|
|
.is_empty()
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn same_model_native_protocols_do_not_borrow_chat_conversion_capabilities() {
|
|
let native = capabilities()
|
|
.with_native_generation_protocols(["openai", "anthropic"])
|
|
.with_translated_generation_protocols([gateway_protocol::chat_completions::CHAT_PROTOCOL]);
|
|
let genai = capabilities()
|
|
.with_generation_protocol("genai")
|
|
.with_translated_generation_protocols([gateway_protocol::chat_completions::CHAT_PROTOCOL]);
|
|
let snapshot = RuntimeSnapshot::new(
|
|
ConfigRevision::new(1).unwrap(),
|
|
settings(),
|
|
vec![
|
|
ProviderKind::new("openai").unwrap(),
|
|
ProviderKind::new("xai").unwrap(),
|
|
],
|
|
vec![
|
|
model("openai", "shared", native),
|
|
model("xai", "shared", genai),
|
|
],
|
|
vec![],
|
|
)
|
|
.unwrap()
|
|
.with_account_directory(account_directory());
|
|
for (protocol, expected) in [
|
|
("openai", vec!["openai"]),
|
|
("anthropic", vec!["openai"]),
|
|
("genai", vec!["xai"]),
|
|
(
|
|
gateway_protocol::chat_completions::CHAT_PROTOCOL,
|
|
vec!["openai", "xai"],
|
|
),
|
|
] {
|
|
let operation = Operation::Generate(GenerateRequest::from_protocol_payload(
|
|
ProtocolPayload::json_object(protocol, Default::default()).unwrap(),
|
|
));
|
|
let plan = snapshot
|
|
.plan(
|
|
&PublicModelId::new("shared").unwrap(),
|
|
&operation,
|
|
account_scope(),
|
|
&RoutingContext::default(),
|
|
)
|
|
.unwrap();
|
|
assert_eq!(
|
|
plan.candidates()
|
|
.iter()
|
|
.map(|candidate| candidate.provider().as_str())
|
|
.collect::<Vec<_>>(),
|
|
expected,
|
|
"{protocol}"
|
|
);
|
|
}
|
|
}
|