Files
sencho/backend/src/__tests__/effective-anatomy-route.test.ts
T
Anso ba09e6f69e fix: base Git multi-file Compose deploy env and dossier on the effective config (#1391)
* fix: resolve the root .env at deploy and render time for Git context-dir stacks

A Git multi-file source with a context dir set --project-directory to that
dir, so Docker Compose looked for .env there and missed the root .env Sencho
writes. Validation already passed the root .env with --env-file, so a stack
could validate with one effective config but deploy or render another.

Add authoredComposeEnvFileArgs, which appends --env-file <stackDir>/.env when
the applied deploy spec has a context dir and a root .env exists, and wire it
into the deploy/update, image-scan, render, and container-listing compose
invocations so they all resolve env from the same file the validator used. A
non-ENOENT access error surfaces instead of silently dropping the flag.

* fix: base multi-file Git dossier and doc-drift on the effective Compose model

The Stack Dossier and its documentation-drift check parsed only the stored root
compose file. For a multi-file Git source, services, ports, networks, or volumes
that an override file adds were invisible, so the dossier showed incomplete facts
and doc-drift could falsely warn that a documented port is unpublished when an
override actually publishes it.

Add a secret-safe GET /stacks/:name/effective-anatomy that renders the merged
effective model and extracts only structural facts (services, ports, volumes,
networks, restart), never env, label, or command values. StackAnatomyPanel
fetches it for multi-file Git stacks and feeds those facts into the dossier and
doc-drift, falling back to the root-only parse for single-file or non-git stacks
and whenever the render is unavailable.

* fix: add an inline path-injection barrier to the Git env-file resolver

CodeQL js/path-injection flagged the fs.access in authoredComposeEnvFileArgs
because the env path derives from the route-supplied stack name and the only
containment check lived in the callers, not at the sink. Resolve the stack dir
against the compose base and assert containment with startsWith inline, then
derive the .env path from the validated dir, mirroring the existing inline guards
in renderConfig and validateCompose. Valid stack names are unaffected; a name
that escapes the base now yields no --env-file.

* test: stabilize the dossier doc-drift e2e against the dossier-load race

The first assertion filled the access_urls field as soon as the Dossier panel
was visible, but the panel's GET /stacks/:name/dossier resolves by overwriting
the fields from the server (empty access_urls) and only then flips the doc-drift
gate on. When the GET landed after the fill, it clobbered the typed value and the
warning never rendered, so the test failed intermittently under CI timing. Wait
for that GET to land before typing, mirroring the spec's openStack helper.
2026-06-18 18:25:58 -04:00

114 lines
4.6 KiB
TypeScript

/**
* GET /api/stacks/:stackName/effective-anatomy: returns the merged effective
* facts, requires stack:read, 404s a missing stack, surfaces a structural (never
* raw) error on render failure, and never leaks an env or label value.
*/
import { describe, it, expect, beforeAll, afterAll, beforeEach, afterEach, vi } from 'vitest';
import fs from 'fs';
import path from 'path';
import request from 'supertest';
import jwt from 'jsonwebtoken';
import { setupTestDb, cleanupTestDb, TEST_USERNAME, TEST_JWT_SECRET } from './helpers/setupTestDb';
import { ComposeService } from '../services/ComposeService';
let tmpDir: string;
let app: import('express').Express;
let authHeader: string;
const STACK = 'effanat';
const ENV_SECRET = 'env-secret-71bd-value';
const LABEL_SECRET = 'label-secret-22ce-value';
function stubRender(rendered: string | null, stderr = '') {
vi.spyOn(ComposeService, 'getInstance').mockReturnValue({
renderConfig: vi.fn().mockResolvedValue({ rendered, stderr, code: rendered === null ? 1 : 0, timedOut: false }),
} as unknown as ComposeService);
}
beforeAll(async () => {
tmpDir = await setupTestDb();
({ app } = await import('../index'));
authHeader = `Bearer ${jwt.sign({ username: TEST_USERNAME }, TEST_JWT_SECRET, { expiresIn: '5m' })}`;
});
afterAll(() => cleanupTestDb(tmpDir));
describe('effective-anatomy route', () => {
let stackDir: string;
beforeEach(() => {
stackDir = path.join(process.env.COMPOSE_DIR as string, STACK);
fs.mkdirSync(stackDir, { recursive: true });
fs.writeFileSync(path.join(stackDir, 'compose.yaml'), 'services:\n web:\n image: nginx:latest\n');
});
afterEach(() => {
vi.restoreAllMocks();
fs.rmSync(stackDir, { recursive: true, force: true });
});
it('returns merged effective facts for a renderable stack', async () => {
stubRender(JSON.stringify({
name: STACK,
services: {
web: {
image: 'nginx:latest',
restart: 'always',
ports: [{ target: 80, published: '8080', protocol: 'tcp' }],
volumes: [{ type: 'volume', source: 'data', target: '/data' }],
networks: { backend: null },
},
},
networks: { backend: {}, default: {} },
volumes: { data: {} },
}));
const res = await request(app).get(`/api/stacks/${STACK}/effective-anatomy`).set('Authorization', authHeader);
expect(res.status).toBe(200);
expect(res.body.renderable).toBe(true);
expect(res.body.services).toEqual(['web']);
expect(res.body.ports.web).toEqual([{ host: '8080', container: '80', proto: 'tcp', published: true }]);
expect(res.body.volumes.web).toEqual([{ host: 'data', container: '/data' }]);
expect(res.body.restart).toBe('always');
expect(res.body.networks).toEqual(['backend', 'default']);
});
it('surfaces a structural error and never raw stderr on render failure', async () => {
stubRender(null, `error: the "${ENV_SECRET}" variable is not set`);
const res = await request(app).get(`/api/stacks/${STACK}/effective-anatomy`).set('Authorization', authHeader);
expect(res.status).toBe(200);
expect(res.body.renderable).toBe(false);
expect(JSON.stringify(res.body)).not.toContain(ENV_SECRET);
});
it('falls back to a structural error when the render is not valid JSON', async () => {
stubRender('this is not json {');
const res = await request(app).get(`/api/stacks/${STACK}/effective-anatomy`).set('Authorization', authHeader);
expect(res.status).toBe(200);
expect(res.body.renderable).toBe(false);
expect(res.body.services).toEqual([]);
});
it('never leaks env or label values into the facts', async () => {
stubRender(JSON.stringify({
name: STACK,
services: { web: { image: 'nginx:latest', environment: { TOKEN: ENV_SECRET }, labels: { 'x.secret': LABEL_SECRET } } },
networks: {},
volumes: {},
}));
const res = await request(app).get(`/api/stacks/${STACK}/effective-anatomy`).set('Authorization', authHeader);
expect(res.status).toBe(200);
const body = JSON.stringify(res.body);
expect(body).not.toContain(ENV_SECRET);
expect(body).not.toContain(LABEL_SECRET);
});
it('rejects an unauthenticated request', async () => {
const res = await request(app).get(`/api/stacks/${STACK}/effective-anatomy`);
expect(res.status).toBe(401);
});
it('returns 404 for a stack that does not exist', async () => {
stubRender(JSON.stringify({ name: 'x', services: {}, networks: {}, volumes: {} }));
const res = await request(app).get('/api/stacks/nope-not-here/effective-anatomy').set('Authorization', authHeader);
expect(res.status).toBe(404);
});
});