mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-11-20 08:01:46 +00:00
Accept optional deployment strings for residency and account routing, discard downstream values when unset, and isolate WebSocket connections by the configured handshake headers. Co-authored-by: Zyy <zyycn@users.noreply.github.com> Co-authored-by: Codex <noreply@openai.com>
462 lines
16 KiB
Rust
462 lines
16 KiB
Rust
//! 验证顶层配置加载、路径解析、显式覆盖与敏感字段脱敏
|
|
|
|
use std::{fs, process::Command};
|
|
|
|
use codex_proxy_rs::bootstrap::GatewayConfig;
|
|
use gateway_host::LoadableConfig;
|
|
|
|
const CONFIG_EXAMPLE: &str = include_str!("../../../../../deploy/config.example.yaml");
|
|
const POSTGRES_PASSWORD: &str = "111111111111111111111111111111111111111111111111";
|
|
const REDIS_PASSWORD: &str = "222222222222222222222222222222222222222222222222";
|
|
const ADMIN_PASSWORD: &str = "test-admin-password";
|
|
const TOPOLOGY_CHILD_ENV: &str = "CPR_TEST_TOPOLOGY_CHILD";
|
|
|
|
#[test]
|
|
fn config_loader_should_load_complete_terminal_example() {
|
|
parse_config(&valid_config()).expect("terminal config example");
|
|
}
|
|
|
|
#[test]
|
|
fn config_loader_should_resolve_paths_relative_to_config_file() {
|
|
let (config, _directory) = parse_config(&valid_config()).expect("resolved config");
|
|
let debug = format!("{config:?}");
|
|
assert!(debug.contains(".runtime/data"));
|
|
assert!(debug.contains(".runtime/logs"));
|
|
assert!(debug.contains("frontend/dist"));
|
|
}
|
|
|
|
#[test]
|
|
fn config_loader_should_share_resolved_assets_with_system_update() {
|
|
const CHILD_ENV: &str = "CPR_TEST_UPDATE_ASSETS_CHILD";
|
|
let Ok(case) = std::env::var(CHILD_ENV) else {
|
|
// 使用子进程覆盖无环境变量、Docker 路径和相对路径,避免污染并行测试
|
|
for (case, web_dist) in [
|
|
("binary", None),
|
|
("docker", Some("/app/web/dist")),
|
|
("relative", Some("../custom/dist")),
|
|
] {
|
|
let mut child = Command::new(std::env::current_exe().expect("test executable"));
|
|
child
|
|
.args([
|
|
"--exact",
|
|
"bootstrap::config::config_loader_should_share_resolved_assets_with_system_update",
|
|
])
|
|
.env(CHILD_ENV, case)
|
|
.env_remove("CPR_WEB_DIST_DIR");
|
|
if let Some(web_dist) = web_dist {
|
|
child.env("CPR_WEB_DIST_DIR", web_dist);
|
|
}
|
|
let output = child.output().expect("isolated configuration test");
|
|
assert!(
|
|
output.status.success(),
|
|
"{case}: {}\n{}",
|
|
String::from_utf8_lossy(&output.stdout),
|
|
String::from_utf8_lossy(&output.stderr)
|
|
);
|
|
}
|
|
return;
|
|
};
|
|
let mut document = valid_config_document();
|
|
document["api"]["asset_directory"] = serde_json::json!("../web/dist");
|
|
let (config, directory) = parse_config(&document.to_string()).expect("binary configuration");
|
|
let assets = match case.as_str() {
|
|
"docker" => std::path::PathBuf::from("/app/web/dist"),
|
|
"relative" => directory.path().join("deploy/../custom/dist"),
|
|
_ => directory.path().join("deploy/../web/dist"),
|
|
};
|
|
let debug = format!("{config:?}");
|
|
assert!(debug.contains(&format!("asset_directory: {assets:?}")));
|
|
assert!(debug.contains(&format!("web_dist_dir: Some({assets:?})")));
|
|
}
|
|
|
|
#[test]
|
|
fn config_loader_should_reject_missing_runtime_data_dir() {
|
|
let config = valid_config().replace(" runtime_data_dir: '../.runtime/data'\n", "");
|
|
|
|
assert!(parse_config(&config).is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn config_loader_should_apply_only_explicit_topology_overrides() {
|
|
let invalid = valid_config()
|
|
.replace("host: '127.0.0.1'", "host: ''")
|
|
.replace("port: 8080", "port: 0")
|
|
.replace(
|
|
"url: 'postgres://codex_proxy@127.0.0.1:5432/codex_proxy'",
|
|
"url: 'invalid-postgres-url'",
|
|
)
|
|
.replace("url: 'redis://127.0.0.1:6379/'", "url: 'invalid-redis-url'")
|
|
.replace(POSTGRES_PASSWORD, "invalid-postgres-password")
|
|
.replace(REDIS_PASSWORD, "invalid-redis-password");
|
|
if std::env::var_os(TOPOLOGY_CHILD_ENV).is_some() {
|
|
parse_config(&invalid).expect("explicit package-owned environment overrides");
|
|
return;
|
|
}
|
|
assert!(parse_config(&invalid).is_err());
|
|
let status = Command::new(std::env::current_exe().expect("current test executable"))
|
|
.args([
|
|
"--exact",
|
|
"bootstrap::config::config_loader_should_apply_only_explicit_topology_overrides",
|
|
])
|
|
.env(TOPOLOGY_CHILD_ENV, "1")
|
|
.env("CPR_SERVER_HOST", "127.0.0.1")
|
|
.env("CPR_SERVER_PORT", "8080")
|
|
.env(
|
|
"CPR_DATABASE_URL",
|
|
"postgres://codex_proxy@127.0.0.1:5432/codex_proxy",
|
|
)
|
|
.env("CPR_REDIS_URL", "redis://127.0.0.1:6379/")
|
|
.env(
|
|
"CPR_DATABASE_PASSWORD",
|
|
"RdsTest9!abcdefGhRdsTest9!abcdefGh",
|
|
)
|
|
.env("CPR_REDIS_PASSWORD", "ManagedRedis9!abcdefGh")
|
|
.status()
|
|
.expect("run isolated environment override test");
|
|
assert!(status.success());
|
|
}
|
|
|
|
#[test]
|
|
fn bootstrap_config_debug_should_redact_all_passwords() {
|
|
let (config, _directory) = parse_config(&valid_config()).expect("config");
|
|
let debug = format!("{config:?}");
|
|
assert!(!debug.contains(POSTGRES_PASSWORD));
|
|
assert!(!debug.contains(REDIS_PASSWORD));
|
|
assert!(!debug.contains(ADMIN_PASSWORD));
|
|
assert!(debug.contains("[REDACTED]"));
|
|
}
|
|
|
|
#[test]
|
|
fn config_loader_should_ignore_unknown_fields_in_configuration_sections() {
|
|
let mut document = valid_config_document();
|
|
document["host"]["system_update"] = serde_json::json!({});
|
|
document["store"]["pool"] = serde_json::json!({});
|
|
for path in [
|
|
"",
|
|
"/host",
|
|
"/host/listen",
|
|
"/host/logging",
|
|
"/host/logging/file",
|
|
"/host/system_update",
|
|
"/store",
|
|
"/store/database",
|
|
"/store/redis",
|
|
"/store/pool",
|
|
"/admin",
|
|
"/client",
|
|
"/api",
|
|
"/openai",
|
|
] {
|
|
let mut extended = document.clone();
|
|
extended.pointer_mut(path).expect("configuration section")["unused_setting"] =
|
|
serde_json::json!({"nested": [true, null, "ignored"]});
|
|
parse_config(&extended.to_string())
|
|
.unwrap_or_else(|error| panic!("unknown field in {path}: {error}"));
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn config_loader_should_reject_invalid_known_fields_alongside_unknown_fields() {
|
|
for port in [serde_json::json!(0), serde_json::json!("not-a-port")] {
|
|
let mut document = valid_config_document();
|
|
document["host"]["listen"]["unused_setting"] = serde_json::json!(true);
|
|
document["host"]["listen"]["port"] = port;
|
|
assert_rejected(document.to_string());
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn config_loader_should_report_startup_configuration_diagnostics() {
|
|
const CHILD_ENV: &str = "CPR_TEST_CONFIG_DIAGNOSTICS_CHILD";
|
|
const UNUSED_SECRET: &str = "unused-value-must-not-appear-in-diagnostics";
|
|
if std::env::var_os(CHILD_ENV).is_some() {
|
|
gateway_host::load_config::<GatewayConfig>().expect("startup configuration");
|
|
return;
|
|
}
|
|
for case in [
|
|
"normal",
|
|
"unused",
|
|
"missing",
|
|
"timezoneEmpty",
|
|
"timezoneInvalid",
|
|
"timezoneNull",
|
|
"timezoneType",
|
|
] {
|
|
let mut document = valid_config_document();
|
|
if case == "unused" {
|
|
document["openai"]["unused_setting"] = serde_json::json!(UNUSED_SECRET);
|
|
} else if case == "missing" {
|
|
document["host"]["listen"]
|
|
.as_object_mut()
|
|
.unwrap()
|
|
.remove("port");
|
|
}
|
|
if case.starts_with("timezone") {
|
|
document["host"]["timezone"] = match case {
|
|
"timezoneEmpty" => serde_json::json!(""),
|
|
"timezoneInvalid" => serde_json::json!(UNUSED_SECRET),
|
|
"timezoneNull" => serde_json::json!(null),
|
|
_ => serde_json::json!(8),
|
|
};
|
|
}
|
|
let directory = tempfile::tempdir().unwrap();
|
|
fs::create_dir(directory.path().join("deploy")).unwrap();
|
|
fs::write(
|
|
directory.path().join("deploy/config.yaml"),
|
|
document.to_string(),
|
|
)
|
|
.unwrap();
|
|
let output = Command::new(std::env::current_exe().unwrap())
|
|
.args([
|
|
"--exact",
|
|
"bootstrap::config::config_loader_should_report_startup_configuration_diagnostics",
|
|
"--nocapture",
|
|
])
|
|
.env(CHILD_ENV, "1")
|
|
.current_dir(directory.path())
|
|
.output()
|
|
.unwrap();
|
|
let stderr = String::from_utf8_lossy(&output.stderr);
|
|
assert_eq!(
|
|
output.status.success(),
|
|
case != "missing" && !case.starts_with("timezone"),
|
|
"{case}: {stderr}"
|
|
);
|
|
match case {
|
|
"unused" => assert!(
|
|
stderr.contains("openai.unused_setting") && stderr.contains("已忽略"),
|
|
"{stderr}"
|
|
),
|
|
"missing" => assert!(stderr.contains("host.listen.port"), "{stderr}"),
|
|
case if case.starts_with("timezone") => {
|
|
assert!(stderr.contains("host.timezone"), "{stderr}")
|
|
}
|
|
_ => assert!(!stderr.contains("警告"), "{stderr}"),
|
|
}
|
|
assert!(!stderr.contains(UNUSED_SECRET), "{stderr}");
|
|
assert!(!stderr.contains("services"), "{stderr}");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn config_loader_should_reject_missing_explicit_fields() {
|
|
assert_rejected(valid_config().replace(" request_id_header: 'x-request-id'\n", ""));
|
|
}
|
|
|
|
#[test]
|
|
fn config_loader_should_allow_missing_provider_configuration() {
|
|
let mut document = valid_config_document();
|
|
document.as_object_mut().unwrap().remove("openai");
|
|
document.as_object_mut().unwrap().remove("xai");
|
|
parse_config(&document.to_string()).expect("providers use defaults when omitted");
|
|
}
|
|
|
|
#[test]
|
|
fn config_loader_should_reject_unsupported_schema_version() {
|
|
assert_rejected(valid_config().replace("schema_version: 1", "schema_version: 2"));
|
|
}
|
|
|
|
#[test]
|
|
fn config_loader_should_reject_embedded_database_password() {
|
|
assert_rejected(valid_config().replace(
|
|
"postgres://codex_proxy@127.0.0.1:5432/codex_proxy",
|
|
"postgres://codex_proxy:embedded@127.0.0.1:5432/codex_proxy",
|
|
));
|
|
}
|
|
|
|
#[test]
|
|
fn config_loader_should_accept_managed_store_passwords() {
|
|
for password in [
|
|
"RdsTest9!abcdefGh".to_owned(),
|
|
"RdsTest9!abcdefGhRdsTest9!abcdefGh".to_owned(),
|
|
POSTGRES_PASSWORD.to_owned(),
|
|
"x".repeat(128),
|
|
"Managed@:/?#%&+Password9!".to_owned(),
|
|
"数据库密码".repeat(4),
|
|
] {
|
|
for field in ["database", "redis"] {
|
|
let mut document = valid_config_document();
|
|
document["store"][field]["password"] = serde_json::json!(password);
|
|
let (config, _directory) =
|
|
parse_config(&document.to_string()).expect("managed store password");
|
|
assert!(!format!("{config:?}").contains(&password));
|
|
}
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn config_loader_should_reject_invalid_store_passwords() {
|
|
for password in [
|
|
String::new(),
|
|
"x".repeat(15),
|
|
"x".repeat(129),
|
|
" ".repeat(32),
|
|
"\u{3000}".repeat(6),
|
|
"数据库密码".repeat(9),
|
|
"RdsTest9!abcdefGh\u{0000}".to_owned(),
|
|
"RdsTest9!abcdefGh\n".to_owned(),
|
|
"RdsTest9!abcdefGh\t".to_owned(),
|
|
"RdsTest9!abcdefGh\u{007f}".to_owned(),
|
|
] {
|
|
for field in ["database", "redis"] {
|
|
let mut document = valid_config_document();
|
|
document["store"][field]["password"] = serde_json::json!(password);
|
|
assert_rejected(document.to_string());
|
|
}
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn config_loader_should_reject_embedded_redis_password() {
|
|
assert_rejected(valid_config().replace(
|
|
"redis://127.0.0.1:6379/",
|
|
"redis://default:embedded@127.0.0.1:6379/",
|
|
));
|
|
}
|
|
|
|
#[test]
|
|
fn config_loader_should_reject_weak_admin_password() {
|
|
assert_rejected(valid_config().replace(ADMIN_PASSWORD, "password"));
|
|
}
|
|
|
|
#[test]
|
|
fn config_loader_should_reject_admin_password_with_compose_interpolation() {
|
|
assert_rejected(valid_config().replace(ADMIN_PASSWORD, "unsafe$password"));
|
|
}
|
|
|
|
#[test]
|
|
fn config_loader_should_reject_zero_client_session_ttl() {
|
|
let mut config = valid_config_document();
|
|
*config
|
|
.pointer_mut("/client/session_ttl_minutes")
|
|
.expect("example client session TTL") = serde_json::json!(0);
|
|
assert_rejected(config.to_string());
|
|
}
|
|
|
|
#[test]
|
|
fn config_loader_should_default_missing_client_section() {
|
|
let mut config = valid_config_document();
|
|
config
|
|
.as_object_mut()
|
|
.expect("example config mapping")
|
|
.remove("client")
|
|
.expect("example client section");
|
|
parse_config(&config.to_string()).expect("client defaults when the section is omitted");
|
|
}
|
|
|
|
#[test]
|
|
fn config_loader_should_reject_missing_client_session_ttl() {
|
|
let mut config = valid_config_document();
|
|
config["client"]
|
|
.as_object_mut()
|
|
.expect("example client mapping")
|
|
.remove("session_ttl_minutes")
|
|
.expect("example client session TTL");
|
|
assert_rejected(config.to_string());
|
|
}
|
|
|
|
#[test]
|
|
fn config_loader_should_reject_disabled_all_log_outputs() {
|
|
assert_rejected(
|
|
valid_config()
|
|
.replace("stdout: true", "stdout: false")
|
|
.replace("enabled: true", "enabled: false"),
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn config_loader_should_reject_zero_server_port() {
|
|
assert_rejected(valid_config().replace("port: 8080", "port: 0"));
|
|
}
|
|
|
|
#[test]
|
|
fn config_loader_should_accept_optional_openai_routing_strings() {
|
|
for value in [
|
|
serde_json::Value::Null,
|
|
serde_json::json!("us"),
|
|
serde_json::json!("custom-value"),
|
|
serde_json::json!(""),
|
|
] {
|
|
let mut document = valid_config_document();
|
|
document["openai"]["residency"] = value.clone();
|
|
document["openai"]["account_routing_override"] = value;
|
|
parse_config(&document.to_string()).expect("optional routing strings");
|
|
}
|
|
let mut document = valid_config_document();
|
|
document["openai"]
|
|
.as_object_mut()
|
|
.unwrap()
|
|
.remove("residency");
|
|
document["openai"]
|
|
.as_object_mut()
|
|
.unwrap()
|
|
.remove("account_routing_override");
|
|
parse_config(&document.to_string()).expect("omitted routing strings");
|
|
}
|
|
|
|
fn assert_rejected(config: String) {
|
|
assert!(parse_config(&config).is_err());
|
|
}
|
|
|
|
fn valid_config() -> String {
|
|
CONFIG_EXAMPLE
|
|
.replacen(
|
|
"password: &postgres_password ''",
|
|
&format!("password: &postgres_password '{POSTGRES_PASSWORD}'"),
|
|
1,
|
|
)
|
|
.replacen(
|
|
"password: &redis_password ''",
|
|
&format!("password: &redis_password '{REDIS_PASSWORD}'"),
|
|
1,
|
|
)
|
|
.replace(
|
|
"default_password: ''",
|
|
&format!("default_password: '{ADMIN_PASSWORD}'"),
|
|
)
|
|
}
|
|
|
|
fn valid_config_document() -> serde_json::Value {
|
|
// 按字段修改样例,避免注释或排版变化让测试输入悄悄失效;JSON 仍可由 YAML 文件入口加载
|
|
config::Config::builder()
|
|
.add_source(config::File::from_str(
|
|
&valid_config(),
|
|
config::FileFormat::Yaml,
|
|
))
|
|
.build()
|
|
.and_then(config::Config::try_deserialize)
|
|
.expect("example config document")
|
|
}
|
|
|
|
fn parse_config(config: &str) -> Result<(GatewayConfig, tempfile::TempDir), String> {
|
|
let directory = tempfile::tempdir().map_err(|error| error.to_string())?;
|
|
let deploy = directory.path().join("deploy");
|
|
fs::create_dir(&deploy).map_err(|error| error.to_string())?;
|
|
let path = deploy.join("config.yaml");
|
|
fs::write(&path, config).map_err(|error| error.to_string())?;
|
|
let mut config = config::Config::builder()
|
|
.add_source(config::File::from(path).required(true))
|
|
.build()
|
|
.and_then(config::Config::try_deserialize::<GatewayConfig>)
|
|
.map_err(|error| error.to_string())?;
|
|
config
|
|
.resolve_and_validate(&deploy)
|
|
.map_err(|error| error.to_string())?;
|
|
Ok((config, directory))
|
|
}
|
|
|
|
#[test]
|
|
fn deployment_timezone_defaults_and_valid_override_are_loaded() {
|
|
let mut document = valid_config_document();
|
|
document["host"].as_object_mut().unwrap().remove("timezone");
|
|
let (_config, _directory) = parse_config(&document.to_string()).unwrap();
|
|
let host: gateway_host::config::HostConfig =
|
|
serde_json::from_value(document["host"].clone()).unwrap();
|
|
assert_eq!(host.timezone.name(), "Asia/Shanghai");
|
|
document["host"]["timezone"] = serde_json::json!("Asia/Kathmandu");
|
|
let (_config, _directory) = parse_config(&document.to_string()).unwrap();
|
|
let host: gateway_host::config::HostConfig =
|
|
serde_json::from_value(document["host"].clone()).unwrap();
|
|
assert_eq!(host.timezone.name(), "Asia/Kathmandu");
|
|
}
|