mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-11-18 16:06:47 +00:00
fix(gateway): restore account mutation semantics
Allow explicitly selected provider accounts to be deleted regardless of scheduling state, matching the pre-refactor behavior. Upsert verified credential imports by upstream identity, preserve existing account IDs, and return the committed IDs to admin callers. Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
@@ -243,6 +243,12 @@ pub struct ImportProviderAccounts {
|
||||
pub audit: AdminAuditEvent,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ProviderAccountAdminImport {
|
||||
pub config_revision: Revision,
|
||||
pub account_ids: Vec<String>,
|
||||
}
|
||||
|
||||
impl fmt::Debug for ImportProviderAccounts {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
formatter
|
||||
@@ -447,7 +453,7 @@ pub trait ProviderAccountAdminRepository: Send + Sync {
|
||||
&self,
|
||||
expected_config_revision: Revision,
|
||||
command: ImportProviderAccounts,
|
||||
) -> StoreResult<Revision>;
|
||||
) -> StoreResult<ProviderAccountAdminImport>;
|
||||
|
||||
async fn rotate_provider_account(
|
||||
&self,
|
||||
@@ -760,7 +766,7 @@ impl ProviderAccountAdminRepository for PgProviderAccountRepository {
|
||||
&self,
|
||||
expected_config_revision: Revision,
|
||||
command: ImportProviderAccounts,
|
||||
) -> StoreResult<Revision> {
|
||||
) -> StoreResult<ProviderAccountAdminImport> {
|
||||
command.validate()?;
|
||||
let mut transaction = self
|
||||
.pool
|
||||
@@ -771,12 +777,17 @@ impl ProviderAccountAdminRepository for PgProviderAccountRepository {
|
||||
let revision =
|
||||
bump_config_revision_in_transaction(&mut transaction, expected_config_revision)
|
||||
.await?;
|
||||
let mut account_ids = Vec::with_capacity(command.accounts.len());
|
||||
for account in &command.accounts {
|
||||
upsert_provider_account_in_transaction(&mut transaction, account).await?;
|
||||
account_ids
|
||||
.push(upsert_provider_account_in_transaction(&mut transaction, account).await?);
|
||||
}
|
||||
append_admin_audit_event_in_transaction(&mut transaction, command.audit, revision)
|
||||
.await?;
|
||||
Ok(revision)
|
||||
Ok(ProviderAccountAdminImport {
|
||||
config_revision: revision,
|
||||
account_ids,
|
||||
})
|
||||
}
|
||||
.await;
|
||||
finish_admin_transaction(transaction, result, "provider account admin import").await
|
||||
@@ -962,18 +973,13 @@ impl PgAdminAccountStore {
|
||||
) -> AdminStoreResult<CredentialImportResult> {
|
||||
let provider_kind = prepared.provider_kind.as_str().to_owned();
|
||||
let provider_instance_id = prepared.provider_instance_id.as_str().to_owned();
|
||||
let credential_ids = prepared
|
||||
.credentials
|
||||
.iter()
|
||||
.map(|credential| credential.account_id.clone())
|
||||
.collect::<Vec<_>>();
|
||||
let accounts = prepared
|
||||
.credentials
|
||||
.into_iter()
|
||||
.map(prepared_account)
|
||||
.collect::<StoreResult<Vec<_>>>()
|
||||
.map_err(|error| admin_store_error(ENTITY, error))?;
|
||||
let revision = self
|
||||
let imported = self
|
||||
.accounts
|
||||
.import_provider_accounts(
|
||||
store_revision(expected_config_revision)?,
|
||||
@@ -995,8 +1001,19 @@ impl PgAdminAccountStore {
|
||||
.await
|
||||
.map_err(|error| admin_store_error(ENTITY, error))?;
|
||||
Ok(CredentialImportResult {
|
||||
config_revision: admin_revision(revision)?,
|
||||
credential_ids,
|
||||
config_revision: admin_revision(imported.config_revision)?,
|
||||
credential_ids: imported
|
||||
.account_ids
|
||||
.into_iter()
|
||||
.map(CoreProviderAccountId::new)
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.map_err(|_| {
|
||||
AdminStoreError::new(
|
||||
AdminStoreErrorKind::Unavailable,
|
||||
ENTITY,
|
||||
"provider account import returned an invalid account ID",
|
||||
)
|
||||
})?,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1835,7 +1852,7 @@ fn admin_account_costs(costs: Vec<CurrencyCostTotal>) -> AdminStoreResult<Vec<Ac
|
||||
async fn upsert_provider_account_in_transaction(
|
||||
transaction: &mut Transaction<'_, Postgres>,
|
||||
account: &NewProviderAccount,
|
||||
) -> StoreResult<()> {
|
||||
) -> StoreResult<String> {
|
||||
account.validate()?;
|
||||
let imported_id = sqlx::query_scalar::<_, String>(
|
||||
"insert into provider_accounts (
|
||||
@@ -1848,7 +1865,11 @@ async fn upsert_provider_account_in_transaction(
|
||||
$1, $2, $3, $4, $5, $6, $7, $8, $9, 1, $10, $11, $12, $13,
|
||||
$14, $15, $16, null, $17, null, now(), greatest(now(), $17)
|
||||
)
|
||||
on conflict (id) do update set
|
||||
on conflict (
|
||||
provider_kind,
|
||||
upstream_user_id,
|
||||
(coalesce(upstream_account_id, ''))
|
||||
) do update set
|
||||
name = excluded.name,
|
||||
email = excluded.email,
|
||||
plan_type = excluded.plan_type,
|
||||
@@ -1866,9 +1887,6 @@ async fn upsert_provider_account_in_transaction(
|
||||
quota_observed_at = null,
|
||||
updated_at = greatest(now(), excluded.availability_observed_at)
|
||||
where provider_accounts.provider_instance_id = excluded.provider_instance_id
|
||||
and provider_accounts.provider_kind = excluded.provider_kind
|
||||
and provider_accounts.upstream_user_id = excluded.upstream_user_id
|
||||
and provider_accounts.upstream_account_id is not distinct from excluded.upstream_account_id
|
||||
returning id",
|
||||
)
|
||||
.bind(&account.id)
|
||||
@@ -1909,8 +1927,7 @@ async fn upsert_provider_account_in_transaction(
|
||||
id: account.id.clone(),
|
||||
kind: ConflictKind::InvalidTransition,
|
||||
})?;
|
||||
debug_assert_eq!(imported_id, account.id);
|
||||
Ok(())
|
||||
Ok(imported_id)
|
||||
}
|
||||
|
||||
async fn rotate_provider_account_in_transaction(
|
||||
@@ -1984,7 +2001,7 @@ async fn delete_provider_accounts_in_transaction(
|
||||
let deleted = sqlx::query_scalar::<_, String>(
|
||||
"delete from provider_accounts
|
||||
where id = any($1::text[]) and provider_instance_id = $2
|
||||
and provider_kind = $3 and not enabled
|
||||
and provider_kind = $3
|
||||
returning id",
|
||||
)
|
||||
.bind(account_ids)
|
||||
@@ -1999,7 +2016,7 @@ async fn delete_provider_accounts_in_transaction(
|
||||
Ok(())
|
||||
} else {
|
||||
Err(invalid(
|
||||
"all deleted accounts must exist, match Provider scope, and be disabled",
|
||||
"all deleted accounts must exist and match Provider scope",
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -536,6 +536,41 @@ async fn terminal_admin_mutations_keep_revision_account_and_audit_atomic() {
|
||||
database.close().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn terminal_admin_delete_removes_an_enabled_account_atomically() {
|
||||
let Some(database) = TestDatabase::create("provider_account_enabled_delete").await else {
|
||||
return;
|
||||
};
|
||||
seed_instance(&database.pool, "inst_openai_admin", "openai")
|
||||
.await
|
||||
.expect("seed OpenAI instance");
|
||||
PgProviderAccountRepository::new(database.pool.clone())
|
||||
.insert_provider_account(account("acct_enabled_delete", "user-enabled-delete"))
|
||||
.await
|
||||
.expect("insert enabled account");
|
||||
|
||||
let revision = PgAdminAccountStore::new(database.pool.clone())
|
||||
.delete_account(
|
||||
DeleteAccount {
|
||||
expected_config_revision: AdminRevision::new(1).expect("initial revision"),
|
||||
account_id: "acct_enabled_delete".to_owned(),
|
||||
},
|
||||
&MutationContext {
|
||||
actor: MutationActor::System,
|
||||
request_id: "request_enabled_delete".to_owned(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("delete enabled account atomically");
|
||||
|
||||
assert_eq!(revision.get(), 2);
|
||||
assert_eq!(
|
||||
account_count(&database.pool, "acct_enabled_delete").await,
|
||||
0
|
||||
);
|
||||
database.close().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn admin_import_updates_the_same_verified_identity_without_rebinding_it() {
|
||||
let Some(database) = TestDatabase::create("provider_account_admin_upsert").await else {
|
||||
@@ -549,7 +584,7 @@ async fn admin_import_updates_the_same_verified_identity_without_rebinding_it()
|
||||
provider_kind: "openai".to_owned(),
|
||||
provider_instance_id: "inst_openai_admin".to_owned(),
|
||||
};
|
||||
let revision = repository
|
||||
let imported = repository
|
||||
.import_provider_accounts(
|
||||
Revision::new(1).expect("initial revision"),
|
||||
ImportProviderAccounts {
|
||||
@@ -560,6 +595,8 @@ async fn admin_import_updates_the_same_verified_identity_without_rebinding_it()
|
||||
)
|
||||
.await
|
||||
.expect("create imported account");
|
||||
assert_eq!(imported.account_ids, ["acct_admin_upsert"]);
|
||||
let revision = imported.config_revision;
|
||||
sqlx::query(
|
||||
"update provider_accounts
|
||||
set provider_quota_json = '{}'::jsonb, quota_observed_at = now(), updated_at = now()
|
||||
@@ -569,12 +606,12 @@ async fn admin_import_updates_the_same_verified_identity_without_rebinding_it()
|
||||
.await
|
||||
.expect("seed stale quota");
|
||||
|
||||
let mut updated = account("acct_admin_upsert", "user-admin-upsert");
|
||||
let mut updated = account("acct_admin_reimport", "user-admin-upsert");
|
||||
updated.name = "updated import".to_owned();
|
||||
updated.provider_credentials_json = credential_json("updated-import-secret");
|
||||
updated.availability = ProviderAccountAvailability::Banned;
|
||||
updated.availability_reason = Some("upstream_account_deactivated".to_owned());
|
||||
let revision = repository
|
||||
let imported = repository
|
||||
.import_provider_accounts(
|
||||
revision,
|
||||
ImportProviderAccounts {
|
||||
@@ -585,6 +622,8 @@ async fn admin_import_updates_the_same_verified_identity_without_rebinding_it()
|
||||
)
|
||||
.await
|
||||
.expect("update the same imported identity");
|
||||
assert_eq!(imported.account_ids, ["acct_admin_upsert"]);
|
||||
let revision = imported.config_revision;
|
||||
assert_eq!(revision.get(), 3);
|
||||
let row: (
|
||||
String,
|
||||
@@ -765,7 +804,7 @@ async fn provider_account_admin_mutations_are_scoped_audited_and_atomic() {
|
||||
let mut cooldown_account = account("acct_admin_b", "user-admin-b");
|
||||
cooldown_account.availability = ProviderAccountAvailability::Cooldown;
|
||||
cooldown_account.cooldown_until = Some(Utc::now() + TimeDelta::minutes(10));
|
||||
let revision = repository
|
||||
let imported = repository
|
||||
.import_provider_accounts(
|
||||
Revision::new(1).expect("initial revision"),
|
||||
ImportProviderAccounts {
|
||||
@@ -776,6 +815,7 @@ async fn provider_account_admin_mutations_are_scoped_audited_and_atomic() {
|
||||
)
|
||||
.await
|
||||
.expect("import provider accounts");
|
||||
let revision = imported.config_revision;
|
||||
assert_eq!(revision.get(), 2);
|
||||
let ready: (bool, String, Option<chrono::DateTime<Utc>>) = sqlx::query_as(
|
||||
"select enabled, availability, cooldown_until from provider_accounts where id = $1",
|
||||
@@ -872,21 +912,6 @@ async fn provider_account_admin_mutations_are_scoped_audited_and_atomic() {
|
||||
)
|
||||
.await
|
||||
.expect("disable provider account");
|
||||
repository
|
||||
.delete_provider_accounts_admin(
|
||||
revision,
|
||||
DeleteProviderAccounts {
|
||||
scope: scope.clone(),
|
||||
account_ids: vec!["acct_admin_a".to_owned(), "acct_admin_b".to_owned()],
|
||||
audit: audit("audit_partial_delete", "delete", "provider_accounts"),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect_err("mixed enabled state batch must roll back every deletion");
|
||||
assert_eq!(current_revision(&database.pool).await, 4);
|
||||
assert_eq!(account_count(&database.pool, "acct_admin_a").await, 1);
|
||||
assert_eq!(account_count(&database.pool, "acct_admin_b").await, 1);
|
||||
|
||||
let exports = repository
|
||||
.export_provider_accounts(
|
||||
scope.clone(),
|
||||
@@ -899,31 +924,19 @@ async fn provider_account_admin_mutations_are_scoped_audited_and_atomic() {
|
||||
assert!(!format!("{exports:?}").contains("rotated-secret"));
|
||||
|
||||
let revision = repository
|
||||
.delete_provider_accounts_admin(
|
||||
revision,
|
||||
DeleteProviderAccounts {
|
||||
scope: scope.clone(),
|
||||
account_ids: vec!["acct_admin_a".to_owned()],
|
||||
audit: audit("audit_account_delete", "delete", "acct_admin_a"),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect("delete disabled provider account");
|
||||
assert_eq!(revision.get(), 5);
|
||||
|
||||
repository
|
||||
.delete_provider_accounts_admin(
|
||||
revision,
|
||||
DeleteProviderAccounts {
|
||||
scope,
|
||||
account_ids: vec!["acct_admin_b".to_owned()],
|
||||
audit: audit("audit_enabled_delete", "delete", "acct_admin_b"),
|
||||
account_ids: vec!["acct_admin_a".to_owned(), "acct_admin_b".to_owned()],
|
||||
audit: audit("audit_account_delete", "delete", "provider_accounts"),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect_err("enabled provider account must not be deleted");
|
||||
assert_eq!(current_revision(&database.pool).await, 5);
|
||||
assert_eq!(account_count(&database.pool, "acct_admin_b").await, 1);
|
||||
.expect("delete selected accounts regardless of enabled state");
|
||||
assert_eq!(revision.get(), 5);
|
||||
assert_eq!(account_count(&database.pool, "acct_admin_a").await, 0);
|
||||
assert_eq!(account_count(&database.pool, "acct_admin_b").await, 0);
|
||||
let audit_count: i64 = sqlx::query_scalar("select count(*) from admin_audit_events")
|
||||
.fetch_one(&database.pool)
|
||||
.await
|
||||
|
||||
Reference in New Issue
Block a user