Skip to content

feat(image): include image OS version in layer cache key - #11770

Open
srinivasKandukuri wants to merge 1 commit into
aquasecurity:mainfrom
srinivasKandukuri:feat/cache-key-image-os-version
Open

srinivasKandukuri wants to merge 1 commit into
aquasecurity:mainfrom
srinivasKandukuri:feat/cache-key-image-os-version

Conversation

@srinivasKandukuri

@srinivasKandukuri srinivasKandukuri commented Nov 27, 2026 •

Copy link
Copy Markdown
Member

Description

Add artifact.Option.ImageOSVersion and include it in the layer (blob) cache key. It is opt-in: when the field is empty, every cache key is exactly the same as today.

Problem

Post-handlers (handler.RegisterPostHandlerInit) can write data that comes from the image config into every layer blob. For Windows images, the main example is the OS build: it isn't in any layer's files (unlike /etc/os-release on Linux), only in the config's os.version, for example 10.0.20348.5499. A scanner therefore turns os.version into a package to match cumulative updates (KBs) against it.

The layer cache key (cache.CalcKey) is built from the diffID, analyzer and handler versions, and a few options. It doesn't include the image config. So two images that contain the same layer but were built on different Windows builds share one cached blob for that layer. Whichever image is scanned second inherits the first image's build. It's reported as more patched than it is, and applicable KBs are missed.

This happens in practice when Windows images are re-based onto the monthly patched base without rebuilding the app layers, for example with crane rebase, crane append / mutate, or builders that create layers independently of the base. The app layers stay byte-identical (same diffID) while os.version changes.

Example with public images

Two images built on Microsoft's nanoserver bases, with the same app layer appended:

Image Base os.version Layer diffIDs
docker.io/srinivaskand/trivy-windows-shared-layer:5622 mcr.microsoft.com/windows/nanoserver:10.0.20348.5622 10.0.20348.5622 e1f0ac6f…, c1a3d9be…
docker.io/srinivaskand/trivy-windows-shared-layer:5499 mcr.microsoft.com/windows/nanoserver:10.0.20348.5499 10.0.20348.5499 91307a1f…, c1a3d9be…

(The appended layer contains only app/hello.txt. Built with crane append --platform windows/amd64 -b <base> -f app.tar.)

Both images were scanned into one cache with pkg/fanal/artifact/image, with a post-handler that writes os.version into each layer blob as an os-build package (code below). :5622 was scanned first:

== ImageOSVersion not set (current behaviour)
  :5622  os.version=10.0.20348.5622  top diffID=c1a3d9be6c99  top layer key=543c6ccfeed1 -> os-build=10.0.20348.5622 OK
  :5499  os.version=10.0.20348.5499  top diffID=c1a3d9be6c99  top layer key=543c6ccfeed1 -> os-build=10.0.20348.5622 WRONG

== ImageOSVersion = image config os.version (this PR)
  :5622  os.version=10.0.20348.5622  top diffID=c1a3d9be6c99  top layer key=d5f833ebdfd3 -> os-build=10.0.20348.5622 OK
  :5499  os.version=10.0.20348.5499  top diffID=c1a3d9be6c99  top layer key=bf1809cd8a2f -> os-build=10.0.20348.5499 OK

Without the field, both images get the same key for the shared top layer, so :5499 reads the blob written for :5622. With the field set, that layer gets one key per OS version, and each image gets its own value.

Repro code (handler + scan loop)
type osBuildHandler struct{ build string }

func (h osBuildHandler) Type() types.HandlerType { return "os-build-repro" }
func (h osBuildHandler) Version() int            { return 1 }
func (h osBuildHandler) Priority() int           { return 0 }
func (h osBuildHandler) Handle(_ context.Context, _ *analyzer.AnalysisResult, blob *types.BlobInfo) error {
        blob.PackageInfos = []types.PackageInfo{{Packages: types.Packages{{Name: "os-build", Version: h.build}}}}
        return nil
}

// For each tag (5622 first, then 5499), sharing one cache.NewMemoryCache():
img, cleanup, _ := image.NewContainerImage(ctx, repo+":"+tag, types.ImageOptions{
        ImageSources:    types.ImageSources{types.RemoteImageSource},
        RegistryOptions: types.RegistryOptions{Platform: types.Platform{Platform: &v1.Platform{OS: "windows", Architecture: "amd64"}}},
})
cfg, _ := img.ConfigFile()
handler.RegisterPostHandlerInit("os-build-repro", func(artifact.Option) (handler.PostHandler, error) {
        return osBuildHandler{build: cfg.OSVersion}, nil
})
art, _ := imageartifact.NewArtifact(img, c, artifact.Option{ImageOSVersion: cfg.OSVersion}) // field omitted for "before"
ref, _ := art.Inspect(ctx)
detail, _ := applier.NewApplier(c).ApplyLayers(ctx, ref.ID, ref.BlobIDs)
// detail.Packages -> "os-build"

Change

  • pkg/fanal/artifact/artifact.go: new ImageOSVersion string field on Option (json:",omitempty").
  • pkg/cache/key.go: CalcKey includes it in the hashed struct (json:",omitempty").
  • pkg/cache/key_test.go: TestCalcKey_ImageOSVersion.

Compatibility

  • When the field is empty (the default), the hashed JSON is byte-for-byte the same, so no existing cache key changes. The existing TestCalcKey expected hashes are unchanged, and the new test checks that an empty value gives exactly the existing "happy path" key.
  • A layer on the same OS version still has one key, so sharing within a build isn't affected.
  • Linux is never affected. OS data and packages there come from files inside the layer, so the same diffID always means the same result.

Design notes (alternatives considered)

  • Hash the config digest instead: it's unique per image, so every layer of every image would get its own entry, which ends layer sharing completely. os.version is the narrowest value that separates only the cases that matter.
  • Use the handler's Version(): it's a fixed int per handler type and can't hold a per-image value.
  • Compute config-derived data once at image level after the merge: also valid, but much larger. It needs new ArtifactInfo fields, applier merging, remote-cache transport, and an image-level hook.
  • Nothing in Trivy sets the field yet. It's an extension point for post-handlers when Trivy is used as a library. If maintainers prefer, the image artifact can fill it from configFile.OSVersion for Windows images (only Windows keys would change, a one-time re-analysis). Happy to add that here or in a follow-up.
  • Client/server mode: keys are calculated on the client, so no server change is needed.

Testing

  • go test ./pkg/cache/ ./pkg/fanal/artifact/image/ passes.
  • The public-image repro above was run against this branch.

Checklist

  • I've read the guidelines for contributing to this repository.
  • I've followed the conventions in the PR title.
  • I've added tests that prove my fix is effective or that my feature works.
  • I've updated the documentation with the relevant information (if needed). (not needed: library option, no CLI flag)
  • I've added usage information (if the PR introduces new options)
  • I've included a "before" and "after" example to the description (if the PR is a user interface change).

@srinivasKandukuri srinivasKandukuri changed the title feat(cache): include image OS version in layer cache key feat(image): include image OS version in layer cache key Nov 27, 2026
Add artifact.Option.ImageOSVersion and include it in the blob cache key.

Post-handlers can write data derived from the image config into each
layer blob, for example a Windows kernel package built from the image's
os.version. The layer cache key is calculated from the diffID, analyzer
and handler versions, and options, but not from the image config. Two
images that share an identical layer but were built on different OS
versions then share that layer's blob, and the second image inherits
the first image's config-derived data.

Setting ImageOSVersion gives such layers a separate cache key per OS
version. The field is omitted from the key when empty, so all existing
cache keys stay the same.
@srinivasKandukuri
srinivasKandukuri force-pushed the feat/cache-key-image-os-version branch from f01d29a to 861c848 Compare November 27, 2026 10:10

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant