fix(image-updates): match any local RepoDigest against the remote tag (#1695)

* fix(image-updates): match any local RepoDigest against the remote tag

Docker can list a stale multi-arch index digest ahead of the current one
on the same image. Selecting only the first RepoDigest caused false
same-tag rebuilds (for example redis:8.8.0) even when another digest
equaled the registry primary. Compare every matching candidate and keep
fail-closed behavior for empty, unknown-platform, and classification errors.

Fixes #1684

* fix(image-updates): surface digest verification failures to operators

Carry comparator errors into update-preview as check_error / verification_failed,
prefer failed checks over sticky has_update in Fleet and the sidebar, and keep
Update Guard from claiming no pending update when verification failed.

* fix(e2e): align sidebar truncation spec with check-failed precedence

StackRow now shows the check-failed icon over a stale update dot, but
this spec still asserted the old precedence and failed deterministically
in CI on every attempt.

* fix(fleet): treat verification-only previews as non-actionable

Fresh update-preview wins over sticky fleet booleans: disable Apply, exclude
from ready counts, and move verification-only stacks into the check-failures
advisory (including remote-labeled names).

* fix(fleet): move preview actionability helpers out of the view

Exporting non-components from AutoUpdateReadinessView tripped react-refresh
lint in CI. Keep the helpers in a shared lib module and drop an unused mock arg.

* fix(fleet): drop sticky cards when fresh preview clears the update

A successful no-update preview now removes the pending Fleet card instead of
leaving Apply enabled. Verification-only stacks still go to the advisory, and
empty-state copy no longer claims all-clear while checks remain unresolved.

* fix(image-updates): hold full-stack apply for review when another image fails verification

A confirmed update or rebuild on one image previously left the whole stack
fully actionable even when a different image in the same stack failed digest
verification: Anatomy claimed "safe to apply", Update Guard reported ready,
and Fleet's full-stack Apply stayed enabled, all while showing the
verification-failure text right next to those claims.

isActionableUpdatePreview now requires no verification failure anywhere in
the stack; a new isReviewRequiredUpdatePreview flags the mixed state so Fleet
still surfaces the card (not silently cleared) with Apply now disabled and a
"Review · unverified" badge. Anatomy's banner says "review required" instead
of a bump-based safety claim and withholds its Apply button. Update Guard's
pending-update signal downgrades from ok to attention. Per-service apply
(Fleet's per-image row) is deliberately left enabled since a service-scoped
update to the confirmed image does not touch the unverified one.

* fix(image-updates): treat rebuild_available symmetrically with has_update in Update Guard

updatePreviewSignal only downgraded to 'attention' inside the has_update
branch, so a rebuild-only stack (has_update false, rebuild_available true)
with a sibling verification failure fell through to the plain
verification-only 'unknown' branch and never mentioned the pending rebuild,
inconsistent with isReviewRequiredUpdatePreview on the frontend which treats
has_update and rebuild_available the same way.

Also adds desktop-card coverage for the mixed state (previously only the
mobile card was exercised) and locks in blocked/major-bump precedence over
the new review-required badge/banner in both Fleet and Anatomy.

* fix(image-updates): derive the mixed-verification review-hold from per-image detail, not the stack aggregate

has_update and check_error are independent per image: a tag-based update can
be confirmed via the registry's tag list even when that same image's own
digest comparison against the current tag errored (already covered by an
existing update-preview-service test). The stack-level verification_failed
and has_update flags can therefore both be true for the SAME single image,
which the previous review-hold treated identically to a genuinely different
image failing verification: Update Guard said "another image failed digest
verification" and Fleet told the user to "apply the confirmed service
individually" on a single-service stack where no such affordance exists.

isReviewRequiredUpdatePreview (and isActionableUpdatePreview) now walk the
preview's images to require a pure failure image (check_error, no has_update
of its own) alongside a genuinely different confirmed image or rebuild,
falling back to the old aggregate-only judgment when per-image detail is
unavailable. StackAnatomyPanel now imports the shared helper instead of
hand-rolling the same predicate, so Fleet and Anatomy cannot drift apart.
Backend updatePreviewSignal gets the same per-image treatment via a new
optional images parameter, threaded through from UpdateGuardService.

* fix(image-updates): fail closed on platform-unavailable indexes and legacy previews, allow anonymous tag listing

Four independent gaps from the same QA pass, all in the digest/tag
verification path this PR introduced or touches:

- compareLocalToRemoteTag now distinguishes a remote index with no descriptor
  at all for the local platform (including an empty or fully-filtered index)
  from a genuine mismatch: the former returns an error instead of reporting a
  speculative update. A node cannot pull a platform the index does not offer.
- selectLocalRepoDigests no longer falls back to a sole unrelated-repository
  RepoDigest when nothing matches the configured repo; comparing against a
  registry state that has nothing to do with the declared image risks a
  false update. Returns unresolved instead of guessing.
- isClearedUpdatePreview no longer treats a preview with verification_failed
  missing entirely (not merely false) as proof the stack is clean. The
  current backend always includes this field, so its absence identifies an
  older remote node's response, which cannot vouch for a clean result the
  way an explicit false can.
- listRegistryTags (and the underlying listRegistryTagsResult) no longer
  short-circuits to an empty list whenever no registry credentials are
  configured. getAuthToken already resolves anonymous tokens for public
  repositories; skipping it meant tag-based update detection silently never
  fired for any public image without a stored credential.

* fix(image-updates): correct platform-check overreach, add cache and advisory for prior fixes

Addresses code-review findings on the previous commit:

- The platform-unavailable check fired too eagerly: an index whose runnable
  descriptors legally omit platform (OCI-permitted, routed to exactDigests)
  has real pullable content, so it must not be confused with a genuinely
  empty or fully-filtered index. Now only errors when both platform-labeled
  descriptors and exactDigests are empty.
- listRegistryTags is now cached (15 min TTL): anonymous listing has no other
  rate limiting, and Fleet fans this out across every image on every reload.
- A legacy preview (kept rather than cleared) now also pushes a check-failure
  advisory entry explaining why, instead of rendering as an unexplained
  pending card.
- Corrected docstrings that described the old sole-unmatched-digest fallback
  and inverted how anonymous registry auth actually resolves.

Adds coverage for: nested-index and attestation-only-filtered platform
unavailability, a platform-less-but-populated index staying a match, the
unrelated-repo digest rejection wired through the real preview-computation
path (not just the registry-api unit), and legacy-preview interaction with
an actionable has_update:true.

* fix(image-updates): fail closed on mixed platform indexes, stop caching tag-list failures

Addresses a second review round on the previous commit, including an
empirically-verified regression:

- The exactDigests fallback was unconditional: an index mixing a
  platform-labeled descriptor for a DIFFERENT platform with an unlabeled leaf
  let that leaf stand in as this platform's content, reporting a speculative
  update for a genuinely incompatible platform. Now an unlabeled leaf is only
  trusted when it is the ONLY kind of descriptor in the index (nothing else
  claims a different platform); a mixed index errors instead.
- listRegistryTags was caching failed lookups for the full 15-minute TTL
  (a 429, an unreachable registry, or credentials not yet configured all
  looked identical to a real empty tag list). The fetcher now throws on
  failure so only a success is ever cached; CacheService's existing
  stale-on-error fallback still serves the last good list when one exists.
- The manual "Recheck" action now also drops the tag-list cache, so a newly
  published tag is visible immediately instead of waiting out the TTL.
- The legacy-preview advisory no longer fires when the same preview is
  already actionable on its own terms (a remote's own confirmed
  has_update/rebuild_available): pairing a "could not be checked" banner
  with an enabled Apply button next to it contradicted itself.
- Corrected docstrings and a self-contradictory inline comment left over
  from the prior fix.

New coverage: the exact mixed-index regression this round found and fixed,
cache hit/no-repeat-fetch and failure-not-cached behavior, and the
legacy-preview-plus-already-actionable non-contradiction.

* fix(image-updates): add digest_error unmasked field, reorder RiskBadge, fix actionability gates

Add digest_error to UpdatePreviewImage as an always-populated field that
is independent of check_status masking: a confirmed tag-based update on
the same image resolves check_status to 'ok' and nulls check_error, but
digest_error stays set since the image's current tag content was never
verified. Switch hasUnverifiedOtherImage to read digest_error.

Reorder RiskBadge precedence so reviewRequired is checked before
uncertain (both derive from check_error, so uncertain was unreachable).

Fix self-contradiction in test fixtures (digest_update:true +
check_error). Add masked-tag regression test with two-image fixture.
Simplify hasUnverifiedOtherImage per code review feedback.
This commit is contained in:
Anso
2026-07-25 21:57:30 -04:00
committed by GitHub
parent 0daddfde00
commit 6688da97b1
16 changed files with 2151 additions and 162 deletions
@@ -110,11 +110,21 @@ vi.mock('../services/NodeRegistry', () => ({
}));
// compareLocalToRemoteTag is module-scoped inside checkImage; mock it to drive the
// comparison outcome while keeping the real parseImageRef / selectLocalRepoDigest.
const { mockCompareLocalToRemoteTag } = vi.hoisted(() => ({ mockCompareLocalToRemoteTag: vi.fn() }));
// comparison outcome while keeping the real parseImageRef / selectLocalRepoDigests.
const { mockCompareLocalToRemoteTag, mockListRegistryTagsResult } = vi.hoisted(() => ({
mockCompareLocalToRemoteTag: vi.fn(),
// Detection now checks tags alongside digests; default to an empty, successful
// list so digest-focused tests are not accidentally driven by a real network
// call finding a genuine newer tag for whatever image ref they pass.
mockListRegistryTagsResult: vi.fn().mockResolvedValue({ ok: true, tags: [] }),
}));
vi.mock('../services/registry-api', async (importOriginal) => {
const actual = await importOriginal<typeof import('../services/registry-api')>();
return { ...actual, compareLocalToRemoteTag: mockCompareLocalToRemoteTag };
return {
...actual,
compareLocalToRemoteTag: mockCompareLocalToRemoteTag,
listRegistryTagsResult: mockListRegistryTagsResult,
};
});
// ── Re-export internal helpers via the module ─────────────────────────
@@ -207,6 +217,17 @@ describe('ImageUpdateService - image ref parsing (via checkImage)', () => {
expect(result.notCheckable).toBeUndefined();
expect(result.error).toContain('Could not resolve a local registry digest');
});
it('errors (not a comparison) when the sole valid RepoDigest belongs to an unrelated repository', async () => {
// A well-formed digest is present, but it names a different repo (e.g.
// left over from a retag): comparing it against this ref's registry state
// would risk a false update against unrelated content.
const docker = makeMockDocker([`ghcr.io/other/image@sha256:${'b'.repeat(64)}`]);
const result = await service.checkImage(docker, 'nginx:latest');
expect(result.hasUpdate).toBe(false);
expect(result.notCheckable).toBeUndefined();
expect(result.error).toContain('Could not resolve a local registry digest');
});
});
// ── checkImage surfaces the comparison resolver's outcome ──────────────
@@ -264,6 +285,36 @@ describe('ImageUpdateService - checkImage surfaces the comparison resolver outco
null,
);
});
it('forwards every matching RepoDigest (stale index ahead of current) to the comparison resolver', async () => {
const STALE = `sha256:${'f'.repeat(64)}`;
const CURRENT = `sha256:${'e'.repeat(64)}`;
const docker = {
getDocker: () => ({
getImage: () => ({
inspect: vi.fn().mockResolvedValue({
RepoDigests: [
`redis@${STALE}`,
`redis@${CURRENT}`,
],
Os: 'linux',
Architecture: 'amd64',
}),
}),
}),
} as any;
mockCompareLocalToRemoteTag.mockResolvedValue({ kind: 'match' });
const result = await service.checkImage(docker, 'redis:8.8.0');
expect(result).toEqual({ hasUpdate: false, digestUpdate: false, tagUpdate: false, checkStatus: 'ok' });
expect(mockCompareLocalToRemoteTag).toHaveBeenCalledWith(
[STALE, CURRENT],
'registry-1.docker.io',
'library/redis',
'8.8.0',
{ os: 'linux', architecture: 'amd64' },
null,
);
});
});
// ── Multi-arch digest comparison persistence (end-to-end via checkNode) ─
+318 -3
View File
@@ -58,6 +58,7 @@ import {
getRemoteDigest,
getRemoteDigestResult,
getAuthToken,
listRegistryTags,
listRegistryTagsResult,
parseImageRef,
selectLocalRepoDigest,
@@ -359,6 +360,31 @@ describe('listRegistryTagsResult', () => {
});
});
describe('listRegistryTags (compatibility wrapper)', () => {
beforeEach(() => {
calls.length = 0;
});
it('lists tags for a public Docker Hub repository with no credentials configured', async () => {
route = (url) => tokenOk(url) ?? (
url.includes('/tags/list')
? { statusCode: 200, headers: {}, body: JSON.stringify({ tags: ['8.7.0', '8.8.0'] }) }
: { statusCode: 500, headers: {} }
);
await expect(listRegistryTags('registry-1.docker.io', 'library/redis', null)).resolves.toEqual(['8.7.0', '8.8.0']);
});
it('still returns empty for a registry that actually requires credentials the caller does not have', async () => {
const CHALLENGE = 'Bearer realm="https://ghcr.io/token",service="ghcr.io",scope="repository:user/image:pull"';
route = (url): FakeResp => {
if (url === 'https://ghcr.io/v2/') return { statusCode: 401, headers: { 'www-authenticate': CHALLENGE } };
if (url.startsWith('https://ghcr.io/token')) return { statusCode: 401, headers: {} };
return { statusCode: 500, headers: {} };
};
await expect(listRegistryTags('ghcr.io', 'private/app', undefined)).resolves.toEqual([]);
});
});
// ─── selectLocalRepoDigest ───────────────────────────────────────────────
describe('selectLocalRepoDigest', () => {
@@ -375,9 +401,9 @@ describe('selectLocalRepoDigest', () => {
expect(selectLocalRepoDigest(repoDigests, parsed('nginx:latest'))).toBe(DIGEST_A);
});
it('falls back to the sole valid entry when nothing matches the ref', () => {
it('returns null when the sole valid entry belongs to an unrelated repository, rather than guessing', () => {
const repoDigests = [`ghcr.io/other/image@${DIGEST_A}`];
expect(selectLocalRepoDigest(repoDigests, parsed('nginx:latest'))).toBe(DIGEST_A);
expect(selectLocalRepoDigest(repoDigests, parsed('nginx:latest'))).toBeNull();
});
it('returns null when multiple valid entries exist and none matches the ref', () => {
@@ -408,6 +434,7 @@ describe('selectLocalRepoDigest', () => {
});
});
// ─── selectLocalRepoDigests ──────────────────────────────────────────────
describe('selectLocalRepoDigests', () => {
const parsed = (ref: string) => {
@@ -417,6 +444,43 @@ describe('selectLocalRepoDigests', () => {
};
const DIGEST_A = `sha256:${'a'.repeat(64)}`;
const DIGEST_B = `sha256:${'b'.repeat(64)}`;
const DIGEST_C = `sha256:${'c'.repeat(64)}`;
it('returns every matching entry in first-seen order', () => {
const repoDigests = [`redis@${DIGEST_A}`, `nginx@${DIGEST_B}`, `redis@${DIGEST_C}`];
expect(selectLocalRepoDigests(repoDigests, parsed('redis:8.8.0'))).toEqual([DIGEST_A, DIGEST_C]);
});
it('deduplicates matching digests while preserving first-seen order', () => {
const repoDigests = [`redis@${DIGEST_A}`, `redis@${DIGEST_B}`, `redis@${DIGEST_A}`];
expect(selectLocalRepoDigests(repoDigests, parsed('redis:latest'))).toEqual([DIGEST_A, DIGEST_B]);
});
it('deduplicates case-insensitively on hex digits', () => {
const upper = `sha256:${'A'.repeat(64)}`;
const lower = `sha256:${'a'.repeat(64)}`;
expect(selectLocalRepoDigests([`nginx@${upper}`, `nginx@${lower}`], parsed('nginx:latest'))).toEqual([upper]);
});
it('filters malformed entries and keeps valid matches', () => {
const repoDigests = ['redis@sha256:tooshort', `redis@${DIGEST_A}`, 'redis:latest', `redis@${DIGEST_B}`];
expect(selectLocalRepoDigests(repoDigests, parsed('redis:latest'))).toEqual([DIGEST_A, DIGEST_B]);
});
it('returns empty when the sole valid entry belongs to an unrelated repository, rather than guessing', () => {
// A legitimate retag can leave a lone RepoDigest from a different repo, but
// comparing it against this ref's registry state risks a false update
// against a registry that has nothing to do with the declared image.
expect(selectLocalRepoDigests([`ghcr.io/other/image@${DIGEST_A}`], parsed('nginx:latest'))).toEqual([]);
});
it('returns empty when multiple valid entries exist and none matches the ref', () => {
expect(selectLocalRepoDigests([`redis@${DIGEST_A}`, `postgres@${DIGEST_B}`], parsed('nginx:latest'))).toEqual([]);
});
it('returns empty for an empty list', () => {
expect(selectLocalRepoDigests([], parsed('nginx:latest'))).toEqual([]);
});
it('returns every matching RepoDigest for the image ref', () => {
const digests = selectLocalRepoDigests([
@@ -545,6 +609,215 @@ describe('compareLocalToRemoteTag', () => {
]);
});
// #1684: Docker can list a stale index digest ahead of the current one.
const STALE_INDEX = `sha256:${'f'.repeat(64)}`;
it('matches when a later candidate equals the primary even if the first candidate is a stale index', async () => {
route = (url, method) => tokenOk(url) ?? (
method === 'HEAD'
? { statusCode: 200, headers: { 'docker-content-digest': INDEX_DIGEST, 'content-type': INDEX_CONTENT_TYPE } }
: { statusCode: 500, headers: {} }
);
const result = await compareLocalToRemoteTag([STALE_INDEX, INDEX_DIGEST], REGISTRY, REPO, TAG, AMD64);
expect(result).toEqual({ kind: 'match' });
expect(calls.filter((c) => c.url.includes('/manifests/'))).toHaveLength(1);
});
it('matches when the current primary is first among multiple candidates', async () => {
route = (url, method) => tokenOk(url) ?? (
method === 'HEAD'
? { statusCode: 200, headers: { 'docker-content-digest': INDEX_DIGEST, 'content-type': INDEX_CONTENT_TYPE } }
: { statusCode: 500, headers: {} }
);
const result = await compareLocalToRemoteTag([INDEX_DIGEST, STALE_INDEX], REGISTRY, REPO, TAG, AMD64);
expect(result).toEqual({ kind: 'match' });
});
it('expands the index once when a later candidate matches a platform child', async () => {
route = (url, method) => {
const token = tokenOk(url);
if (token) return token;
if (url === MANIFEST_URL_TAG && method === 'HEAD') {
return { statusCode: 200, headers: { 'docker-content-digest': INDEX_DIGEST, 'content-type': INDEX_CONTENT_TYPE } };
}
if (url === manifestDigestUrl(INDEX_DIGEST) && method === 'GET') {
return { statusCode: 200, headers: { 'docker-content-digest': INDEX_DIGEST }, body: STANDARD_INDEX_BODY };
}
return { statusCode: 500, headers: {} };
};
const result = await compareLocalToRemoteTag([STALE_INDEX, CHILD_AMD64], REGISTRY, REPO, TAG, AMD64);
expect(result).toEqual({ kind: 'match' });
expect(calls.filter((c) => c.url.includes('/manifests/'))).toEqual([
{ url: MANIFEST_URL_TAG, method: 'HEAD' },
{ url: manifestDigestUrl(INDEX_DIGEST), method: 'GET' },
]);
});
it('reports update when every candidate is stale after a complete index classification', async () => {
route = (url, method) => {
const token = tokenOk(url);
if (token) return token;
if (url === MANIFEST_URL_TAG && method === 'HEAD') {
return { statusCode: 200, headers: { 'docker-content-digest': INDEX_DIGEST, 'content-type': INDEX_CONTENT_TYPE } };
}
if (url === manifestDigestUrl(INDEX_DIGEST) && method === 'GET') {
return { statusCode: 200, headers: { 'docker-content-digest': INDEX_DIGEST }, body: STANDARD_INDEX_BODY };
}
return { statusCode: 500, headers: {} };
};
const result = await compareLocalToRemoteTag([STALE_INDEX], REGISTRY, REPO, TAG, AMD64);
expect(result).toEqual({ kind: 'update' });
});
it('errors (not update) when the remote index has no descriptor at all for the local platform', async () => {
// STANDARD_INDEX_BODY only carries linux/amd64 and linux/arm64 children.
// A windows/amd64 node cannot pull anything from this index; that is not
// the same fact as "a newer build is available".
route = (url, method) => {
const token = tokenOk(url);
if (token) return token;
if (url === MANIFEST_URL_TAG && method === 'HEAD') {
return { statusCode: 200, headers: { 'docker-content-digest': INDEX_DIGEST, 'content-type': INDEX_CONTENT_TYPE } };
}
if (url === manifestDigestUrl(INDEX_DIGEST) && method === 'GET') {
return { statusCode: 200, headers: { 'docker-content-digest': INDEX_DIGEST }, body: STANDARD_INDEX_BODY };
}
return { statusCode: 500, headers: {} };
};
const result = await compareLocalToRemoteTag([STALE_INDEX], REGISTRY, REPO, TAG, { os: 'windows', architecture: 'amd64' });
expect(result).toEqual({ kind: 'error', reason: expect.stringContaining('no windows/amd64 variant') });
});
it('errors (not update) for an empty index with no manifests, rather than a speculative update', async () => {
const emptyIndexBody = indexBody([]);
const emptyIndexDigest = contentDigest(emptyIndexBody);
route = (url, method) => {
const token = tokenOk(url);
if (token) return token;
if (url === MANIFEST_URL_TAG && method === 'HEAD') {
return { statusCode: 200, headers: { 'docker-content-digest': emptyIndexDigest, 'content-type': INDEX_CONTENT_TYPE } };
}
if (url === manifestDigestUrl(emptyIndexDigest) && method === 'GET') {
return { statusCode: 200, headers: { 'docker-content-digest': emptyIndexDigest }, body: emptyIndexBody };
}
return { statusCode: 500, headers: {} };
};
const result = await compareLocalToRemoteTag([STALE_INDEX], REGISTRY, REPO, TAG, AMD64);
expect(result.kind).toBe('error');
});
it('errors (not update) for an index whose only entries are filtered out (attestation-only), not just a literally empty one', async () => {
// Exercises the filtering path (parseIndexBody's attestation-manifest and
// unknown/unknown continues), distinct from manifests:[] never entering
// the per-entry loop at all.
const filteredIndexBody = indexBody([
{
digest: CHILD_AMD64, os: 'unknown', architecture: 'unknown',
annotations: { 'vnd.docker.reference.type': 'attestation-manifest', 'vnd.docker.reference.digest': CHILD_ARM64 },
},
]);
const filteredIndexDigest = contentDigest(filteredIndexBody);
route = (url, method) => {
const token = tokenOk(url);
if (token) return token;
if (url === MANIFEST_URL_TAG && method === 'HEAD') {
return { statusCode: 200, headers: { 'docker-content-digest': filteredIndexDigest, 'content-type': INDEX_CONTENT_TYPE } };
}
if (url === manifestDigestUrl(filteredIndexDigest) && method === 'GET') {
return { statusCode: 200, headers: { 'docker-content-digest': filteredIndexDigest }, body: filteredIndexBody };
}
return { statusCode: 500, headers: {} };
};
const result = await compareLocalToRemoteTag([STALE_INDEX], REGISTRY, REPO, TAG, AMD64);
expect(result).toEqual({ kind: 'error', reason: expect.stringContaining('no linux/amd64 variant') });
});
it('matches (not errors) a platform-less runnable descriptor even though no platform-labeled descriptor exists', async () => {
// OCI allows a runnable descriptor to omit platform; parseIndexBody routes
// it to exactDigests. The index has real, pullable content, so this must
// not be confused with the "nothing to pull" case.
const platformlessDigest = `sha256:${'7'.repeat(64)}`;
const noPlatformBody = JSON.stringify({
schemaVersion: 2,
mediaType: INDEX_CONTENT_TYPE,
manifests: [{ digest: platformlessDigest, mediaType: 'application/vnd.oci.image.manifest.v1+json' }],
});
const noPlatformDigest = contentDigest(noPlatformBody);
route = (url, method) => {
const token = tokenOk(url);
if (token) return token;
if (url === MANIFEST_URL_TAG && method === 'HEAD') {
return { statusCode: 200, headers: { 'docker-content-digest': noPlatformDigest, 'content-type': INDEX_CONTENT_TYPE } };
}
if (url === manifestDigestUrl(noPlatformDigest) && method === 'GET') {
return { statusCode: 200, headers: { 'docker-content-digest': noPlatformDigest }, body: noPlatformBody };
}
return { statusCode: 500, headers: {} };
};
const result = await compareLocalToRemoteTag([platformlessDigest], REGISTRY, REPO, TAG, AMD64);
expect(result).toEqual({ kind: 'match' });
});
it('errors (not update) for a mixed index: a platform-less leaf cannot be attributed when another descriptor is explicitly labeled for a different platform', async () => {
// Regression: an index with one arm64-labeled descriptor and one
// unlabeled leaf must not let the unlabeled leaf stand in as amd64
// content just because SOME descriptor in the index is unlabeled.
const unrelatedLeaf = `sha256:${'6'.repeat(64)}`;
const mixedIndexBody = JSON.stringify({
schemaVersion: 2,
mediaType: INDEX_CONTENT_TYPE,
manifests: [
{ digest: CHILD_ARM64, mediaType: 'application/vnd.oci.image.manifest.v1+json', platform: { os: 'linux', architecture: 'arm64' } },
{ digest: unrelatedLeaf, mediaType: 'application/vnd.oci.image.manifest.v1+json' },
],
});
const mixedIndexDigest = contentDigest(mixedIndexBody);
route = (url, method) => {
const token = tokenOk(url);
if (token) return token;
if (url === MANIFEST_URL_TAG && method === 'HEAD') {
return { statusCode: 200, headers: { 'docker-content-digest': mixedIndexDigest, 'content-type': INDEX_CONTENT_TYPE } };
}
if (url === manifestDigestUrl(mixedIndexDigest) && method === 'GET') {
return { statusCode: 200, headers: { 'docker-content-digest': mixedIndexDigest }, body: mixedIndexBody };
}
return { statusCode: 500, headers: {} };
};
// A local candidate that matches neither the arm64 descriptor nor the
// unlabeled leaf: with no confirmed amd64 variant, this must fail closed.
const result = await compareLocalToRemoteTag([STALE_INDEX], REGISTRY, REPO, TAG, AMD64);
expect(result).toEqual({ kind: 'error', reason: expect.stringContaining('no confirmed linux/amd64 variant') });
});
it('errors (not update) when a nested index also has no descriptor for the local platform after full expansion', async () => {
const nestedIndexBody = indexBody([{ digest: CHILD_ARM64, os: 'linux', architecture: 'arm64' }]);
const nestedIndexDigest = contentDigest(nestedIndexBody);
const outerIndexBody = JSON.stringify({
schemaVersion: 2,
mediaType: INDEX_CONTENT_TYPE,
manifests: [{ digest: nestedIndexDigest, mediaType: INDEX_CONTENT_TYPE }],
});
const outerIndexDigest = contentDigest(outerIndexBody);
route = (url, method) => {
const token = tokenOk(url);
if (token) return token;
if (url === MANIFEST_URL_TAG && method === 'HEAD') {
return { statusCode: 200, headers: { 'docker-content-digest': outerIndexDigest, 'content-type': INDEX_CONTENT_TYPE } };
}
if (url === manifestDigestUrl(outerIndexDigest) && method === 'GET') {
return { statusCode: 200, headers: { 'docker-content-digest': outerIndexDigest }, body: outerIndexBody };
}
if (url === manifestDigestUrl(nestedIndexDigest) && method === 'GET') {
return { statusCode: 200, headers: { 'docker-content-digest': nestedIndexDigest }, body: nestedIndexBody };
}
return { statusCode: 500, headers: {} };
};
// The outer index only nests an arm64-only child index; an amd64 node has
// no descriptor anywhere in the fully-expanded tree.
const result = await compareLocalToRemoteTag([STALE_INDEX], REGISTRY, REPO, TAG, AMD64);
expect(result).toEqual({ kind: 'error', reason: expect.stringContaining('no linux/amd64 variant') });
});
it('never re-fetches the mutable tag: the expansion GET targets the primary digest from HEAD, not a second tag lookup', async () => {
const DIVERGED_DIGEST = `sha256:${'e'.repeat(64)}`;
let tagCallCount = 0;
@@ -709,7 +982,13 @@ describe('compareLocalToRemoteTag', () => {
});
it('misses the cache when the primary digest changes (new manifest, new immutable key)', async () => {
const INDEX_BODY_2 = indexBody([{ digest: CHILD_AMD64, os: 'linux', architecture: 'amd64' }]);
// Carries a genuinely different arm64 child (not CHILD_ARM64) so the second
// lookup is a real same-platform mismatch, not an absent-platform index.
const NEW_CHILD_ARM64 = `sha256:${'9'.repeat(64)}`;
const INDEX_BODY_2 = indexBody([
{ digest: CHILD_AMD64, os: 'linux', architecture: 'amd64' },
{ digest: NEW_CHILD_ARM64, os: 'linux', architecture: 'arm64' },
]);
const INDEX_DIGEST_2 = contentDigest(INDEX_BODY_2);
let headDigest = INDEX_DIGEST;
let digestGetCount = 0;
@@ -927,6 +1206,42 @@ describe('compareLocalToRemoteTag', () => {
expect(calls).toHaveLength(0);
});
it('rejects an empty candidate list as an error without contacting the registry', async () => {
route = () => ({ statusCode: 500, headers: {} });
const result = await compareLocalToRemoteTag([], REGISTRY, REPO, TAG, AMD64);
expect(result).toEqual({ kind: 'error', reason: 'Local digest is malformed or truncated' });
expect(calls).toHaveLength(0);
});
it('rejects an all-malformed candidate list as an error without contacting the registry', async () => {
route = () => ({ statusCode: 500, headers: {} });
const result = await compareLocalToRemoteTag(['sha256:short', 'not-a-digest'], REGISTRY, REPO, TAG, AMD64);
expect(result).toEqual({ kind: 'error', reason: 'Local digest is malformed or truncated' });
expect(calls).toHaveLength(0);
});
it('errors on unknown platform for a multi-candidate index mismatch (fail closed)', async () => {
route = (url, method) => {
const token = tokenOk(url);
if (token) return token;
if (url === MANIFEST_URL_TAG && method === 'HEAD') {
return { statusCode: 200, headers: { 'docker-content-digest': INDEX_DIGEST, 'content-type': INDEX_CONTENT_TYPE } };
}
if (url === manifestDigestUrl(INDEX_DIGEST) && method === 'GET') {
return { statusCode: 200, headers: { 'docker-content-digest': INDEX_DIGEST }, body: STANDARD_INDEX_BODY };
}
return { statusCode: 500, headers: {} };
};
const result = await compareLocalToRemoteTag(
[STALE_INDEX, `sha256:${'e'.repeat(64)}`],
REGISTRY,
REPO,
TAG,
{ os: '', architecture: '' },
);
expect(result.kind).toBe('error');
});
it('degrades to an uncached comparison (not an error) when the classification cache is at capacity', async () => {
const cache = CacheService.getInstance();
for (let i = 0; i < 1000; i++) cache.set(`filler:${i}`, { kind: 'single' as const }, 3_600_000);
@@ -11,7 +11,7 @@ import {
buildServicesSignal,
} from '../services/updateGuard/readiness';
import type { ContainerProbe, ReadinessSignal } from '../services/updateGuard/types';
import type { UpdatePreviewSummary } from '../services/UpdatePreviewService';
import type { UpdatePreviewImage, UpdatePreviewSummary } from '../services/UpdatePreviewService';
const NOW = 1_750_000_000_000;
@@ -38,6 +38,8 @@ const summary = (over: Partial<UpdatePreviewSummary> = {}): UpdatePreviewSummary
has_build_services: false,
rebuild_available: false,
check_status: 'ok',
verification_failed: false,
verification_error: null,
...over,
});
@@ -226,3 +228,77 @@ describe('aggregateVerdict', () => {
expect(aggregateVerdict([driftSignal(0), preflightSignal({ activeStatus: 'pass' }), healthchecksSignal([probe()])])).toBe('ready');
});
});
describe('updatePreviewSignal verification failure', () => {
it('does not claim no pending update when digest verification failed', () => {
const signal = updatePreviewSignal(summary({
verification_failed: true,
verification_error: 'Registry unreachable',
}));
expect(signal.status).toBe('unknown');
expect(signal.detail).toMatch(/Digest verification failed/);
expect(signal.detail).toMatch(/Registry unreachable/);
expect(signal.detail).not.toMatch(/No pending image update detected/);
});
it('holds a confirmed update for review, not ok, when another image failed digest verification', () => {
const signal = updatePreviewSignal(summary({
has_update: true,
semver_bump: 'patch',
update_kind: 'digest',
verification_failed: true,
verification_error: 'Registry unreachable',
}));
expect(signal.status).toBe('attention');
expect(signal.detail).toMatch(/Registry unreachable/);
});
it('holds a pending rebuild for review, not verification-only, when another image failed digest verification', () => {
const signal = updatePreviewSignal(summary({
rebuild_available: true,
has_build_services: true,
verification_failed: true,
verification_error: 'Registry unreachable',
}));
expect(signal.status).toBe('attention');
expect(signal.detail).toMatch(/rebuild/);
expect(signal.detail).toMatch(/Registry unreachable/);
});
const image = (over: Partial<UpdatePreviewImage> = {}): UpdatePreviewImage => ({
service: 'web',
image: 'nginx:1',
current_tag: '1',
next_tag: null,
has_update: false,
digest_update: false,
tag_update: false,
semver_bump: 'none',
check_status: 'ok',
check_error: null,
digest_error: null,
...over,
});
it('keeps a single image with its own confirmed update ok even though that same image also failed its own digest check', () => {
// has_update and check_error are independent per image; there is no
// "other image" here, so per-image detail must clear the review hold
// that the aggregate-only fallback would otherwise apply.
const signal = updatePreviewSignal(
summary({ has_update: true, semver_bump: 'patch', update_kind: 'tag', verification_failed: true, verification_error: 'Registry unreachable' }),
[image({ has_update: true, check_error: 'Registry unreachable' })],
);
expect(signal.status).toBe('ok');
});
it('holds a confirmed update for review when per-image detail proves a genuinely different image failed verification', () => {
const signal = updatePreviewSignal(
summary({ has_update: true, semver_bump: 'patch', update_kind: 'tag', verification_failed: true, verification_error: 'Registry unreachable' }),
[
image({ service: 'confirmed', has_update: true, check_error: null }),
image({ service: 'failing', has_update: false, check_error: 'Registry unreachable' }),
],
);
expect(signal.status).toBe('attention');
});
});
@@ -159,7 +159,7 @@ describe('UpdateGuardService.computeUpdateReadiness wiring', () => {
summary: {
has_update: true, primary_image: 'nginx', current_tag: '1.27.0', next_tag: '1.27.1',
semver_bump: 'patch', update_kind: 'tag', blocked: false, blocked_reason: null,
has_build_services: false, rebuild_available: false, check_status: 'ok',
has_build_services: false, rebuild_available: false, check_status: 'ok', verification_failed: false, verification_error: null,
},
rollback_target: 'nginx:1.27.0',
changelog: null,
@@ -190,7 +190,7 @@ describe('UpdateGuardService.computeUpdateReadiness with a serviceName', () => {
summary: {
has_update: true, primary_image: 'nginx', current_tag: '1.27.0', next_tag: '1.27.1',
semver_bump: 'patch', update_kind: 'tag', blocked: false, blocked_reason: null,
has_build_services: false, rebuild_available: false, check_status: 'ok',
has_build_services: false, rebuild_available: false, check_status: 'ok', verification_failed: false, verification_error: null,
},
rollback_target: 'nginx:1.27.0',
changelog: null,
@@ -284,7 +284,7 @@ describe('UpdateGuardService.computeRollbackReadiness moving-tag wiring', () =>
summary: {
has_update: false, primary_image: 'app', current_tag: images[0]?.current_tag ?? null,
next_tag: null, semver_bump: 'none', update_kind: 'none', blocked: false, blocked_reason: null,
has_build_services: false, rebuild_available: false, check_status: 'ok',
has_build_services: false, rebuild_available: false, check_status: 'ok', verification_failed: false, verification_error: null,
},
rollback_target: 'app:1.2.3',
changelog: null,
@@ -47,6 +47,8 @@ function negativeOkPreview(stackName = 'web') {
tag_update: false,
semver_bump: 'none' as const,
check_status: 'ok' as const,
check_error: null,
digest_error: null,
}],
build_services: [] as string[],
summary: {
@@ -61,6 +63,8 @@ function negativeOkPreview(stackName = 'web') {
has_build_services: false,
rebuild_available: false,
check_status: 'ok' as const,
verification_failed: false,
verification_error: null,
},
rollback_target: null,
changelog: null,
@@ -12,12 +12,21 @@ import {
type ComputePreviewDeps,
type LocalDigestInfo,
} from '../services/UpdatePreviewService';
import type { DigestComparisonResult, TagListResult } from '../services/registry-api';
import { selectLocalRepoDigests, type DigestComparisonResult, type ParsedRef, type TagListResult } from '../services/registry-api';
const PLATFORM = { os: 'linux', architecture: 'amd64' };
function localDigest(digest: string | null): LocalDigestInfo {
return { digests: digest ? [digest] : [], platform: PLATFORM };
function localDigest(
digest: string | null | string[],
emptyReason: LocalDigestInfo['emptyReason'] = null,
): LocalDigestInfo {
if (Array.isArray(digest)) return { digests: digest, platform: PLATFORM, emptyReason };
if (digest) return { digests: [digest], platform: PLATFORM, emptyReason: null };
return {
digests: [],
platform: PLATFORM,
emptyReason: emptyReason ?? 'not_checkable',
};
}
function tagsOk(tags: string[], nextCursor?: string): TagListResult {
@@ -168,9 +177,13 @@ describe('computeImagePreview', () => {
expect(result.has_update).toBe(true);
expect(result.next_tag).toBe('1.2.4');
expect(result.semver_bump).toBe('patch');
// A confirmed tag-based update overrides the digest hiccup: the overall
// check_status resolves 'ok' and check_error is not surfaced (see the
// "treats digest error + higher tag as a confirmed update" test below).
expect(result.check_error).toBeNull();
});
it('fails soft to no-update when the comparison resolver errors and no higher tag exists', async () => {
it('surfaces verification failure when the comparison resolver errors and no higher tag exists', async () => {
const deps = makeDeps({
getLocalDigest: vi.fn().mockResolvedValue(localDigest('sha256:aaa')),
compareDigest: vi.fn().mockResolvedValue({ kind: 'error', reason: 'Registry unreachable' }),
@@ -180,10 +193,11 @@ describe('computeImagePreview', () => {
expect(result.has_update).toBe(false);
expect(result.next_tag).toBeNull();
expect(result.semver_bump).toBe('none');
expect(result.check_error).toBe('Registry unreachable');
expect(result.check_status).toBe('partial');
});
it('treats digest error + higher tag as a confirmed update (ok)', async () => {
it('treats digest error + higher tag as a confirmed update (ok), but keeps digest_error unmasked for the collateral-risk gate', async () => {
const result = await computeImagePreview('web', 'nginx:1.2.3', makeDeps({
getLocalDigest: vi.fn().mockResolvedValue(localDigest('sha256:aaa')),
compareDigest: vi.fn().mockResolvedValue({ kind: 'error', reason: 'Registry unreachable' }),
@@ -192,18 +206,71 @@ describe('computeImagePreview', () => {
expect(result.has_update).toBe(true);
expect(result.next_tag).toBe('1.2.4');
expect(result.check_status).toBe('ok');
// The tag compare independently confirmed the update, so check_status
// masks the digest failure. digest_error must survive that masking: a
// full-stack apply still re-pulls this image's unverified current tag.
expect(result.digest_error).toBe('Registry unreachable');
});
it('never calls the comparison resolver when no local digest is resolvable', async () => {
it('treats empty RepoDigests as not_checkable (no verification failure)', async () => {
const compareDigest = vi.fn().mockResolvedValue({ kind: 'update' });
const deps = makeDeps({
getLocalDigest: vi.fn().mockResolvedValue(localDigest(null)),
getLocalDigest: vi.fn().mockResolvedValue(localDigest(null, 'not_checkable')),
compareDigest,
listRegistryTagsResult: vi.fn().mockResolvedValue(tagsOk([])),
});
const result = await computeImagePreview('web', 'nginx:1.2.3', deps);
expect(compareDigest).not.toHaveBeenCalled();
expect(result.has_update).toBe(false);
expect(result.check_error).toBeNull();
});
it('surfaces unresolved RepoDigests as verification failure without claiming an update', async () => {
const compareDigest = vi.fn().mockResolvedValue({ kind: 'update' });
const deps = makeDeps({
getLocalDigest: vi.fn().mockResolvedValue(localDigest(null, 'unresolved')),
compareDigest,
listRegistryTagsResult: vi.fn().mockResolvedValue(tagsOk([])),
});
const result = await computeImagePreview('web', 'nginx:1.2.3', deps);
expect(compareDigest).not.toHaveBeenCalled();
expect(result.has_update).toBe(false);
expect(result.check_error).toBe('Could not resolve a local registry digest');
});
it('wires a real unrelated-repository RepoDigest through selectLocalRepoDigests to an unresolved verification failure', async () => {
// getLocalDigest here is not a canned stand-in: it runs the real
// selectLocalRepoDigests against a RepoDigests array whose sole valid
// entry belongs to a different repository, proving the removed
// sole-unmatched-digest fallback stays removed through the actual
// preview-computation path, not just at the registry-api unit level.
const compareDigest = vi.fn().mockResolvedValue({ kind: 'update' });
const deps = makeDeps({
getLocalDigest: async (_imageRef: string, parsed: ParsedRef) => {
const digests = selectLocalRepoDigests(
[`ghcr.io/other/image@sha256:${'b'.repeat(64)}`],
parsed,
);
return { digests, platform: PLATFORM, emptyReason: digests.length === 0 ? 'unresolved' as const : null };
},
compareDigest,
listRegistryTagsResult: vi.fn().mockResolvedValue(tagsOk([])),
});
const result = await computeImagePreview('web', 'nginx:1.2.3', deps);
expect(compareDigest).not.toHaveBeenCalled();
expect(result.has_update).toBe(false);
expect(result.check_error).toBe('Could not resolve a local registry digest');
});
it('surfaces inspect failure as verification failure', async () => {
const deps = makeDeps({
getLocalDigest: vi.fn().mockResolvedValue(localDigest(null, 'inspect_failed')),
compareDigest: vi.fn(),
listRegistryTagsResult: vi.fn().mockResolvedValue(tagsOk([])),
});
const result = await computeImagePreview('web', 'nginx:1.2.3', deps);
expect(result.has_update).toBe(false);
expect(result.check_error).toBe('Failed to inspect local image');
});
it('passes the local digest, tag, and platform through to the comparison resolver', async () => {
@@ -216,10 +283,35 @@ describe('computeImagePreview', () => {
await computeImagePreview('web', 'ghcr.io/linuxserver/radarr:latest', deps);
expect(compareDigest).toHaveBeenCalledWith(['sha256:aaa'], 'ghcr.io', 'linuxserver/radarr', 'latest', PLATFORM, null);
});
it('forwards every local digest candidate and reports no same-tag rebuild on match', async () => {
const STALE = `sha256:${'f'.repeat(64)}`;
const CURRENT = `sha256:${'e'.repeat(64)}`;
const compareDigest = vi.fn().mockResolvedValue({ kind: 'match' });
const deps = makeDeps({
getLocalDigest: vi.fn().mockResolvedValue(localDigest([STALE, CURRENT])),
compareDigest,
listRegistryTagsResult: vi.fn().mockResolvedValue(tagsOk([])),
});
const result = await computeImagePreview('broker', 'redis:8.8.0', deps);
expect(compareDigest).toHaveBeenCalledWith(
[STALE, CURRENT],
'registry-1.docker.io',
'library/redis',
'8.8.0',
PLATFORM,
null,
);
expect(result).toMatchObject({
has_update: false,
next_tag: null,
semver_bump: 'none',
});
});
});
describe('buildSummary', () => {
const baseImage = (partial: Partial<Parameters<typeof buildSummary>[1][number]>) => ({
const baseImage = (partial: Partial<Parameters<typeof buildSummary>[1][number]> = {}) => ({
service: 'svc',
image: 'nginx:1.0.0',
current_tag: '1.0.0',
@@ -229,6 +321,8 @@ describe('buildSummary', () => {
tag_update: false,
semver_bump: 'none' as const,
check_status: 'ok' as const,
check_error: null as string | null,
digest_error: null as string | null,
...partial,
});
@@ -241,6 +335,41 @@ describe('buildSummary', () => {
expect(preview.summary.blocked).toBe(true);
expect(preview.summary.blocked_reason).toMatch(/major/i);
expect(preview.summary.semver_bump).toBe('major');
expect(preview.summary.verification_failed).toBe(false);
expect(preview.summary.verification_error).toBeNull();
});
it('aggregates digest verification failure without claiming a digest rebuild', () => {
const images = [
baseImage({
service: 'broker',
image: 'redis:8.8.0',
current_tag: '8.8.0',
check_error: 'Local image platform is unknown; cannot verify multi-arch membership',
}),
];
const preview = buildSummary('app', images);
expect(preview.summary.has_update).toBe(false);
expect(preview.summary.update_kind).toBe('none');
expect(preview.summary.verification_failed).toBe(true);
expect(preview.summary.verification_error).toContain('cannot verify multi-arch membership');
});
it('keeps a tag update when digest verification failed on the same image', () => {
const images = [
baseImage({
service: 'web',
has_update: true,
semver_bump: 'patch',
next_tag: '1.0.1',
check_error: 'Registry unreachable',
}),
];
const preview = buildSummary('app', images);
expect(preview.summary.has_update).toBe(true);
expect(preview.summary.update_kind).toBe('tag');
expect(preview.summary.verification_failed).toBe(true);
expect(preview.summary.verification_error).toBe('Registry unreachable');
});
it('picks first updated image as primary', () => {
@@ -410,6 +539,8 @@ describe('preview authority', () => {
tag_update: false,
semver_bump: 'none',
check_status: 'not_checkable',
check_error: null,
digest_error: null,
},
]))).toBe(false);
});