fix(misconf): .Config.User always takes precedence over USER in .History (#9050)

Co-authored-by: DmitriyLewen <91113035+DmitriyLewen@users.noreply.github.com>
This commit is contained in:
Luke Young
2025-06-19 02:10:45 -07:00
committed by GitHub
parent 3f41ffa5b8
commit 371b8cc02f
2 changed files with 6 additions and 3 deletions

View File

@@ -76,7 +76,6 @@ func (a *historyAnalyzer) Analyze(ctx context.Context, input analyzer.ConfigAnal
func imageConfigToDockerfile(cfg *v1.ConfigFile) []byte {
dockerfile := new(bytes.Buffer)
var userFound bool
baseLayerIndex := image.GuessBaseImageIndex(cfg.History)
for i := baseLayerIndex + 1; i < len(cfg.History); i++ {
h := cfg.History[i]
@@ -101,7 +100,6 @@ func imageConfigToDockerfile(cfg *v1.ConfigFile) []byte {
case strings.HasPrefix(h.CreatedBy, "USER"):
// USER instruction
createdBy = h.CreatedBy
userFound = true
case strings.HasPrefix(h.CreatedBy, "HEALTHCHECK"):
// HEALTHCHECK instruction
createdBy = buildHealthcheckInstruction(cfg.Config.Healthcheck)
@@ -119,7 +117,8 @@ func imageConfigToDockerfile(cfg *v1.ConfigFile) []byte {
dockerfile.WriteString(strings.TrimSpace(createdBy) + "\n")
}
if !userFound && cfg.Config.User != "" {
// The user can be changed from the config file or with the `--user` flag (for docker CLI), so we need to add this user to avoid incorrect user detection
if cfg.Config.User != "" {
user := fmt.Sprintf("USER %s", cfg.Config.User)
dockerfile.WriteString(user)
}

View File

@@ -167,6 +167,10 @@ func Test_historyAnalyzer_Analyze(t *testing.T) {
CreatedBy: "RUN /bin/sh -c ls -hl /foo # buildkit",
EmptyLayer: false,
},
{
CreatedBy: "USER root", // .Config.User takes precedence over this line
EmptyLayer: true,
},
{
CreatedBy: `HEALTHCHECK &{["CMD-SHELL" "curl -sS 127.0.0.1 || exit 1"] "10s" "3s" "0s" '\x00'}`,
EmptyLayer: true,