feat: configure key model access after creation

This commit is contained in:
wlx committed 2026-08-27 17:36:37 +08:00
1 parent 6de29ebd6d
commit 7f35960ba6
8 files changed
+175 -23

No files matched your search

+23 -2
View File
@@ -76,6 +76,7 @@ export interface CatalogRepository {
createApiKey(key: ApiKeyRecord): Promise<void>
listApiKeys(userId?: string): Promise<ApiKeyRecord[]>
findApiKeyByHash(keyHash: string): Promise<ApiKeyRecord | undefined>
updateApiKeyModels(id: string, userId: string, modelIds: string[]): Promise<ApiKeyRecord | undefined>
revokeApiKey(id: string, userId: string, at: string): Promise<boolean>
touchApiKey(id: string, at: string): Promise<void>
}
@@ -215,6 +216,14 @@ export class MemoryCatalogRepository implements CatalogRepository {
return [...this.apiKeys.values()].find((key) => key.keyHash === keyHash)
}
async updateApiKeyModels(id: string, userId: string, modelIds: string[]) {
const key = this.apiKeys.get(id)
if (!key || key.userId !== userId || key.status === 'disabled') return undefined
const updated = { ...key, modelIds: [...modelIds] }
this.apiKeys.set(id, updated)
return updated
}
async revokeApiKey(id: string, userId: string, at: string) {
const key = this.apiKeys.get(id)
if (!key || key.userId !== userId || key.status === 'disabled') return false
@@ -322,7 +331,8 @@ export class CatalogService {
if (!scopes.length || scopes.some((scope) => !/^[a-z][a-z:_-]{1,31}$/.test(scope))) throw new CatalogError('INVALID_KEY_SCOPE', 'Key 权限范围格式无效')
const modelIds = [...new Set(input.modelIds || [])]
for (const modelId of modelIds) {
if (!await this.repository.findModelById(modelId)) throw new CatalogError('MODEL_NOT_FOUND', `模型不存在:${modelId}`, 404)
const model = await this.repository.findModelById(modelId)
if (!model || model.status !== 'active') throw new CatalogError('MODEL_NOT_FOUND', `模型不存在或已下线:${modelId}`, 404)
}
if (input.projectId) {
const project = await this.repository.findProjectById(input.projectId)
@@ -350,6 +360,17 @@ export class CatalogService {
return (await this.repository.listApiKeys(userId)).map(toPublicApiKey)
}
async updateApiKeyModels(userId: string, id: string, inputModelIds: string[]) {
const modelIds = [...new Set(inputModelIds.map((modelId) => modelId.trim()).filter(Boolean))]
for (const modelId of modelIds) {
const model = await this.repository.findModelById(modelId)
if (!model || model.status !== 'active') throw new CatalogError('MODEL_NOT_FOUND', `模型不存在或已下线:${modelId}`, 404)
}
const updated = await this.repository.updateApiKeyModels(id, userId, modelIds)
if (!updated) throw new CatalogError('KEY_NOT_FOUND', 'Key 不存在、已停用或无权修改', 404)
return toPublicApiKey(updated)
}
async revokeApiKey(userId: string, id: string) {
const changed = await this.repository.revokeApiKey(id, userId, new Date().toISOString())
if (!changed) throw new CatalogError('KEY_NOT_FOUND', 'Key 不存在或已停用', 404)
@@ -364,7 +385,7 @@ export class CatalogService {
}
canInvoke(record: ApiKeyRecord, modelId: string) {
return record.status === 'active' && record.scopes.includes('invoke') && (!record.modelIds.length || record.modelIds.includes(modelId))
return record.status === 'active' && record.scopes.includes('invoke') && record.modelIds.includes(modelId)
}
}
+10
View File
@@ -326,6 +326,16 @@ async function route(request: IncomingMessage, response: ServerResponse) {
return
}
const keyModelsMatch = path.match(/^\/api\/keys\/([^/]+)\/models$/)
const keyModelsId = keyModelsMatch?.[1]
if (method === 'POST' && keyModelsId) {
const user = await auth.requireUser(token)
const body = await readJson(request)
const apiKey = await catalog.updateApiKeyModels(user.id, keyModelsId, stringArrayValue(body.modelIds))
send(response, 200, { apiKey })
return
}
const keyRevokeMatch = path.match(/^\/api\/keys\/([^/]+)\/revoke$/)
const keyId = keyRevokeMatch?.[1]
if (method === 'POST' && keyId) {
+14 -2
View File
@@ -38,10 +38,22 @@ test('platform key is returned once, hashed at rest, and can be revoked', async
test('key model allowlist is enforced by the service', async () => {
const catalog = createCatalog()
const created = await catalog.createApiKey('user-1', { modelIds: ['model-mock-text'] })
const created = await catalog.createApiKey('user-1', {})
const unconfigured = await catalog.authenticateApiKey(created.key)
assert.equal(created.apiKey.modelIds[0], 'model-mock-text')
assert.deepEqual(created.apiKey.modelIds, [])
assert.equal(created.apiKey.scopes.includes('invoke'), true)
assert.equal(catalog.canInvoke(unconfigured!, 'model-mock-text'), false)
const updated = await catalog.updateApiKeyModels('user-1', created.apiKey.id, ['model-mock-3d', 'model-mock-3d'])
const configured = await catalog.authenticateApiKey(created.key)
assert.deepEqual(updated.modelIds, ['model-mock-3d'])
assert.equal(catalog.canInvoke(configured!, 'model-mock-3d'), true)
assert.equal(catalog.canInvoke(configured!, 'model-mock-text'), false)
await assert.rejects(
catalog.updateApiKeyModels('user-2', created.apiKey.id, ['model-mock-text']),
(error: unknown) => error instanceof Error && error.message === 'Key 不存在、已停用或无权修改',
)
})
test('personal and project keys can coexist with project ownership checks', async () => {