diff --git a/apps/device-manager/public/installers/nodedc-arnavi-vps-0.2.2.pyz b/apps/device-manager/public/installers/nodedc-arnavi-vps-0.2.2.pyz new file mode 100644 index 0000000..38558b3 Binary files /dev/null and b/apps/device-manager/public/installers/nodedc-arnavi-vps-0.2.2.pyz differ diff --git a/apps/device-manager/server/installer-release.test.mjs b/apps/device-manager/server/installer-release.test.mjs new file mode 100644 index 0000000..c51f6d2 --- /dev/null +++ b/apps/device-manager/server/installer-release.test.mjs @@ -0,0 +1,17 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import { createHash } from 'node:crypto'; + +test('downloadable VPS installer matches its immutable release metadata and deploy size limit', async () => { + const metadata = JSON.parse(await readFile(new URL('../src/b2/installer-release.json', import.meta.url), 'utf8')); + assert.match(metadata.filename, /^nodedc-arnavi-vps-\d+\.\d+\.\d+\.pyz$/); + assert.equal(metadata.environment, 'ubuntu-24.04-amd64'); + assert.match(metadata.sourceCommit, /^[a-f0-9]{40}$/); + assert.equal(metadata.sourceRepository, 'https://git.dcserve.ru/SILVER/NODEDC_MISSION_CORE_ARNAVI-VPS.git'); + const file = await readFile(new URL('../public/installers/' + metadata.filename, import.meta.url)); + assert.equal(file.length, metadata.bytes); + assert.ok(file.length < 16 * 1024 * 1024); + assert.equal(createHash('sha256').update(file).digest('hex'), metadata.sha256); + assert.equal(file.subarray(0, 2).toString(), 'PK'); +}); diff --git a/apps/device-manager/src/DeviceControlViews.tsx b/apps/device-manager/src/DeviceControlViews.tsx index 2e65272..ae195a2 100644 --- a/apps/device-manager/src/DeviceControlViews.tsx +++ b/apps/device-manager/src/DeviceControlViews.tsx @@ -17,6 +17,7 @@ import { } from "@nodedc/ui-react"; import { useB2Inventory } from "./b2/useB2Inventory"; +import { B2AddHost } from "./b2/B2AddHost"; import { B2HostSettings } from "./b2/B2HostSettings"; import { @@ -30,7 +31,6 @@ import { ensureEdge, ensureInfrastructureDeployment, ensureInfrastructureEndpoint, - ensureInfrastructureHost, ensureInfrastructureServiceInstance, ensureRoute, registerAdapterVersion, @@ -308,7 +308,8 @@ export function DeviceControlView({ onCreated={completed} onError={onError} /> - {remote ? remote.reachable ? 'Подключён' : 'Нет связи' : host.lifecycleState === 'suspended' ? 'В архиве' : freshnessLabel(host.telemetry.freshness)}} actions={<> {canManageInfrastructure && (isB2(host) || (!host.managementCredentialConfigured && !topology.serviceInstances.some((item) => item.hostRef === host.hostRef))) ? setSettingsHost(host)}> : null} - + onSelectHost(host.hostRef)}> setExpandedHost(expanded ? null : host.hostRef)}> } /> {expanded ? + {isB2(host) ?
  • : null} {topology.endpoints.filter((item) => item.hostRef === host.hostRef).map((item) =>
  • )} {topology.deployments.filter((item) => item.hostRef === host.hostRef).map((item) =>
  • )} {topology.serviceInstances.filter((item) => item.hostRef === host.hostRef).map((item) =>
  • )}
    - {canManageInfrastructure ?
    : null} + {canManageInfrastructure ?
    {!isB2(host) ? <> : null}
    : null}
    : null} ; })} @@ -1340,35 +1342,6 @@ function AssetBindingDialog({ workspace, ...props }: DialogBaseProps & { workspa ; } -function HostDialog({ projectRef, ...props }: DialogBaseProps & { projectRef: string }) { - const [advanced, setAdvanced] = useState(false); - const [hostKey, setHostKey] = useState(""); - const [displayName, setDisplayName] = useState(""); - const [providerRef, setProviderRef] = useState(""); - const [externalRef, setExternalRef] = useState(""); - const [credentialRef, setCredentialRef] = useState(""); - return { - await ensureInfrastructureHost({ - projectRef, - hostKey, - displayName, - providerRef: providerRef || null, - externalRef: externalRef || null, - managementCredentialRef: credentialRef || null, - lifecycleState: "active", - }); - }}> - - setDisplayName(event.target.value)} required /> - - {advanced ? <> - setProviderRef(event.target.value)} placeholder="provider:beget" /> - setExternalRef(event.target.value)} placeholder="provider-resource:vps-123" /> - setCredentialRef(event.target.value)} placeholder="secret-ref:device-core/host-key" description="Ссылка secret-ref из хранилища сервера." /> - : null} - ; -} - function EndpointDialog({ workspace, initialHostRef, ...props }: DialogBaseProps & { workspace: ProjectWorkspace; initialHostRef: string | null }) { const hosts = workspace.ontology.hosts.filter((host) => host.lifecycleState === "active"); const [hostRef, setHostRef] = useState(initialHostRef || hosts[0]?.hostRef || ""); diff --git a/apps/device-manager/src/b2/B2AddHost.tsx b/apps/device-manager/src/b2/B2AddHost.tsx new file mode 100644 index 0000000..dd1cecf --- /dev/null +++ b/apps/device-manager/src/b2/B2AddHost.tsx @@ -0,0 +1,57 @@ +import { useRef, useState } from 'react'; +import { Button, Icon, Select, SettingsCard, TextAreaField, TextField, Window, WindowFooterActions } from '@nodedc/ui-react'; +import { b2Request } from './api'; +import release from './installer-release.json'; +import './b2.css'; + +const installCommand = `sudo python3 ${release.filename} --device-core`; +const keyCommand = 'sudo python3 /opt/nodedc-mission-vps/current/shared_install.py connection'; +export function B2AddHost({ open, projectRef, onClose, onCreated, onError }: { + open: boolean; projectRef: string; onClose: () => void; onCreated: () => Promise; onError: (error: unknown) => void; +}) { + const [name, setName] = useState('ARNavi VPS'), [connection, setConnection] = useState(''); + const [pending, setPending] = useState(false); + const fileInput = useRef(null); + return + }> +
    { + event.preventDefault(); if (pending) return; + setPending(true); + try { + await b2Request(projectRef, '', 'register-host', { name: name.trim(), connection }); + setConnection(''); await onCreated(); + } catch (error) { onError(error); } finally { setPending(false); } + }}> + { + const file = event.currentTarget.files?.[0]; event.currentTarget.value = ''; if (!file) return; + try { if (file.size > 16384) throw new Error('Файл ключа слишком большой.'); const text = await file.text(); JSON.parse(text); setConnection(text); } + catch { onError(new Error('Не удалось прочитать JSON ключа сервера.')); } + }} /> + setConnection(event.target.value)} /> + + + + +
    ; +} diff --git a/apps/device-manager/src/b2/B2HostSettings.tsx b/apps/device-manager/src/b2/B2HostSettings.tsx index a819054..134f10d 100644 --- a/apps/device-manager/src/b2/B2HostSettings.tsx +++ b/apps/device-manager/src/b2/B2HostSettings.tsx @@ -21,7 +21,8 @@ export function B2HostSettings({ host, workspace, onClose, onChanged, onError }: const [creating, setCreating] = useState(''), [name, setName] = useState(''); const [creationIntent, setCreationIntent] = useState<{ id: string; name: string } | null>(null); const [history, setHistory] = useState([]); - const [issued, setIssued] = useState<{ application: string; value: string } | null>(null); + const [issued, setIssued] = useState<{ applicationId: string; clientId: string; value: string } | null>(null); + const [credentialRows, setCredentialRows] = useState([]); const [confirm, setConfirm] = useState<{ action: string; fields: Record; text: string } | null>(null); const request = (action: string, data: Record = {}, requestId?: string) => b2Request(project.projectRef, host.hostRef, action, data, requestId); const refresh = () => request('status').then(setStatus); @@ -37,8 +38,14 @@ export function B2HostSettings({ host, workspace, onClose, onChanged, onError }: async function run(action: string, data: Record = {}, requestId?: string) { setPending(action); try { - const result = await request<{ connection?: unknown; id?: string }>(action, data, requestId); - if (result.connection) setIssued({ application: String(data.name || name || 'Приложение'), value: JSON.stringify(result.connection, null, 2) }); + const result = await request<{ connection?: { integration_id: string; client_id: string }; id?: string }>(action, data, requestId); + if (result.connection) { + const { integration_id: applicationId, client_id: clientId } = result.connection; + setIssued({ applicationId, clientId, value: JSON.stringify(result.connection, null, 2) }); + setKeyRows((rows) => [...new Set([...rows, applicationId])]); + setCredentialRows((rows) => [...new Set([...rows, clientId])]); + } + if (action === 'key-revoke' && issued?.clientId === data.clientId) setIssued(null); if (action === 'connect') { setConnection(''); setImportOpen(false); setSection('contours'); } setCreating(''); setName(''); setCreationIntent(null); try { await refresh(); await onChanged(); } catch (error) { onError(error); } @@ -57,17 +64,34 @@ export function B2HostSettings({ host, workspace, onClose, onChanged, onError }: const legacy = app.key === 'legacy-mission-core'; const open = keyRows.includes(app.id), active = app.credentials.some((item) => item.enabled); return
  • - setKeyRows(toggle(keyRows, app.id))}> : undefined} /> - {open && !legacy ?
    - {app.credentials.filter((item) => item.enabled || history.includes(app.id)).map((item) =>
  • {item.client_id}} metadata="ID ключа" - status={{item.enabled ? 'Действует' : 'Отозван'}} - actions={item.enabled && canManage ? : undefined} />
  • )} -
    - {app.credentials.some((item) => !item.enabled) ? : null} - {canManage ? : null} -
    + setKeyRows(toggle(keyRows, app.id))}>} /> + {open ?
    + {legacy ? <> +
    Тип подключения
    Прямая привязка Mission Core
    ID приложения
    {app.id}
    +

    Это прежняя привязка сервера, без OAuth-ключа. Выпуск и отзыв ключей ниже относятся к приложениям API v2 и не изменяют эту привязку.

    + : <> + {app.credentials.filter((item) => item.enabled || history.includes(app.id)).map((item) => { + const keyOpen = credentialRows.includes(item.client_id); + const secret = issued?.applicationId === app.id && issued.clientId === item.client_id ? issued : null; + return
  • + {item.enabled ? 'Действует' : 'Отозван'}} + actions={ setCredentialRows(toggle(credentialRows, item.client_id))}>} /> + {keyOpen ?
    +
    ID для сверки
    {item.client_id}
    VPS
    {status?.endpoint}
    + {secret ?
    + +
    +
    :

    Секрет скрыт. ID ключа можно сверить с полем client_id в сохранённом файле подключения.

    } + {item.enabled && canManage ?
    : null} +
    : null} +
  • ; + })}
    +
    + {app.credentials.some((item) => !item.enabled) ? : null} + {canManage ? : null} +
    + }
    : null} ; } @@ -80,10 +104,6 @@ export function B2HostSettings({ host, workspace, onClose, onChanged, onError }: setPending('refresh'); try { await refresh(); } catch (error) { onError(error); } finally { setPending(''); } }}>}>
    - {issued ?
    - -
    -
    : null} {section === 'connection' ? <> {status?.connected ? 'Доступен' : pending === 'load' ? 'Проверка…' : 'Не подключён'}} diff --git a/apps/device-manager/src/b2/api.ts b/apps/device-manager/src/b2/api.ts index 1575d08..5094c35 100644 --- a/apps/device-manager/src/b2/api.ts +++ b/apps/device-manager/src/b2/api.ts @@ -12,6 +12,8 @@ const messages: Record = { b2_request_invalid: 'Проверьте параметры: VPS отклонил запрос.', b2_infrastructure_unavailable: 'Подключение ARNavi пока не настроено на сервере Device Core.', b2_host_unavailable: 'VPS не отвечает. Проверьте доступность сервера.', + b2_host_management_required: 'Нужен ключ администратора VPS из установщика. Ключ приложения подходит только для доступа к его контуру.', + b2_host_identity_mismatch: 'Сервер не совпадает с идентификатором в файле подключения.', b2_host_not_connected: 'Сначала подключите VPS.', b2_access_denied: 'Ключ отозван или не даёт доступа к этому действию.', b2_key_rejected: 'VPS не принял ключ подключения.', diff --git a/apps/device-manager/src/b2/b2.css b/apps/device-manager/src/b2/b2.css index bf04c17..47d4578 100644 --- a/apps/device-manager/src/b2/b2.css +++ b/apps/device-manager/src/b2/b2.css @@ -11,3 +11,7 @@ .b2-tracker-facts { display: grid; grid-template-columns: minmax(8rem, 1fr) minmax(0, 2fr); gap: .65rem 1rem; margin: 0; font-size: var(--nodedc-font-size-sm); } .b2-tracker-facts dt { color: var(--nodedc-text-muted); } .b2-tracker-facts dd { margin: 0; overflow-wrap: anywhere; } + +.b2-onboarding-grid { display: grid; grid-template-columns: minmax(0, 1.15fr) minmax(0, 1fr); gap: var(--nodedc-space-4); align-items: start; } +.b2-onboarding-grid > * { min-width: 0; } +@media (max-width: 760px) { .b2-onboarding-grid { grid-template-columns: minmax(0, 1fr); } } diff --git a/apps/device-manager/src/b2/installer-release.json b/apps/device-manager/src/b2/installer-release.json new file mode 100644 index 0000000..e6df36b --- /dev/null +++ b/apps/device-manager/src/b2/installer-release.json @@ -0,0 +1,10 @@ +{ + "version": "0.2.2", + "filename": "nodedc-arnavi-vps-0.2.2.pyz", + "sha256": "de509d4029a0276d42937a5e5f0aacaf7e0851826ad935c0b6679a9212dec2de", + "bytes": 16126396, + "sourceRepository": "https://git.dcserve.ru/SILVER/NODEDC_MISSION_CORE_ARNAVI-VPS.git", + "sourceCommit": "c67afcd6a1328f00bef4f86f1b1baea2cf277f45", + "manifestSha256": "dd819af361dee4df4b13e769c3b7a9a7f542f07de30364a6a110b9e6dc8c9108", + "environment": "ubuntu-24.04-amd64" +} diff --git a/docs/ARNAVI_VPS_ONBOARDING.md b/docs/ARNAVI_VPS_ONBOARDING.md new file mode 100644 index 0000000..2644d45 --- /dev/null +++ b/docs/ARNAVI_VPS_ONBOARDING.md @@ -0,0 +1,74 @@ +# ARNavi VPS: установка и подключение из Device Core + +## Пользовательский путь + +«Инфраструктура → VPS и хосты → +» открывает один диалог с выбором +поддерживаемого продукта и двумя блоками. Сейчас поддерживается ARNavi VPS. + +1. Скачать установщик 0.2.2, перенести на новый Ubuntu Server 24.04 LTS x86-64. +2. В терминале **этого VPS** выполнить + `sudo python3 nodedc-arnavi-vps-0.2.2.pyz --device-core`. + Установщик запрашивает публичный IP/домен. Требуются 19443/TCP для API и + 9922/TCP для трекеров на VPS; это не порты Synology. +3. В том же терминале выполнить + `sudo python3 /opt/nodedc-mission-vps/current/shared_install.py connection`. + Это чтение уже созданного закрытого JSON подключения, а не выпуск ещё одного ключа. +4. Вставить JSON или загрузить его файлом во второй блок Device Core, + указать название и нажать «Подключить VPS». + +Сервер проверяет полномочия пользователя, TLS fingerprint, identity VPS и +доступ администратора **до** создания записи. Ключ отдельного приложения +не подходит для регистрации VPS. Повторное подключение того же сервера в +том же проекте использует существующую запись. Секрет сохраняется только +в закрытом хранилище Core, не в журнале аудита. + +Установщик в режиме `--device-core` создаёт администратора без фиктивного +Mission Core и без заранее выдуманных контуров. Контуры связываются с уже +существующими проектами Device Core через настройки VPS. Существующий VPS +с прямой привязкой Mission Core этот режим менять отказывается: для него +нужен ранее экспортированный ключ администратора, не повторная установка. + +## Ключи приложений + +Настройки VPS → Контуры → нужный проект → Приложения и ключи. +Выпущенный JSON появляется внутри соответствующей строки ключа. Его нужно +импортировать в приложение, реализующее ARNavi API v2; он содержит endpoint, +TLS fingerprint и OAuth client credentials. Создание ключа само по себе не +подключает и не запускает другое приложение. Для отдельного приложения +создаётся отдельная интеграция в том же контуре. + +Полный секрет доступен один раз. После скрытия/закрытия остаётся `client_id` +для сверки с сохранённым JSON, состояние и отзыв. Перевыпуск явно предупреждает +об отключении предыдущего ключа. Отозванные ключи доступны в истории. +Строка прямой привязки Mission Core v1 раскрывает её тип и ID; это не OAuth +credential и кнопка отзыва ключа v2 не должна притворяться её отключением. + +## Инфраструктурный реестр + +Для подключённого ARNavi VPS строка содержит настройки, круглую кнопку +мониторинга и раскрытие сведений. «В архив» обратимо скрывает локальную запись, +не удаляет VPS. Ручные действия «Адрес», «Развёртывание», «Сервис» оставлены +для общего инфраструктурного реестра, но не предлагаются в обычном ARNavi +сценарии. Они регистрируют метаданные, не устанавливают ПО: сервис требует +записи развёртывания именно выбранного хоста. + +## Происхождение скачиваемого файла + +Исходный сервер остаётся в отдельном репозитории +`SILVER/NODEDC_MISSION_CORE_ARNAVI-VPS`, commit +`c67afcd6a1328f00bef4f86f1b1baea2cf277f45`. Device Core раздаёт только +неизменяемый официальный установщик из `public/installers`. +Метаданные в `src/b2/installer-release.json`; тест проверяет размер и SHA-256. + +Сборка: `scripts/build_vps_host.py` отдельного VPS-репозитория с закреплённым +Hydra 26.2.0 archive. Две сборки дали одинаковый SHA-256: +`de509d4029a0276d42937a5e5f0aacaf7e0851826ad935c0b6679a9212dec2de`. +Размер 16126396 байт, ниже лимита одного файла канонического deploy artifact. +Для обновления скачать/собрать новый проверенный релиз в VPS-репозитории, +опубликовать его commit, заменить asset и metadata вместе и пройти CI. +Нельзя редактировать содержимое PYZ в Device Core или переписывать старый релиз. + +303 серверных теста покрывают пустое состояние, отдельный bootstrap, +изоляцию контуров, отказ смены режима и прежнюю привязку. Полная установка +0.2.2 на чистую Ubuntu в этой задаче **не выполнялась**. Действующий VPS +остаётся на 0.2.1. Прохождение тестов не является актом приёмки новой машины. diff --git a/services/device-control-core/src/b2/infrastructure.mjs b/services/device-control-core/src/b2/infrastructure.mjs index 23f7e1a..5f83160 100644 --- a/services/device-control-core/src/b2/infrastructure.mjs +++ b/services/device-control-core/src/b2/infrastructure.mjs @@ -32,6 +32,66 @@ export class B2Infrastructure { this.clients.set(source.secret_ref, client); return client; } + async verifyConnection(input) { + let value; + try { value = typeof input === 'string' ? JSON.parse(input) : input; } + catch { throw b2Error('b2_connection_invalid'); } + const pkg = connectionPackage(value); + const remote = this.clientFactory(pkg); + const identity = await remote.call('/v2/identity'); + if (identity.host_id !== pkg.host_id) throw b2Error('b2_host_identity_mismatch', 409); + const status = await remote.call(pkg.authority === 'host' ? '/v2/management' : '/v2/contours'); + if (pkg.authority === 'host' && status.host_id !== pkg.host_id) throw b2Error('b2_host_identity_mismatch', 409); + return pkg; + } + async saveSource(db, project, pkg) { + const secret = await this.secrets.save(pkg); + const saved = (await db.query(`insert into device_b2_hosts + (id,owner_scope_id,remote_host_id,endpoint,fingerprint,integration_id,authority,secret_ref) + values($1,$2,$3,$4,$5,$6,$7,$8) + on conflict(owner_scope_id,remote_host_id) do update set + secret_ref=excluded.secret_ref,revision=device_b2_hosts.revision+1,updated_at=now() + where device_b2_hosts.integration_id=excluded.integration_id + and device_b2_hosts.endpoint=excluded.endpoint and device_b2_hosts.fingerprint=excluded.fingerprint + and device_b2_hosts.authority=excluded.authority returning id`, + [randomUUID(), project.owner_scope_id, pkg.host_id, pkg.endpoint, pkg.fingerprint, pkg.integration_id, pkg.authority, secret])).rows[0]; + if (!saved) throw b2Error('b2_connection_identity_conflict', 409); + return saved; + } + async registerHost(actor, input, requestId) { + fields(input, ['connection', 'name']); + const projectId = ref(input.projectRef, 'project'); + if (typeof input.name !== 'string' || !input.name.trim() || input.name.length > 160) throw b2Error('b2_name_invalid'); + const db = await this.pool.connect(); + try { + await db.query('begin'); + const project = await findProjectWithCapability(db, actor, projectId, 'infrastructure.manage'); + assertActorCanManageOwnerScope(actor, { scopeKind: project.scope_kind, ownerRef: project.owner_ref }); + await findProjectWithCapability(db, actor, projectId, 'credential.manage'); + // A rejected key never leaves an empty host in the user's registry. + const pkg = await this.verifyConnection(input.connection); + if (pkg.authority !== 'host') throw b2Error('b2_host_management_required', 403); + await db.query('select pg_advisory_xact_lock(hashtextextended($1,0))', [project.owner_scope_id + ':' + pkg.host_id]); + const saved = await this.saveSource(db, project, pkg); + const existing = (await db.query(`select h.host_key from device_b2_host_views v + join device_infrastructure_hosts h on h.id=v.host_id + where v.source_id=$1 and v.project_id=$2`, [saved.id, projectId])).rows[0]; + const registered = await applyOntologyManagementCommand(db, { actor, commandKind: 'infrastructure_host.ensure', + command: normalizeOntologyManagementCommand('infrastructure_host.ensure', { + projectRef: input.projectRef, hostKey: existing?.host_key || `b2-${saved.id}`, + displayName: input.name.trim(), providerRef: null, externalRef: pkg.host_id, + managementCredentialRef: null, lifecycleState: 'active', + }) }); + const hostRef = registered.host.hostRef; + await db.query(`insert into device_b2_host_views(host_id,project_id,owner_scope_id,source_id) + values($1,$2,$3,$4) on conflict(host_id) do nothing`, [ref(hostRef, 'host'), projectId, project.owner_scope_id, saved.id]); + await db.query(`insert into device_audit_events(id,event_type,actor_ref,payload,project_id) + values($1,$2,$3,$4::jsonb,$5)`, [randomUUID(), 'b2.register-host', actor.userRef, + JSON.stringify({ projectRef: input.projectRef, hostRef, requestId }), projectId]); + await db.query('commit'); + return { connected: true, hostRef, endpoint: pkg.endpoint, authority: pkg.authority }; + } catch (error) { await db.query('rollback'); throw error; } finally { db.release(); } + } async inventory(actor, input) { fields(input, []); const projectId = ref(input.projectRef, 'project'); @@ -105,6 +165,7 @@ export class B2Infrastructure { return remote.call(`/v2/contours/${contourId}/devices/${deviceId}/settings`, request); } async execute(actor, input, requestId) { + if (input.action === 'register-host') return this.registerHost(actor, input, requestId); if (input.action === 'inventory') return this.inventory(actor, input); if (input.action === 'tracker') return this.tracker(actor, input); const projectId = ref(input.projectRef, 'project'); @@ -138,16 +199,7 @@ export class B2Infrastructure { if (identity.host_id !== pkg.host_id) throw b2Error('b2_host_identity_mismatch', 409); const status = pkg.authority === 'host' ? await remote.call('/v2/management') : await remote.call('/v2/contours'); if (pkg.authority === 'host' && status.host_id !== pkg.host_id) throw b2Error('b2_host_identity_mismatch', 409); - const secret = await this.secrets.save(pkg); - const saved = (await db.query(`insert into device_b2_hosts - (id,owner_scope_id,remote_host_id,endpoint,fingerprint,integration_id,authority,secret_ref) - values($1,$2,$3,$4,$5,$6,$7,$8) - on conflict(owner_scope_id,remote_host_id) do update set - secret_ref=excluded.secret_ref,revision=device_b2_hosts.revision+1,updated_at=now() - where device_b2_hosts.integration_id=excluded.integration_id - and device_b2_hosts.endpoint=excluded.endpoint and device_b2_hosts.fingerprint=excluded.fingerprint - and device_b2_hosts.authority=excluded.authority returning id`, - [randomUUID(), project.owner_scope_id, pkg.host_id, pkg.endpoint, pkg.fingerprint, pkg.integration_id, pkg.authority, secret])).rows[0]; + const saved = await this.saveSource(db, project, pkg); if (!saved) throw b2Error('b2_connection_identity_conflict', 409); await db.query(`insert into device_b2_host_views(host_id,project_id,owner_scope_id,source_id) values($1,$2,$3,$4) on conflict(host_id) do nothing`, [hostId, projectId, project.owner_scope_id, saved.id]); diff --git a/services/device-control-core/test/b2-infrastructure.test.mjs b/services/device-control-core/test/b2-infrastructure.test.mjs index d900394..f3e3644 100644 --- a/services/device-control-core/test/b2-infrastructure.test.mjs +++ b/services/device-control-core/test/b2-infrastructure.test.mjs @@ -264,3 +264,42 @@ test('tracker settings keep project and contour authority across remote calls', await assert.rejects(service.execute(actor,input), /b2_access_denied/); assert.equal(calls.length,2); }); + +test('VPS onboarding rejects invalid or application-only credentials without creating a host', async () => { + for (const input of ['bad-json', JSON.stringify({ ...pkg, authority: 'contours' }), JSON.stringify(pkg)]) { + const repo = repository(); let secrets = 0; + const service = new B2Infrastructure({ pool: repo.pool, + secrets: { save: async () => { secrets += 1; return 'private-ref'; } }, + clientFactory: () => ({ call: async (path) => path === '/v2/identity' ? { host_id: input === JSON.stringify(pkg) ? 'foreign-host' : pkg.host_id } : { items: [] } }) }); + await assert.rejects(service.execute(actor, { action: 'register-host', projectRef: `project:${projectId}`, name: 'VPS', connection: input }, 'a'.repeat(32))); + assert.equal(secrets, 0); assert.deepEqual(repo.writes, []); + } +}); + +test('VPS onboarding reuses the project host and audits no credential material', async () => { + const queries = []; let existing = false; + const base = repository(); const db = await base.pool.connect(); const original = db.query.bind(db); + db.query = async (sql, values) => { + queries.push({ sql, values }); + if (sql.includes('pg_advisory_xact_lock')) return { rows: [] }; + if (sql.startsWith('insert into device_b2_hosts')) return { rows: [{ id: source.id }] }; + if (sql.startsWith('select h.host_key')) return { rows: existing ? [{ host_key: 'b2-existing-project-view' }] : [] }; + if (sql.startsWith('insert into device_infrastructure_hosts')) return { rows: [{ id: hostId, host_key: values[3], + display_name: values[4], project_id: projectId, owner_scope_id: ownerId, lifecycle_state: 'active', created: !existing }] }; + if (sql.startsWith('insert into device_b2_host_views')) { existing = true; return { rows: [] }; } + return original(sql, values); + }; + const service = new B2Infrastructure({ pool: base.pool, secrets: { save: async () => 'private-ref' }, + clientFactory: () => ({ call: async () => ({ host_id: pkg.host_id }) }) }); + const input = { action: 'register-host', projectRef: `project:${projectId}`, name: 'VPS', connection: JSON.stringify(pkg) }; + const first = await service.execute(actor, input, 'a'.repeat(32)); + const second = await service.execute(actor, input, 'b'.repeat(32)); + assert.equal(first.hostRef, second.hostRef); + assert.equal(queries.filter((q) => q.sql === 'commit').length, 2); + const hosts = queries.filter((q) => q.sql.startsWith('insert into device_infrastructure_hosts')); + assert.equal(hosts[0].values[3], `b2-${source.id}`); + assert.equal(hosts[1].values[3], 'b2-existing-project-view'); + const audit = queries.filter((q) => q.sql.includes('insert into device_audit_events')); + assert.ok(audit.length > 0); + assert.ok(!JSON.stringify(audit).includes(pkg.client_secret)); +});