mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-11-29 16:00:51 +00:00
545 lines
18 KiB
Rust
545 lines
18 KiB
Rust
//! 验证账号分组 HTTP 接口的请求校验、权限与响应合同
|
|
|
|
use axum::{
|
|
Router,
|
|
body::{Body, to_bytes},
|
|
http::{Method, Request, StatusCode, header},
|
|
};
|
|
use gateway_api::admin::account_groups;
|
|
use serde_json::{Value, json};
|
|
use tower::ServiceExt as _;
|
|
|
|
use super::{AdminTestFixture, AdminTestState, PRIMARY_GROUP_ID};
|
|
|
|
const SESSION_COOKIE: &str = "cpr_session=valid-session";
|
|
|
|
#[tokio::test]
|
|
async fn list_route_should_keep_camel_case_group_and_page_wire() {
|
|
let fixture = authenticated_fixture().await;
|
|
let response = request(
|
|
router(&fixture),
|
|
Method::GET,
|
|
"/api/admin/account-groups?page=1&pageSize=1&search=alpha&enabled=true",
|
|
None,
|
|
true,
|
|
)
|
|
.await;
|
|
|
|
assert_eq!(response.status(), StatusCode::OK);
|
|
let value = response_json(response).await;
|
|
assert_eq!(value["data"]["page"]["page"], 1);
|
|
assert_eq!(value["data"]["page"]["pageSize"], 1);
|
|
assert_eq!(value["data"]["page"]["total"], 1);
|
|
assert_eq!(value["data"]["page"]["totalPages"], 1);
|
|
assert_eq!(value["data"]["configRevision"], 7);
|
|
assert_eq!(value["data"]["items"][0]["id"], PRIMARY_GROUP_ID);
|
|
assert_eq!(value["data"]["items"][0]["memberCount"], 2);
|
|
assert_eq!(value["data"]["items"][0]["providerCounts"]["openai"], 1);
|
|
assert_eq!(value["data"]["items"][0]["clientKeyCount"], 2);
|
|
assert_eq!(value["data"]["items"][0]["accountSummary"]["available"], 1);
|
|
assert_eq!(value["data"]["items"][0]["accountSummary"]["limited"], 1);
|
|
assert_eq!(value["data"]["items"][0]["accountSummary"]["total"], 2);
|
|
assert_eq!(value["data"]["items"][0]["capacity"]["usedSlots"], 0);
|
|
assert_eq!(value["data"]["items"][0]["capacity"]["totalSlots"], 1);
|
|
assert_eq!(value["data"]["items"][0]["usage"]["todayUsd"], "1.25");
|
|
assert_eq!(
|
|
value["data"]["items"][0]["usage"]["retainedTotalUsd"],
|
|
"5.5"
|
|
);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn options_route_should_return_only_lightweight_group_fields() {
|
|
let fixture = authenticated_fixture().await;
|
|
let response = request(
|
|
router(&fixture),
|
|
Method::GET,
|
|
"/api/admin/account-groups/options?page=1&pageSize=1&search=alpha&enabled=true",
|
|
None,
|
|
true,
|
|
)
|
|
.await;
|
|
|
|
assert_eq!(response.status(), StatusCode::OK);
|
|
let value = response_json(response).await;
|
|
assert_eq!(
|
|
value["data"]["items"][0],
|
|
json!({
|
|
"id": PRIMARY_GROUP_ID,
|
|
"name": "Alpha routing",
|
|
"color": "#2563EBFF",
|
|
"enabled": true
|
|
})
|
|
);
|
|
assert_eq!(value["data"]["page"]["page"], 1);
|
|
assert_eq!(value["data"]["page"]["pageSize"], 1);
|
|
assert_eq!(value["data"]["page"]["total"], 1);
|
|
assert_eq!(value["data"]["page"]["totalPages"], 1);
|
|
assert_eq!(value["data"]["configRevision"], 7);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn models_route_reads_the_published_group_catalog() {
|
|
use gateway_core::{
|
|
account::ProviderAccountId,
|
|
routing::{
|
|
ConfigRevision, ModelCapabilities, ProviderKind, ProviderModel, RuntimeAccount,
|
|
RuntimeAccountDirectory, RuntimeSnapshot, UpstreamModelId,
|
|
},
|
|
};
|
|
use std::{
|
|
collections::{BTreeMap, BTreeSet},
|
|
sync::Arc,
|
|
};
|
|
|
|
let fixture = authenticated_fixture().await;
|
|
let uri = format!("/api/admin/account-groups/models?id={PRIMARY_GROUP_ID}");
|
|
let unavailable = request(router(&fixture), Method::GET, &uri, None, true).await;
|
|
assert_eq!(unavailable.status(), StatusCode::SERVICE_UNAVAILABLE);
|
|
let provider = ProviderKind::new("openai").unwrap();
|
|
let snapshot = RuntimeSnapshot::new(
|
|
ConfigRevision::new(7).unwrap(),
|
|
gateway_core::settings::SettingsValues::new(1, "smart", Default::default(), None, None),
|
|
vec![provider.clone()],
|
|
vec![ProviderModel::new(
|
|
provider.clone(),
|
|
UpstreamModelId::new("model-a").unwrap(),
|
|
ModelCapabilities::new(
|
|
BTreeSet::from([gateway_core::operation::OperationKind::Generate]),
|
|
None,
|
|
),
|
|
)],
|
|
vec![],
|
|
)
|
|
.unwrap()
|
|
.with_account_directory(Arc::new(RuntimeAccountDirectory::new(BTreeMap::from([(
|
|
ProviderAccountId::new("acct_member").unwrap(),
|
|
RuntimeAccount::new(
|
|
provider,
|
|
BTreeSet::from([super::group_id(PRIMARY_GROUP_ID)]),
|
|
),
|
|
)]))));
|
|
fixture.published_snapshot.publish(snapshot);
|
|
let response = request(router(&fixture), Method::GET, &uri, None, true).await;
|
|
assert_eq!(response.status(), StatusCode::OK);
|
|
assert_eq!(
|
|
response_json(response).await["data"],
|
|
json!({"models":[{"id":"model-a", "label":"model-a"}]})
|
|
);
|
|
let unauthorized = request(router(&fixture), Method::GET, &uri, None, false).await;
|
|
assert_eq!(unauthorized.status(), StatusCode::UNAUTHORIZED);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn create_route_should_create_an_empty_group() {
|
|
let fixture = authenticated_fixture().await;
|
|
let response = request(
|
|
router(&fixture),
|
|
Method::POST,
|
|
"/api/admin/account-groups/create",
|
|
Some(json!({
|
|
"name": "Gamma routing",
|
|
"description": "New traffic pool",
|
|
"color": "#a855f780"
|
|
})),
|
|
true,
|
|
)
|
|
.await;
|
|
|
|
assert_eq!(response.status(), StatusCode::CREATED);
|
|
let value = response_json(response).await;
|
|
assert!(
|
|
value["data"]["id"]
|
|
.as_str()
|
|
.is_some_and(|id| id.starts_with("grp_") && id.len() == 36)
|
|
);
|
|
assert_eq!(value["data"]["record"]["name"], "Gamma routing");
|
|
assert_eq!(value["data"]["record"]["memberCount"], 0);
|
|
assert_eq!(value["data"]["record"]["color"], "#A855F780");
|
|
assert_eq!(value["data"]["record"]["fastMode"], "default");
|
|
assert_eq!(value["data"]["record"]["allowImageGeneration"], true);
|
|
assert_eq!(value["data"]["record"]["allowSubagents"], true);
|
|
assert_eq!(
|
|
value["data"]["record"]["modelAccess"],
|
|
json!({"mode":"all","models":[]})
|
|
);
|
|
assert_eq!(value["data"]["configRevision"], 8);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn update_route_should_replace_group_fields() {
|
|
let fixture = authenticated_fixture().await;
|
|
let response = request(
|
|
router(&fixture),
|
|
Method::POST,
|
|
"/api/admin/account-groups/update",
|
|
Some(json!({
|
|
"id": PRIMARY_GROUP_ID,
|
|
"name": "Renamed routing",
|
|
"description": null,
|
|
"color": "#F43F5ECC"
|
|
})),
|
|
true,
|
|
)
|
|
.await;
|
|
|
|
assert_eq!(response.status(), StatusCode::OK);
|
|
let value = response_json(response).await;
|
|
assert_eq!(value["data"]["record"]["name"], "Renamed routing");
|
|
assert!(value["data"]["record"]["description"].is_null());
|
|
assert_eq!(value["data"]["record"]["color"], "#F43F5ECC");
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn enable_and_disable_routes_should_set_explicit_group_state() {
|
|
let fixture = authenticated_fixture().await;
|
|
let disabled = request(
|
|
router(&fixture),
|
|
Method::POST,
|
|
"/api/admin/account-groups/disable",
|
|
Some(json!({ "id": PRIMARY_GROUP_ID })),
|
|
true,
|
|
)
|
|
.await;
|
|
let enabled = request(
|
|
router(&fixture),
|
|
Method::POST,
|
|
"/api/admin/account-groups/enable",
|
|
Some(json!({ "id": PRIMARY_GROUP_ID })),
|
|
true,
|
|
)
|
|
.await;
|
|
|
|
assert_eq!(disabled.status(), StatusCode::OK);
|
|
assert!(
|
|
!response_json(disabled).await["data"]["record"]["enabled"]
|
|
.as_bool()
|
|
.expect("disabled flag")
|
|
);
|
|
assert_eq!(enabled.status(), StatusCode::OK);
|
|
assert!(
|
|
response_json(enabled).await["data"]["record"]["enabled"]
|
|
.as_bool()
|
|
.expect("enabled flag")
|
|
);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn delete_route_should_return_deleted_id_without_a_live_record() {
|
|
let fixture = authenticated_fixture().await;
|
|
let response = request(
|
|
router(&fixture),
|
|
Method::POST,
|
|
"/api/admin/account-groups/delete",
|
|
Some(json!({ "id": PRIMARY_GROUP_ID })),
|
|
true,
|
|
)
|
|
.await;
|
|
|
|
assert_eq!(response.status(), StatusCode::OK);
|
|
let value = response_json(response).await;
|
|
assert_eq!(value["data"]["id"], PRIMARY_GROUP_ID);
|
|
assert!(value["data"]["record"].is_null());
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn list_route_should_reject_unknown_and_invalid_pagination_fields() {
|
|
let fixture = authenticated_fixture().await;
|
|
for uri in [
|
|
"/api/admin/account-groups/models",
|
|
"/api/admin/account-groups/models?id=bad",
|
|
"/api/admin/account-groups?other=true",
|
|
"/api/admin/account-groups?page=0",
|
|
"/api/admin/account-groups?pageSize=0",
|
|
"/api/admin/account-groups?pageSize=201",
|
|
"/api/admin/account-groups/options?other=true",
|
|
"/api/admin/account-groups/options?page=0",
|
|
"/api/admin/account-groups/options?pageSize=0",
|
|
"/api/admin/account-groups/options?pageSize=201",
|
|
"/api/admin/account-groups/options?search=%00",
|
|
] {
|
|
let response = request(router(&fixture), Method::GET, uri, None, true).await;
|
|
assert_eq!(response.status(), StatusCode::BAD_REQUEST, "{uri}");
|
|
}
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn mutation_route_should_reject_unknown_json_fields() {
|
|
let fixture = authenticated_fixture().await;
|
|
let response = request(
|
|
router(&fixture),
|
|
Method::POST,
|
|
"/api/admin/account-groups/create",
|
|
Some(json!({
|
|
"name": "Unknown field",
|
|
"description": null,
|
|
"color": "#2563EBFF",
|
|
"unknownField": true
|
|
})),
|
|
true,
|
|
)
|
|
.await;
|
|
|
|
assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn create_route_should_reject_six_digit_color_without_alpha() {
|
|
let fixture = authenticated_fixture().await;
|
|
let response = request(
|
|
router(&fixture),
|
|
Method::POST,
|
|
"/api/admin/account-groups/create",
|
|
Some(json!({
|
|
"name": "Color without alpha",
|
|
"description": null,
|
|
"color": "#2563EB"
|
|
})),
|
|
true,
|
|
)
|
|
.await;
|
|
|
|
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn account_group_routes_should_require_admin_authentication() {
|
|
let fixture = AdminTestFixture::new().await;
|
|
let get_response = request(
|
|
router(&fixture),
|
|
Method::GET,
|
|
"/api/admin/account-groups",
|
|
None,
|
|
false,
|
|
)
|
|
.await;
|
|
let options_response = request(
|
|
router(&fixture),
|
|
Method::GET,
|
|
"/api/admin/account-groups/options",
|
|
None,
|
|
false,
|
|
)
|
|
.await;
|
|
let post_response = request(
|
|
router(&fixture),
|
|
Method::POST,
|
|
"/api/admin/account-groups/create",
|
|
Some(json!({ "name": "Unauthorized", "description": null, "color": "#2563EBFF" })),
|
|
false,
|
|
)
|
|
.await;
|
|
|
|
assert_eq!(get_response.status(), StatusCode::UNAUTHORIZED);
|
|
assert_eq!(options_response.status(), StatusCode::UNAUTHORIZED);
|
|
assert_eq!(post_response.status(), StatusCode::UNAUTHORIZED);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn options_route_should_reject_client_key_identity() {
|
|
let fixture = crate::support::key_fixture().await;
|
|
let response = router(&fixture)
|
|
.oneshot(
|
|
Request::builder()
|
|
.method(Method::GET)
|
|
.uri("/api/admin/account-groups/options")
|
|
.header("x-api-key", crate::support::RAW_KEY)
|
|
.header("x-request-id", "req_account_group_options_client_key")
|
|
.body(Body::empty())
|
|
.expect("client key options request"),
|
|
)
|
|
.await
|
|
.expect("client key options response");
|
|
|
|
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
|
|
}
|
|
|
|
async fn authenticated_fixture() -> AdminTestFixture {
|
|
let fixture = AdminTestFixture::new().await;
|
|
fixture.auth.insert_session("valid-session");
|
|
fixture
|
|
}
|
|
|
|
fn router(fixture: &AdminTestFixture) -> Router {
|
|
account_groups::router::<AdminTestState>().with_state(fixture.state())
|
|
}
|
|
|
|
async fn request(
|
|
router: Router,
|
|
method: Method,
|
|
uri: &str,
|
|
body: Option<Value>,
|
|
authenticated: bool,
|
|
) -> axum::response::Response {
|
|
let mut builder = Request::builder()
|
|
.method(method)
|
|
.uri(uri)
|
|
.header("x-request-id", "req_account_groups");
|
|
if authenticated {
|
|
builder = builder.header(header::COOKIE, SESSION_COOKIE);
|
|
}
|
|
let body = match body {
|
|
Some(value) => {
|
|
builder = builder.header(header::CONTENT_TYPE, "application/json");
|
|
Body::from(serde_json::to_vec(&value).expect("serialize request body"))
|
|
}
|
|
None => Body::empty(),
|
|
};
|
|
router
|
|
.oneshot(builder.body(body).expect("account group request"))
|
|
.await
|
|
.expect("account group response")
|
|
}
|
|
|
|
async fn response_json(response: axum::response::Response) -> Value {
|
|
let body = to_bytes(response.into_body(), 64 * 1024)
|
|
.await
|
|
.expect("account group response body");
|
|
serde_json::from_slice(&body).expect("account group response JSON")
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn fast_mode_group_updates_preserve_omitted_and_null_values() {
|
|
let fixture = authenticated_fixture().await;
|
|
for (value, expected) in [
|
|
(Some(json!("disabled")), "disabled"),
|
|
(None, "disabled"),
|
|
(Some(json!("ultrafast")), "ultrafast"),
|
|
(None, "ultrafast"),
|
|
(Some(json!("enabled")), "enabled"),
|
|
(None, "enabled"),
|
|
(Some(Value::Null), "enabled"),
|
|
(Some(json!("default")), "default"),
|
|
] {
|
|
let mut body = json!({"id": PRIMARY_GROUP_ID, "name":"Policy", "description":null,"color":"#F43F5ECC"});
|
|
if let Some(value) = value {
|
|
body["fastMode"] = value;
|
|
}
|
|
let response = request(
|
|
router(&fixture),
|
|
Method::POST,
|
|
"/api/admin/account-groups/update",
|
|
Some(body),
|
|
true,
|
|
)
|
|
.await;
|
|
assert_eq!(response.status(), StatusCode::OK);
|
|
assert_eq!(
|
|
response_json(response).await["data"]["record"]["fastMode"],
|
|
expected
|
|
);
|
|
}
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn fast_mode_rejects_invalid_values_and_creates_groups_in_each_mode() {
|
|
let fixture = authenticated_fixture().await;
|
|
for (mode, expected) in [
|
|
(json!("enabled"), StatusCode::CREATED),
|
|
(json!("disabled"), StatusCode::CREATED),
|
|
(json!("ultrafast"), StatusCode::CREATED),
|
|
(json!("default"), StatusCode::CREATED),
|
|
(json!("force"), StatusCode::UNPROCESSABLE_ENTITY),
|
|
(json!(true), StatusCode::BAD_REQUEST),
|
|
] {
|
|
let response = request(
|
|
router(&fixture), Method::POST, "/api/admin/account-groups/create",
|
|
Some(json!({"name":format!("Fast {mode}"),"description":null,"color":"#F43F5ECC","fastMode":mode})), true,
|
|
).await;
|
|
assert_eq!(response.status(), expected, "mode={mode}");
|
|
if expected == StatusCode::CREATED {
|
|
assert_eq!(
|
|
response_json(response).await["data"]["record"]["fastMode"],
|
|
mode
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn image_generation_flag_round_trips_and_omitted_updates_preserve_it() {
|
|
let fixture = authenticated_fixture().await;
|
|
let created = request(router(&fixture), Method::POST, "/api/admin/account-groups/create", Some(json!({
|
|
"name":"No images", "description":null, "color":"#2563EBFF", "allowImageGeneration":false
|
|
})), true).await;
|
|
assert_eq!(created.status(), StatusCode::CREATED);
|
|
let created = response_json(created).await;
|
|
assert_eq!(created["data"]["record"]["allowImageGeneration"], false);
|
|
let id = created["data"]["id"].as_str().unwrap();
|
|
for (value, expected) in [
|
|
(None, false),
|
|
(Some(true), true),
|
|
(Some(false), false),
|
|
(None, false),
|
|
] {
|
|
let mut body =
|
|
json!({"id":id,"name":"Image policy","description":null,"color":"#2563EBFF"});
|
|
if let Some(value) = value {
|
|
body["allowImageGeneration"] = json!(value);
|
|
}
|
|
let response = request(
|
|
router(&fixture),
|
|
Method::POST,
|
|
"/api/admin/account-groups/update",
|
|
Some(body),
|
|
true,
|
|
)
|
|
.await;
|
|
assert_eq!(response.status(), StatusCode::OK);
|
|
assert_eq!(
|
|
response_json(response).await["data"]["record"]["allowImageGeneration"],
|
|
expected
|
|
);
|
|
}
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn subagent_and_model_policies_round_trip_independently() {
|
|
let fixture = authenticated_fixture().await;
|
|
let policy = json!({"mode":"allowlist", "models":["model-a"]});
|
|
let created = request(
|
|
router(&fixture),
|
|
Method::POST,
|
|
"/api/admin/account-groups/create",
|
|
Some(json!({
|
|
"name":"Model policy", "color":"#2563EBFF", "modelAccess":policy, "allowSubagents":false
|
|
})),
|
|
true,
|
|
)
|
|
.await;
|
|
assert_eq!(created.status(), StatusCode::CREATED);
|
|
let created = response_json(created).await;
|
|
assert_eq!(created["data"]["record"]["modelAccess"], policy);
|
|
assert_eq!(created["data"]["record"]["allowSubagents"], false);
|
|
let mut update = json!({"id":created["data"]["id"], "name":"Model policy", "color":"#2563EBFF", "allowSubagents":true});
|
|
let send = |body| {
|
|
request(
|
|
router(&fixture),
|
|
Method::POST,
|
|
"/api/admin/account-groups/update",
|
|
Some(body),
|
|
true,
|
|
)
|
|
};
|
|
let changed = send(update.clone()).await;
|
|
assert_eq!(changed.status(), StatusCode::OK);
|
|
let changed = response_json(changed).await;
|
|
assert_eq!(changed["data"]["record"]["modelAccess"], policy);
|
|
assert_eq!(changed["data"]["record"]["allowSubagents"], true);
|
|
update.as_object_mut().unwrap().remove("allowSubagents");
|
|
update["modelAccess"] = json!({"mode":"denylist","models":["model-b"]});
|
|
let changed = send(update.clone()).await;
|
|
assert_eq!(changed.status(), StatusCode::OK);
|
|
let changed = response_json(changed).await;
|
|
assert_eq!(
|
|
changed["data"]["record"]["modelAccess"],
|
|
update["modelAccess"]
|
|
);
|
|
assert_eq!(changed["data"]["record"]["allowSubagents"], true);
|
|
update["modelAccess"] = json!({"mode":"allowlist","models":[]});
|
|
assert_eq!(
|
|
send(update).await.status(),
|
|
StatusCode::UNPROCESSABLE_ENTITY
|
|
);
|
|
}
|