feat: add admin account cookie routes

Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
Zyy
2026-06-12 14:07:23 +08:00
co-authored by Codex
parent 81ce66d449
commit 203270f97b
6 changed files with 475 additions and 5 deletions
+2 -2
View File
@@ -12,11 +12,11 @@ Update this file before each feature commit.
| Secret encryption | Completed | `105aa58` + `228febd` | `cargo test secret_box_encrypts_and_decrypts_without_storing_plaintext`; `cargo test secret_box_load_or_create_should_reuse_existing_master_key_file`; full `fmt/test/clippy` before commit | AES-256-GCM `SecretBox` stores upstream secrets as `v1:<nonce>:<ciphertext>` without plaintext and can load/create the runtime master key file used by repositories. |
| 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. |
| Cookie persistence | Completed | `4710926` + `5d3cc6e` + pending | `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 pending | Adds account-scoped in-memory Cookie jar and encrypted SQLite Cookie repository; Cookies are replayed only for the same account/domain. Admin-pasted browser Cookie headers are stored encrypted and can be cleared per account. |
| Account pool and refresh | Partial | `0f97c5c` + `2f25db8` + `4dc0c9a` + `c2cf7a6` + `636fa79` + `fdb9374` + `3ecd5b6` + `3960a35` + `db6cb98` | `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 `db6cb98` | 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` + `db6cb98` | `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 `db6cb98` | 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` + `db6cb98` + `16eb4ed` + `8af350d` | `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 `db6cb98`; full `fmt/test/clippy` before `16eb4ed`; full `fmt/test/clippy` before `8af350d` | Adds Axum router, health route, `/v1/models`, `/v1/models/catalog`, `/v1/models/{id}`, `/v1/models/{id}/info`, `/debug/models`, `/admin/accounts`, `/admin/accounts/batch-delete`, `/admin/accounts/batch-status`, `/admin/accounts/{id}`, `/admin/accounts/{id}/label`, `/admin/accounts/{id}/status`, `/admin/accounts/import`, `/admin/api-keys`, `/admin/api-keys/{id}`, `/admin/api-keys/{id}/status`, `/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`, delete, batch-delete, and batch-status mutate SQLite plus runtime account pool. `/admin/api-keys/{id}/status` and delete mutate local client key rows used by `/v1` auth. `/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/health/quota/Cookie routes, local admin API-key batch/label/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` + `db6cb98` + `16eb4ed` + `8af350d` + 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 `db6cb98`; full `fmt/test/clippy` before `16eb4ed`; full `fmt/test/clippy` before `8af350d`; 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/batch-delete`, `/admin/accounts/batch-status`, `/admin/accounts/{id}`, `/admin/accounts/{id}/label`, `/admin/accounts/{id}/status`, `/admin/accounts/{id}/cookies`, `/admin/accounts/import`, `/admin/api-keys`, `/admin/api-keys/{id}`, `/admin/api-keys/{id}/status`, `/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`, delete, batch-delete, and batch-status mutate SQLite plus runtime account pool. `/admin/accounts/{id}/cookies` stores/reads/deletes encrypted per-account browser cookies. `/admin/api-keys/{id}/status` and delete mutate local client key rows used by `/v1` auth. `/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/health/quota routes, local admin API-key batch/label/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. Commit `db6cb98` adds admin account label/status/delete mutations with runtime pool synchronization. Commit `16eb4ed` adds batch delete/status mutations. Commit `8af350d` adds local client API key status/delete mutations. 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. Commit `db6cb98` adds admin account label/status/delete mutations with runtime pool synchronization. Commit `16eb4ed` adds batch delete/status mutations. Commit `8af350d` adds local client API key status/delete mutations. Pending Task 7 follow-up adds encrypted account Cookie get/set/delete. Remaining major work continues with WebSocket/history fallback policy and scoped admin operations.
---
@@ -123,7 +123,10 @@
- [x] Write failing tests for local client API key disable/delete mutations.
- [x] Implement local client API key disable/delete mutations without third-party provider key pools.
- [x] Run: `cargo test --test admin_api_keys_route_test`
- [ ] Write failing tests for manual add, quota fetch, health check, cookie get/set/delete, remaining import/export, API key batch/delete export/import variants.
- [x] Write failing tests for account Cookie get/set/delete routes.
- [x] Implement encrypted account Cookie get/set/delete routes.
- [x] Run: `cargo test --test admin_accounts_route_test`
- [ ] Write failing tests for manual add, quota fetch, health check, remaining import/export, API key batch/delete export/import variants.
- [ ] 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`
+8 -1
View File
@@ -9,7 +9,8 @@ use crate::{
http::{
admin::{
accounts, api_keys, batch_delete_accounts, batch_update_account_status, create_api_key,
delete_account, delete_api_key, import_accounts, login, logs, refresh_models, settings,
delete_account, delete_account_cookies, delete_api_key, get_account_cookies,
import_accounts, login, logs, refresh_models, set_account_cookies, settings,
update_account_label, update_account_status, update_api_key_status, usage_stats,
usage_stats_summary,
},
@@ -45,6 +46,12 @@ pub fn build_router(state: AppState) -> Router {
"/admin/accounts/batch-status",
post(batch_update_account_status),
)
.route(
"/admin/accounts/{account_id}/cookies",
get(get_account_cookies)
.post(set_account_cookies)
.delete(delete_account_cookies),
)
.route("/admin/accounts/{account_id}", delete(delete_account))
.route(
"/admin/accounts/{account_id}/label",
+42
View File
@@ -31,6 +31,19 @@ impl CookieRepository {
let Some(parsed) = parse_set_cookie(raw) else {
return Ok(());
};
self.upsert_cookie(account_id, parsed).await
}
pub async fn set_cookie_header(&self, account_id: &str, raw: &str) -> CookieResult<usize> {
let parsed = parse_cookie_header(raw);
let count = parsed.len();
for cookie in parsed {
self.upsert_cookie(account_id, cookie).await?;
}
Ok(count)
}
async fn upsert_cookie(&self, account_id: &str, parsed: ParsedCookie) -> CookieResult<()> {
let now = Utc::now().to_rfc3339();
let value_cipher = self
.secret_box
@@ -79,6 +92,14 @@ impl CookieRepository {
Ok(Some(pairs.join("; ")))
}
}
pub async fn delete_account_cookies(&self, account_id: &str) -> CookieResult<u64> {
let result = sqlx::query("delete from account_cookies where account_id = ?")
.bind(account_id)
.execute(&self.pool)
.await?;
Ok(result.rows_affected())
}
}
struct ParsedCookie {
@@ -113,6 +134,27 @@ fn parse_set_cookie(raw: &str) -> Option<ParsedCookie> {
})
}
fn parse_cookie_header(raw: &str) -> Vec<ParsedCookie> {
raw.split(';')
.map(str::trim)
.filter_map(|part| {
let (name, value) = part.split_once('=')?;
let name = name.trim();
let value = value.trim();
if name.is_empty() || value.is_empty() {
return None;
}
Some(ParsedCookie {
domain: "chatgpt.com".to_string(),
name: name.to_string(),
value: value.to_string(),
path: "/".to_string(),
expires_at: None,
})
})
.collect()
}
fn domain_matches(request_domain: &str, cookie_domain: &str) -> bool {
request_domain == cookie_domain
|| request_domain
+293
View File
@@ -288,6 +288,24 @@ pub struct BatchUpdateAccountStatusData {
pub not_found: Vec<String>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SetAccountCookiesRequest {
pub cookies: Value,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AccountCookiesData {
pub cookies: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DeleteAccountCookiesData {
pub deleted: bool,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RefreshModelsData {
@@ -1310,6 +1328,252 @@ pub async fn batch_update_account_status(
.into_response()
}
pub async fn get_account_cookies(
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(account_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 account_repo.exists(&account_id).await {
Ok(true) => {}
Ok(false) => {
return AdminResponse::new(
StatusCode::NOT_FOUND,
AdminEnvelope::new(40401, "Account not found", (), request_id),
)
.into_response();
}
Err(_) => {
return AdminResponse::new(
StatusCode::INTERNAL_SERVER_ERROR,
AdminEnvelope::new(50001, "Failed to inspect account", (), request_id),
)
.into_response();
}
}
let Some(cookie_repo) = state.cookie_repository() else {
return AdminResponse::new(
StatusCode::INTERNAL_SERVER_ERROR,
AdminEnvelope::new(
50001,
"Cookie repository is not initialized",
(),
request_id,
),
)
.into_response();
};
match cookie_repo.cookie_header(&account_id, "chatgpt.com").await {
Ok(cookies) => AdminResponse::new(
StatusCode::OK,
AdminEnvelope::ok(AccountCookiesData { cookies }, request_id),
)
.into_response(),
Err(_) => AdminResponse::new(
StatusCode::INTERNAL_SERVER_ERROR,
AdminEnvelope::new(50001, "Failed to load account cookies", (), request_id),
)
.into_response(),
}
}
pub async fn set_account_cookies(
State(state): State<AppState>,
Extension(request_id): Extension<RequestId>,
headers: HeaderMap,
Path(account_id): Path<String>,
Json(payload): Json<SetAccountCookiesRequest>,
) -> Response {
let request_id = request_id.as_str().to_string();
let cookie_header = match admin_cookie_header(&payload.cookies) {
Ok(cookie_header) => cookie_header,
Err(message) => {
return AdminResponse::new(
StatusCode::BAD_REQUEST,
AdminEnvelope::new(40001, message, (), request_id),
)
.into_response();
}
};
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(account_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 account_repo.exists(&account_id).await {
Ok(true) => {}
Ok(false) => {
return AdminResponse::new(
StatusCode::NOT_FOUND,
AdminEnvelope::new(40401, "Account not found", (), request_id),
)
.into_response();
}
Err(_) => {
return AdminResponse::new(
StatusCode::INTERNAL_SERVER_ERROR,
AdminEnvelope::new(50001, "Failed to inspect account", (), request_id),
)
.into_response();
}
}
let Some(cookie_repo) = state.cookie_repository() else {
return AdminResponse::new(
StatusCode::INTERNAL_SERVER_ERROR,
AdminEnvelope::new(
50001,
"Cookie repository is not initialized",
(),
request_id,
),
)
.into_response();
};
// 管理端粘贴的是浏览器 Cookie header;保存时逐项加密,读取时只回放当前账号自己的 Cookie。
match cookie_repo
.set_cookie_header(&account_id, &cookie_header)
.await
{
Ok(0) => AdminResponse::new(
StatusCode::BAD_REQUEST,
AdminEnvelope::new(40001, "No valid cookies found", (), request_id),
)
.into_response(),
Ok(_) => match cookie_repo.cookie_header(&account_id, "chatgpt.com").await {
Ok(cookies) => AdminResponse::new(
StatusCode::OK,
AdminEnvelope::ok(AccountCookiesData { cookies }, request_id),
)
.into_response(),
Err(_) => AdminResponse::new(
StatusCode::INTERNAL_SERVER_ERROR,
AdminEnvelope::new(50001, "Failed to load account cookies", (), request_id),
)
.into_response(),
},
Err(_) => AdminResponse::new(
StatusCode::INTERNAL_SERVER_ERROR,
AdminEnvelope::new(50001, "Failed to store account cookies", (), request_id),
)
.into_response(),
}
}
pub async fn delete_account_cookies(
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(account_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 account_repo.exists(&account_id).await {
Ok(true) => {}
Ok(false) => {
return AdminResponse::new(
StatusCode::NOT_FOUND,
AdminEnvelope::new(40401, "Account not found", (), request_id),
)
.into_response();
}
Err(_) => {
return AdminResponse::new(
StatusCode::INTERNAL_SERVER_ERROR,
AdminEnvelope::new(50001, "Failed to inspect account", (), request_id),
)
.into_response();
}
}
let Some(cookie_repo) = state.cookie_repository() else {
return AdminResponse::new(
StatusCode::INTERNAL_SERVER_ERROR,
AdminEnvelope::new(
50001,
"Cookie repository is not initialized",
(),
request_id,
),
)
.into_response();
};
match cookie_repo.delete_account_cookies(&account_id).await {
Ok(_) => AdminResponse::new(
StatusCode::OK,
AdminEnvelope::ok(DeleteAccountCookiesData { deleted: true }, request_id),
)
.into_response(),
Err(_) => AdminResponse::new(
StatusCode::INTERNAL_SERVER_ERROR,
AdminEnvelope::new(50001, "Failed to delete account cookies", (), request_id),
)
.into_response(),
}
}
pub async fn import_accounts(
State(state): State<AppState>,
Extension(request_id): Extension<RequestId>,
@@ -2089,6 +2353,35 @@ fn parse_client_api_key_enabled_status(status: &str) -> Result<bool, String> {
}
}
fn admin_cookie_header(value: &Value) -> Result<String, &'static str> {
if let Some(cookies) = value.as_str() {
let cookies = cookies.trim();
if cookies.is_empty() {
return Err("cookies field is required");
}
return Ok(cookies.to_string());
}
let Some(object) = value.as_object() else {
return Err("cookies must be a string or object");
};
if object.is_empty() {
return Err("cookies field is required");
}
let pairs = object
.iter()
.filter_map(|(name, value)| {
let value = value.as_str()?.trim();
(!name.trim().is_empty() && !value.is_empty())
.then(|| format!("{}={value}", name.trim()))
})
.collect::<Vec<_>>();
if pairs.is_empty() {
Err("No valid cookies found")
} else {
Ok(pairs.join("; "))
}
}
fn account_status_value(status: AccountStatus) -> &'static str {
match status {
AccountStatus::Active => "active",
+125
View File
@@ -699,6 +699,131 @@ async fn admin_accounts_batch_status_should_update_found_accounts_and_reject_inv
assert_eq!(empty.status(), StatusCode::BAD_REQUEST);
}
#[tokio::test]
async fn admin_account_cookies_should_set_get_and_delete_encrypted_cookie_header() {
let (app, _state, pool, _dir) =
admin_accounts_test_app("admin-account-cookies.sqlite", 22).await;
import_test_account(&app, "session_1", "acct_cookies").await;
let set_response = app
.clone()
.oneshot(
Request::builder()
.method("POST")
.uri("/admin/accounts/acct_cookies/cookies")
.header("content-type", "application/json")
.header("cookie", "cpr_admin_session=session_1")
.body(Body::from(
r#"{"cookies":"cf_clearance=clear-secret; __cf_bm=bm-secret"}"#,
))
.unwrap(),
)
.await
.unwrap();
assert_eq!(set_response.status(), StatusCode::OK);
let body = response_json(set_response).await;
assert_eq!(
body["data"]["cookies"],
"__cf_bm=bm-secret; cf_clearance=clear-secret"
);
let stored = sqlx::query_as::<_, (String, String)>(
"select name, value_cipher from account_cookies where account_id = ? order by name asc",
)
.bind("acct_cookies")
.fetch_all(&pool)
.await
.unwrap();
assert_eq!(stored.len(), 2);
assert!(stored.iter().all(|(_, cipher)| cipher.starts_with("v1:")));
assert!(stored
.iter()
.all(|(_, cipher)| !cipher.contains("clear-secret") && !cipher.contains("bm-secret")));
let get_response = app
.clone()
.oneshot(
Request::builder()
.method("GET")
.uri("/admin/accounts/acct_cookies/cookies")
.header("cookie", "cpr_admin_session=session_1")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(get_response.status(), StatusCode::OK);
let body = response_json(get_response).await;
assert_eq!(
body["data"]["cookies"],
"__cf_bm=bm-secret; cf_clearance=clear-secret"
);
let delete_response = app
.clone()
.oneshot(
Request::builder()
.method("DELETE")
.uri("/admin/accounts/acct_cookies/cookies")
.header("cookie", "cpr_admin_session=session_1")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(delete_response.status(), StatusCode::OK);
let get_empty = app
.oneshot(
Request::builder()
.method("GET")
.uri("/admin/accounts/acct_cookies/cookies")
.header("cookie", "cpr_admin_session=session_1")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(get_empty.status(), StatusCode::OK);
let body = response_json(get_empty).await;
assert!(body["data"]["cookies"].is_null());
}
#[tokio::test]
async fn admin_account_cookies_should_require_existing_account_and_non_empty_cookies() {
let (app, _state, _pool, _dir) =
admin_accounts_test_app("admin-account-cookies-invalid.sqlite", 23).await;
let missing = app
.clone()
.oneshot(
Request::builder()
.method("GET")
.uri("/admin/accounts/missing/cookies")
.header("cookie", "cpr_admin_session=session_1")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(missing.status(), StatusCode::NOT_FOUND);
import_test_account(&app, "session_1", "acct_cookie_invalid").await;
let invalid = app
.oneshot(
Request::builder()
.method("POST")
.uri("/admin/accounts/acct_cookie_invalid/cookies")
.header("content-type", "application/json")
.header("cookie", "cpr_admin_session=session_1")
.body(Body::from(r#"{"cookies":""}"#))
.unwrap(),
)
.await
.unwrap();
assert_eq!(invalid.status(), StatusCode::BAD_REQUEST);
}
async fn admin_accounts_test_app(
db_name: &str,
key_byte: u8,