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.
This commit is contained in:
Anso
2026-06-18 18:25:58 -04:00
committed by GitHub
parent 5f1baa7522
commit ba09e6f69e
11 changed files with 747 additions and 22 deletions
@@ -6,6 +6,7 @@
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
vi.mock('@/lib/api', () => ({ apiFetch: vi.fn() }));
vi.mock('./stack/StackActivityTimeline', () => ({
@@ -338,6 +339,83 @@ describe('StackAnatomyPanel exposed footer', () => {
});
});
describe('StackAnatomyPanel effective dossier (multi-file Git)', () => {
const ROOT_NO_PORTS = 'services:\n web:\n image: nginx:1.25\n';
function renderPanel(content = ROOT_NO_PORTS) {
return render(
<StackAnatomyPanel
stackName="web"
content={content}
envContent=""
selectedEnvFile=".env"
gitSourcePending={false}
onEditCompose={vi.fn()}
onOpenGitSource={vi.fn()}
onApplyUpdate={vi.fn()}
canEdit
applying={false}
/>,
);
}
it('reads override-published ports from the effective model, so the dossier shows them and doc-drift does not false-warn', async () => {
vi.mocked(apiFetch).mockImplementation(async (input: RequestInfo | URL) => {
const url = String(input);
if (url.includes('/update-preview')) return jsonRes(previewBody(false));
if (url.includes('/scan-status')) return jsonRes({ status: 'ok' });
// Multi-file source: two configured compose paths.
if (url.includes('/git-source')) return jsonRes({
repo_url: 'https://github.com/org/repo.git', branch: 'main',
compose_path: 'compose.yaml', compose_paths: ['compose.yaml', 'infra/override.yaml'],
});
// An override publishes :9000, absent from the root file above.
if (url.includes('/effective-anatomy')) return jsonRes({
renderable: true, services: ['web'],
ports: { web: [{ host: '9000', container: '9000', proto: 'tcp', published: true }] },
volumes: {}, restart: null, networks: ['default'],
});
// The operator documented the override's port.
if (url.includes('/dossier')) return jsonRes({ access_urls: 'http://192.168.1.5:9000' });
return jsonRes(null, false);
});
renderPanel();
await userEvent.click(await screen.findByRole('tab', { name: 'Dossier' }));
await screen.findByTestId('dossier-panel');
// The generated-facts ports row counts the override-published port, proving the
// dossier read the merged effective model rather than the port-less root file.
// (Scoped to the SPAN so it does not also match the access_urls value below.)
await screen.findByText((content, el) => el?.tagName === 'SPAN' && content.startsWith('1 published'));
// And doc-drift stays silent: the documented :9000 is published in the effective
// model, so a root-only parse would false-warn here but the effective view must not.
await waitFor(() => expect(screen.queryByTestId('dossier-doc-drift')).not.toBeInTheDocument());
expect(vi.mocked(apiFetch).mock.calls.some(([u]) => String(u).includes('/effective-anatomy'))).toBe(true);
});
it('does not fetch the effective model for a single-file Git stack', async () => {
vi.mocked(apiFetch).mockImplementation(async (input: RequestInfo | URL) => {
const url = String(input);
if (url.includes('/update-preview')) return jsonRes(previewBody(false));
if (url.includes('/scan-status')) return jsonRes({ status: 'ok' });
if (url.includes('/git-source')) return jsonRes({
repo_url: 'https://github.com/org/repo.git', branch: 'main',
compose_path: 'compose.yaml', compose_paths: ['compose.yaml'],
});
if (url.includes('/dossier')) return jsonRes({});
return jsonRes(null, false);
});
renderPanel();
await userEvent.click(await screen.findByRole('tab', { name: 'Dossier' }));
await screen.findByText(/github\.com\/org\/repo#main/);
// Give any (incorrect) effective fetch a chance to fire before asserting absence.
await waitFor(() => expect(vi.mocked(apiFetch).mock.calls.some(([u]) => String(u).includes('/git-source'))).toBe(true));
expect(vi.mocked(apiFetch).mock.calls.some(([u]) => String(u).includes('/effective-anatomy'))).toBe(false);
});
});
describe('StackAnatomyPanel capability gating (capability off)', () => {
it('hides the Networking and Doctor tabs when the capabilities are absent', async () => {
render(panel(false));
+71 -9
View File
@@ -5,7 +5,7 @@ import { Tabs, TabsContent, TabsList, TabsTrigger } from './ui/tabs';
import { ScrollableTabRow } from './ui/ScrollableTabRow';
import { apiFetch } from '@/lib/api';
import { cn } from '@/lib/utils';
import { type AnatomyMarkdownInput } from '@/lib/anatomyMarkdown';
import { type AnatomyMarkdownInput, type PortRow, type VolumeRow } from '@/lib/anatomyMarkdown';
import { parseAnatomy, parseEnvKeys, formatGitSource, primaryPublishedHostPort, type GitSourceInfo } from '@/lib/anatomy';
import { buildServiceUrl } from '@/lib/serviceUrl';
import { StackActivityTimeline } from './stack/StackActivityTimeline';
@@ -48,6 +48,15 @@ interface UpdatePreview {
changelog: string | null;
}
/** Secret-safe effective facts from GET /stacks/:name/effective-anatomy. */
interface EffectiveAnatomyFacts {
services: string[];
ports: Record<string, PortRow[]>;
volumes: Record<string, VolumeRow[]>;
restart: string | null;
networks: string[];
}
function Row({ label, children }: { label: string; children: React.ReactNode }) {
return (
<div className="grid grid-cols-[72px_1fr] gap-3 border-t border-muted py-2 first:border-t-0">
@@ -84,7 +93,12 @@ export default function StackAnatomyPanel({
const doctorEnabled = hasCapability('compose-doctor');
const networkingEnabled = hasCapability('compose-networking');
const [gitSource, setGitSource] = useState<{ stack: string; info: GitSourceInfo } | null>(null);
const [gitSource, setGitSource] = useState<{ stack: string; info: GitSourceInfo; multiFile: boolean } | null>(null);
// Merged effective facts (services/ports/volumes/networks/restart) for a
// multi-file Git stack, fetched from the backend's rendered model so the Dossier
// and its doc-drift reflect every override file. Null for single-file / non-git
// stacks and whenever the render is unavailable, where the root-only parse stands.
const [effectiveAnatomy, setEffectiveAnatomy] = useState<({ stack: string } & EffectiveAnatomyFacts) | null>(null);
const [updatePreview, setUpdatePreview] = useState<UpdatePreview | null>(null);
// Last preflight severity, used only to dot the Doctor tab. Radix mounts the
// active tab content lazily, so the badge cannot come from PreflightPanel; the
@@ -129,9 +143,13 @@ export default function StackAnatomyPanel({
if (data && data.linked === false) {
setGitSource(null);
} else {
// More than one configured compose path means override files merge into
// the deployed model, so the dossier must read the effective render.
const multiFile = Array.isArray(data.compose_paths) && data.compose_paths.length > 1;
setGitSource({
stack: stackName,
info: { repo_url: data.repo_url, branch: data.branch, compose_path: data.compose_path },
multiFile,
});
}
} else {
@@ -145,6 +163,41 @@ export default function StackAnatomyPanel({
return () => { cancelled = true; };
}, [stackName]);
// Multi-file Git stacks deploy a merged model, so the dossier reads the backend's
// rendered effective facts instead of the root compose alone.
useEffect(() => {
// Single-file / non-git stacks keep the root-only parse and skip the fetch.
// Any tagged result left from a previous stack is ignored downstream by the
// stack-name guard, so there is no need to clear state synchronously here.
if (!(gitSource?.stack === stackName && gitSource.multiFile)) return;
let cancelled = false;
const run = async () => {
try {
const res = await apiFetch(`/stacks/${stackName}/effective-anatomy`);
if (cancelled) return;
if (res.ok) {
const data = await res.json();
// Adopt the merged facts only when the model actually rendered; on a render
// error keep the root-only parse so the dossier never shows an empty summary.
setEffectiveAnatomy(data && data.renderable ? {
stack: stackName,
services: Array.isArray(data.services) ? data.services : [],
ports: data.ports ?? {},
volumes: data.volumes ?? {},
restart: data.restart ?? null,
networks: Array.isArray(data.networks) ? data.networks : [],
} : null);
} else {
setEffectiveAnatomy(null);
}
} catch {
if (!cancelled) setEffectiveAnatomy(null);
}
};
void run();
return () => { cancelled = true; };
}, [stackName, activeNode?.id, gitSource]);
useEffect(() => {
let cancelled = false;
const run = async () => {
@@ -235,20 +288,29 @@ export default function StackAnatomyPanel({
// Assembled facts for this stack, passed to the Dossier tab for its read-only
// summary and Markdown export. Null until compose parses.
const anatomyInput = useMemo<AnatomyMarkdownInput | null>(() => {
if (!anatomy) return null;
// Prefer the merged effective facts for multi-file Git stacks so the dossier and
// its doc-drift reflect every override file; fall back to the root-only parse.
// Env-derived fields (count, missing vars, env file) always come from the raw
// parse, which reads the unresolved `${VAR}` references the render has substituted.
// `anatomy` already carries the same structural fields (plus env-only extras we
// read separately below), so the raw parse stands in directly when there are no
// effective facts for this stack.
const activeEffective = effectiveAnatomy?.stack === stackName ? effectiveAnatomy : null;
const structural = activeEffective ?? anatomy;
if (!structural) return null;
return {
stackName,
services: anatomy.services,
ports: anatomy.ports,
volumes: anatomy.volumes,
restart: anatomy.restart,
services: structural.services,
ports: structural.ports,
volumes: structural.volumes,
restart: structural.restart,
envFile: firstEnvFile,
envVarCount,
missingVars,
networkName,
networkName: structural.networks.length > 0 ? structural.networks[0] : `${stackName}_default`,
gitSource: activeGitSource ? formatGitSource(activeGitSource) : null,
};
}, [anatomy, stackName, firstEnvFile, envVarCount, missingVars, networkName, activeGitSource]);
}, [effectiveAnatomy, anatomy, stackName, firstEnvFile, envVarCount, missingVars, activeGitSource]);
const bump = updatePreview?.summary.semver_bump ?? 'none';
const hasUpdate = Boolean(updatePreview?.summary.has_update);