feat: add admin account mutations

Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
Zyy
2026-06-12 13:35:36 +08:00
co-authored by Codex
parent 5ce1315d07
commit db6cb98bbf
7 changed files with 566 additions and 11 deletions
+3 -3
View File
@@ -13,10 +13,10 @@ Update this file before each feature commit.
| Logging and pagination | Completed | `eb0341e` + `fc16c48` + `b0c10f2` + `ee0ed90` + `fdb9374` + `5bf012c` | `cargo test event_logs_are_cursor_paginated`; `cargo test admin_logs_are_cursor_paginated_and_include_request_id`; `cargo test rotating_writer_splits_files_when_size_limit_is_reached`; `cargo test --test admin_usage_stats_route_test`; `cargo test --test v1_upstream_route_test`; full `fmt/test/clippy` before commit | Adds cursor pagination, `Page<T>` camelCase serialization, admin `/admin/logs` query API, admin `/admin/usage-stats` and `/admin/usage-stats/summary`, event log repository, runtime tracing initialization, HTTP trace layer, date/size-based file rotation, v1 response lifecycle events with request/account/route/model/status/latency/non-secret metadata, and non-secret `account.refresh` events for upstream-401 refresh failures. |
| TLS headers and fingerprint | Completed | `1bdd08c` | `cargo test codex_headers_include_desktop_identity_and_turn_state`; `cargo tree \| rg 'reqwest\|rustls'`; full `fmt/test/clippy` before commit | Adds Codex Desktop fingerprint model, exact identity/request headers, and pinned reqwest/rustls client builder. |
| Cookie persistence | Completed | `4710926` + `5d3cc6e` | `cargo test cookie_jar_captures_and_replays_account_scoped_cookies`; `cargo test cookie_repository_encrypts_and_replays_account_scoped_cookies`; full `fmt/test/clippy` before commit | Adds account-scoped in-memory Cookie jar and encrypted SQLite Cookie repository; Cookies are replayed only for the same account/domain. |
| Account pool and refresh | Partial | `0f97c5c` + `2f25db8` + `4dc0c9a` + `c2cf7a6` + `636fa79` + `fdb9374` + `3ecd5b6` + `3960a35` | `cargo test account_pool_skips_expired_disabled_banned_and_quota_exhausted_accounts`; `cargo test --test account_pool_scheduling_test`; `cargo test --test account_refresh_test`; `cargo test --test oauth_refresh_test`; `cargo test --test v1_upstream_route_test`; `cargo test --test account_pool_startup_test`; Task 5 targeted `cargo test --test v1_upstream_route_test`, `cargo test --test chat_completions_route_test`, and `cargo test --test account_pool_scheduling_test`; full `fmt/test/clippy` before commit | Implements base account status filtering, refresh scheduler semantics, real OpenAI OAuth refresh-token exchange, 401-triggered refresh and single retry for `/v1/responses`, max concurrent slots, stale slot cleanup, least-used/round-robin/sticky strategies, tier priority, quota-cache filtering, Cloudflare cooldown skip, request staggering metadata, preferred account selection, exclude IDs, capacity summary, settings-backed pool construction, same-process import-to-pool sync, startup pool snapshots from SQLite with usage-based last-used metadata, in-memory 429 quota cooldown marking, Cloudflare cooldown mutation, pool status mutation for upstream fallback, and shared fallback acquisition for non-streaming Responses, HTTP SSE Responses setup, and Chat Completions. Still missing durable release-time slot state, WebSocket/history fallback policy, durable quota cooldown persistence, and admin account CRUD. |
| Account repository | Completed | `14fe706` | `cargo test --test account_repository_test`; `cargo fmt --check`; `cargo clippy --all-targets --all-features --locked -- -D warnings`; `cargo test` | Adds encrypted SQLite account token storage, decrypting reads, cursor pagination, status/label updates, release-time usage counter persistence, and refresh-token-preserving token updates. |
| Account pool and refresh | Partial | `0f97c5c` + `2f25db8` + `4dc0c9a` + `c2cf7a6` + `636fa79` + `fdb9374` + `3ecd5b6` + `3960a35` + pending | `cargo test account_pool_skips_expired_disabled_banned_and_quota_exhausted_accounts`; `cargo test --test account_pool_scheduling_test`; `cargo test --test account_refresh_test`; `cargo test --test oauth_refresh_test`; `cargo test --test v1_upstream_route_test`; `cargo test --test account_pool_startup_test`; Task 5 targeted `cargo test --test v1_upstream_route_test`, `cargo test --test chat_completions_route_test`, and `cargo test --test account_pool_scheduling_test`; full `fmt/test/clippy` before pending | Implements base account status filtering, refresh scheduler semantics, real OpenAI OAuth refresh-token exchange, 401-triggered refresh and single retry for `/v1/responses`, max concurrent slots, stale slot cleanup, least-used/round-robin/sticky strategies, tier priority, quota-cache filtering, Cloudflare cooldown skip, request staggering metadata, preferred account selection, exclude IDs, capacity summary, settings-backed pool construction, same-process import-to-pool sync, startup pool snapshots from SQLite with usage-based last-used metadata, in-memory 429 quota cooldown marking, Cloudflare cooldown mutation, pool status mutation for upstream fallback, admin label/status/delete runtime pool synchronization, and shared fallback acquisition for non-streaming Responses, HTTP SSE Responses setup, and Chat Completions. Still missing durable release-time slot state, WebSocket/history fallback policy, durable quota cooldown persistence, and remaining admin account operations. |
| Account repository | Completed | `14fe706` + pending | `cargo test --test account_repository_test`; `cargo fmt --check`; `cargo clippy --all-targets --all-features --locked -- -D warnings`; `cargo test`; full `fmt/test/clippy` before pending | Adds encrypted SQLite account token storage, decrypting reads, cursor pagination, status/label updates, account deletion, release-time usage counter persistence, and refresh-token-preserving token updates. |
| Translation | Completed | `eff182e` + `b9c30ba` | `cargo test --test routes_chat_test`; `cargo test --test chat_completions_route_test`; full `cargo fmt --check && cargo test && cargo clippy --all-targets --all-features --locked -- -D warnings` before `b9c30ba` | Adds OpenAI Chat request types, expanded Codex Responses request type, OpenAI Chat to Codex translation for system/developer instructions, multimodal content, tool/function calls, response formats, reasoning effort, service tier, and parallel tool calls. Codex SSE now converts back to OpenAI chat completions and chat chunks with text deltas, reasoning content, tool calls, usage details, and OpenAI-compatible error bodies. |
| HTTP routes | Partial | `ab0ad8f` + `3830b21` + `6179d44` + `cfec8ba` + `6341336` + `228febd` + `c2cf7a6` + `e9fdea0` + `ee0ed90` + `fdb9374` + `9ca5c7d` + `b9c30ba` + `350ffbe` + `3ecd5b6` + `3960a35` + `1738f24` + `0b6cc7e` + `f75db60` + `4b19846` | `cargo test v1_requires_client_api_key_not_admin_cookie`; `cargo test models_route_returns_openai_compatible_codex_model_list`; `cargo test --test admin_settings_route_test`; `cargo test --test model_catalog_test`; `cargo test --test admin_accounts_route_test`; `cargo test --test admin_api_keys_route_test`; `cargo test --test admin_usage_stats_route_test`; `cargo test --test v1_upstream_route_test`; `cargo test --test chat_completions_route_test`; `cargo test --test codex_websocket_test`; full `cargo fmt --check && cargo test && cargo clippy --all-targets --all-features --locked -- -D warnings` before `b9c30ba` and `350ffbe`; Task 5 targeted verification before `3ecd5b6` and `3960a35`; full `fmt/test/clippy` before `1738f24`; full `fmt/test/clippy` plus real-file smoke before `0b6cc7e`; full `fmt/test/clippy` before `f75db60`; full `fmt/test/clippy` before `4b19846` | Adds Axum router, health route, `/v1/models`, `/v1/models/catalog`, `/v1/models/{id}`, `/v1/models/{id}/info`, `/debug/models`, `/admin/accounts`, `/admin/accounts/import`, `/admin/api-keys`, `/admin/usage-stats`, `/admin/usage-stats/summary`, `/admin/refresh-models`, `/v1/responses` HTTP SSE collection with output item/delta reconstruction plus `output_text` sync for non-streaming clients, default streaming Responses passthrough when `stream` is omitted, WebSocket-backed Responses streaming for `previous_response_id`, non-streaming and HTTP SSE setup fallback to another imported account after 429/402/403 account-state failures, Responses field parity for service tier, tool choice, parallel tool calls, text format, prompt cache key, include, client metadata, reasoning include default, and Codex context headers, plus a dedicated `/v1/chat/completions` route backed by imported Codex accounts with fallback for buffered non-streaming and client-streaming output conversion. `/v1` unauthorized and model errors remain OpenAI-compatible, cached backend model snapshots are used by `/v1/models*` when present, global request-id response headers are preserved, `gpt-5.5` remains the default/test model baseline, and `/admin/settings` is read-only with admin-session auth and lower camelCase envelope. `/admin/accounts` reads metadata only and does not decrypt tokens for list views. `/admin/accounts/import` accepts native and Sub2API OpenAI OAuth account exports, returns `sourceFormat`, and ignores proxy-only metadata. `/admin/refresh-models` fetches backend model lists through imported accounts only, stores plan snapshots, and syncs runtime model-plan allowlists. Still missing OAuth/device/CLI account login flows, admin account mutation/health/quota/Cookie routes, full admin API-key mutation/export/import routes, settings mutation/persistence, diagnostics, live Chat streaming transform, and WebSocket/history fallback policy. |
| HTTP routes | Partial | `ab0ad8f` + `3830b21` + `6179d44` + `cfec8ba` + `6341336` + `228febd` + `c2cf7a6` + `e9fdea0` + `ee0ed90` + `fdb9374` + `9ca5c7d` + `b9c30ba` + `350ffbe` + `3ecd5b6` + `3960a35` + `1738f24` + `0b6cc7e` + `f75db60` + `4b19846` + pending | `cargo test v1_requires_client_api_key_not_admin_cookie`; `cargo test models_route_returns_openai_compatible_codex_model_list`; `cargo test --test admin_settings_route_test`; `cargo test --test model_catalog_test`; `cargo test --test admin_accounts_route_test`; `cargo test --test admin_api_keys_route_test`; `cargo test --test admin_usage_stats_route_test`; `cargo test --test v1_upstream_route_test`; `cargo test --test chat_completions_route_test`; `cargo test --test codex_websocket_test`; full `cargo fmt --check && cargo test && cargo clippy --all-targets --all-features --locked -- -D warnings` before `b9c30ba` and `350ffbe`; Task 5 targeted verification before `3ecd5b6` and `3960a35`; full `fmt/test/clippy` before `1738f24`; full `fmt/test/clippy` plus real-file smoke before `0b6cc7e`; full `fmt/test/clippy` before `f75db60`; full `fmt/test/clippy` before `4b19846`; full `fmt/test/clippy` before pending | Adds Axum router, health route, `/v1/models`, `/v1/models/catalog`, `/v1/models/{id}`, `/v1/models/{id}/info`, `/debug/models`, `/admin/accounts`, `/admin/accounts/{id}`, `/admin/accounts/{id}/label`, `/admin/accounts/{id}/status`, `/admin/accounts/import`, `/admin/api-keys`, `/admin/usage-stats`, `/admin/usage-stats/summary`, `/admin/refresh-models`, `/v1/responses` HTTP SSE collection with output item/delta reconstruction plus `output_text` sync for non-streaming clients, default streaming Responses passthrough when `stream` is omitted, WebSocket-backed Responses streaming for `previous_response_id`, non-streaming and HTTP SSE setup fallback to another imported account after 429/402/403 account-state failures, Responses field parity for service tier, tool choice, parallel tool calls, text format, prompt cache key, include, client metadata, reasoning include default, and Codex context headers, plus a dedicated `/v1/chat/completions` route backed by imported Codex accounts with fallback for buffered non-streaming and client-streaming output conversion. `/v1` unauthorized and model errors remain OpenAI-compatible, cached backend model snapshots are used by `/v1/models*` when present, global request-id response headers are preserved, `gpt-5.5` remains the default/test model baseline, and `/admin/settings` is read-only with admin-session auth and lower camelCase envelope. `/admin/accounts` reads metadata only and does not decrypt tokens for list views. `/admin/accounts/import` accepts native and Sub2API OpenAI OAuth account exports, returns `sourceFormat`, and ignores proxy-only metadata. `/admin/accounts/{id}/label`, `/status`, and delete mutate SQLite plus runtime account pool. `/admin/refresh-models` fetches backend model lists through imported accounts only, stores plan snapshots, and syncs runtime model-plan allowlists. Still missing OAuth/device/CLI account login flows, admin account manual add/batch/health/quota/Cookie routes, full admin API-key mutation/export/import routes, settings mutation/persistence, diagnostics, live Chat streaming transform, and WebSocket/history fallback policy. |
| Admin/frontend response contract | Completed | `1c34ea7` + `b0c10f2` | `cargo test admin_envelope_serializes_lower_camel_case_request_id`; `cargo test admin_logs_reject_missing_admin_session_cookie`; `cargo test v1_response_has_request_id_header_without_admin_body_field`; full `fmt/test/clippy` before commit | Adds reusable admin envelopes with body codes, lower camelCase JSON, paginated list shape, requestId bodies, admin session cookie enforcement, and keeps `/v1/*` OpenAI-compatible. |
| HTTP auth boundary | Completed | `cec4607` + `e9fdea0` | `cargo test --test http_auth_test`; `cargo test --test routes_responses_test`; `cargo test --test admin_api_keys_route_test`; `cargo test --test admin_logs_route_test`; `cargo fmt --check`; `cargo clippy --all-targets --all-features --locked -- -D warnings`; `cargo test` | Adds a real `src/http/auth.rs` boundary for client API key and admin session cookie parsing. `/v1/*` accepts only enabled local `Bearer cpr_...` client API keys verified from SQLite, admin session parsing ignores client API keys, and route handlers no longer own ad hoc credential parsing. |
| Model catalog | Partial | `6341336` + `1738f24` + `f75db60` + `4b19846` | `cargo test --test model_catalog_test`; `cargo test model_catalog_route_returns_codex_metadata_without_alias_entries`; `cargo test --test storage_schema_test`; `cargo test --test routes_responses_test model_catalog_route_returns_cached_backend_models`; `cargo test --test admin_models_route_test`; full `fmt/test/clippy` before `1738f24`; full `fmt/test/clippy` before `f75db60`; full `fmt/test/clippy` before `4b19846` | Adds a native static Codex model catalog with `gpt-5.5` default, configured aliases, reasoning/service-tier suffix parsing including `none` and `minimal`, OpenAI-compatible `/v1/models`, extended catalog/detail/info routes, debug summary, SQLite-backed backend model snapshots by plan, cached backend catalog merge, model-to-plan allowlist derivation, and an admin refresh route that probes Codex model endpoints with one imported account per plan and syncs the runtime account-pool allowlist. Still missing full model metadata parity. |
@@ -8,7 +8,7 @@
**Tech Stack:** Rust, Axum, Reqwest/rustls, serde, sqlx/SQLite, wiremock, tokio, futures, optional WebSocket transport dependency.
**Checkpoint 2026-06-12:** Commit `b9c30ba` completed Tasks 1-3 for the in-scope OpenAI GPT/Codex path: Chat Completions route/translation/output, Responses request field parity, default Responses streaming, Codex context headers, and local-only WebSocket flag serialization cleanup. Commit `350ffbe` completed Task 4: `previous_response_id` requests use WebSocket `response.create` and return SSE-compatible output. Commit `3ecd5b6` partially completed Task 5 for non-streaming `/v1/responses`: 429/402/403 account-state classification and fallback retry across imported accounts. Commit `3960a35` extends the same fallback path to HTTP SSE Responses setup and Chat Completions. Commit `1738f24` adds Task 6 cache groundwork: persisted backend model snapshots and cached `/v1/models*` reads. Commit `0b6cc7e` adds Task 7 import compatibility for Sub2API OpenAI OAuth exports and marks the detected source format while ignoring proxy-only fields. Commit `f75db60` adds `/admin/refresh-models` backed by imported accounts. Commit `4b19846` syncs refreshed model-plan allowlists into the runtime account pool. Remaining major work continues with WebSocket/history fallback policy and scoped admin operations.
**Checkpoint 2026-06-12:** Commit `b9c30ba` completed Tasks 1-3 for the in-scope OpenAI GPT/Codex path: Chat Completions route/translation/output, Responses request field parity, default Responses streaming, Codex context headers, and local-only WebSocket flag serialization cleanup. Commit `350ffbe` completed Task 4: `previous_response_id` requests use WebSocket `response.create` and return SSE-compatible output. Commit `3ecd5b6` partially completed Task 5 for non-streaming `/v1/responses`: 429/402/403 account-state classification and fallback retry across imported accounts. Commit `3960a35` extends the same fallback path to HTTP SSE Responses setup and Chat Completions. Commit `1738f24` adds Task 6 cache groundwork: persisted backend model snapshots and cached `/v1/models*` reads. Commit `0b6cc7e` adds Task 7 import compatibility for Sub2API OpenAI OAuth exports and marks the detected source format while ignoring proxy-only fields. Commit `f75db60` adds `/admin/refresh-models` backed by imported accounts. Commit `4b19846` syncs refreshed model-plan allowlists into the runtime account pool. Pending Task 7 follow-up adds admin account label/status/delete mutations with runtime pool synchronization. Remaining major work continues with WebSocket/history fallback policy and scoped admin operations.
---
@@ -114,7 +114,10 @@
- [x] Write failing tests for Sub2API OpenAI OAuth import payloads and native exports that carry proxy/runtime metadata.
- [x] Run: `cargo test --test admin_accounts_route_test`
- [x] Implement Sub2API import normalization, `sourceFormat` response marking, and proxy-field ignoring.
- [ ] Write failing tests for manual add, delete, batch status, label, quota fetch, health check, cookie get/set/delete, remaining import/export, API key disable/delete.
- [x] Write failing tests for account label/status/delete mutations and runtime pool synchronization.
- [x] Implement account label/status/delete mutations without adding proxy-pool support.
- [x] Run: `cargo test --test admin_accounts_route_test`
- [ ] Write failing tests for manual add, batch status, quota fetch, health check, cookie get/set/delete, remaining import/export, API key disable/delete.
- [ ] Run: `cargo test --test admin_accounts_route_test --test admin_api_keys_route_test`
- [ ] Implement scoped admin operations needed to operate Codex-backed OpenAI GPT routes.
- [ ] Run: `cargo test --test admin_accounts_route_test --test admin_api_keys_route_test`
+14
View File
@@ -108,10 +108,24 @@ impl AccountPool {
self.accounts.insert(account.id.clone(), account);
}
pub fn remove(&mut self, account_id: &str) -> bool {
let removed = self.accounts.remove(account_id).is_some();
self.slots.remove(account_id);
removed
}
pub fn set_model_plan_allowlist(&mut self, allowlist: BTreeMap<String, Vec<String>>) {
self.options.model_plan_allowlist = allowlist;
}
pub fn set_label(&mut self, account_id: &str, label: Option<String>) -> bool {
let Some(account) = self.accounts.get_mut(account_id) else {
return false;
};
account.label = label;
true
}
pub fn set_status(&mut self, account_id: &str, status: AccountStatus) -> bool {
let Some(account) = self.accounts.get_mut(account_id) else {
return false;
+8
View File
@@ -321,6 +321,14 @@ impl AccountRepository {
Ok(result.rows_affected() > 0)
}
pub async fn delete(&self, id: &str) -> AccountRepositoryResult<bool> {
let result = sqlx::query("delete from accounts where id = ?")
.bind(id)
.execute(&self.pool)
.await?;
Ok(result.rows_affected() > 0)
}
pub async fn update_tokens(
&self,
id: &str,
+13 -3
View File
@@ -1,6 +1,6 @@
use axum::{
middleware::from_fn,
routing::{get, post},
routing::{delete, get, patch, post},
Router,
};
use tower_http::trace::TraceLayer;
@@ -8,8 +8,9 @@ use tower_http::trace::TraceLayer;
use crate::{
http::{
admin::{
accounts, api_keys, create_api_key, import_accounts, login, logs, refresh_models,
settings, usage_stats, usage_stats_summary,
accounts, api_keys, create_api_key, delete_account, import_accounts, login, logs,
refresh_models, settings, update_account_label, update_account_status, usage_stats,
usage_stats_summary,
},
health::health,
middleware::attach_request_id,
@@ -38,6 +39,15 @@ pub fn build_router(state: AppState) -> Router {
.route("/admin/usage-stats", get(usage_stats))
.route("/admin/usage-stats/summary", get(usage_stats_summary))
.route("/admin/accounts", get(accounts))
.route("/admin/accounts/{account_id}", delete(delete_account))
.route(
"/admin/accounts/{account_id}/label",
patch(update_account_label),
)
.route(
"/admin/accounts/{account_id}/status",
patch(update_account_status),
)
.route("/admin/accounts/import", post(import_accounts))
.route("/admin/api-keys", get(api_keys).post(create_api_key))
.with_state(state)
+302 -3
View File
@@ -1,5 +1,5 @@
use axum::{
extract::{Query, State},
extract::{Path, Query, State},
http::{
header::{HeaderValue, SET_COOKIE},
HeaderMap, StatusCode,
@@ -8,7 +8,7 @@ use axum::{
Extension, Json,
};
use chrono::{Duration, Utc};
use secrecy::SecretString;
use secrecy::{ExposeSecret, SecretString};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use sqlx::Row;
@@ -19,7 +19,7 @@ use crate::{
model::{Account, AccountStatus},
repository::{
AccountRepositoryError, AccountUsageListRecord, AccountUsageSummary, NewAccount,
StoredAccountMetadata,
StoredAccount, StoredAccountMetadata,
},
},
auth::admin_session::verify_admin_password,
@@ -229,6 +229,38 @@ pub struct AccountImportData {
pub source_format: String,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UpdateAccountLabelRequest {
pub label: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct UpdateAccountLabelData {
pub id: String,
pub label: Option<String>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UpdateAccountStatusRequest {
pub status: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct UpdateAccountStatusData {
pub id: String,
pub status: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DeleteAccountData {
pub deleted: bool,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RefreshModelsData {
@@ -873,6 +905,217 @@ pub async fn accounts(
}
}
pub async fn update_account_label(
State(state): State<AppState>,
Extension(request_id): Extension<RequestId>,
headers: HeaderMap,
Path(account_id): Path<String>,
Json(payload): Json<UpdateAccountLabelRequest>,
) -> Response {
let request_id = request_id.as_str().to_string();
let Some(pool) = state.db() else {
return AdminResponse::new(
StatusCode::INTERNAL_SERVER_ERROR,
AdminEnvelope::new(50001, "Database is not initialized", (), request_id),
)
.into_response();
};
if let Err(response) = require_admin_session(pool, &headers, &request_id).await {
return response;
}
let Some(repo) = state.account_repository() else {
return AdminResponse::new(
StatusCode::INTERNAL_SERVER_ERROR,
AdminEnvelope::new(
50001,
"Account repository is not initialized",
(),
request_id,
),
)
.into_response();
};
if payload
.label
.as_ref()
.is_some_and(|label| label.chars().count() > 64)
{
return AdminResponse::new(
StatusCode::BAD_REQUEST,
AdminEnvelope::new(
40001,
"Account label must be 64 characters or fewer",
(),
request_id,
),
)
.into_response();
}
match repo.set_label(&account_id, payload.label.clone()).await {
Ok(true) => {
// 管理后台改名后要同步内存调度池,否则列表和实际调度状态会短暂不一致。
state
.account_pool()
.lock()
.await
.set_label(&account_id, payload.label.clone());
AdminResponse::new(
StatusCode::OK,
AdminEnvelope::ok(
UpdateAccountLabelData {
id: account_id,
label: payload.label,
},
request_id,
),
)
.into_response()
}
Ok(false) => AdminResponse::new(
StatusCode::NOT_FOUND,
AdminEnvelope::new(40401, "Account not found", (), request_id),
)
.into_response(),
Err(_) => AdminResponse::new(
StatusCode::INTERNAL_SERVER_ERROR,
AdminEnvelope::new(50001, "Failed to update account label", (), request_id),
)
.into_response(),
}
}
pub async fn update_account_status(
State(state): State<AppState>,
Extension(request_id): Extension<RequestId>,
headers: HeaderMap,
Path(account_id): Path<String>,
Json(payload): Json<UpdateAccountStatusRequest>,
) -> Response {
let request_id = request_id.as_str().to_string();
let Some(pool) = state.db() else {
return AdminResponse::new(
StatusCode::INTERNAL_SERVER_ERROR,
AdminEnvelope::new(50001, "Database is not initialized", (), request_id),
)
.into_response();
};
if let Err(response) = require_admin_session(pool, &headers, &request_id).await {
return response;
}
let status = match parse_admin_account_status(&payload.status) {
Ok(status) => status,
Err(message) => {
return AdminResponse::new(
StatusCode::BAD_REQUEST,
AdminEnvelope::new(40001, message, (), request_id),
)
.into_response();
}
};
let Some(repo) = state.account_repository() else {
return AdminResponse::new(
StatusCode::INTERNAL_SERVER_ERROR,
AdminEnvelope::new(
50001,
"Account repository is not initialized",
(),
request_id,
),
)
.into_response();
};
match repo.set_status(&account_id, status).await {
Ok(true) => {
if sync_runtime_account_status(&state, &repo, &account_id, status)
.await
.is_err()
{
return AdminResponse::new(
StatusCode::INTERNAL_SERVER_ERROR,
AdminEnvelope::new(50001, "Failed to sync account status", (), request_id),
)
.into_response();
}
AdminResponse::new(
StatusCode::OK,
AdminEnvelope::ok(
UpdateAccountStatusData {
id: account_id,
status: account_status_value(status).to_string(),
},
request_id,
),
)
.into_response()
}
Ok(false) => AdminResponse::new(
StatusCode::NOT_FOUND,
AdminEnvelope::new(40401, "Account not found", (), request_id),
)
.into_response(),
Err(_) => AdminResponse::new(
StatusCode::INTERNAL_SERVER_ERROR,
AdminEnvelope::new(50001, "Failed to update account status", (), request_id),
)
.into_response(),
}
}
pub async fn delete_account(
State(state): State<AppState>,
Extension(request_id): Extension<RequestId>,
headers: HeaderMap,
Path(account_id): Path<String>,
) -> Response {
let request_id = request_id.as_str().to_string();
let Some(pool) = state.db() else {
return AdminResponse::new(
StatusCode::INTERNAL_SERVER_ERROR,
AdminEnvelope::new(50001, "Database is not initialized", (), request_id),
)
.into_response();
};
if let Err(response) = require_admin_session(pool, &headers, &request_id).await {
return response;
}
let Some(repo) = state.account_repository() else {
return AdminResponse::new(
StatusCode::INTERNAL_SERVER_ERROR,
AdminEnvelope::new(
50001,
"Account repository is not initialized",
(),
request_id,
),
)
.into_response();
};
match repo.delete(&account_id).await {
Ok(true) => {
// DB 外键会级联清理账号关联数据;内存池仍需立即摘除,避免删除后继续被调度。
state.account_pool().lock().await.remove(&account_id);
AdminResponse::new(
StatusCode::OK,
AdminEnvelope::ok(DeleteAccountData { deleted: true }, request_id),
)
.into_response()
}
Ok(false) => AdminResponse::new(
StatusCode::NOT_FOUND,
AdminEnvelope::new(40401, "Account not found", (), request_id),
)
.into_response(),
Err(_) => AdminResponse::new(
StatusCode::INTERNAL_SERVER_ERROR,
AdminEnvelope::new(50001, "Failed to delete account", (), request_id),
)
.into_response(),
}
}
pub async fn import_accounts(
State(state): State<AppState>,
Extension(request_id): Extension<RequestId>,
@@ -1204,6 +1447,54 @@ async fn require_admin_session(
}
}
async fn sync_runtime_account_status(
state: &AppState,
repo: &crate::accounts::repository::AccountRepository,
account_id: &str,
status: AccountStatus,
) -> Result<(), AccountRepositoryError> {
let updated = state
.account_pool()
.lock()
.await
.set_status(account_id, status);
if updated || status != AccountStatus::Active {
return Ok(());
}
if let Some(account) = repo.get(account_id).await? {
state
.account_pool()
.lock()
.await
.insert(pool_account_from_stored(account));
}
Ok(())
}
fn pool_account_from_stored(account: StoredAccount) -> Account {
Account {
id: account.id,
email: account.email,
account_id: account.account_id,
user_id: account.user_id,
label: account.label,
plan_type: account.plan_type,
access_token: account.access_token.expose_secret().to_string(),
refresh_token: account
.refresh_token
.as_ref()
.map(|token| token.expose_secret().to_string()),
access_token_expires_at: account.access_token_expires_at,
status: account.status,
quota_limit_reached: false,
quota_cooldown_until: None,
cloudflare_cooldown_until: None,
added_at: account.added_at.to_rfc3339(),
last_used_at: None,
}
}
fn normalized_account_id(id: Option<String>) -> String {
id.and_then(|id| empty_to_none(Some(id)))
.unwrap_or_else(|| format!("acct_{}", Uuid::new_v4().simple()))
@@ -1473,6 +1764,14 @@ fn parse_import_status(status: Option<&str>) -> Result<AccountStatus, String> {
}
}
fn parse_admin_account_status(status: &str) -> Result<AccountStatus, String> {
match status.trim().to_ascii_lowercase().as_str() {
"active" => Ok(AccountStatus::Active),
"disabled" => Ok(AccountStatus::Disabled),
other => Err(format!("Unsupported account status: {other}")),
}
}
fn account_status_value(status: AccountStatus) -> &'static str {
match status {
AccountStatus::Active => "active",
+221
View File
@@ -3,6 +3,7 @@ use std::collections::BTreeMap;
use axum::{
body::{to_bytes, Body},
http::{Request, StatusCode},
Router,
};
use chrono::Utc;
use serde_json::{json, Value};
@@ -379,6 +380,226 @@ async fn admin_accounts_list_should_not_decrypt_account_tokens() {
assert_eq!(body["data"][0]["id"], "acct_corrupt");
}
#[tokio::test]
async fn admin_account_label_should_update_and_clear_label() {
let (app, state, pool, _dir) = admin_accounts_test_app("admin-account-label.sqlite", 16).await;
import_test_account(&app, "session_1", "acct_label").await;
let set_response = app
.clone()
.oneshot(
Request::builder()
.method("PATCH")
.uri("/admin/accounts/acct_label/label")
.header("content-type", "application/json")
.header("cookie", "cpr_admin_session=session_1")
.header("x-request-id", "req_label")
.body(Body::from(r#"{"label":"Team Alpha"}"#))
.unwrap(),
)
.await
.unwrap();
assert_eq!(set_response.status(), StatusCode::OK);
let body = response_json(set_response).await;
assert_eq!(body["data"]["label"], "Team Alpha");
let clear_response = app
.oneshot(
Request::builder()
.method("PATCH")
.uri("/admin/accounts/acct_label/label")
.header("content-type", "application/json")
.header("cookie", "cpr_admin_session=session_1")
.body(Body::from(r#"{"label":null}"#))
.unwrap(),
)
.await
.unwrap();
assert_eq!(clear_response.status(), StatusCode::OK);
let body = response_json(clear_response).await;
assert!(body["data"]["label"].is_null());
let stored: (Option<String>,) = sqlx::query_as("select label from accounts where id = ?")
.bind("acct_label")
.fetch_one(&pool)
.await
.unwrap();
assert_eq!(stored.0, None);
assert!(state
.account_pool()
.lock()
.await
.acquire("gpt-5.5")
.is_some());
}
#[tokio::test]
async fn admin_account_label_should_reject_too_long_or_missing_account() {
let (app, _state, _pool, _dir) =
admin_accounts_test_app("admin-account-label-invalid.sqlite", 17).await;
import_test_account(&app, "session_1", "acct_label_invalid").await;
let long_label = "x".repeat(65);
let too_long = app
.clone()
.oneshot(
Request::builder()
.method("PATCH")
.uri("/admin/accounts/acct_label_invalid/label")
.header("content-type", "application/json")
.header("cookie", "cpr_admin_session=session_1")
.body(Body::from(json!({ "label": long_label }).to_string()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(too_long.status(), StatusCode::BAD_REQUEST);
let missing = app
.oneshot(
Request::builder()
.method("PATCH")
.uri("/admin/accounts/missing/label")
.header("content-type", "application/json")
.header("cookie", "cpr_admin_session=session_1")
.body(Body::from(r#"{"label":"Team Alpha"}"#))
.unwrap(),
)
.await
.unwrap();
assert_eq!(missing.status(), StatusCode::NOT_FOUND);
}
#[tokio::test]
async fn admin_account_status_should_update_database_and_runtime_pool() {
let (app, state, pool, _dir) = admin_accounts_test_app("admin-account-status.sqlite", 18).await;
import_test_account(&app, "session_1", "acct_status").await;
let response = app
.oneshot(
Request::builder()
.method("PATCH")
.uri("/admin/accounts/acct_status/status")
.header("content-type", "application/json")
.header("cookie", "cpr_admin_session=session_1")
.header("x-request-id", "req_status")
.body(Body::from(r#"{"status":"disabled"}"#))
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let body = response_json(response).await;
assert_eq!(body["data"]["status"], "disabled");
let stored: (String,) = sqlx::query_as("select status from accounts where id = ?")
.bind("acct_status")
.fetch_one(&pool)
.await
.unwrap();
assert_eq!(stored.0, "disabled");
assert!(state
.account_pool()
.lock()
.await
.acquire("gpt-5.5")
.is_none());
}
#[tokio::test]
async fn admin_account_delete_should_remove_database_row_and_runtime_pool_entry() {
let (app, state, pool, _dir) = admin_accounts_test_app("admin-account-delete.sqlite", 19).await;
import_test_account(&app, "session_1", "acct_delete").await;
let response = app
.clone()
.oneshot(
Request::builder()
.method("DELETE")
.uri("/admin/accounts/acct_delete")
.header("cookie", "cpr_admin_session=session_1")
.header("x-request-id", "req_delete")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let body = response_json(response).await;
assert_eq!(body["data"]["deleted"], true);
let row_count: (i64,) = sqlx::query_as("select count(*) from accounts where id = ?")
.bind("acct_delete")
.fetch_one(&pool)
.await
.unwrap();
assert_eq!(row_count.0, 0);
assert!(state
.account_pool()
.lock()
.await
.acquire("gpt-5.5")
.is_none());
let missing = app
.oneshot(
Request::builder()
.method("DELETE")
.uri("/admin/accounts/acct_delete")
.header("cookie", "cpr_admin_session=session_1")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(missing.status(), StatusCode::NOT_FOUND);
}
async fn admin_accounts_test_app(
db_name: &str,
key_byte: u8,
) -> (Router, AppState, sqlx::SqlitePool, tempfile::TempDir) {
let dir = tempfile::tempdir().unwrap();
let db = dir.path().join(db_name);
let url = format!("sqlite://{}", db.display());
let pool = connect_sqlite(&url).await.unwrap();
seed_admin_session(&pool, "session_1").await;
let state = AppState::with_pool_and_secret_box(
test_config(url),
pool.clone(),
SecretBox::new([key_byte; 32]),
);
let app = build_router(state.clone());
(app, state, pool, dir)
}
async fn import_test_account(app: &Router, session_id: &str, account_id: &str) {
let import_body = json!({
"accounts": [{
"id": account_id,
"email": format!("{account_id}@example.com"),
"planType": "plus",
"token": format!("access-{account_id}"),
"refreshToken": format!("refresh-{account_id}"),
"status": "active"
}]
});
let response = app
.clone()
.oneshot(
Request::builder()
.method("POST")
.uri("/admin/accounts/import")
.header("content-type", "application/json")
.header("cookie", format!("cpr_admin_session={session_id}"))
.body(Body::from(import_body.to_string()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
}
async fn seed_admin_session(pool: &sqlx::SqlitePool, session_id: &str) {
let now = Utc::now().to_rfc3339();
sqlx::query(