Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions docs/gemini-host.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Gemini 宿主机候选

「导入 → Gemini」管理宿主机环境。「虚拟机」页的 Gemini 宿主环境区展示相同的数据,不创建 VM、Docker 槽、VM 调度记录或 `vm.json`。默认不启用,仅管理员可操作。服务运行在 Linux amd64 宿主,Docker 控制面通过只读挂载的 Unix socket 目录连接;ARM64 和远端集群不受支持。
「导入 → Gemini」创建宿主机环境。「虚拟机」页将 Gemini 账号显示在同一机架和列表中,管理员可按平台筛选,并从账号详情授权或刷新。不创建 VM、Docker 槽、VM 调度记录或 `vm.json`。默认不启用,仅管理员可操作。服务运行在 Linux amd64 宿主,Docker 控制面通过只读挂载的 Unix socket 目录连接;ARM64 和远端集群不受支持。

## 启用服务与自动安装

Expand All @@ -19,4 +19,4 @@
- `0.3.0-rc.1` 已用真实 `agy` 验证受管 PTY 和隔离回环上游 SSE。自动安装和数据读取可用本地夹具验证;真实 Google 换票和 OAuth 推理未验收,不标记推理就绪。
- 可使用非 root 账号运行 `bash test/deploy/gemini-host-egress-smoke.sh /absolute/path/kin-egress`,在一次性 Linux 命名空间用 `iptables` 模拟 Docker 的默认转发丢弃策略,检查选定 SOCKS5 的透明转发、转发器退出后失败和网络清理。该测试不访问 Google 或主机代理池。
- 有测试签名产物时,可在带 Node 和 Python 的一次性 Linux amd64 容器内以 root 运行 `bash test/deploy/gemini-host-install-smoke.sh /path/to/signed-payload /path/to/public-key`。禁用容器网络即可验证 Unix socket 启动、签名失败不建环境、首次创建自动安装和重启持久化。
- `/v1/gemini/sessions` 命名空间保持付费关闭,鉴权后返回 `gemini_official_billing_unavailable`,不分配会话或扣费。没有逐回合可核销的官方金额,不启用 Gemini 专用调用密钥、对外推理或美元结算;不把订阅等级、Token 数或余额变化当成实扣凭证。
- 管理员可生成 `Gemini · CRAGAnti` 专用密钥,只能访问 Gemini 会话入口及密钥查询,不会落入 Claude、Codex 或 API 直连。当前二进制的推理桥仅验收过 Gemini API Key provider;即使 Google OAuth 已授权,`/v1/gemini/sessions` 也会返回 `gemini_runtime_not_supported`,不会分配会话或扣费。对外推理还需支持 OAuth 的载荷及逐回合可核销的官方结算;不把订阅等级、Token 数或余额变化当成实扣凭证。
25 changes: 18 additions & 7 deletions src/lib/admin/key-scope.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -43,14 +43,15 @@ export function parseAllowedVms(value) {
]
}

/** null when the value is present but not all/anthropic/openai. Empty uses fallback. */
/** Empty uses fallback; an unsupported platform returns null. */
export function normalizeGroupType(value, { fallback = 'all' } = {}) {
if (value == null || value === '') return fallback
if (value === 'pool') return null
const v = String(value).trim().toLowerCase()
if (v === 'all') return 'all'
if (v === 'anthropic' || v === 'claude') return 'anthropic'
if (v === 'openai' || v === 'gpt' || v === 'codex') return 'openai'
if (v === 'gemini') return 'gemini'
return null
}

Expand All @@ -71,10 +72,10 @@ function poolIdOf(value) {
export function keyScopeFromRecord(rec) {
if (!rec) return { group_type: 'all', allowed_vms: [], vm_pool_id: null }
const group_type = normalizeGroupType(rec.group_type) || 'all'
const vm_pool_id = poolIdOf(rec.vm_pool_id)
const vm_pool_id = group_type === 'gemini' ? null : poolIdOf(rec.vm_pool_id)
return {
group_type,
allowed_vms: vm_pool_id || group_type === 'all' ? [] : parseAllowedVms(rec.allowed_vms),
allowed_vms: vm_pool_id || group_type === 'all' || group_type === 'gemini' ? [] : parseAllowedVms(rec.allowed_vms),
vm_pool_id,
}
}
Expand Down Expand Up @@ -109,6 +110,7 @@ export function vmPoolDenial(scope) {
}

export function keyAllowsVm(scope, vm) {
if (scope?.group_type === 'gemini') return false
if (scope?.vm_pool_id) {
if (scope.vm_pool_error) return false
if (!vm?.id || !(scope.allowed_vms || []).includes(vm.id)) return false
Expand All @@ -133,14 +135,14 @@ export function normalizeKeyScope(input = {}, { partial = false, current = null,
const hasType = input.group_type != null && input.group_type !== ''
const hasVms = input.allowed_vms != null
const hasPool = Object.prototype.hasOwnProperty.call(input, 'vm_pool_id')
if (partial && !hasType && !hasVms && !hasPool) return null

const base = current ? keyScopeFromRecord(current) : { group_type: 'all', allowed_vms: [], vm_pool_id: null }
let group_type = !partial && !hasType ? 'all' : base.group_type
if (hasType) {
const parsed = normalizeGroupType(input.group_type, { fallback: null })
if (!parsed) {
throw Object.assign(new Error('group_type 只能是 all、anthropic 或 openai'), { code: 'invalid_group_type' })
throw Object.assign(new Error('group_type 只能是 all、anthropic、openai 或 gemini'), {
code: 'invalid_group_type',
})
}
group_type = parsed
}
Expand All @@ -149,6 +151,15 @@ export function normalizeKeyScope(input = {}, { partial = false, current = null,
String(input.category || current?.category || '')
.trim()
.toLowerCase() === 'api'
if (group_type === 'gemini') {
if (apiMode || (hasVms && parseAllowedVms(input.allowed_vms).length) || (hasPool && input.vm_pool_id)) {
throw Object.assign(new Error('Gemini 密钥只能使用宿主机 OAuth 池,不能绑定 VM、账号池或 API 渠道'), {
code: 'invalid_gemini_key_scope',
})
}
return { group_type, allowed_vms: [], vm_pool_id: null }
}
if (partial && !hasType && !hasVms && !hasPool) return null
let allowed_vms = hasVms ? parseAllowedVms(input.allowed_vms) : !partial && !hasType ? [] : base.allowed_vms
let vm_pool_id = hasPool ? parsePoolId(input.vm_pool_id) : base.vm_pool_id
if (apiMode) {
Expand All @@ -168,7 +179,7 @@ export function normalizeKeyScope(input = {}, { partial = false, current = null,

/** Panel check: every id is a live VM of the chosen platform. Pool membership is checked separately. */
export function assertVmScope(vms, scope) {
if (!scope || scope.group_type === 'all' || scope.vm_pool_id) return []
if (!scope || scope.group_type === 'all' || scope.group_type === 'gemini' || scope.vm_pool_id) return []
const byId = new Map((vms || []).map((vm) => [vm.id, vm]))
for (const id of scope.allowed_vms) {
const vm = byId.get(id)
Expand Down
21 changes: 18 additions & 3 deletions src/lib/admin/panel-routes.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ import { readCatalogSync, syncClaudeCatalog, syncGptCatalog } from './catalog-mo
import { setPriceOverride, listPriceOverrides, syncModelsDev } from './price-catalog.mjs'
import { buildPricing } from './pricing-view.mjs'
import { publicKeyView } from './api-keys.mjs'
import { assertVmScope, normalizeKeyScope } from './key-scope.mjs'
import { assertVmScope, normalizeGroupType, normalizeKeyScope } from './key-scope.mjs'
import {
assertVmPoolExists,
createVmPool,
Expand Down Expand Up @@ -2007,6 +2007,12 @@ export function createPanelHandler(ctx) {
if (req.method === 'POST' && p === '/api/panel/api-keys') {
const body = await readBody(req, API_KEY_BODY_MAX).catch(() => ({}))
const ident = panelIdentity(req)
if (ident.role !== 'admin' && normalizeGroupType(body?.group_type) === 'gemini') {
return json(res, 403, {
ok: false,
error: { code: 'gemini_key_forbidden', message: '只有管理员可以生成 Gemini 密钥' },
})
}
if (ident.role !== 'admin' && body?.vm_pool_id != null && String(body.vm_pool_id).trim() !== '') {
return json(res, 403, {
ok: false,
Expand Down Expand Up @@ -2086,6 +2092,16 @@ export function createPanelHandler(ctx) {
if (denyIfUserMissesKey(req, res, { apiKeyStore, json, keyId: id })) return true
const body = await readBody(req, API_KEY_BODY_MAX).catch(() => ({}))
const ident = panelIdentity(req)
const currentRec = apiKeyStore.getById(id)
if (
ident.role !== 'admin' &&
(normalizeGroupType(body?.group_type) === 'gemini' || currentRec?.group_type === 'gemini')
) {
return json(res, 403, {
ok: false,
error: { code: 'gemini_key_forbidden', message: '只有管理员可以修改 Gemini 密钥' },
})
}
if (ident.role !== 'admin' && body?.vm_pool_id != null && String(body.vm_pool_id).trim() !== '') {
return json(res, 403, {
ok: false,
Expand All @@ -2100,15 +2116,14 @@ export function createPanelHandler(ctx) {
}
try {
const input = normalizePanelApiKeyInput(body || {}, req)
const currentRec = apiKeyStore.getById(id)
const isApi = isApiCategory(body?.category ?? currentRec?.category)
if (Object.hasOwn(input, 'api_endpoint_id')) {
input.api_endpoint_id = validateKeyEndpoint(input.api_endpoint_id, isApi, currentRec?.api_endpoint_id)
}
const scopeInput = {
group_type: body?.group_type,
allowed_vms: body?.allowed_vms,
...(isApi ? { category: 'api' } : {}),
category: isApi ? 'api' : 'oauth',
}
if (ident.role === 'admin' && Object.prototype.hasOwnProperty.call(body || {}, 'vm_pool_id')) {
scopeInput.vm_pool_id = body.vm_pool_id
Expand Down
22 changes: 19 additions & 3 deletions src/lib/gemini/routes.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,13 @@ export function isGeminiPublicPath(value) {
return value === PUBLIC_PATH || value.startsWith(`${PUBLIC_PATH}/`)
}

export function geminiKeyAllowsPath(pathname, method) {
return (
isGeminiPublicPath(pathname) ||
(method === 'GET' && ['/models', '/v1/models', '/v1/usage', '/v1/me/quota', '/v1/me/usage'].includes(pathname))
)
}

function hostError(code, status = 503) {
return Object.assign(new Error(code), { code, status })
}
Expand Down Expand Up @@ -327,13 +334,22 @@ export function createGeminiPanelHandler({
}
}

export function geminiBillingUnavailable(json, res) {
export function handleGeminiPublic(req, res, json) {
res.setHeader('Cache-Control', 'no-store')
if (req.apiKeyKind !== 'managed' || req.apiKeyRecord?.group_type !== 'gemini') {
return json(res, 403, {
error: {
type: 'permission_error',
code: 'gemini_key_required',
message: 'This endpoint requires a dedicated Gemini API key.',
},
})
}
return json(res, 503, {
error: {
type: 'service_unavailable',
code: 'gemini_official_billing_unavailable',
message: 'Gemini paid inference is disabled until verified per-turn official settlement is available.',
code: 'gemini_runtime_not_supported',
message: 'The current CRAGAnti payload does not support Google OAuth inference.',
},
})
}
20 changes: 18 additions & 2 deletions src/server.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import http from 'node:http'
import fs from 'node:fs'
import path from 'node:path'
import { loadConfig, reloadActiveVm, routingConfigFile } from './lib/core/config.mjs'
import { geminiBillingUnavailable, isGeminiPublicPath } from './lib/gemini/routes.mjs'
import { geminiKeyAllowsPath, handleGeminiPublic, isGeminiPublicPath } from './lib/gemini/routes.mjs'
import {
extractApiKey,
timingSafeEqualStr,
Expand Down Expand Up @@ -822,6 +822,21 @@ function requireAuth(req, res, { keyGate = true, buyer = false, optionalBuyer =
}),
)
}
if (
managed.record.group_type === 'gemini' &&
!geminiKeyAllowsPath(parseRequestUrl(req)?.pathname || '', req.method)
) {
return rejectAuth(
req,
res,
makeError({
type: ErrorType.PERMISSION,
code: 'key_group_mismatch',
message: 'This key can only call Gemini endpoints.',
status: 403,
}),
)
}
const gate = keyGate ? apiKeyStore.canAccept(managed.record) : { ok: true }
if (!gate.ok) {
const type =
Expand Down Expand Up @@ -1325,6 +1340,7 @@ const server = http.createServer(async (req, res) => {
if (req.method === 'GET' && (p === '/v1/models' || p === '/models')) {
if (!requireAuth(req, res)) return
const groupType = keyScopeFromRequest(req).group_type
if (groupType === 'gemini') return json(res, 200, { object: 'list', data: [] })
if (resolveInferenceBackend(req) === 'api') {
return json(res, 200, filterModelCatalogForKey(apiScheduler.catalog(apiScheduleScope(req, groupType)), req))
}
Expand Down Expand Up @@ -1356,7 +1372,7 @@ const server = http.createServer(async (req, res) => {

if (isGeminiPublicPath(p)) {
if (!requireAuth(req, res)) return
return geminiBillingUnavailable(json, res)
return handleGeminiPublic(req, res, json)
}

if (req.method === 'POST' && (p === '/v1/chat/completions' || p === '/chat/completions')) {
Expand Down
42 changes: 42 additions & 0 deletions test/e2e/api-keys.e2e.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,16 @@ test('real admin and user sessions cannot list or operate each other personal ke
const userKey = await personal(userCookie, 'POST', '/api/panel/api-keys', { name: 'user-key' })
assert.equal(userKey.status, 201, userKey.text)
assert.equal(userKey.json.item.user_id, userId)
const deniedGeminiKey = await personal(userCookie, 'POST', '/api/panel/api-keys', {
name: 'tenant-gemini',
group_type: 'Gemini',
})
assert.equal(deniedGeminiKey.status, 403)
assert.equal(deniedGeminiKey.json.error.code, 'gemini_key_forbidden')
const deniedGeminiPatch = await personal(userCookie, 'PATCH', `/api/panel/api-keys/${userKey.json.item.id}`, {
group_type: 'gemini',
})
assert.equal(deniedGeminiPatch.status, 403)
const adminKey = await personal(adminCookie, 'POST', '/api/panel/api-keys', { name: 'admin-key', user_id: userId })
assert.equal(adminKey.status, 201, adminKey.text)
assert.ok(adminKey.json.item.user_id)
Expand Down Expand Up @@ -102,6 +112,38 @@ test('panel creates managed key; key can call /v1/messages', async () => {
}
})

test('Gemini keys persist, remain isolated and fail closed without an OAuth runtime', async () => {
const gw = await startGateway()
try {
const created = await api(gw, 'POST', '/api/panel/api-keys', { body: { name: 'host-oauth', group_type: 'gemini' } })
assert.equal(created.status, 201, created.text)
const { id, key } = created.json.item
assert.equal(created.json.item.group_type, 'gemini')
const updated = await api(gw, 'PATCH', `/api/panel/api-keys/${id}`, { body: { rpm: 2 } })
assert.equal(updated.status, 200, updated.text)
assert.equal(updated.json.item.group_type, 'gemini')
const wrongCategory = await api(gw, 'PATCH', `/api/panel/api-keys/${id}`, { body: { category: 'api' } })
assert.equal(wrongCategory.status, 400, wrongCategory.text)
assert.equal(wrongCategory.json.error.code, 'invalid_gemini_key_scope')
const headers = { authorization: `Bearer ${key}` }

const wrongKey = await api(gw, 'POST', '/v1/gemini/sessions', { body: {} })
assert.equal(wrongKey.status, 403, wrongKey.text)
assert.equal(wrongKey.json.error.code, 'gemini_key_required')
const unavailable = await api(gw, 'POST', '/v1/gemini/sessions', { headers, body: {} })
assert.equal(unavailable.status, 503, unavailable.text)
assert.equal(unavailable.json.error.code, 'gemini_runtime_not_supported')
const models = await api(gw, 'GET', '/v1/models', { headers })
assert.equal(models.status, 200, models.text)
assert.deepEqual(models.json.data, [])
const messages = await api(gw, 'POST', '/v1/messages', { headers, body: {} })
assert.equal(messages.status, 403, messages.text)
assert.equal(messages.json.error.code, 'key_group_mismatch')
} finally {
await gw.stop()
}
})

test('panel re-reveals a used key; rotate swaps the plaintext', async () => {
const gw = await startGateway({ mockText: 'copyable' })
try {
Expand Down
31 changes: 28 additions & 3 deletions test/unit/gemini-host.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ import { authorizePanelRoute } from '../../src/lib/admin/panel-acl.mjs'
import { AGY_SHA256, installGeminiPayload, readSignedGeminiManifest } from '../../src/lib/gemini/payload.mjs'
import {
createGeminiPanelHandler,
geminiBillingUnavailable,
geminiKeyAllowsPath,
handleGeminiPublic,
officialGeminiAuthUrl,
} from '../../src/lib/gemini/routes.mjs'

Expand Down Expand Up @@ -173,9 +174,33 @@ test('official login links are validated and code is returned only to its select
})

test('missing official settlement cannot be enabled by a host response or a paid route request', () => {
const result = geminiBillingUnavailable((_res, status, body) => ({ status, body }), { setHeader() {} })
const respond = (_res, status, body) => ({ status, body })
const res = { setHeader() {} }
for (const group_type of ['all', 'anthropic', 'openai']) {
const denied = handleGeminiPublic({ apiKeyKind: 'managed', apiKeyRecord: { group_type } }, res, respond)
assert.equal(denied.status, 403)
assert.equal(denied.body.error.code, 'gemini_key_required')
}
assert.equal(handleGeminiPublic({ apiKeyKind: 'master' }, res, respond).status, 403)
const result = handleGeminiPublic({ apiKeyKind: 'managed', apiKeyRecord: { group_type: 'gemini' } }, res, respond)
assert.equal(result.status, 503)
assert.equal(result.body.error.code, 'gemini_official_billing_unavailable')
assert.equal(result.body.error.code, 'gemini_runtime_not_supported')
})

test('Gemini keys cannot reach other inference endpoints via HTTP or WebSocket', () => {
for (const route of [
'/v1/responses',
'/responses',
'/v1/chat/completions',
'/v1/messages',
'/v1/images/edits',
'/admin/models/refresh',
]) {
assert.equal(geminiKeyAllowsPath(route, 'POST'), false)
assert.equal(geminiKeyAllowsPath(route, 'GET'), false)
}
assert.equal(geminiKeyAllowsPath('/v1/gemini/sessions', 'POST'), true)
assert.equal(geminiKeyAllowsPath('/v1/me/quota', 'GET'), true)
})

test('host installer refuses an unsigned manifest and never activates damaged payload members', async (t) => {
Expand Down
16 changes: 16 additions & 0 deletions test/unit/key-scope.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -89,3 +89,19 @@ test('api category allows anthropic and openai groups without VMs', () => {
const patched = normalizeKeyScope({ group_type: 'openai' }, { partial: true, current })
assert.deepEqual(patched, { group_type: 'openai', allowed_vms: [], vm_pool_id: null })
})

test('Gemini is a dedicated OAuth scope and cannot inherit VM or API access', () => {
const scope = normalizeKeyScope({ group_type: ' Gemini ' })
assert.deepEqual(scope, { group_type: 'gemini', allowed_vms: [], vm_pool_id: null })
assert.deepEqual(keyScopeFromRecord({ ...scope, allowed_vms: [codex.id], vm_pool_id: 'pool_abcd1234' }), scope)
assert.equal(keyAllowsVm({ ...scope, allowed_vms: [codex.id] }, codex), false)
assert.throws(() => normalizeKeyScope({ group_type: 'gemini', allowed_vms: [codex.id] }), {
code: 'invalid_gemini_key_scope',
})
assert.throws(() => normalizeKeyScope({ group_type: 'gemini', vm_pool_id: 'pool_abcd1234' }), {
code: 'invalid_gemini_key_scope',
})
assert.throws(() => normalizeKeyScope({ category: 'api' }, { partial: true, current: scope }), {
code: 'invalid_gemini_key_scope',
})
})
6 changes: 3 additions & 3 deletions web/src/components/platform-chip.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,10 @@ export function PlatformChip({
className,
}: {
vm?: Vm
kind?: VmKind
kind?: VmKind | 'gemini'
className?: string
}) {
const resolved = kind ?? (vm ? vmKindOf(vm) : 'claude')
const resolved = kind ?? (vm?.gemini ? 'gemini' : vmKindOf(vm))
const gpt = resolved === 'codex'
return (
<span
Expand All @@ -35,7 +35,7 @@ export function PlatformChip({
className
)}
>
{platformLabelOf(resolved)}
{resolved === 'gemini' ? 'Gemini' : platformLabelOf(resolved)}
</span>
)
}
Expand Down
Loading
Loading