From d41282e3520995ec54d8f51eff9b97d791ab03c7 Mon Sep 17 00:00:00 2001 From: Anso Date: Fri, 29 May 2026 15:12:48 -0400 Subject: [PATCH] fix(blueprints): gate Federation pin control on admin role (#1252) * fix(blueprints): gate Federation pin control on admin role The Federation tab rendered an editable pin control to any Admiral-tier user, but PUT /api/blueprints/:id/pin requires admin role, so a non-admin Admiral user saw a dropdown that returned 403 on use. Thread the admin flag into FederationTab and render the pin placement read-only (with an administrator-required hint) for non-admins, matching the existing canEdit pattern in the Deployments tab. The backend guard already enforced admin; this aligns the UI affordance with it. Add backend coverage for the tier/role authorization matrix across the blueprint routes, remote-node deploy/withdraw ordering and failure mapping, edge cases (disable-with-active 409, selector cap, marker drift, cross-blueprint withdraw refusal), service developer-mode diagnostics, and a frontend render-gate test for both admin and non-admin states. * fix(blueprints): gate Apply action on admin role in blueprint detail The blueprint detail sheet rendered an enabled "Apply now" control to any paid user, but POST /api/blueprints/:id/apply requires admin. Gate the primary action on canEdit so it matches the already-gated Edit / Disable / Delete actions and the backend guard; non-admins keep a read-only detail view. Add a render test covering both the admin and non-admin action bars. Also strengthen the remote-deploy ordering test to assert global call order across spies (create < compose < marker < deploy) via invocationCallOrder, not just per-method indices. --- .../src/__tests__/blueprints-authz.test.ts | 236 ++++++++++++++++++ .../__tests__/blueprints-edge-cases.test.ts | 187 ++++++++++++++ .../blueprints-remote-deploy.test.ts | 193 ++++++++++++++ frontend/src/components/FleetView.tsx | 2 +- .../blueprints/BlueprintDetail.test.tsx | 84 +++++++ .../components/blueprints/BlueprintDetail.tsx | 2 +- .../components/fleet/FederationTab.test.tsx | 94 +++++++ .../src/components/fleet/FederationTab.tsx | 51 ++-- 8 files changed, 828 insertions(+), 21 deletions(-) create mode 100644 backend/src/__tests__/blueprints-authz.test.ts create mode 100644 backend/src/__tests__/blueprints-edge-cases.test.ts create mode 100644 backend/src/__tests__/blueprints-remote-deploy.test.ts create mode 100644 frontend/src/components/blueprints/BlueprintDetail.test.tsx create mode 100644 frontend/src/components/fleet/FederationTab.test.tsx diff --git a/backend/src/__tests__/blueprints-authz.test.ts b/backend/src/__tests__/blueprints-authz.test.ts new file mode 100644 index 00000000..8fe435b7 --- /dev/null +++ b/backend/src/__tests__/blueprints-authz.test.ts @@ -0,0 +1,236 @@ +/** + * Authorization parity tests for /api/blueprints. + * + * The Blueprints UI gates affordances on license tier (Skipper / Admiral) and + * admin role; these tests pin the matching server-side guards so a UI gate and a + * route guard cannot silently drift apart. Specifically: + * - PUT /:id/pin requires Admiral tier AND admin role (the admin-role half is + * the parity gap the Federation pin control was hardened to match). + * - The mutation routes require admin role. + * - The read routes require paid tier but NOT admin role. + */ +import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from 'vitest'; +import request from 'supertest'; +import type { LicenseTier, LicenseVariant } from '../services/license-types'; +import { setupTestDb, cleanupTestDb, loginAsTestAdmin } from './helpers/setupTestDb'; + +let tmpDir: string; +let app: import('express').Express; +let DatabaseService: typeof import('../services/DatabaseService').DatabaseService; +let LicenseService: typeof import('../services/LicenseService').LicenseService; +let BlueprintReconciler: typeof import('../services/BlueprintReconciler').BlueprintReconciler; +let adminCookie: string; +let viewerCookie: string; +let counter = 0; + +function setLicense(tier: LicenseTier, variant: LicenseVariant): void { + vi.spyOn(LicenseService.getInstance(), 'getTier').mockReturnValue(tier); + vi.spyOn(LicenseService.getInstance(), 'getVariant').mockReturnValue(variant); +} + +function seedNode(): { id: number; name: string } { + counter += 1; + const name = `bp-authz-node-${counter}`; + const db = DatabaseService.getInstance().getDb(); + const result = db.prepare( + `INSERT INTO nodes (name, type, mode, compose_dir, is_default, status, created_at) + VALUES (?, 'local', 'proxy', '/tmp/compose', 0, 'online', ?)`, + ).run(name, Date.now()); + return { id: result.lastInsertRowid as number, name }; +} + +function seedBlueprint(nodeIds: number[]) { + counter += 1; + return DatabaseService.getInstance().createBlueprint({ + name: `bp-authz-${counter}`, + description: null, + compose_content: 'services:\n app:\n image: nginx\n', + selector: { type: 'nodes', ids: nodeIds }, + drift_mode: 'suggest', + classification: 'stateless', + classification_reasons: [], + enabled: true, + created_by: 'admin', + }); +} + +async function seedAndLoginViewer(): Promise { + const bcrypt = (await import('bcrypt')).default; + const supertest = (await import('supertest')).default; + const passwordHash = await bcrypt.hash('bp-viewer-pass', 1); + DatabaseService.getInstance().addUser({ username: 'bp-viewer', password_hash: passwordHash, role: 'viewer' }); + const res = await supertest(app) + .post('/api/auth/login') + .send({ username: 'bp-viewer', password: 'bp-viewer-pass' }); + const cookies = res.headers['set-cookie'] as string | string[]; + return Array.isArray(cookies) ? cookies[0] : cookies; +} + +beforeAll(async () => { + tmpDir = await setupTestDb(); + ({ DatabaseService } = await import('../services/DatabaseService')); + ({ LicenseService } = await import('../services/LicenseService')); + ({ BlueprintReconciler } = await import('../services/BlueprintReconciler')); + + vi.spyOn(LicenseService.getInstance(), 'getTier').mockReturnValue('paid'); + vi.spyOn(LicenseService.getInstance(), 'getVariant').mockReturnValue('admiral'); + vi.spyOn(LicenseService.getInstance(), 'getSeatLimits').mockReturnValue({ maxAdmins: null, maxViewers: null }); + + ({ app } = await import('../index')); + adminCookie = await loginAsTestAdmin(app); + viewerCookie = await seedAndLoginViewer(); +}); + +afterAll(() => cleanupTestDb(tmpDir)); + +beforeEach(() => { + vi.restoreAllMocks(); + setLicense('paid', 'admiral'); + vi.spyOn(LicenseService.getInstance(), 'getSeatLimits').mockReturnValue({ maxAdmins: null, maxViewers: null }); + // Neutralize the post-pin background reconcile so the 200 path has no side effects. + vi.spyOn(BlueprintReconciler.getInstance(), 'reconcileOne').mockResolvedValue(undefined); + const db = DatabaseService.getInstance().getDb(); + db.prepare('DELETE FROM blueprint_deployments').run(); + db.prepare('DELETE FROM blueprints').run(); + db.prepare('DELETE FROM nodes WHERE is_default = 0').run(); +}); + +describe('PUT /api/blueprints/:id/pin authorization', () => { + it('allows an admin on an Admiral license to pin a blueprint', async () => { + const node = seedNode(); + const bp = seedBlueprint([node.id]); + + const res = await request(app) + .put(`/api/blueprints/${bp.id}/pin`) + .set('Cookie', adminCookie) + .send({ nodeId: node.id }); + + expect(res.status).toBe(200); + expect(res.body.pinned_node_id).toBe(node.id); + }); + + it('allows an admin on an Admiral license to unpin (nodeId null)', async () => { + const node = seedNode(); + const bp = seedBlueprint([node.id]); + DatabaseService.getInstance().setBlueprintPinnedNode(bp.id, node.id); + + const res = await request(app) + .put(`/api/blueprints/${bp.id}/pin`) + .set('Cookie', adminCookie) + .send({ nodeId: null }); + + expect(res.status).toBe(200); + expect(res.body.pinned_node_id).toBeNull(); + }); + + it('rejects an admin on a Skipper license with ADMIRAL_REQUIRED', async () => { + setLicense('paid', 'skipper'); + const node = seedNode(); + const bp = seedBlueprint([node.id]); + + const res = await request(app) + .put(`/api/blueprints/${bp.id}/pin`) + .set('Cookie', adminCookie) + .send({ nodeId: node.id }); + + expect(res.status).toBe(403); + expect(res.body.code).toBe('ADMIRAL_REQUIRED'); + }); + + it('rejects an admin on a Community license with PAID_REQUIRED', async () => { + setLicense('community', null); + const node = seedNode(); + const bp = seedBlueprint([node.id]); + + const res = await request(app) + .put(`/api/blueprints/${bp.id}/pin`) + .set('Cookie', adminCookie) + .send({ nodeId: node.id }); + + expect(res.status).toBe(403); + expect(res.body.code).toBe('PAID_REQUIRED'); + }); + + it('rejects a non-admin on an Admiral license with ADMIN_REQUIRED', async () => { + const node = seedNode(); + const bp = seedBlueprint([node.id]); + + const res = await request(app) + .put(`/api/blueprints/${bp.id}/pin`) + .set('Cookie', viewerCookie) + .send({ nodeId: node.id }); + + expect(res.status).toBe(403); + expect(res.body.code).toBe('ADMIN_REQUIRED'); + }); +}); + +describe('Blueprint mutation routes require admin role', () => { + // Tier is paid+admiral in beforeEach, so requirePaid passes and the admin + // guard is what rejects. The gate short-circuits before id parsing, so dummy + // ids are sufficient to prove the role boundary. + const mutations: Array<{ name: string; method: 'post' | 'put' | 'delete'; path: string }> = [ + { name: 'create', method: 'post', path: '/api/blueprints' }, + { name: 'update', method: 'put', path: '/api/blueprints/1' }, + { name: 'delete', method: 'delete', path: '/api/blueprints/1' }, + { name: 'apply', method: 'post', path: '/api/blueprints/1/apply' }, + { name: 'withdraw', method: 'post', path: '/api/blueprints/1/withdraw/1' }, + { name: 'accept', method: 'post', path: '/api/blueprints/1/accept/1' }, + ]; + + it.each(mutations)('rejects a non-admin on $name with ADMIN_REQUIRED', async ({ method, path }) => { + const res = await request(app)[method](path).set('Cookie', viewerCookie).send({}); + expect(res.status).toBe(403); + expect(res.body.code).toBe('ADMIN_REQUIRED'); + }); + + it('rejects an admin on a Community license from creating with PAID_REQUIRED', async () => { + setLicense('community', null); + const res = await request(app) + .post('/api/blueprints') + .set('Cookie', adminCookie) + .send({}); + expect(res.status).toBe(403); + expect(res.body.code).toBe('PAID_REQUIRED'); + }); +}); + +describe('Blueprint read routes require paid tier but not admin role', () => { + it('lets a non-admin paid user list blueprints', async () => { + seedBlueprint([]); + const res = await request(app).get('/api/blueprints').set('Cookie', viewerCookie); + expect(res.status).toBe(200); + expect(Array.isArray(res.body)).toBe(true); + }); + + it('lets a non-admin paid user fetch a blueprint detail', async () => { + const bp = seedBlueprint([]); + const res = await request(app).get(`/api/blueprints/${bp.id}`).set('Cookie', viewerCookie); + expect(res.status).toBe(200); + expect(res.body.blueprint.id).toBe(bp.id); + }); + + it('lets a non-admin paid user preview a blueprint', async () => { + const node = seedNode(); + const bp = seedBlueprint([node.id]); + const res = await request(app).get(`/api/blueprints/${bp.id}/preview`).set('Cookie', viewerCookie); + expect(res.status).toBe(200); + expect(res.body.blueprintId).toBe(bp.id); + }); + + it('lets a non-admin paid user analyze compose', async () => { + const res = await request(app) + .post('/api/blueprints/analyze') + .set('Cookie', viewerCookie) + .send({ compose_content: 'services:\n app:\n image: nginx\n' }); + expect(res.status).toBe(200); + expect(res.body.classification).toBeDefined(); + }); + + it('rejects an admin on a Community license from listing with PAID_REQUIRED', async () => { + setLicense('community', null); + const res = await request(app).get('/api/blueprints').set('Cookie', adminCookie); + expect(res.status).toBe(403); + expect(res.body.code).toBe('PAID_REQUIRED'); + }); +}); diff --git a/backend/src/__tests__/blueprints-edge-cases.test.ts b/backend/src/__tests__/blueprints-edge-cases.test.ts new file mode 100644 index 00000000..5cfc420d --- /dev/null +++ b/backend/src/__tests__/blueprints-edge-cases.test.ts @@ -0,0 +1,187 @@ +/** + * Edge-case coverage for the Blueprints feature that the existing suites leave open: + * - PUT /:id refusing to disable a blueprint that still has active deployments (409). + * - POST / rejecting a selector that exceeds the 200-entry cap (400). + * - checkForDrift flagging revision drift when the on-node marker is stale. + * - withdrawFromNode refusing to act when the marker belongs to a different blueprint. + */ +import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from 'vitest'; +import request from 'supertest'; +import { setupTestDb, cleanupTestDb, loginAsTestAdmin } from './helpers/setupTestDb'; + +let tmpDir: string; +let app: import('express').Express; +let DatabaseService: typeof import('../services/DatabaseService').DatabaseService; +let LicenseService: typeof import('../services/LicenseService').LicenseService; +let BlueprintService: typeof import('../services/BlueprintService').BlueprintService; +let adminCookie: string; +let counter = 0; + +function seedNode(): { id: number; name: string } { + counter += 1; + const name = `bp-edge-node-${counter}`; + const db = DatabaseService.getInstance().getDb(); + const result = db.prepare( + `INSERT INTO nodes (name, type, mode, compose_dir, is_default, status, created_at) + VALUES (?, 'local', 'proxy', '/tmp/compose', 0, 'online', ?)`, + ).run(name, Date.now()); + return { id: result.lastInsertRowid as number, name }; +} + +function seedBlueprint(nodeIds: number[]) { + counter += 1; + return DatabaseService.getInstance().createBlueprint({ + name: `bp-edge-${counter}`, + description: null, + compose_content: 'services:\n app:\n image: nginx\n', + selector: { type: 'nodes', ids: nodeIds }, + drift_mode: 'suggest', + classification: 'stateless', + classification_reasons: [], + enabled: true, + created_by: 'admin', + }); +} + +beforeAll(async () => { + tmpDir = await setupTestDb(); + ({ DatabaseService } = await import('../services/DatabaseService')); + ({ LicenseService } = await import('../services/LicenseService')); + ({ BlueprintService } = await import('../services/BlueprintService')); + + vi.spyOn(LicenseService.getInstance(), 'getTier').mockReturnValue('paid'); + vi.spyOn(LicenseService.getInstance(), 'getVariant').mockReturnValue('skipper'); + vi.spyOn(LicenseService.getInstance(), 'getSeatLimits').mockReturnValue({ maxAdmins: null, maxViewers: null }); + + ({ app } = await import('../index')); + adminCookie = await loginAsTestAdmin(app); +}); + +afterAll(() => cleanupTestDb(tmpDir)); + +beforeEach(() => { + vi.restoreAllMocks(); + vi.spyOn(LicenseService.getInstance(), 'getTier').mockReturnValue('paid'); + vi.spyOn(LicenseService.getInstance(), 'getVariant').mockReturnValue('skipper'); + vi.spyOn(LicenseService.getInstance(), 'getSeatLimits').mockReturnValue({ maxAdmins: null, maxViewers: null }); + // Reset developer mode so the diagnostics matrix below is order-independent. + DatabaseService.getInstance().updateGlobalSetting('developer_mode', '0'); + const db = DatabaseService.getInstance().getDb(); + db.prepare('DELETE FROM blueprint_deployments').run(); + db.prepare('DELETE FROM blueprints').run(); + db.prepare('DELETE FROM nodes WHERE is_default = 0').run(); +}); + +describe('Blueprint route edge cases', () => { + it('refuses to disable a blueprint that still has an active deployment', async () => { + const node = seedNode(); + const bp = seedBlueprint([node.id]); + DatabaseService.getInstance().upsertDeployment({ + blueprint_id: bp.id, + node_id: node.id, + status: 'active', + applied_revision: bp.revision, + }); + + const res = await request(app) + .put(`/api/blueprints/${bp.id}`) + .set('Cookie', adminCookie) + .send({ enabled: false }); + + expect(res.status).toBe(409); + expect(res.body.code).toBe('has_active_deployments'); + // The blueprint must remain enabled. + expect(DatabaseService.getInstance().getBlueprint(bp.id)?.enabled).toBe(true); + }); + + it('rejects a node selector that exceeds the 200-entry cap', async () => { + const ids = Array.from({ length: 201 }, (_, i) => i + 1); + const res = await request(app) + .post('/api/blueprints') + .set('Cookie', adminCookie) + .send({ + name: 'bp-edge-oversized', + compose_content: 'services:\n app:\n image: nginx\n', + selector: { type: 'nodes', ids }, + drift_mode: 'suggest', + }); + + expect(res.status).toBe(400); + expect(res.body.error).toContain('200'); + expect(DatabaseService.getInstance().listBlueprints()).toHaveLength(0); + }); +}); + +describe('BlueprintService marker edge cases', () => { + it('flags revision drift when the on-node marker is stale', async () => { + const localNode = DatabaseService.getInstance().getNodes()[0]; + const bp = seedBlueprint([localNode.id]); + const bpObj = DatabaseService.getInstance().getBlueprint(bp.id)!; + + vi.spyOn(BlueprintService.getInstance(), 'readMarker').mockResolvedValue({ + blueprintId: bp.id, + revision: bpObj.revision + 5, + lastApplied: 0, + }); + + const result = await BlueprintService.getInstance().checkForDrift(bpObj, localNode); + + expect(result.drifted).toBe(true); + expect(result.reason).toContain('revision drift'); + }); + + it('refuses to withdraw when the marker belongs to a different blueprint', async () => { + const localNode = DatabaseService.getInstance().getNodes()[0]; + const bp = seedBlueprint([localNode.id]); + const bpObj = DatabaseService.getInstance().getBlueprint(bp.id)!; + + vi.spyOn(BlueprintService.getInstance(), 'readMarker').mockResolvedValue({ + blueprintId: bp.id + 999, + revision: 1, + lastApplied: 0, + }); + + const result = await BlueprintService.getInstance().withdrawFromNode(bpObj, localNode); + + expect(result.status).toBe('name_conflict'); + // The deployment row must record the conflict, not silently disappear. + const dep = DatabaseService.getInstance().getDeployment(bp.id, localNode.id); + expect(dep).toBeDefined(); + expect(dep?.status).toBe('name_conflict'); + }); +}); + +describe('BlueprintService developer-mode diagnostics', () => { + // withdrawFromNode emits its "withdraw inputs" diagnostic line before reading the + // marker, so a cross-blueprint marker stub lets us assert the gate without Docker. + function arrangeWithdraw() { + const localNode = DatabaseService.getInstance().getNodes()[0]; + const bp = seedBlueprint([localNode.id]); + const bpObj = DatabaseService.getInstance().getBlueprint(bp.id)!; + vi.spyOn(BlueprintService.getInstance(), 'readMarker').mockResolvedValue({ + blueprintId: bp.id + 999, + revision: 1, + lastApplied: 0, + }); + return { bpObj, localNode }; + } + + it('does not emit diagnostic logs when developer mode is off', async () => { + const { bpObj, localNode } = arrangeWithdraw(); + const infoSpy = vi.spyOn(console, 'info').mockImplementation(() => undefined); + + await BlueprintService.getInstance().withdrawFromNode(bpObj, localNode); + + expect(infoSpy.mock.calls.some(([m]) => String(m).includes('[BlueprintService:diag]'))).toBe(false); + }); + + it('emits diagnostic logs when developer mode is on', async () => { + DatabaseService.getInstance().updateGlobalSetting('developer_mode', '1'); + const { bpObj, localNode } = arrangeWithdraw(); + const infoSpy = vi.spyOn(console, 'info').mockImplementation(() => undefined); + + await BlueprintService.getInstance().withdrawFromNode(bpObj, localNode); + + expect(infoSpy.mock.calls.some(([m]) => String(m).includes('[BlueprintService:diag]'))).toBe(true); + }); +}); diff --git a/backend/src/__tests__/blueprints-remote-deploy.test.ts b/backend/src/__tests__/blueprints-remote-deploy.test.ts new file mode 100644 index 00000000..081087d9 --- /dev/null +++ b/backend/src/__tests__/blueprints-remote-deploy.test.ts @@ -0,0 +1,193 @@ +/** + * Unit tests for the remote (proxy) branch of BlueprintService deploy/withdraw. + * + * The remote path talks to a sibling Sencho's /api/stacks surface over HTTP + * (create stack, write compose, write marker, deploy). These tests mock that + * surface via axios so we can assert the call ordering, the 409-on-create + * "already exists" tolerance, the failure mapping to status='failed', the + * name-conflict guard, and the withdraw delete path, without a live remote. + */ +import { describe, it, expect, beforeAll, afterAll, beforeEach, afterEach, vi } from 'vitest'; +import axios from 'axios'; + +let tmpDir: string; +let DatabaseService: typeof import('../services/DatabaseService').DatabaseService; +let BlueprintService: typeof import('../services/BlueprintService').BlueprintService; +let NodeRegistry: typeof import('../services/NodeRegistry').NodeRegistry; +let setupTestDb: typeof import('./helpers/setupTestDb').setupTestDb; +let cleanupTestDb: typeof import('./helpers/setupTestDb').cleanupTestDb; +let counter = 0; + +function seedRemoteNode(): { id: number; name: string } { + counter += 1; + const name = `bp-remote-${counter}`; + const id = DatabaseService.getInstance().addNode({ + name, + type: 'remote', + mode: 'proxy', + compose_dir: '/tmp/compose', + is_default: false, + api_url: 'https://remote.example.com:1852', + api_token: 'remote-tok', + }); + return { id, name }; +} + +function seedBlueprint(nodeIds: number[]) { + counter += 1; + return DatabaseService.getInstance().createBlueprint({ + name: `bp-remote-bp-${counter}`, + description: null, + compose_content: 'services:\n app:\n image: nginx\n', + selector: { type: 'nodes', ids: nodeIds }, + drift_mode: 'suggest', + classification: 'stateless', + classification_reasons: [], + enabled: true, + created_by: 'admin', + }); +} + +beforeAll(async () => { + ({ setupTestDb, cleanupTestDb } = await import('./helpers/setupTestDb')); + tmpDir = await setupTestDb(); + ({ DatabaseService } = await import('../services/DatabaseService')); + ({ BlueprintService } = await import('../services/BlueprintService')); + ({ NodeRegistry } = await import('../services/NodeRegistry')); +}); + +afterAll(() => cleanupTestDb(tmpDir)); + +beforeEach(() => { + vi.restoreAllMocks(); + vi.spyOn(NodeRegistry.getInstance(), 'getProxyTarget').mockReturnValue({ + apiUrl: 'https://remote.example.com:1852', + apiToken: 'remote-tok', + }); + const db = DatabaseService.getInstance().getDb(); + db.prepare('DELETE FROM blueprint_deployments').run(); + db.prepare('DELETE FROM blueprints').run(); + db.prepare('DELETE FROM nodes WHERE is_default = 0').run(); +}); + +afterEach(() => vi.restoreAllMocks()); + +describe('BlueprintService remote deploy', () => { + it('creates the stack, writes compose then marker, then deploys, in order', async () => { + const node = seedRemoteNode(); + const bp = seedBlueprint([node.id]); + const nodeObj = DatabaseService.getInstance().getNode(node.id)!; + const bpObj = DatabaseService.getInstance().getBlueprint(bp.id)!; + + vi.spyOn(axios, 'get').mockResolvedValue({ status: 200, data: [] }); // hasNameConflict: no stacks + const putSpy = vi.spyOn(axios, 'put').mockResolvedValue({ status: 200, data: {} }); + const postSpy = vi.spyOn(axios, 'post') + .mockResolvedValueOnce({ status: 201, data: {} }) // create stack + .mockResolvedValueOnce({ status: 200, data: {} }); // deploy + + const result = await BlueprintService.getInstance().deployToNode(bpObj, nodeObj); + + expect(result.status).toBe('active'); + expect(postSpy.mock.calls[0][0]).toMatch(/\/api\/stacks$/); + expect(putSpy.mock.calls[0][0]).toContain('docker-compose.yml'); + expect(putSpy.mock.calls[1][0]).toContain('.blueprint.json'); + expect(postSpy.mock.calls[1][0]).toMatch(/\/deploy$/); + // Assert global interleaving across spies, not just per-method order: + // create < compose < marker < deploy. (mock.calls indices alone would not + // catch the deploy POST firing before the file PUTs.) + const [createOrder, deployOrder] = postSpy.mock.invocationCallOrder; + const [composeOrder, markerOrder] = putSpy.mock.invocationCallOrder; + expect(createOrder).toBeLessThan(composeOrder); + expect(composeOrder).toBeLessThan(markerOrder); + expect(markerOrder).toBeLessThan(deployOrder); + + const dep = DatabaseService.getInstance().getDeployment(bp.id, node.id); + expect(dep?.status).toBe('active'); + expect(dep?.applied_revision).toBe(bpObj.revision); + }); + + it('treats a 409 on stack create as already-exists and proceeds', async () => { + const node = seedRemoteNode(); + const bp = seedBlueprint([node.id]); + const nodeObj = DatabaseService.getInstance().getNode(node.id)!; + const bpObj = DatabaseService.getInstance().getBlueprint(bp.id)!; + + vi.spyOn(axios, 'get').mockResolvedValue({ status: 200, data: [] }); + const putSpy = vi.spyOn(axios, 'put').mockResolvedValue({ status: 200, data: {} }); + const postSpy = vi.spyOn(axios, 'post') + .mockResolvedValueOnce({ status: 409, data: { error: 'already exists' } }) + .mockResolvedValueOnce({ status: 200, data: {} }); + + const result = await BlueprintService.getInstance().deployToNode(bpObj, nodeObj); + + expect(result.status).toBe('active'); + expect(putSpy).toHaveBeenCalledTimes(2); + expect(postSpy).toHaveBeenCalledTimes(2); + }); + + it('maps a remote deploy failure to status=failed with the HTTP error', async () => { + const node = seedRemoteNode(); + const bp = seedBlueprint([node.id]); + const nodeObj = DatabaseService.getInstance().getNode(node.id)!; + const bpObj = DatabaseService.getInstance().getBlueprint(bp.id)!; + + vi.spyOn(axios, 'get').mockResolvedValue({ status: 200, data: [] }); + vi.spyOn(axios, 'put').mockResolvedValue({ status: 200, data: {} }); + vi.spyOn(axios, 'post') + .mockResolvedValueOnce({ status: 201, data: {} }) + .mockResolvedValueOnce({ status: 500, data: { error: 'boom' } }); + + const result = await BlueprintService.getInstance().deployToNode(bpObj, nodeObj); + + expect(result.status).toBe('failed'); + expect(result.error).toContain('HTTP 500'); + const dep = DatabaseService.getInstance().getDeployment(bp.id, node.id); + expect(dep?.status).toBe('failed'); + expect(dep?.last_error).toContain('HTTP 500'); + }); + + it('refuses to deploy when an unmanaged stack of the same name exists on the remote', async () => { + const node = seedRemoteNode(); + const bp = seedBlueprint([node.id]); + const nodeObj = DatabaseService.getInstance().getNode(node.id)!; + const bpObj = DatabaseService.getInstance().getBlueprint(bp.id)!; + + // hasNameConflict lists /api/stacks first, then reads the marker. A 404 marker on an + // existing stack means it is unmanaged, so the deploy must refuse. + vi.spyOn(axios, 'get') + .mockResolvedValueOnce({ status: 200, data: [{ name: bpObj.name }] }) + .mockResolvedValueOnce({ status: 404, data: {} }); + const postSpy = vi.spyOn(axios, 'post'); + + const result = await BlueprintService.getInstance().deployToNode(bpObj, nodeObj); + + expect(result.status).toBe('name_conflict'); + expect(postSpy).not.toHaveBeenCalled(); + const dep = DatabaseService.getInstance().getDeployment(bp.id, node.id); + expect(dep).toBeDefined(); + expect(dep?.status).toBe('name_conflict'); + }); + + it('withdraws a remote deployment by deleting the stack and removing the row', async () => { + const node = seedRemoteNode(); + const bp = seedBlueprint([node.id]); + const nodeObj = DatabaseService.getInstance().getNode(node.id)!; + const bpObj = DatabaseService.getInstance().getBlueprint(bp.id)!; + DatabaseService.getInstance().upsertDeployment({ + blueprint_id: bp.id, + node_id: node.id, + status: 'active', + applied_revision: bpObj.revision, + }); + + vi.spyOn(axios, 'get').mockResolvedValue({ status: 404, data: {} }); // readMarker → null → proceed + vi.spyOn(axios, 'post').mockResolvedValue({ status: 200, data: {} }); // remote down (best-effort) + const delSpy = vi.spyOn(axios, 'delete').mockResolvedValue({ status: 200, data: {} }); + + const result = await BlueprintService.getInstance().withdrawFromNode(bpObj, nodeObj); + + expect(result.status).toBe('withdrawn'); + expect(delSpy.mock.calls[0][0]).toMatch(/\/api\/stacks\//); + expect(DatabaseService.getInstance().getDeployment(bp.id, node.id)).toBeUndefined(); + }); +}); diff --git a/frontend/src/components/FleetView.tsx b/frontend/src/components/FleetView.tsx index 51a84e0c..f433e87a 100644 --- a/frontend/src/components/FleetView.tsx +++ b/frontend/src/components/FleetView.tsx @@ -213,7 +213,7 @@ export function FleetView({ onNavigateToNode }: FleetViewProps) { {isAdmiral && ( - + )} diff --git a/frontend/src/components/blueprints/BlueprintDetail.test.tsx b/frontend/src/components/blueprints/BlueprintDetail.test.tsx new file mode 100644 index 00000000..9bf51774 --- /dev/null +++ b/frontend/src/components/blueprints/BlueprintDetail.test.tsx @@ -0,0 +1,84 @@ +/** + * Render-gate coverage for BlueprintDetail's action bar. + * + * The Apply / Edit / Disable / Delete actions all hit admin-only routes + * (e.g. POST /api/blueprints/:id/apply requires admin). This locks the UI gate: + * an admin (canEdit) sees the action affordances; a non-admin viewer sees none + * of them, so the sheet can never issue a request the API answers with 403. + */ +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { render, screen } from '@testing-library/react'; +import type { BlueprintSummary } from '@/lib/blueprintsApi'; + +vi.mock('@/lib/blueprintsApi', async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, getBlueprint: vi.fn(), applyBlueprint: vi.fn() }; +}); + +vi.mock('@/context/NodeContext', () => ({ useNodes: () => ({ nodes: [] }) })); + +vi.mock('@/components/ui/toast-store', () => ({ + toast: { error: vi.fn(), success: vi.fn(), warning: vi.fn(), info: vi.fn(), loading: vi.fn(), dismiss: vi.fn() }, +})); + +vi.mock('./BlueprintDeploymentTable', () => ({ + BlueprintDeploymentTable: () =>
, +})); + +import { getBlueprint } from '@/lib/blueprintsApi'; +import { BlueprintDetail } from './BlueprintDetail'; + +function summary(): BlueprintSummary { + return { + blueprint: { + id: 1, + name: 'web-blueprint', + description: null, + compose_content: 'services:\n web:\n image: nginx\n', + selector: { type: 'labels', any: ['prod'], all: [] }, + drift_mode: 'suggest', + classification: 'stateless', + classification_reasons: [], + enabled: true, + revision: 1, + created_at: 0, + updated_at: 0, + created_by: 'admin', + pinned_node_id: null, + }, + deployments: [], + statusCounts: {}, + }; +} + +const noop = () => {}; + +beforeEach(() => { + vi.mocked(getBlueprint).mockResolvedValue(summary()); +}); + +describe('BlueprintDetail action gating', () => { + it('shows the Apply / Edit / Delete actions for an admin (canEdit)', async () => { + render( + , + ); + + expect(await screen.findByText('Show compose source')).toBeInTheDocument(); + expect(screen.getByRole('button', { name: /apply now/i })).toBeInTheDocument(); + expect(screen.getByRole('button', { name: /^edit$/i })).toBeInTheDocument(); + expect(screen.getByRole('button', { name: /^delete$/i })).toBeInTheDocument(); + }); + + it('hides every mutating action for a non-admin (read-only)', async () => { + render( + , + ); + + expect(await screen.findByText('Show compose source')).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: /apply now/i })).not.toBeInTheDocument(); + expect(screen.queryByRole('button', { name: /^edit$/i })).not.toBeInTheDocument(); + expect(screen.queryByRole('button', { name: /^delete$/i })).not.toBeInTheDocument(); + // The detail is still viewable: the compose source and deployment table render. + expect(screen.getByTestId('deployment-table')).toBeInTheDocument(); + }); +}); diff --git a/frontend/src/components/blueprints/BlueprintDetail.tsx b/frontend/src/components/blueprints/BlueprintDetail.tsx index 403080ef..686e6997 100644 --- a/frontend/src/components/blueprints/BlueprintDetail.tsx +++ b/frontend/src/components/blueprints/BlueprintDetail.tsx @@ -229,7 +229,7 @@ export function BlueprintDetail({ blueprintId, open, onOpenChange, onChanged, ca crumb={['Blueprints', blueprint?.name ?? '…']} name={blueprint?.name ?? } meta={meta} - primaryAction={blueprint ? { + primaryAction={blueprint && canEdit ? { label: 'Apply now', icon: Play, onClick: handleApply, diff --git a/frontend/src/components/fleet/FederationTab.test.tsx b/frontend/src/components/fleet/FederationTab.test.tsx new file mode 100644 index 00000000..3a29f881 --- /dev/null +++ b/frontend/src/components/fleet/FederationTab.test.tsx @@ -0,0 +1,94 @@ +/** + * Render-gate coverage for FederationTab's pin control. + * + * Pinning a blueprint to a node is admin-only on the backend + * (PUT /api/blueprints/:id/pin requires admin). This test locks the matching UI + * gate: an admin sees an editable Select, a non-admin sees the placement + * read-only with an explanatory hint. Without this the affordance can drift + * back to rendering an enabled control that the API rejects with 403. + */ +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { render, screen } from '@testing-library/react'; +import type { BlueprintListItem } from '@/lib/blueprintsApi'; +import type { NodeRecord } from '@/lib/nodesApi'; + +vi.mock('@/lib/blueprintsApi', async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, listBlueprints: vi.fn(), pinBlueprint: vi.fn() }; +}); + +vi.mock('@/lib/nodesApi', async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, listNodes: vi.fn() }; +}); + +vi.mock('@/components/ui/toast-store', () => ({ + toast: { error: vi.fn(), success: vi.fn(), warning: vi.fn(), info: vi.fn(), loading: vi.fn(), dismiss: vi.fn() }, +})); + +import { listBlueprints, pinBlueprint } from '@/lib/blueprintsApi'; +import { listNodes } from '@/lib/nodesApi'; +import { FederationTab } from './FederationTab'; + +function node(id: number, name: string, overrides: Partial = {}): NodeRecord { + return { id, name, type: 'local', status: 'online', cordoned: false, cordoned_at: null, cordoned_reason: null, ...overrides }; +} + +function blueprint(overrides: Partial = {}): BlueprintListItem { + return { + id: 1, + name: 'web-blueprint', + description: 'edge web tier', + compose_content: 'services:\n web:\n image: nginx\n', + selector: { type: 'labels', any: ['prod'], all: [] }, + drift_mode: 'suggest', + classification: 'stateless', + classification_reasons: [], + enabled: true, + revision: 1, + created_at: 0, + updated_at: 0, + created_by: 'admin', + pinned_node_id: null, + deploymentCounts: {}, + deploymentTotal: 0, + ...overrides, + }; +} + +beforeEach(() => { + vi.mocked(listNodes).mockResolvedValue([node(1, 'node-alpha')]); + vi.mocked(listBlueprints).mockResolvedValue([blueprint()]); +}); + +describe('FederationTab pin gating', () => { + it('renders an editable pin control for an admin', async () => { + render(); + + expect(await screen.findByText('web-blueprint')).toBeInTheDocument(); + expect(screen.getByRole('combobox')).toBeInTheDocument(); + expect(screen.queryByText(/Pin changes require an administrator/i)).not.toBeInTheDocument(); + }); + + it('renders the pin placement read-only for a non-admin', async () => { + render(); + + expect(await screen.findByText('web-blueprint')).toBeInTheDocument(); + expect(screen.queryByRole('combobox')).not.toBeInTheDocument(); + expect(screen.getByText(/Pin changes require an administrator/i)).toBeInTheDocument(); + expect(screen.getByText('(unpinned)')).toBeInTheDocument(); + // The read-only branch must never be able to issue the admin-only pin request. + expect(vi.mocked(pinBlueprint)).not.toHaveBeenCalled(); + }); + + it('shows the pinned node name read-only for a non-admin when a pin exists', async () => { + vi.mocked(listBlueprints).mockResolvedValue([blueprint({ pinned_node_id: 1 })]); + render(); + + expect(await screen.findByText('web-blueprint')).toBeInTheDocument(); + expect(screen.queryByRole('combobox')).not.toBeInTheDocument(); + // The pinned node name renders in both the read-only "Pinned to" cell and the + // "Effective" column, so getAllByText (not getByText) is required. + expect(screen.getAllByText('node-alpha').length).toBeGreaterThan(0); + }); +}); diff --git a/frontend/src/components/fleet/FederationTab.tsx b/frontend/src/components/fleet/FederationTab.tsx index 2e618dff..8944f203 100644 --- a/frontend/src/components/fleet/FederationTab.tsx +++ b/frontend/src/components/fleet/FederationTab.tsx @@ -24,7 +24,13 @@ function formatTimestamp(ms: number | null): string { return date.toLocaleString(); } -export function FederationTab() { +interface FederationTabProps { + /** Whether the current user may change pin placement. Pinning is admin-only on the backend + * (PUT /api/blueprints/:id/pin requires admin); non-admins see the placement read-only. */ + canManage: boolean; +} + +export function FederationTab({ canManage }: FederationTabProps) { const [nodes, setNodes] = useState([]); const [blueprints, setBlueprints] = useState([]); const [loading, setLoading] = useState(true); @@ -150,6 +156,7 @@ export function FederationTab() {

Pin policy

Force a blueprint onto a specific node, overriding its selector. + {!canManage && ' Pin changes require an administrator.'}
@@ -188,24 +195,30 @@ export function FederationTab() { {describeSelector(bp.selector)} - + {canManage ? ( + + ) : ( + + {pinnedName ?? '(unpinned)'} + + )} {effective}