mirror of
https://github.com/Studio-Saelix/sencho.git
synced 2026-08-18 14:33:19 +00:00
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.
This commit is contained in:
@@ -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<string> {
|
||||
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');
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user