The staging gate failed on this new test only: the psql fixture rewrites a colon-joined false to f, and four expectations spelled it out. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DbBXp2Vp62Ur3C7yRWQdSq
154 lines
13 KiB
TypeScript
154 lines
13 KiB
TypeScript
import assert from "node:assert/strict";
|
|
import { spawnSync } from "node:child_process";
|
|
import { readFileSync } from "node:fs";
|
|
import { fileURLToPath } from "node:url";
|
|
import test from "node:test";
|
|
|
|
import { startPostgresFixture } from "./helpers/postgres-fixture.ts";
|
|
|
|
const runnerPath = fileURLToPath(new URL("../scripts/db-migrate.mjs", import.meta.url));
|
|
const migrationSql = readFileSync(
|
|
new URL("../supabase/migrations/20261116030000_model_provider_keys.sql", import.meta.url),
|
|
"utf8",
|
|
);
|
|
const ids = {
|
|
owner: "10000000-0000-4000-8000-000000000001",
|
|
support: "10000000-0000-4000-8000-000000000004",
|
|
};
|
|
|
|
// The psql fixture prints a colon-joined "false" as "f" (tests/helpers/postgres-fixture.ts), so expectations use "f".
|
|
test("provider keys: copy of the old key, audited writes, last-key rule and admin_runtime reads", async () => {
|
|
const fixture = startPostgresFixture();
|
|
const sql = (statement: string) => fixture.psql(statement);
|
|
const sqlAsOwner = (statement: string) => fixture.psqlAs("schema_owner", "schema-owner-test-password", statement);
|
|
const sqlAsAdminRuntime = (statement: string) => fixture.psqlAs("admin_runtime", "admin-runtime-test-password", statement);
|
|
const expectSqlError = (statement: string, pattern: RegExp) => assert.throws(() => sqlAsOwner(statement), pattern);
|
|
const legacyKey = (providerId: string) => sql(`select coalesce(encrypted_api_key,'<null>') from public.model_providers where id='${providerId}'`);
|
|
const saveKey = (actor: string, providerId: string, keyId: string | null, label: string, encrypted: string | null, enabled: boolean, limit: number | null, requestId: string) =>
|
|
`select public.admin_save_model_provider_key('${actor}','${providerId}',${keyId ? `'${keyId}'` : "null"},'${label}',${encrypted ? `'${encrypted}'` : "null"},${enabled},${limit ?? "null"},'测试','${requestId}')`;
|
|
|
|
try {
|
|
const migration = spawnSync(process.execPath, [runnerPath], {
|
|
encoding: "utf8",
|
|
env: {
|
|
...process.env,
|
|
SCHEMA_DATABASE_URL: fixture.connectionUrl("schema_owner", "schema-owner-test-password"),
|
|
},
|
|
});
|
|
assert.equal(migration.status, 0, migration.stderr);
|
|
assert.match(migration.stdout, /applied 20261116030000_model_provider_keys\.sql/);
|
|
assert.match(migration.stdout, /notice model_provider_keys: copied \d+ existing provider key\(s\)/);
|
|
|
|
fixture.psqlAs("identity_runtime", "identity-runtime-test-password", `
|
|
insert into identity.users (id,name,email,email_verified,email_verified_at,role) values
|
|
('${ids.owner}','Owner','owner@example.com',true,now(),'admin'),
|
|
('${ids.support}','Support','support@example.com',true,now(),'user')
|
|
`);
|
|
sql(`
|
|
insert into public.admin_users(user_id,created_by) values ('${ids.owner}','${ids.owner}'),('${ids.support}','${ids.owner}');
|
|
insert into public.admin_user_roles(admin_user_id,role_id,assigned_by)
|
|
select v.user_id,r.id,'${ids.owner}'::uuid
|
|
from (values ('${ids.owner}'::uuid,'owner'),('${ids.support}'::uuid,'support')) v(user_id,role_code)
|
|
join public.admin_roles r on r.code=v.role_code
|
|
`);
|
|
assert.equal(sql(`select public.admin_has_permission('${ids.owner}','models.write')`), "t");
|
|
assert.equal(sql(`select public.admin_has_permission('${ids.support}','models.write')`), "f");
|
|
|
|
// A provider saved through the single-key function gets its 「默认」 key row.
|
|
const provider = sqlAsOwner(`select public.admin_save_model_provider('${ids.owner}',null,'DeepSeek','openai-compatible','https://api.deepseek.com/v1','ciphertext-one',true,'建供应商','provider-create')`);
|
|
assert.equal(sql(`select label||':'||encrypted_api_key||':'||enabled||':'||coalesce(max_concurrency::text,'null') from public.model_provider_keys where provider_id='${provider}'`), "默认:ciphertext-one:true:null");
|
|
const first = sql(`select id from public.model_provider_keys where provider_id='${provider}'`);
|
|
|
|
// The forward copy: remove the row as a pre-migration database would look, then re-run the migration file.
|
|
sql(`delete from public.model_provider_keys where provider_id='${provider}'`);
|
|
fixture.psqlScriptAs("schema_owner", "schema-owner-test-password", migrationSql);
|
|
assert.equal(sql(`select label||':'||encrypted_api_key||':'||enabled from public.model_provider_keys where provider_id='${provider}'`), "默认:ciphertext-one:true");
|
|
const copied = sql(`select id from public.model_provider_keys where provider_id='${provider}'`);
|
|
assert.notEqual(copied, first);
|
|
fixture.psqlScriptAs("schema_owner", "schema-owner-test-password", migrationSql);
|
|
assert.equal(sql(`select count(*) from public.model_provider_keys where provider_id='${provider}'`), "1", "re-running copies nothing twice");
|
|
|
|
// Permission and argument checks.
|
|
expectSqlError(saveKey(ids.support, provider, null, "二号", "ciphertext-two", true, 2, "denied-save"), /admin_permission_denied/);
|
|
expectSqlError(`select public.admin_delete_model_provider_key('${ids.support}','${copied}','测试','denied-delete')`, /admin_permission_denied/);
|
|
expectSqlError(saveKey(ids.owner, provider, null, "二号", null, true, null, "no-key"), /model_provider_key_required/);
|
|
expectSqlError(saveKey(ids.owner, provider, null, "二号", "ciphertext-two", true, 65, "bad-limit"), /invalid_model_provider_key/);
|
|
expectSqlError(saveKey(ids.owner, provider, null, "x".repeat(41), "ciphertext-two", true, null, "bad-label"), /invalid_model_provider_key/);
|
|
expectSqlError(saveKey(ids.owner, provider, null, "默认", "ciphertext-two", true, null, "taken"), /model_provider_key_label_taken/);
|
|
expectSqlError(saveKey(ids.owner, "00000000-0000-4000-8000-000000000000", null, "二号", "ciphertext-two", true, null, "no-provider"), /model_provider_not_found/);
|
|
|
|
// A second key; the legacy column keeps the first enabled key.
|
|
const second = sqlAsOwner(saveKey(ids.owner, provider, null, "二号", "ciphertext-two", true, 2, "key-add"));
|
|
assert.equal(sql(`select label||':'||max_concurrency||':'||(created_by='${ids.owner}') from public.model_provider_keys where id='${second}'`), "二号:2:true");
|
|
assert.equal(legacyKey(provider), "ciphertext-one");
|
|
|
|
// Disabling the first key moves the legacy column to the next enabled key.
|
|
sqlAsOwner(saveKey(ids.owner, provider, copied, "默认", null, false, null, "key-disable"));
|
|
assert.equal(sql(`select encrypted_api_key||':'||enabled from public.model_provider_keys where id='${copied}'`), "ciphertext-one:f", "a null key keeps the stored one");
|
|
assert.equal(legacyKey(provider), "ciphertext-two");
|
|
|
|
// The last enabled key of an enabled provider can be neither disabled nor deleted.
|
|
expectSqlError(saveKey(ids.owner, provider, second, "二号", null, false, 2, "last-disable"), /model_provider_last_key/);
|
|
expectSqlError(`select public.admin_delete_model_provider_key('${ids.owner}','${second}','测试','last-delete')`, /model_provider_last_key/);
|
|
assert.equal(sql(`select enabled from public.model_provider_keys where id='${second}'`), "t");
|
|
|
|
// A disabled key can be deleted; replacing a key updates the legacy column.
|
|
sqlAsOwner(`select public.admin_delete_model_provider_key('${ids.owner}','${copied}','测试','key-delete')`);
|
|
assert.equal(sql(`select count(*) from public.model_provider_keys where provider_id='${provider}'`), "1");
|
|
sqlAsOwner(saveKey(ids.owner, provider, second, "主账号", "ciphertext-two-b", true, null, "key-replace"));
|
|
assert.equal(sql(`select label||':'||encrypted_api_key||':'||coalesce(max_concurrency::text,'null') from public.model_provider_keys where id='${second}'`), "主账号:ciphertext-two-b:null");
|
|
assert.equal(legacyKey(provider), "ciphertext-two-b");
|
|
|
|
// The single-key save (older web image, launch setup page) replaces the first enabled key row.
|
|
sqlAsOwner(`select public.admin_save_model_provider('${ids.owner}','${provider}','DeepSeek','openai-compatible','https://api.deepseek.com/v1','ciphertext-legacy',true,'换密钥','provider-rekey')`);
|
|
assert.equal(sql(`select encrypted_api_key from public.model_provider_keys where id='${second}'`), "ciphertext-legacy");
|
|
assert.equal(legacyKey(provider), "ciphertext-legacy");
|
|
assert.equal(sql(`select count(*) from public.model_provider_keys where provider_id='${provider}'`), "1");
|
|
|
|
// A disabled provider may lose every enabled key; it then cannot be enabled without one.
|
|
const spare = sqlAsOwner(`select public.admin_save_model_provider('${ids.owner}',null,'Spare','openai',null,null,false,'建供应商','spare-create')`);
|
|
assert.equal(sql(`select count(*) from public.model_provider_keys where provider_id='${spare}'`), "0");
|
|
const spareKey = sqlAsOwner(saveKey(ids.owner, spare, null, "甲", "ciphertext-spare", true, 1, "spare-add"));
|
|
assert.equal(legacyKey(spare), "ciphertext-spare");
|
|
sqlAsOwner(saveKey(ids.owner, spare, spareKey, "甲", null, false, 1, "spare-disable"));
|
|
assert.equal(legacyKey(spare), "<null>");
|
|
expectSqlError(`select public.admin_save_model_provider('${ids.owner}','${spare}','Spare','openai',null,null,true,'启用','spare-enable')`, /model_provider_key_required/);
|
|
sqlAsOwner(saveKey(ids.owner, spare, spareKey, "甲", null, true, 1, "spare-enable-key"));
|
|
sqlAsOwner(`select public.admin_save_model_provider('${ids.owner}','${spare}','Spare','openai',null,null,true,'启用','spare-enable-2')`);
|
|
assert.equal(sql(`select enabled from public.model_providers where id='${spare}'`), "t");
|
|
|
|
// At most 20 keys per provider.
|
|
for (let index = 0; index < 19; index += 1) {
|
|
sqlAsOwner(saveKey(ids.owner, spare, null, `备用${index}`, "ciphertext-bulk", false, null, `bulk-${index}`));
|
|
}
|
|
expectSqlError(saveKey(ids.owner, spare, null, "第二十一把", "ciphertext-bulk", false, null, "bulk-over"), /model_provider_key_limit/);
|
|
|
|
// Audit rows: one per write, permission recorded, no key material.
|
|
assert.equal(sql(`select string_agg(distinct action||':'||target_type||':'||permission_used, ',' order by action||':'||target_type||':'||permission_used) from audit.admin_audit_logs where action like 'models.provider_key.%'`),
|
|
"models.provider_key.delete:model_provider_key:models.write,models.provider_key.save:model_provider_key:models.write");
|
|
assert.equal(sql(`select after_value::text from audit.admin_audit_logs where request_id='key-add'`), `{"label": "二号", "enabled": true, "providerId": "${provider}", "maxConcurrency": 2, "credentialReplaced": true}`);
|
|
assert.equal(sql(`select (after_value->>'credentialReplaced')||':'||(before_value->>'enabled') from audit.admin_audit_logs where request_id='key-disable'`), "f:true");
|
|
assert.equal(sql(`select count(*) from audit.admin_audit_logs where action like 'models.provider%' and (coalesce(before_value::text,'')||coalesce(after_value::text,'')) like '%ciphertext%'`), "0");
|
|
assert.equal(sql(`select count(*) from audit.admin_audit_logs where request_id in ('denied-save','denied-delete','last-disable','last-delete')`), "0");
|
|
|
|
// admin_runtime (the web process): reads rows, calls the functions, cannot write the table.
|
|
assert.equal(sqlAsAdminRuntime(`select label from public.model_provider_keys where id='${second}'`), "主账号");
|
|
assert.equal(sql("select count(*) from pg_policies where schemaname='public' and tablename='model_provider_keys' and policyname='model_provider_keys_admin_select' and cmd='SELECT' and roles='{admin_runtime}'"), "1");
|
|
assert.equal(sql("select relrowsecurity from pg_class where oid='public.model_provider_keys'::regclass"), "t");
|
|
assert.equal(sql("select has_table_privilege('admin_runtime','public.model_provider_keys','select')||':'||has_table_privilege('admin_runtime','public.model_provider_keys','insert')||':'||has_table_privilege('admin_runtime','public.model_provider_keys','update')||':'||has_table_privilege('admin_runtime','public.model_provider_keys','delete')"), "true:f:f:f");
|
|
assert.equal(sql("select has_table_privilege('service_role','public.model_provider_keys','select')||':'||has_table_privilege('authenticated','public.model_provider_keys','select')||':'||has_table_privilege('anon','public.model_provider_keys','select')"), "true:f:f");
|
|
assert.equal(sql("select has_function_privilege('admin_runtime','public.admin_save_model_provider_key(uuid,uuid,uuid,text,text,boolean,integer,text,text)','execute')||':'||has_function_privilege('admin_runtime','public.admin_delete_model_provider_key(uuid,uuid,text,text)','execute')||':'||has_function_privilege('authenticated','public.admin_save_model_provider_key(uuid,uuid,uuid,text,text,boolean,integer,text,text)','execute')||':'||has_function_privilege('admin_runtime','public.sync_model_provider_legacy_key(uuid)','execute')"), "true:true:f:f");
|
|
assert.throws(() => sqlAsAdminRuntime(`update public.model_provider_keys set enabled=false where id='${second}'`), /permission denied/);
|
|
const runtimeKey = sqlAsAdminRuntime(saveKey(ids.owner, provider, null, "三号", "ciphertext-three", true, 8, "runtime-add"));
|
|
// The catalog query shape: enabled keys oldest first.
|
|
assert.equal(sqlAsAdminRuntime(`select string_agg(k.label, ',' order by k.created_at,k.id) from public.model_provider_keys k where k.provider_id='${provider}' and k.enabled`), "主账号,三号");
|
|
sqlAsAdminRuntime(`select public.admin_delete_model_provider_key('${ids.owner}','${runtimeKey}','测试','runtime-delete')`);
|
|
|
|
// Deleting a provider removes its keys.
|
|
sql(`delete from public.model_providers where id='${spare}'`);
|
|
assert.equal(sql(`select count(*) from public.model_provider_keys where provider_id='${spare}'`), "0");
|
|
} finally {
|
|
fixture.stop();
|
|
}
|
|
});
|