Complete shared contour project linking and scoped application onboarding

This commit is contained in:
DCCONSTRUCTIONS
2026-10-01 14:47:07 +03:00
parent 1b3001dfa1
commit 5200159d0b
18 changed files with 883 additions and 75 deletions
@@ -22,6 +22,10 @@ export class B2Infrastructure {
this.pool = pool; this.secrets = secrets; this.clientFactory = clientFactory;
this.clients = new Map();
}
async supportsSharedProjects(db) {
const row = (await db.query("select obj_description('device_b2_contour_links'::regclass) as marker")).rows[0];
return row?.marker === 'nodedc.device-b2-shared-contours/v1';
}
async clientFor(source) {
// Private file refs are immutable. Re-importing/replacing a key creates a
// new ref and therefore cannot reuse the previous OAuth token cache.
@@ -272,44 +276,57 @@ export class B2Infrastructure {
fields(input, []);
const value = source.authority === 'host' ? await remote.call('/v2/management') : await remote.call('/v2/contours');
result = { connected: true, endpoint: source.endpoint, authority: source.authority,
sharedProjects: await this.supportsSharedProjects(db),
contours: value.contours || value.items, applications: value.applications || [],
links: links.map((link) => ({ contourId: link.contour_id, projectRef: `project:${link.project_id}` })) };
} else if (action === 'link' || action === 'project-connect') {
fields(input, action === 'link' ? ['contourId', 'targetProjectRef'] : ['targetProjectRef']);
} else if (['link', 'unlink', 'project-connect', 'contour-connect'].includes(action)) {
fields(input, action === 'contour-connect' ? ['name', 'targetProjectRef'] : action === 'project-connect' ? ['targetProjectRef'] : ['contourId', 'targetProjectRef']);
const targetId = ref(input.targetProjectRef || input.projectRef, 'project');
const target = await findProjectWithCapability(db, actor, targetId, 'infrastructure.manage');
if (target.owner_scope_id !== project.owner_scope_id) throw b2Error('b2_company_mismatch', 403);
let contour;
if (action === 'project-connect') {
if (source.authority !== 'host') throw b2Error('b2_host_management_required', 403);
const linked = links.filter((link) => link.project_id === targetId);
if (linked.length > 1) throw b2Error('b2_conflict', 409);
// Stable project identity makes a retry recover the same contour.
contour = linked[0]?.contour_id || (await remote.call('/v2/management/contours', {
key: 'dc-' + targetId, name: target.name,
})).id;
} else contour = opaque(input.contourId);
const permitted = await remote.call('/v2/contours');
if (!permitted.items.some((item) => item.id === contour)) throw b2Error('b2_access_denied', 403);
const current = links.find((link) => link.contour_id === contour);
if (current && current.project_id !== targetId) throw b2Error('b2_contour_already_linked', 409);
await db.query(`insert into device_b2_contour_links(source_id,contour_id,project_id,owner_scope_id,created_by_ref)
values($1,$2,$3,$4,$5) on conflict(source_id,contour_id) do nothing`,
[source.id, contour, targetId, project.owner_scope_id, actor.userRef]);
if (targetId !== projectId) {
const related = (await db.query('select host_id from device_b2_host_views where source_id=$1 and project_id=$2', [source.id, targetId])).rows[0];
if (!related) {
const registered = await applyOntologyManagementCommand(db, { actor, commandKind: 'infrastructure_host.ensure',
command: normalizeOntologyManagementCommand('infrastructure_host.ensure', {
projectRef: `project:${targetId}`, hostKey: `b2-${source.id}`, displayName: host.display_name,
providerRef: host.provider_ref, externalRef: source.remote_host_id,
managementCredentialRef: null, lifecycleState: 'active',
}) });
await db.query(`insert into device_b2_host_views(host_id,project_id,owner_scope_id,source_id)
values($1,$2,$3,$4)`, [ref(registered.host.hostRef, 'host'), targetId, project.owner_scope_id, source.id]);
if (action === 'unlink') {
contour = opaque(input.contourId);
await db.query('delete from device_b2_contour_links where source_id=$1 and contour_id=$2 and project_id=$3', [source.id, contour, targetId]);
result = { linked: false, contourId: contour, projectRef: `project:${targetId}` };
} else {
if (action === 'contour-connect') {
if (source.authority !== 'host') throw b2Error('b2_host_management_required', 403);
if (typeof input.name !== 'string' || !input.name.trim() || input.name.length > 160) throw b2Error('b2_name_invalid');
if (!/^[a-f0-9]{32}$/.test(requestId)) throw b2Error('b2_request_invalid');
// Retry a lost response without creating another remote contour.
contour = (await remote.call('/v2/management/contours', { key: 'dc-' + requestId, name: input.name.trim() })).id;
} else if (action === 'project-connect') {
if (source.authority !== 'host') throw b2Error('b2_host_management_required', 403);
const linked = links.filter((link) => link.project_id === targetId);
if (linked.length > 1) throw b2Error('b2_conflict', 409);
// Stable project identity makes a retry recover the same contour.
contour = linked[0]?.contour_id || (await remote.call('/v2/management/contours', {
key: 'dc-' + targetId, name: target.name,
})).id;
} else contour = opaque(input.contourId);
const permitted = await remote.call('/v2/contours');
if (!permitted.items.some((item) => item.id === contour)) throw b2Error('b2_access_denied', 403);
if (links.some((link) => link.contour_id === contour && link.project_id !== targetId)
&& !await this.supportsSharedProjects(db)) throw b2Error('b2_shared_projects_migration_required', 409);
await db.query(`insert into device_b2_contour_links(source_id,contour_id,project_id,owner_scope_id,created_by_ref)
values($1,$2,$3,$4,$5) on conflict do nothing`,
[source.id, contour, targetId, project.owner_scope_id, actor.userRef]);
if (targetId !== projectId) {
const related = (await db.query('select host_id from device_b2_host_views where source_id=$1 and project_id=$2', [source.id, targetId])).rows[0];
if (!related) {
const registered = await applyOntologyManagementCommand(db, { actor, commandKind: 'infrastructure_host.ensure',
command: normalizeOntologyManagementCommand('infrastructure_host.ensure', {
projectRef: `project:${targetId}`, hostKey: `b2-${source.id}`, displayName: host.display_name,
providerRef: host.provider_ref, externalRef: source.remote_host_id,
managementCredentialRef: null, lifecycleState: 'active',
}) });
await db.query(`insert into device_b2_host_views(host_id,project_id,owner_scope_id,source_id)
values($1,$2,$3,$4)`, [ref(registered.host.hostRef, 'host'), targetId, project.owner_scope_id, source.id]);
}
}
result = { linked: true, contourId: contour, projectRef: `project:${targetId}` };
}
result = { linked: true, contourId: contour, projectRef: `project:${targetId}` };
} else if (action === 'devices') {
fields(input, []);
const contours = links.filter((link) => link.project_id === projectId);
@@ -331,13 +348,14 @@ export class B2Infrastructure {
key: input.key, name: input.name, grants: { [opaque(input.contourId)]: 'manage' },
});
} else if (action === 'application-connect') {
fields(input, ['name', 'contourId']);
fields(input, ['name', 'contourId', 'access']);
if (typeof input.name !== 'string' || !input.name.trim() || input.name.length > 160) throw b2Error('b2_name_invalid');
const contour = opaque(input.contourId);
if (!links.some((link) => link.contour_id === contour)) throw b2Error('b2_access_denied', 403);
const access = input.access ?? 'manage';
if (!['read', 'control', 'manage'].includes(access)) throw b2Error('b2_request_invalid');
if (!/^[a-f0-9]{32}$/.test(requestId)) throw b2Error('b2_request_invalid');
const app = await remote.call('/v2/management/applications', {
key: 'app-' + requestId, name: input.name.trim(), grants: { [contour]: 'manage' },
key: 'app-' + requestId, name: input.name.trim(), grants: { [contour]: access },
});
// The VPS reserves issuance before returning a one-time secret. If
// the response is lost, status exposes the app for explicit reissue.
@@ -19,10 +19,11 @@ const actor = { userRef: 'user:operator', hubRole: 'owner', groupRefs: [], owner
const source = { id: '55555555-5555-4555-8555-555555555555', owner_scope_id: ownerId,
remote_host_id: pkg.host_id, endpoint: pkg.endpoint, fingerprint: pkg.fingerprint,
integration_id: pkg.integration_id, authority: pkg.authority, secret_ref: 'private-ref' };
function repository({ role = 'owner', links = [], otherOwner = ownerId } = {}) {
function repository({ role = 'owner', links = [], otherOwner = ownerId, sharedProjects = true } = {}) {
const writes = [];
const db = { release() {}, async query(sql, values) {
if (['begin', 'commit', 'rollback'].includes(sql)) return { rows: [] };
if (sql.includes('obj_description')) return { rows: [{ marker: sharedProjects ? 'nodedc.device-b2-shared-contours/v1' : 'nodedc.device-b2-foundation/v1' }] };
if (sql.includes('from device_projects')) return { rows: [{ id: values[0], owner_scope_id: values[0] === projectId ? ownerId : otherOwner,
name: 'Test project', lifecycle_state: 'active', owner_lifecycle_state: 'active', scope_kind: 'company', owner_ref: 'company:example' }] };
if (sql.includes('from device_project_grants')) return { rows: [{ id: 'grant', principal_kind: 'user', principal_ref: actor.userRef,
@@ -231,10 +232,50 @@ test('application creation and issuance use one server-generated request identit
assert.equal(result.id, app);
assert.ok(result.connection);
assert.equal(JSON.stringify(repo.writes).includes('synthetic'), false);
await assert.rejects(service.execute(actor, { action: 'application-connect', projectRef: `project:${projectId}`, hostRef: `host:${hostId}`, name: 'Other', contourId: 'f'.repeat(32) }, requestId), /b2_access_denied/);
await assert.rejects(service.execute(actor, { action: 'application-connect', projectRef: `project:${projectId}`, hostRef: `host:${hostId}`, name: 'Other', contourId: 'f'.repeat(32), access: 'host' }, requestId), /b2_request_invalid/);
assert.equal(calls.length, 2);
});
test('host catalogue includes external unlinked contours without creating local projects', async () => {
const repo = repository();
const contours = [{ id: 'a'.repeat(32), key: 'external', name: 'External fleet' }];
const service = new B2Infrastructure({ pool: repo.pool, secrets: { read: async () => pkg }, clientFactory: () => ({ call: async () => ({ contours }) }) });
const result = await service.execute(actor, { action: 'status', projectRef: `project:${projectId}`, hostRef: `host:${hostId}` });
assert.deepEqual(result.contours, contours);
assert.deepEqual(result.links, []);
assert.equal(result.sharedProjects, true);
assert.deepEqual(repo.writes, []);
});
test('second project can share a contour after migration and old foundation fails explicitly', async () => {
for (const sharedProjects of [true, false]) {
const contour = 'c'.repeat(32);
const repo = repository({ sharedProjects, links: [{ contour_id: contour, project_id: otherProject }] });
const service = new B2Infrastructure({ pool: repo.pool, secrets: { read: async () => pkg }, clientFactory: () => ({ call: async () => ({ items: [{ id: contour }] }) }) });
const result = service.execute(actor, { action: 'link', projectRef: `project:${projectId}`, hostRef: `host:${hostId}`, contourId: contour });
if (sharedProjects) {
assert.equal((await result).linked, true);
assert.equal(repo.writes.filter(item => item.sql.includes('device_b2_contour_links')).length, 1);
} else {
await assert.rejects(result, /b2_shared_projects_migration_required/);
assert.deepEqual(repo.writes, []);
}
}
});
test('new contour retries retain remote identity and authorize target before creation', async () => {
const contour = 'c'.repeat(32), calls = [], requestId = 'd'.repeat(32);
const repo = repository();
const service = new B2Infrastructure({ pool: repo.pool, secrets: { read: async () => pkg }, clientFactory: () => ({ call: async (path, body) => {
calls.push({ path, body }); return path.endsWith('/management/contours') ? { id: contour } : { items: [{ id: contour }] };
} }) });
const input = { action: 'contour-connect', projectRef: `project:${projectId}`, hostRef: `host:${hostId}`, name: 'New fleet' };
assert.equal((await service.execute(actor, input, requestId)).contourId, contour);
assert.equal((await service.execute(actor, input, requestId)).contourId, contour);
assert.equal(calls[0].body.key, calls[2].body.key);
assert.equal(calls[0].body.key, 'dc-' + requestId);
});
test('tracker settings keep project and contour authority across remote calls', async () => {
const contour = 'c'.repeat(32), device = 'd'.repeat(32), calls = [];
const repo = repository({ role: 'viewer' }); const db = await repo.pool.connect();