mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-11-18 00:07:02 +00:00
feat: add read-only admin settings
Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
@@ -1,3 +1,5 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use axum::{
|
||||
body::{to_bytes, Body},
|
||||
http::{Request, StatusCode},
|
||||
@@ -10,8 +12,9 @@ use codex_proxy_rs::{
|
||||
app::build_router,
|
||||
auth::admin_session::hash_admin_password,
|
||||
config::{
|
||||
AdminConfig, ApiConfig, AppConfig, AuthConfig, DatabaseConfig, LoggingConfig,
|
||||
SecurityConfig, ServerConfig, TlsConfig,
|
||||
AdminConfig, ApiConfig, AppConfig, AuthConfig, DatabaseConfig, LoggingConfig, ModelConfig,
|
||||
QuotaConfig, QuotaWarningThresholds, SecurityConfig, ServerConfig, TlsConfig,
|
||||
UsageStatsConfig,
|
||||
},
|
||||
state::AppState,
|
||||
storage::db::connect_sqlite,
|
||||
@@ -26,10 +29,31 @@ fn test_config(database_url: String) -> AppConfig {
|
||||
api: ApiConfig {
|
||||
base_url: "https://chatgpt.com/backend-api".to_string(),
|
||||
},
|
||||
model: ModelConfig {
|
||||
default_model: "gpt-5.5".to_string(),
|
||||
default_reasoning_effort: None,
|
||||
service_tier: None,
|
||||
aliases: BTreeMap::new(),
|
||||
},
|
||||
auth: AuthConfig {
|
||||
refresh_margin_seconds: 300,
|
||||
refresh_enabled: true,
|
||||
refresh_concurrency: 2,
|
||||
max_concurrent_per_account: 3,
|
||||
request_interval_ms: 50,
|
||||
rotation_strategy: "least_used".to_string(),
|
||||
tier_priority: Vec::new(),
|
||||
},
|
||||
quota: QuotaConfig {
|
||||
refresh_interval_minutes: 5,
|
||||
warning_thresholds: QuotaWarningThresholds {
|
||||
primary: vec![80, 90],
|
||||
secondary: vec![80, 90],
|
||||
},
|
||||
skip_exhausted: true,
|
||||
},
|
||||
usage_stats: UsageStatsConfig {
|
||||
history_retention_days: None,
|
||||
},
|
||||
database: DatabaseConfig { url: database_url },
|
||||
security: SecurityConfig {
|
||||
@@ -46,6 +70,9 @@ fn test_config(database_url: String) -> AppConfig {
|
||||
directory: "logs".to_string(),
|
||||
max_file_bytes: 10_485_760,
|
||||
retention_days: 14,
|
||||
enabled: false,
|
||||
capacity: 2_000,
|
||||
capture_body: false,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use axum::{
|
||||
body::{to_bytes, Body},
|
||||
http::{Request, StatusCode},
|
||||
@@ -9,8 +11,9 @@ use tower::ServiceExt;
|
||||
use codex_proxy_rs::{
|
||||
app::build_router,
|
||||
config::{
|
||||
AdminConfig, ApiConfig, AppConfig, AuthConfig, DatabaseConfig, LoggingConfig,
|
||||
SecurityConfig, ServerConfig, TlsConfig,
|
||||
AdminConfig, ApiConfig, AppConfig, AuthConfig, DatabaseConfig, LoggingConfig, ModelConfig,
|
||||
QuotaConfig, QuotaWarningThresholds, SecurityConfig, ServerConfig, TlsConfig,
|
||||
UsageStatsConfig,
|
||||
},
|
||||
logs::{
|
||||
event::{EventLevel, EventLog},
|
||||
@@ -29,10 +32,31 @@ fn test_config(database_url: String) -> AppConfig {
|
||||
api: ApiConfig {
|
||||
base_url: "https://chatgpt.com/backend-api".to_string(),
|
||||
},
|
||||
model: ModelConfig {
|
||||
default_model: "gpt-5.5".to_string(),
|
||||
default_reasoning_effort: None,
|
||||
service_tier: None,
|
||||
aliases: BTreeMap::new(),
|
||||
},
|
||||
auth: AuthConfig {
|
||||
refresh_margin_seconds: 300,
|
||||
refresh_enabled: true,
|
||||
refresh_concurrency: 2,
|
||||
max_concurrent_per_account: 3,
|
||||
request_interval_ms: 50,
|
||||
rotation_strategy: "least_used".to_string(),
|
||||
tier_priority: Vec::new(),
|
||||
},
|
||||
quota: QuotaConfig {
|
||||
refresh_interval_minutes: 5,
|
||||
warning_thresholds: QuotaWarningThresholds {
|
||||
primary: vec![80, 90],
|
||||
secondary: vec![80, 90],
|
||||
},
|
||||
skip_exhausted: true,
|
||||
},
|
||||
usage_stats: UsageStatsConfig {
|
||||
history_retention_days: None,
|
||||
},
|
||||
database: DatabaseConfig { url: database_url },
|
||||
security: SecurityConfig {
|
||||
@@ -49,6 +73,9 @@ fn test_config(database_url: String) -> AppConfig {
|
||||
directory: "logs".to_string(),
|
||||
max_file_bytes: 10_485_760,
|
||||
retention_days: 14,
|
||||
enabled: false,
|
||||
capacity: 2_000,
|
||||
capture_body: false,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use axum::{
|
||||
body::{to_bytes, Body},
|
||||
http::{Request, StatusCode},
|
||||
};
|
||||
use chrono::Utc;
|
||||
use serde_json::{json, Value};
|
||||
use tower::ServiceExt;
|
||||
|
||||
use codex_proxy_rs::{
|
||||
app::build_router,
|
||||
config::{
|
||||
AdminConfig, ApiConfig, AppConfig, AuthConfig, DatabaseConfig, LoggingConfig, ModelConfig,
|
||||
QuotaConfig, QuotaWarningThresholds, SecurityConfig, ServerConfig, TlsConfig,
|
||||
UsageStatsConfig,
|
||||
},
|
||||
state::AppState,
|
||||
storage::db::connect_sqlite,
|
||||
};
|
||||
|
||||
fn test_config(database_url: String) -> AppConfig {
|
||||
let mut aliases = BTreeMap::new();
|
||||
aliases.insert("codex-fast".to_string(), "gpt-5.5".to_string());
|
||||
AppConfig {
|
||||
server: ServerConfig {
|
||||
host: "127.0.0.1".to_string(),
|
||||
port: 0,
|
||||
},
|
||||
api: ApiConfig {
|
||||
base_url: "https://chatgpt.com/backend-api".to_string(),
|
||||
},
|
||||
model: ModelConfig {
|
||||
default_model: "gpt-5.5".to_string(),
|
||||
default_reasoning_effort: Some("high".to_string()),
|
||||
service_tier: Some("flex".to_string()),
|
||||
aliases,
|
||||
},
|
||||
auth: AuthConfig {
|
||||
refresh_margin_seconds: 240,
|
||||
refresh_enabled: true,
|
||||
refresh_concurrency: 2,
|
||||
max_concurrent_per_account: 4,
|
||||
request_interval_ms: 50,
|
||||
rotation_strategy: "least_used".to_string(),
|
||||
tier_priority: vec!["team".to_string(), "plus".to_string()],
|
||||
},
|
||||
quota: QuotaConfig {
|
||||
refresh_interval_minutes: 5,
|
||||
warning_thresholds: QuotaWarningThresholds {
|
||||
primary: vec![80, 90],
|
||||
secondary: vec![70, 95],
|
||||
},
|
||||
skip_exhausted: true,
|
||||
},
|
||||
usage_stats: UsageStatsConfig {
|
||||
history_retention_days: Some(30),
|
||||
},
|
||||
database: DatabaseConfig { url: database_url },
|
||||
security: SecurityConfig {
|
||||
master_key_file: "data/master.key".to_string(),
|
||||
api_key_pepper_file: "data/api-key-pepper.key".to_string(),
|
||||
},
|
||||
tls: TlsConfig {
|
||||
force_http11: false,
|
||||
},
|
||||
admin: AdminConfig {
|
||||
session_ttl_minutes: 1440,
|
||||
},
|
||||
logging: LoggingConfig {
|
||||
directory: "logs".to_string(),
|
||||
max_file_bytes: 10_485_760,
|
||||
retention_days: 14,
|
||||
enabled: true,
|
||||
capacity: 2_000,
|
||||
capture_body: false,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn admin_settings_should_require_admin_session_cookie() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let db = dir.path().join("admin-settings.sqlite");
|
||||
let url = format!("sqlite://{}", db.display());
|
||||
let pool = connect_sqlite(&url).await.unwrap();
|
||||
let app = build_router(AppState::with_pool(test_config(url), pool));
|
||||
|
||||
let response = app
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("GET")
|
||||
.uri("/admin/settings")
|
||||
.header("x-request-id", "req_settings")
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
|
||||
let body = response_json(response).await;
|
||||
assert_eq!(body["code"], 40101);
|
||||
assert_eq!(body["requestId"], "req_settings");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn admin_settings_should_return_only_in_scope_runtime_fields() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let db = dir.path().join("admin-settings.sqlite");
|
||||
let url = format!("sqlite://{}", db.display());
|
||||
let pool = connect_sqlite(&url).await.unwrap();
|
||||
seed_admin_session(&pool, "session_1").await;
|
||||
let app = build_router(AppState::with_pool(test_config(url), pool));
|
||||
|
||||
let response = app
|
||||
.oneshot(
|
||||
Request::builder()
|
||||
.method("GET")
|
||||
.uri("/admin/settings")
|
||||
.header("cookie", "cpr_admin_session=session_1")
|
||||
.header("x-request-id", "req_settings")
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let body = response_json(response).await;
|
||||
assert_eq!(body["code"], 200);
|
||||
assert_eq!(body["requestId"], "req_settings");
|
||||
assert_eq!(
|
||||
body["data"],
|
||||
json!({
|
||||
"defaultModel": "gpt-5.5",
|
||||
"defaultReasoningEffort": "high",
|
||||
"serviceTier": "flex",
|
||||
"modelAliases": { "codex-fast": "gpt-5.5" },
|
||||
"refreshEnabled": true,
|
||||
"refreshMarginSeconds": 240,
|
||||
"refreshConcurrency": 2,
|
||||
"maxConcurrentPerAccount": 4,
|
||||
"requestIntervalMs": 50,
|
||||
"rotationStrategy": "least_used",
|
||||
"tierPriority": ["team", "plus"],
|
||||
"quotaRefreshIntervalMinutes": 5,
|
||||
"quotaWarningThresholds": {
|
||||
"primary": [80, 90],
|
||||
"secondary": [70, 95]
|
||||
},
|
||||
"quotaSkipExhausted": true,
|
||||
"logsEnabled": true,
|
||||
"logsCapacity": 2000,
|
||||
"logsCaptureBody": false,
|
||||
"usageHistoryRetentionDays": 30
|
||||
})
|
||||
);
|
||||
for removed_key in [
|
||||
"proxyUrl",
|
||||
"openaiApiKey",
|
||||
"ollama",
|
||||
"provider",
|
||||
"proxyApiKey",
|
||||
"autoUpdate",
|
||||
] {
|
||||
assert!(
|
||||
body["data"].get(removed_key).is_none(),
|
||||
"{removed_key} must stay out of the Rust settings API"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async fn seed_admin_session(pool: &sqlx::SqlitePool, session_id: &str) {
|
||||
let now = Utc::now().to_rfc3339();
|
||||
sqlx::query(
|
||||
"insert into admin_users (id, password_hash, created_at, updated_at) values (?, ?, ?, ?)",
|
||||
)
|
||||
.bind("admin_1")
|
||||
.bind("hash")
|
||||
.bind(&now)
|
||||
.bind(&now)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query(
|
||||
"insert into admin_sessions (id, user_id, expires_at, created_at) values (?, ?, ?, ?)",
|
||||
)
|
||||
.bind(session_id)
|
||||
.bind("admin_1")
|
||||
.bind("2999-01-01T00:00:00Z")
|
||||
.bind(now)
|
||||
.execute(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
async fn response_json(response: axum::response::Response) -> Value {
|
||||
let bytes = to_bytes(response.into_body(), usize::MAX).await.unwrap();
|
||||
serde_json::from_slice(&bytes).unwrap()
|
||||
}
|
||||
@@ -9,10 +9,31 @@ server:
|
||||
port: 8080
|
||||
api:
|
||||
base_url: https://chatgpt.com/backend-api
|
||||
model:
|
||||
default: gpt-5.5
|
||||
default_reasoning_effort: null
|
||||
default_service_tier: null
|
||||
aliases: {}
|
||||
auth:
|
||||
refresh_margin_seconds: 300
|
||||
refresh_enabled: true
|
||||
refresh_concurrency: 2
|
||||
max_concurrent_per_account: 3
|
||||
request_interval_ms: 50
|
||||
rotation_strategy: least_used
|
||||
tier_priority: []
|
||||
quota:
|
||||
refresh_interval_minutes: 5
|
||||
warning_thresholds:
|
||||
primary:
|
||||
- 80
|
||||
- 90
|
||||
secondary:
|
||||
- 80
|
||||
- 90
|
||||
skip_exhausted: true
|
||||
usage_stats:
|
||||
history_retention_days: null
|
||||
database:
|
||||
url: sqlite://data/codex-proxy-rs.sqlite
|
||||
security:
|
||||
@@ -26,10 +47,15 @@ logging:
|
||||
directory: logs
|
||||
max_file_bytes: 10485760
|
||||
retention_days: 14
|
||||
enabled: false
|
||||
capacity: 2000
|
||||
capture_body: false
|
||||
"#;
|
||||
let cfg: AppConfig = serde_yaml::from_str(yaml).unwrap();
|
||||
assert_eq!(cfg.api.base_url, "https://chatgpt.com/backend-api");
|
||||
assert_eq!(cfg.model.default_model, "gpt-5.5");
|
||||
assert_eq!(cfg.auth.refresh_margin_seconds, 300);
|
||||
assert_eq!(cfg.auth.rotation_strategy, "least_used");
|
||||
assert_eq!(cfg.database.url, "sqlite://data/codex-proxy-rs.sqlite");
|
||||
assert_eq!(cfg.security.master_key_file, "data/master.key");
|
||||
}
|
||||
@@ -45,10 +71,31 @@ server:
|
||||
port: 8080
|
||||
api:
|
||||
base_url: https://chatgpt.com/backend-api
|
||||
model:
|
||||
default: gpt-5.5
|
||||
default_reasoning_effort: null
|
||||
default_service_tier: null
|
||||
aliases: {}
|
||||
auth:
|
||||
refresh_margin_seconds: 300
|
||||
refresh_enabled: true
|
||||
refresh_concurrency: 2
|
||||
max_concurrent_per_account: 3
|
||||
request_interval_ms: 50
|
||||
rotation_strategy: least_used
|
||||
tier_priority: []
|
||||
quota:
|
||||
refresh_interval_minutes: 5
|
||||
warning_thresholds:
|
||||
primary:
|
||||
- 80
|
||||
- 90
|
||||
secondary:
|
||||
- 80
|
||||
- 90
|
||||
skip_exhausted: true
|
||||
usage_stats:
|
||||
history_retention_days: null
|
||||
database:
|
||||
url: sqlite://data/codex-proxy-rs.sqlite
|
||||
security:
|
||||
@@ -62,6 +109,9 @@ logging:
|
||||
directory: logs
|
||||
max_file_bytes: 10485760
|
||||
retention_days: 14
|
||||
enabled: false
|
||||
capacity: 2000
|
||||
capture_body: false
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
@@ -82,6 +132,8 @@ logging:
|
||||
("CPRS_PORT", "19090"),
|
||||
("CPRS_DATABASE_URL", "sqlite://override.sqlite"),
|
||||
("CPRS_LOG_MAX_FILE_BYTES", "4096"),
|
||||
("CPRS_DEFAULT_MODEL", "gpt-5.5"),
|
||||
("CPRS_MAX_CONCURRENT_PER_ACCOUNT", "4"),
|
||||
],
|
||||
)
|
||||
.unwrap();
|
||||
@@ -89,6 +141,8 @@ logging:
|
||||
assert_eq!(cfg.server.host, "0.0.0.0");
|
||||
assert_eq!(cfg.server.port, 19090);
|
||||
assert_eq!(cfg.database.url, "sqlite://override.sqlite");
|
||||
assert_eq!(cfg.model.default_model, "gpt-5.5");
|
||||
assert_eq!(cfg.auth.max_concurrent_per_account, 4);
|
||||
assert_eq!(cfg.logging.directory, "local-logs");
|
||||
assert_eq!(cfg.logging.max_file_bytes, 4096);
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use axum::{
|
||||
body::{to_bytes, Body},
|
||||
http::{Request, StatusCode},
|
||||
@@ -8,8 +10,9 @@ use tower::ServiceExt;
|
||||
use codex_proxy_rs::{
|
||||
app::build_router,
|
||||
config::{
|
||||
AdminConfig, ApiConfig, AppConfig, AuthConfig, DatabaseConfig, LoggingConfig,
|
||||
SecurityConfig, ServerConfig, TlsConfig,
|
||||
AdminConfig, ApiConfig, AppConfig, AuthConfig, DatabaseConfig, LoggingConfig, ModelConfig,
|
||||
QuotaConfig, QuotaWarningThresholds, SecurityConfig, ServerConfig, TlsConfig,
|
||||
UsageStatsConfig,
|
||||
},
|
||||
state::AppState,
|
||||
};
|
||||
@@ -23,10 +26,31 @@ fn test_config() -> AppConfig {
|
||||
api: ApiConfig {
|
||||
base_url: "https://chatgpt.com/backend-api".to_string(),
|
||||
},
|
||||
model: ModelConfig {
|
||||
default_model: "gpt-5.5".to_string(),
|
||||
default_reasoning_effort: None,
|
||||
service_tier: None,
|
||||
aliases: BTreeMap::new(),
|
||||
},
|
||||
auth: AuthConfig {
|
||||
refresh_margin_seconds: 300,
|
||||
refresh_enabled: true,
|
||||
refresh_concurrency: 2,
|
||||
max_concurrent_per_account: 3,
|
||||
request_interval_ms: 50,
|
||||
rotation_strategy: "least_used".to_string(),
|
||||
tier_priority: Vec::new(),
|
||||
},
|
||||
quota: QuotaConfig {
|
||||
refresh_interval_minutes: 5,
|
||||
warning_thresholds: QuotaWarningThresholds {
|
||||
primary: vec![80, 90],
|
||||
secondary: vec![80, 90],
|
||||
},
|
||||
skip_exhausted: true,
|
||||
},
|
||||
usage_stats: UsageStatsConfig {
|
||||
history_retention_days: None,
|
||||
},
|
||||
database: DatabaseConfig {
|
||||
url: "sqlite://:memory:".to_string(),
|
||||
@@ -45,6 +69,9 @@ fn test_config() -> AppConfig {
|
||||
directory: "logs".to_string(),
|
||||
max_file_bytes: 10_485_760,
|
||||
retention_days: 14,
|
||||
enabled: false,
|
||||
capacity: 2_000,
|
||||
capture_body: false,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user