Files
sencho/frontend/src/components/stack/GitSourcePanel.test.tsx
T
Anso d5ef403f67 feat(git): per-source private CA bundles and redirect credential guard (#1870)
* feat(git): add per-source private CA bundles and redirect credential guard

Let operators trust self-hosted HTTPS git servers by storing an encrypted
per-source CA PEM that is combined with system anchors at fetch time, and
block smart-HTTP redirects plus credential helper host scoping so PATs
cannot follow a cross-host Location header.

* fix(git): support removing a stored custom CA bundle

The custom CA bundle field in the Git source edit panel could be
replaced but not removed. The textarea starts empty after load, and
the save body omitted ca_bundle whenever the field was empty, which
the backend interpreted as "keep existing." An operator who retired
or no longer trusted a private CA had no way to revoke the stored
trust anchor.

Add an explicit remove_ca_bundle: true flag the UI sends alongside
the empty ca_bundle when the operator clicks "Remove stored CA."
The backend treats the flag as a clear, even when the field is
omitted, so saved revisions can revoke trust. Round-trip tests at
the service and route layers store, revoke, reload, and confirm
has_ca_bundle is false and the encrypted column is null.

In the same change, address three follow-on gaps in the same surface:

* Extract the per-fetch PEM-file write to
  backend/src/services/git/gitCaBundleSink.ts and add the file to
  paths-ignore in .github/codeql/codeql-config.yml with a comment
  explaining the trust boundary. The sink validates every PEM it
  writes and refuses non-PEM material; the path is always under the
  caller's per-fetch workspace.
* Add e2e/git-source-ca.spec.ts, which drives the full chain
  (API PUT with ca_bundle, API GET, real HTTPS pull, API PUT with
  remove_ca_bundle, API GET) against a local TLS fixture server.
* Drop http.followRedirects=false for HTTPS. Cross-host credential
  safety is already enforced by the host-scoped credential helper,
  which refuses to emit credentials to a host that does not match
  the configured repository. Same-host redirects now continue to
  work, and a new live integration test proves a cross-host
  redirect receives no credentials and the fetch fails closed
  (the redirected host records no Authorization header).

Extract the buildBareRepo helper into a shared test fixture so the
two git integration tests no longer duplicate the bootstrap.

* chore(git): clean up test surfaces on the private-CA branch

Two small follow-ups on the per-source custom CA bundle work:

* Drop the unused Page import in e2e/git-source-ca.spec.ts that the
  code-quality review surfaced. The test body never referenced the
  type, so the import is dead weight.
* Tighten the file header in
  backend/src/__tests__/git-redirect.integration.test.ts so it
  describes what the test pins (cross-host credential refusal, with
  same-host redirects preserved) instead of how it came to be
  written. No behavior change; the assertion set is unchanged.

* fix(git): restore additive platform CA trust and redirect-scope validation

* fix(git): redirect protection, CA bundle fixtures, docs accuracy

* fix(git): redirect enforcement, fixtures, docs, E2E, packet

* fix(git): validate redirect destinations before contacting them

Git ran with http.followRedirects=false and the code that was meant to
recover legitimate redirects keyed off a `Location:` header in git's
stderr. git-remote-http never prints one: it reports only
"The requested URL returned error: 302" when following is disabled, and
prints the destination only on the path where it has already followed
the redirect. The parser therefore never matched, the same-host retry
never fired, and the policy collapsed into deny-all, so every same-host
redirect failed with exit 128 across resolve, fetch, and fast-forward
verification. The retry itself was also malformed: it dropped the config
value while leaving its preceding `-c`.

Redirect policy now lives in redirectPreflight.ts. When git refuses a
redirect, the chain is walked here with an unauthenticated request and
every hop is validated before it is followed: HTTPS only, no loopback,
RFC 1918 or link-local destination, and no host outside the credential
scope. Only an approved chain yields a URL git is re-run against, and it
is applied consistently to resolveRef, fetchAtCommit and
verifyFastForward. A rejected destination is never contacted at all,
which is what keeps the internal-range guard preventive rather than
after the fact.

* test(git): prove redirect policy and per-source CA trust from observed behaviour

The redirect tests asserted only that a fetch rejected, which any failure
satisfied, including one where git never reached the fixture at all. They
are now a matrix over the cases that actually differ: a same-host
redirect resolves the ref both anonymously and with a token, a wrong
token behind that redirect still reports an authentication failure rather
than a redirect failure, and a cross-host redirect is refused against a
destination proven in the same run to serve the ref. Each fixture records
the requests it received, so "never contacted" and "never offered the
token" are read off the server rather than inferred. A probe detects
environments where a spawned git cannot reach loopback and skips there
instead of passing without asserting anything.

The per-source CA E2E ran against a fixture whose certificate the backend
also trusted process-wide, so it passed whether or not the stored bundle
ever reached git, and its closing assertion accepted 200, 500 or 404. The
fixture now presents a certificate from a separate CA that nothing else
trusts, which makes the stored bundle the only thing that can authorise
the fetch, and removing it is required to produce the classified TLS
trust failure.

* fix(git): report why a redirect preflight declined instead of failing quietly

Review of the redirect work found two fail-closed paths that were correct
but undiagnosable. A probe that could not complete was swallowed by a bare
catch, so a private CA that fails to validate looked exactly like a server
that does not redirect. A CA bundle that could not be read fell back to
default trust, which would then validate the operator's private-CA host
against the wrong anchors and fail for a reason nothing reported.

Both now say what happened. An unreadable bundle also stops authorising a
retry rather than probing with trust the operator did not configure, since
that file was written moments earlier by the same invocation and failing
to read it back is a fault rather than a missing option.

Also pins the stderr wording the redirect detector matches, so a git
upgrade that rephrases it fails a test instead of quietly making relocated
repositories unreachable, covers the absolute-Location branch of the
chain walker, and makes the real-git matrix a hard failure in CI when git
cannot reach a loopback fixture. Skipping is right on a workstation that
cannot do this, but in CI it would retire the whole matrix and leave a
green run with nothing exercised.

Documents the redirect behaviour operators can now rely on: a relocation
that stays on the same server keeps working, and one that points
elsewhere is refused without that server being contacted.

* fix(git): run the redirect matrix instead of skipping it, and sanitize its logs

The reachability probe added with the matrix used spawnSync, which blocks
the event loop, so the in-process TLS fixture could never answer it. The
probe timed out and concluded git could not reach loopback, which was
wrong: the cases themselves drive git through the non-blocking spawn path
and work fine. Locally that silently skipped all five, and in CI the guard
turned the mistake into a failure. Removed, so the matrix runs everywhere:
all five now execute in well under a second each.

The two warnings added for declined preflights interpolated a host and an
error message straight into the log line. Both now go through the
sanitizer the repository already registers as a log-injection barrier.

The preflight's outbound request is reported as request forgery because
the URL derives from the configured repository. The first request goes to
that same URL git fetches from anyway, and every later hop is checked
against its origin before being requested, so the walk cannot reach a host
the operator did not configure. Recorded as a scoped exclusion for that one
query, alongside the existing entries that settle the same trust model, so
every other query still analyzes this file.

* fix(git): route every preflight request through one origin check

The redirect preflight necessarily sends the operator's configured
repository URL to an outbound request, which reads as request forgery. The
guarantee the module provides is narrower than the URL being trusted:
nothing is requested that has not first been checked against the
configured origin. That was true of the loop but only as a property of its
shape, so it is now a single function every URL passes through, the seed
included, leaving no path to the network that skips the check.

Declaring that function a barrier states the property to the analysis
instead of excluding the file, so every other query keeps analyzing the
one module whose job is preventing this class of bug. Same mechanism the
repository already uses for log sanitization.

Also sanitizes the kill-confirmation log line, which interpolates a
repository host label supplied by configuration.

* fix(git): fall back to excluding the redirect preflight from CodeQL JS analysis

The barrier model on approvedUrl did not clear the request-forgery alert:
js/request-forgery does not consult the general dataflow barrierModel the
way js/log-injection does, so declaring the origin check's return value
clean had no effect on this query. Falling back to the paths-ignore
mechanism already proven for the two credential sink modules, with the
same trust-model rationale recorded inline: every URL requested, the seed
included, is checked against the configured repository's origin first,
so the walk cannot reach a host the operator did not configure.

The origin-check refactor itself stays; it is a real improvement (one
inspectable choke point instead of a property of the loop's shape) whether
or not the analysis can see it.

* fix(git): allow explicit CA removal to save even when the server currently needs it

Every save runs a dry-run reachability fetch before persisting, including
a revocation. Resolving the stored CA bundle for that fetch already
returns null once removeCaBundle is set, so removing a CA that the
server actually needs to be reached makes the dry-run fail on certificate
trust, and the removal itself gets refused with the same TLS error the
operator was trying to get past. Retiring a certificate that is expiring,
rotated, or no longer trusted was blocked by exactly the unreachability
that retiring it causes.

The dry-run now runs only when a CA bundle is not being explicitly
removed. Every other save path (add or replace a CA, change the
repository or branch) keeps the check unchanged; only remove_ca_bundle
skips it, and only for that one field. Removal always persists, and the
next pull reports the real reachability state.

This surfaced from the E2E hardening in the previous commit: isolating
the CA fixture so the stored bundle is actually load-bearing exposed a
save-time check that the old, globally-trusted fixture had always masked.

* fix(git-source): classify IP-SAN TLS mismatches, fix redirect probe URL, show CA-removal armed state

Live fleet QA against this branch surfaced three defects introduced by
this PR:

- classifyGitFailure's hostname-mismatch regex missed curl's actual
  wording for an IP-address SAN mismatch, so the raw stderr leaked
  through instead of the classified TLS message.
- resolveRedirectedRepoUrl built its initial ref-advertise probe URL by
  string concatenation, corrupting the URL when the source repo URL
  already carried a query string.
- Clicking "Remove stored CA" armed a revocation flag with no visible
  feedback, so an operator could not tell whether the click registered
  or whether typing in the textarea had silently un-armed it.

Adds regression tests for all three.
2026-09-01 09:33:27 -04:00

571 lines
22 KiB
TypeScript

/**
* Covers the panel's load path for the unlinked-stack contract: when the
* backend answers 200 { linked: false } (an existing stack with no Git source
* attached), the form must land in the empty/unlinked state rather than
* treating the sentinel as a configured source.
*/
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, waitFor, fireEvent, within } from '@testing-library/react';
// Mutable controls so a deploy-mode test can set the active node and capture the
// runWithLog params, while the load tests keep the default (no active node).
const nodeCtl = vi.hoisted(() => ({ activeNode: null as { id: number; type?: string } | null }));
const dfCtl = vi.hoisted(() => ({ params: null as null | { stackName: string; action: string; nodeId: number | null } }));
vi.mock('@/lib/api', () => ({ apiFetch: vi.fn() }));
vi.mock('@/context/DeployFeedbackContext', () => ({
useDeployFeedback: () => ({
runWithLog: vi.fn(
async (
params: { stackName: string; action: string; nodeId: number | null },
run: (started: Promise<void>) => Promise<{ ok: boolean }>,
) => {
dfCtl.params = params;
return run(Promise.resolve());
},
),
}),
}));
vi.mock('@/context/NodeContext', () => ({
useNodes: () => ({ activeNode: nodeCtl.activeNode }),
}));
// Drive applyPull(commitSha, deploy=true) directly without standing up the real
// diff UI; the panel passes applyPull as onApply.
vi.mock('./GitSourceDiffDialog', () => ({
GitSourceDiffDialog: ({
open,
onApply,
onDismiss,
pull,
}: {
open: boolean;
onApply: (sha: string, deploy: boolean, fp: string) => void;
onDismiss: () => void;
pull: PullResult | null;
}) => open ? (
<div>
<span data-testid="plan-fingerprint">{pull?.planFingerprint ?? ''}</span>
<button
data-testid="apply-deploy"
onClick={() => onApply('sha-123', true, pull?.planFingerprint ?? 'fp-test')}
>
apply deploy
</button>
<button
data-testid="apply-only"
onClick={() => onApply('sha-123', false, pull?.planFingerprint ?? 'fp-test')}
>
apply
</button>
<button data-testid="dismiss" onClick={onDismiss}>
dismiss
</button>
</div>
) : null,
}));
vi.mock('@/components/ui/toast-store', () => ({
toast: {
success: vi.fn(),
error: vi.fn(),
warning: vi.fn(),
loading: vi.fn(() => 'toast-id'),
dismiss: vi.fn(),
},
}));
import { apiFetch } from '@/lib/api';
import { GitSourcePanel } from './GitSourcePanel';
import { toast } from '@/components/ui/toast-store';
import type { PullResult } from './GitSourceDiffDialog';
import {
absentRevision,
facets,
liveRevision,
missingApplicationLimitation,
sourceRevision,
} from '@/__tests__/gitopsFixtures';
import { SOURCE_STATE } from '@/lib/gitopsState';
function jsonRes(body: unknown, ok = true, status = 200) {
return { ok, status, json: async () => body, text: async () => '' } as unknown as Response;
}
const LINKED_SOURCE = {
id: 1,
stack_name: 'web',
repo_url: 'https://github.com/org/repo.git',
branch: 'main',
compose_path: 'compose.yaml',
sync_env: false,
env_path: null,
auth_type: 'none' as const,
has_token: false,
auto_apply_on_webhook: false,
auto_deploy_on_apply: false,
last_applied_commit_sha: null,
pending_commit_sha: null,
pending_fetched_at: null,
created_at: 0,
updated_at: 0,
manifest_state: 'absent' as const,
manifest: null,
gitopsRevision: sourceRevision('application_generation_accepted', { candidateGenerationId: null }),
};
/** The linked source with its GitOps projection swapped for a specific state. */
function linkedWith(revision: unknown) {
return { ...LINKED_SOURCE, gitopsRevision: revision };
}
const PULL_RESULT: PullResult = {
commitSha: 'sha-old',
validation: { ok: true },
refusals: [],
warnings: [],
plan: {
blocked: false,
counts: {
add: 0,
modify: 0,
delete: 0,
rename: 0,
unchanged: 1,
localModified: 0,
localMissing: 0,
typeChanged: 0,
unmanagedCollision: 0,
invocation: 0,
},
operations: [],
invocation: { candidateChanged: false, liveDiverged: false },
},
planFingerprint: 'fp-old',
};
function panel() {
return (
<GitSourcePanel
open
onOpenChange={vi.fn()}
stackName="web"
canEdit
isDarkMode={false}
/>
);
}
beforeEach(() => {
vi.mocked(apiFetch).mockReset();
nodeCtl.activeNode = null;
dfCtl.params = null;
vi.mocked(toast.success).mockClear();
vi.mocked(toast.warning).mockClear();
vi.mocked(toast.error).mockClear();
});
describe('GitSourcePanel load', () => {
it('treats a 200 { linked: false } response as the empty/unlinked state', async () => {
vi.mocked(apiFetch).mockResolvedValue(jsonRes({ linked: false }));
render(panel());
// The repository field replaces the loading skeleton, so waiting on it is
// what proves the load settled. The footer buttons render in both states.
expect(await screen.findByLabelText(/repository url/i)).toHaveValue('');
// Save (not Update) and no Pull now / Remove affordances means the panel
// did not mistake the { linked: false } sentinel for a configured source.
expect(screen.getByRole('button', { name: /^save$/i })).toBeInTheDocument();
expect(screen.queryByRole('button', { name: /update/i })).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: /pull now/i })).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: 'Remove' })).not.toBeInTheDocument();
});
it('renders the configured source when one is attached', async () => {
vi.mocked(apiFetch).mockResolvedValue(jsonRes(LINKED_SOURCE));
render(panel());
// A real source flips the primary action to Update and exposes Pull now / Remove.
await screen.findByRole('button', { name: /update/i });
expect(screen.getByRole('button', { name: /pull now/i })).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Remove' })).toBeInTheDocument();
await waitFor(() =>
expect(screen.getByLabelText(/repository url/i)).toHaveValue('https://github.com/org/repo.git'),
);
});
});
describe('GitSourcePanel CA bundle removal', () => {
it('shows an armed indicator on Remove click and clears it when a new PEM is typed', async () => {
vi.mocked(apiFetch).mockResolvedValue(jsonRes({ ...LINKED_SOURCE, has_ca_bundle: true }));
render(panel());
await screen.findByRole('button', { name: /update/i });
expect(screen.queryByTestId('git-source-ca-remove-armed')).not.toBeInTheDocument();
fireEvent.click(screen.getByRole('button', { name: /remove stored ca/i }));
expect(screen.getByTestId('git-source-ca-remove-armed')).toBeInTheDocument();
expect(screen.getByText(/will revoke trust for this ca on the next save/i)).toBeInTheDocument();
fireEvent.change(screen.getByLabelText(/custom ca certificate/i), {
target: { value: '-----BEGIN CERTIFICATE-----\nMII...\n-----END CERTIFICATE-----' },
});
expect(screen.queryByTestId('git-source-ca-remove-armed')).not.toBeInTheDocument();
});
});
describe('GitSourcePanel deploy-mode apply node binding', () => {
beforeEach(() => {
nodeCtl.activeNode = { id: 4, type: 'local' };
vi.mocked(apiFetch).mockResolvedValue(jsonRes({ applied: true, deployed: true }));
});
it('binds both runWithLog and the apply POST to the captured node when deploying', async () => {
vi.mocked(apiFetch).mockImplementation(async (url: string) => {
if (String(url).includes('/git-source/apply')) {
return jsonRes({ applied: true, deployed: true });
}
return jsonRes(LINKED_SOURCE);
});
render(panel());
fireEvent.click(await screen.findByRole('button', { name: /pull now/i }));
fireEvent.click(await screen.findByTestId('apply-deploy'));
await waitFor(() => {
const applyCall = vi.mocked(apiFetch).mock.calls.find(c => String(c[0]).includes('/git-source/apply'));
expect(applyCall?.[1]).toEqual(expect.objectContaining({ nodeId: 4 }));
expect(JSON.parse(String((applyCall?.[1] as { body?: string })?.body))).toEqual({
commitSha: 'sha-123',
planFingerprint: 'fp-test',
deploy: true,
});
});
expect(dfCtl.params).toEqual(expect.objectContaining({ action: 'deploy', nodeId: 4 }));
});
});
describe('GitSourcePanel stale plan handling', () => {
beforeEach(() => {
vi.mocked(apiFetch).mockImplementation(async (url: string) => {
if (String(url).includes('/git-source/pull')) {
return jsonRes(PULL_RESULT);
}
if (String(url).includes('/git-source/apply')) {
return jsonRes({
error: 'The change plan is stale.',
code: 'STALE_PLAN',
planFingerprint: 'fp-new',
plan: { ...PULL_RESULT.plan, blocked: true },
}, false, 409);
}
return jsonRes(LINKED_SOURCE);
});
});
it('keeps the diff open and replaces the pending plan on STALE_PLAN', async () => {
render(panel());
fireEvent.click(await screen.findByRole('button', { name: /pull now/i }));
await screen.findByTestId('plan-fingerprint');
expect(screen.getByTestId('plan-fingerprint')).toHaveTextContent('fp-old');
fireEvent.click(screen.getByTestId('apply-only'));
await waitFor(() => {
expect(toast.warning).toHaveBeenCalledWith(expect.stringMatching(/stale/i));
expect(screen.getByTestId('plan-fingerprint')).toHaveTextContent('fp-new');
});
expect(toast.success).not.toHaveBeenCalled();
});
});
describe('GitSourcePanel dismiss handling', () => {
beforeEach(() => {
vi.mocked(apiFetch).mockImplementation(async (url: string) => {
if (String(url).includes('/git-source/pull')) {
return jsonRes(PULL_RESULT);
}
if (String(url).includes('/git-source/dismiss-pending')) {
return jsonRes({
error: 'Cannot dismiss the pending update for web: cannot dismiss while an operation is in flight',
code: 'OPERATION_IN_FLIGHT',
}, false, 409);
}
return jsonRes(LINKED_SOURCE);
});
});
it('surfaces an error toast and keeps the diff open when dismiss is refused as in-flight', async () => {
render(panel());
fireEvent.click(await screen.findByRole('button', { name: /pull now/i }));
await screen.findByTestId('plan-fingerprint');
fireEvent.click(screen.getByTestId('dismiss'));
await waitFor(() => {
expect(toast.error).toHaveBeenCalledWith(expect.stringMatching(/operation is in flight/i));
});
expect(toast.success).not.toHaveBeenCalled();
expect(screen.getByTestId('plan-fingerprint')).toHaveTextContent('fp-old');
});
});
describe('GitSourcePanel manifest summary', () => {
it('renders the managed-project section when the source carries a manifest', async () => {
const summary = {
state: 'active',
manifestVersion: 2,
resolvedCommitSha: 'abc1234567890abc1234567890abc1234567890a',
managedCount: 3,
unmanagedCount: 1,
refusedCount: 0,
refused: [],
hasBuildContexts: true,
generatedAt: 1,
};
vi.mocked(apiFetch).mockImplementation(async (url: string) =>
url.includes('/git-source/manifest')
? jsonRes({
// The manifest endpoint serves the redacted PUBLIC projection
// (path, not sourcePath/materializedPath; no hashes or internals).
manifest: {
manifestVersion: 2,
state: 'active',
inputs: [
{ path: 'compose.yaml', role: 'compose-primary', dependencyKind: 'explicit', ownership: 'managed', sensitivity: 'medium', state: 'present', note: null },
],
},
})
: jsonRes({ ...LINKED_SOURCE, manifest_state: 'active', manifest: summary }),
);
render(panel());
const toggle = await screen.findByText('Managed project');
expect(screen.getByText('abc1234')).toBeTruthy();
expect(screen.getByText('Active')).toBeTruthy();
// Counts render in the expanded section; the inventory is lazy-fetched.
fireEvent.click(toggle);
await waitFor(() => expect(screen.getByText('3')).toBeTruthy());
expect(screen.getByText('1')).toBeTruthy();
expect(screen.getByText('unmanaged')).toBeTruthy();
await waitFor(() => expect(screen.getByText('explicit')).toBeTruthy());
});
it('renders the manifest section with the DB state when the source has no manifest file', async () => {
vi.mocked(apiFetch).mockResolvedValue(jsonRes(LINKED_SOURCE));
render(panel());
await waitFor(() => expect(screen.getByText('Last applied commit')).toBeTruthy());
// The section is driven by the DB manifest_state ('absent') when the file
// has not been materialized yet.
expect(screen.getByText('Managed project')).toBeTruthy();
expect(screen.getByText('Not materialized')).toBeTruthy();
});
});
describe('GitSourcePanel GitOps state', () => {
it('names the waiting state rather than a generic pending update', async () => {
vi.mocked(apiFetch).mockResolvedValue(
jsonRes(linkedWith(sourceRevision('source_conflict_blocker'))),
);
render(panel());
const banner = await screen.findByTestId('git-pending');
expect(banner).toHaveAttribute('data-state', 'source_conflict_blocker');
expect(within(banner).getByText(SOURCE_STATE.source_conflict_blocker.line)).toBeInTheDocument();
// The short sha stays, so the operator can still see which commit it is.
expect(within(banner).getByText('a1b2c3d')).toBeInTheDocument();
});
it('offers apply wording for a candidate that needs no review', async () => {
vi.mocked(apiFetch).mockResolvedValue(
jsonRes(linkedWith(sourceRevision('candidate_ready'))),
);
render(panel());
const banner = await screen.findByTestId('git-pending');
expect(within(banner).getByText(SOURCE_STATE.candidate_ready.line)).toBeInTheDocument();
});
it('shows no banner when the accepted generation has no candidate behind it', async () => {
vi.mocked(apiFetch).mockResolvedValue(jsonRes(LINKED_SOURCE));
render(panel());
await screen.findByRole('button', { name: /pull now/i });
expect(screen.queryByTestId('git-pending')).not.toBeInTheDocument();
expect(screen.getByTestId('git-source-state')).toHaveTextContent(
SOURCE_STATE.application_generation_accepted.label,
);
});
it('reports an application the projection could not reach', async () => {
vi.mocked(apiFetch).mockResolvedValue(
jsonRes(linkedWith(absentRevision([missingApplicationLimitation]))),
);
render(panel());
const fault = await screen.findByTestId('gitops-fault');
expect(fault).toHaveTextContent(missingApplicationLimitation.message);
});
it('stays silent for a stack the model was never asked about', async () => {
// Empty limitations is the ordinary case and must not read as a failure.
vi.mocked(apiFetch).mockResolvedValue(jsonRes({ linked: false, gitopsRevision: absentRevision() }));
render(panel());
await screen.findByRole('button', { name: /^save$/i });
expect(screen.queryByTestId('gitops-fault')).not.toBeInTheDocument();
expect(screen.queryByTestId('git-pending')).not.toBeInTheDocument();
expect(screen.queryByTestId('git-source-state')).not.toBeInTheDocument();
});
it('drops the pending card once the source is detached', async () => {
// The card is derived from the revision alone, so a detach that only
// cleared the source would keep advertising a commit for a stack Git no
// longer manages, behind a Review button that does nothing.
vi.mocked(apiFetch).mockImplementation(async (url: string) => {
if (String(url).endsWith('/git-source') && !String(url).includes('?')) {
return jsonRes(linkedWith(sourceRevision('candidate_ready')));
}
return jsonRes({ ok: true });
});
render(panel());
await screen.findByTestId('git-pending');
fireEvent.click(screen.getByRole('button', { name: 'Remove' }));
fireEvent.click(await screen.findByRole('button', { name: /^detach/i }));
await waitFor(() => expect(screen.queryByTestId('git-pending')).not.toBeInTheDocument());
});
it('drops the revision when a later read fails, so one stack cannot report another stack state', async () => {
// The panel is reused across stacks. A read that throws after a successful
// one has to clear the projection, or stack A's pending commit renders
// under stack B's header.
vi.mocked(apiFetch).mockResolvedValue(
jsonRes(linkedWith(sourceRevision('candidate_ready'))),
);
const { rerender } = render(
<GitSourcePanel open onOpenChange={vi.fn()} stackName="web" canEdit isDarkMode={false} />,
);
await screen.findByTestId('git-pending');
vi.mocked(apiFetch).mockRejectedValue(new Error('offline'));
rerender(<GitSourcePanel open onOpenChange={vi.fn()} stackName="api" canEdit isDarkMode={false} />);
// Wait for the load to settle before asserting: the body is skeletons while
// it is in flight, so an assertion there would pass without the fix.
await waitFor(() => expect(toast.error).toHaveBeenCalled());
await screen.findByLabelText(/repository url/i);
expect(screen.queryByTestId('git-pending')).not.toBeInTheDocument();
});
it('re-reads after a save and shows the state the server reports', async () => {
// The save answers with a bare source row and no revision, so the panel
// cannot learn the new state from it. Keeping the old one would report a
// candidate the save has just invalidated; showing nothing would report
// "no GitOps here" for a stack that has it.
vi.mocked(apiFetch).mockResolvedValue(
jsonRes(linkedWith(sourceRevision('candidate_ready'))),
);
render(panel());
await screen.findByTestId('git-pending');
vi.mocked(apiFetch)
// The PUT.
.mockResolvedValueOnce(jsonRes({ ...LINKED_SOURCE, gitopsRevision: undefined }))
// The re-read, which is where the state actually comes from.
.mockResolvedValueOnce(jsonRes(linkedWith(
sourceRevision('source_reconcile_required', { candidateGenerationId: null }),
)));
fireEvent.click(screen.getByRole('button', { name: /update/i }));
await waitFor(() => expect(screen.getByTestId('git-source-state'))
.toHaveTextContent(SOURCE_STATE.source_reconcile_required.label));
// The staged candidate is gone, so nothing is offered to review.
expect(screen.queryByTestId('git-pending')).not.toBeInTheDocument();
});
it('does not go blank after a save', async () => {
// The save response carries no revision. Before the re-read, the panel
// dropped its copy and rendered nothing until the next open, which reads
// as a stack the model knows nothing about.
vi.mocked(apiFetch).mockResolvedValue(
jsonRes(linkedWith(sourceRevision('application_generation_accepted', { candidateGenerationId: null }))),
);
render(panel());
await screen.findByTestId('git-source-state');
vi.mocked(apiFetch)
.mockResolvedValueOnce(jsonRes({ ...LINKED_SOURCE, gitopsRevision: undefined }))
.mockResolvedValueOnce(jsonRes(linkedWith(
sourceRevision('application_generation_accepted', { candidateGenerationId: null }),
)));
fireEvent.click(screen.getByRole('button', { name: /update/i }));
await waitFor(() => expect(toast.success).toHaveBeenCalled());
expect(screen.getByTestId('git-source-state')).toBeInTheDocument();
});
it('shows no source card for an application that has no Git source', async () => {
// Guards the panel against a projection whose source facet is not
// applicable: without it the card renders "no git source" with a live
// Review button.
vi.mocked(apiFetch).mockResolvedValue(jsonRes(linkedWith(liveRevision({
targetMode: 'inline_blueprint',
facets: facets({
source: { status: 'not_applicable' },
placement: { status: 'blueprint_bound', completion: 'unknown' },
}),
}))));
render(panel());
await screen.findByRole('button', { name: /pull now/i });
expect(screen.queryByTestId('git-pending')).not.toBeInTheDocument();
expect(screen.queryByTestId('git-source-state')).not.toBeInTheDocument();
});
it('still reports a waiting commit when no projection answered', async () => {
// A swallowed GitOps write leaves the flat pointer as the only evidence.
// The sidebar keeps showing it, so the panel has to agree.
vi.mocked(apiFetch).mockResolvedValue(jsonRes({
...LINKED_SOURCE,
pending_commit_sha: 'f00ba12345',
gitopsRevision: absentRevision(),
}));
render(panel());
const banner = await screen.findByTestId('git-pending');
expect(within(banner).getByText('f00ba12')).toBeInTheDocument();
});
it('does not treat a live application caveat as a fault', async () => {
vi.mocked(apiFetch).mockResolvedValue(jsonRes(linkedWith(liveRevision({
limitations: [{ code: 'repo_identity_invalid', message: 'Repository identity could not be read.', evidence: null }],
}))));
render(panel());
await screen.findByTestId('git-source-state');
expect(screen.queryByTestId('gitops-fault')).not.toBeInTheDocument();
});
it('routes the pending card Review button to the pull endpoint', async () => {
vi.mocked(apiFetch).mockResolvedValue(
jsonRes(linkedWith(sourceRevision('candidate_ready'))),
);
render(panel());
const banner = await screen.findByTestId('git-pending');
fireEvent.click(within(banner).getByRole('button', { name: 'Review' }));
await waitFor(() => expect(
vi.mocked(apiFetch).mock.calls.some(c => String(c[0]).includes('/git-source/pull')),
).toBe(true));
});
});