Bump to Buildah v1.40.0

Bumps to Buildah v1.40.0 and adds the `--inherits-labels` option to
build and farm build man pages.

Also turn off the inherit-labels option test for now as it seems to be
rathr unhappy.

Issue for inherit-labels test failure: https://github.com/containers/podman/issues/25938

Signed-off-by: tomsweeneyredhat <tsweeney@redhat.com>
This commit is contained in:
tomsweeneyredhat 2025-04-21 15:45:26 -04:00
parent a3e132055d
commit 76b07dd48d
54 changed files with 661 additions and 305 deletions

View File

@ -0,0 +1,7 @@
####> This option file is used in:
####> podman build, farm build
####> If file is edited, make sure the changes
####> are applicable to all of those.
#### **--inherit-labels**
Inherit the labels from the base image or base stages. (default true).

View File

@ -221,6 +221,8 @@ It does not affect _/etc/resolv.conf_ in the final image.
@@option iidfile @@option iidfile
@@option inherit-labels
@@option ipc.image @@option ipc.image
@@option isolation @@option isolation

View File

@ -123,6 +123,8 @@ This option specifies the name of the farm to be used in the build process.
@@option iidfile @@option iidfile
@@option inherit-labels
@@option ipc.image @@option ipc.image
@@option isolation @@option isolation

9
go.mod
View File

@ -12,7 +12,7 @@ require (
github.com/checkpoint-restore/checkpointctl v1.3.0 github.com/checkpoint-restore/checkpointctl v1.3.0
github.com/checkpoint-restore/go-criu/v7 v7.2.0 github.com/checkpoint-restore/go-criu/v7 v7.2.0
github.com/containernetworking/plugins v1.6.2 github.com/containernetworking/plugins v1.6.2
github.com/containers/buildah v1.39.1-0.20250401180830-32d78c69be17 github.com/containers/buildah v1.40.0
github.com/containers/common v0.63.0 github.com/containers/common v0.63.0
github.com/containers/conmon v2.0.20+incompatible github.com/containers/conmon v2.0.20+incompatible
github.com/containers/gvisor-tap-vsock v0.8.5 github.com/containers/gvisor-tap-vsock v0.8.5
@ -27,7 +27,7 @@ require (
github.com/cyphar/filepath-securejoin v0.4.1 github.com/cyphar/filepath-securejoin v0.4.1
github.com/digitalocean/go-qemu v0.0.0-20250212194115-ee9b0668d242 github.com/digitalocean/go-qemu v0.0.0-20250212194115-ee9b0668d242
github.com/docker/distribution v2.8.3+incompatible github.com/docker/distribution v2.8.3+incompatible
github.com/docker/docker v28.1.1+incompatible github.com/docker/docker v28.1.0+incompatible
github.com/docker/go-connections v0.5.0 github.com/docker/go-connections v0.5.0
github.com/docker/go-plugins-helpers v0.0.0-20240701071450-45e2431495c8 github.com/docker/go-plugins-helpers v0.0.0-20240701071450-45e2431495c8
github.com/docker/go-units v0.5.0 github.com/docker/go-units v0.5.0
@ -151,7 +151,7 @@ require (
github.com/miekg/pkcs11 v1.1.1 // indirect github.com/miekg/pkcs11 v1.1.1 // indirect
github.com/mistifyio/go-zfs/v3 v3.0.1 // indirect github.com/mistifyio/go-zfs/v3 v3.0.1 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/moby/buildkit v0.20.2 // indirect github.com/moby/buildkit v0.21.0 // indirect
github.com/moby/docker-image-spec v1.3.1 // indirect github.com/moby/docker-image-spec v1.3.1 // indirect
github.com/moby/go-archive v0.1.0 // indirect github.com/moby/go-archive v0.1.0 // indirect
github.com/moby/patternmatcher v0.6.0 // indirect github.com/moby/patternmatcher v0.6.0 // indirect
@ -203,11 +203,10 @@ require (
go.opentelemetry.io/otel/metric v1.34.0 // indirect go.opentelemetry.io/otel/metric v1.34.0 // indirect
go.opentelemetry.io/otel/trace v1.34.0 // indirect go.opentelemetry.io/otel/trace v1.34.0 // indirect
go.uber.org/automaxprocs v1.6.0 // indirect go.uber.org/automaxprocs v1.6.0 // indirect
golang.org/x/exp v0.0.0-20250128182459-e0ece0dbea4c // indirect
golang.org/x/mod v0.24.0 // indirect golang.org/x/mod v0.24.0 // indirect
golang.org/x/oauth2 v0.29.0 // indirect golang.org/x/oauth2 v0.29.0 // indirect
golang.org/x/time v0.11.0 // indirect golang.org/x/time v0.11.0 // indirect
golang.org/x/tools v0.31.0 // indirect golang.org/x/tools v0.32.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20250303144028-a0af3efb3deb // indirect google.golang.org/genproto/googleapis/api v0.0.0-20250303144028-a0af3efb3deb // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20250313205543-e70fdf4c4cb4 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20250313205543-e70fdf4c4cb4 // indirect
google.golang.org/grpc v1.71.0 // indirect google.golang.org/grpc v1.71.0 // indirect

20
go.sum
View File

@ -66,8 +66,8 @@ github.com/containernetworking/cni v1.3.0 h1:v6EpN8RznAZj9765HhXQrtXgX+ECGebEYEm
github.com/containernetworking/cni v1.3.0/go.mod h1:Bs8glZjjFfGPHMw6hQu82RUgEPNGEaBb9KS5KtNMnJ4= github.com/containernetworking/cni v1.3.0/go.mod h1:Bs8glZjjFfGPHMw6hQu82RUgEPNGEaBb9KS5KtNMnJ4=
github.com/containernetworking/plugins v1.6.2 h1:pqP8Mq923TLyef5g97XfJ/xpDeVek4yF8A4mzy9Tc4U= github.com/containernetworking/plugins v1.6.2 h1:pqP8Mq923TLyef5g97XfJ/xpDeVek4yF8A4mzy9Tc4U=
github.com/containernetworking/plugins v1.6.2/go.mod h1:SP5UG3jDO9LtmfbBJdP+nl3A1atOtbj2MBOYsnaxy64= github.com/containernetworking/plugins v1.6.2/go.mod h1:SP5UG3jDO9LtmfbBJdP+nl3A1atOtbj2MBOYsnaxy64=
github.com/containers/buildah v1.39.1-0.20250401180830-32d78c69be17 h1:mfnd0BqHdV8p6+pol7SelIEgG7NbJQYW4IPywGakmCY= github.com/containers/buildah v1.40.0 h1:qCHTKnL/UEutxT6ZS8Zvhy7QUpe719jEIeGMSlcN3j4=
github.com/containers/buildah v1.39.1-0.20250401180830-32d78c69be17/go.mod h1:AvIRsFvWfSuMNGoMm8hXFaOGvzhsnujWz1C38rk+mk4= github.com/containers/buildah v1.40.0/go.mod h1:U6qj0nseq6t97T2kkNpjgo0WBVRYIXASIOlS5eWvlhM=
github.com/containers/common v0.63.0 h1:ox6vgUYX5TSvt4W+bE36sYBVz/aXMAfRGVAgvknSjBg= github.com/containers/common v0.63.0 h1:ox6vgUYX5TSvt4W+bE36sYBVz/aXMAfRGVAgvknSjBg=
github.com/containers/common v0.63.0/go.mod h1:+3GCotSqNdIqM3sPs152VvW7m5+Mg8Kk+PExT3G9hZw= github.com/containers/common v0.63.0/go.mod h1:+3GCotSqNdIqM3sPs152VvW7m5+Mg8Kk+PExT3G9hZw=
github.com/containers/conmon v2.0.20+incompatible h1:YbCVSFSCqFjjVwHTPINGdMX1F6JXHGTUje2ZYobNrkg= github.com/containers/conmon v2.0.20+incompatible h1:YbCVSFSCqFjjVwHTPINGdMX1F6JXHGTUje2ZYobNrkg=
@ -121,8 +121,8 @@ github.com/docker/cli v28.0.4+incompatible h1:pBJSJeNd9QeIWPjRcV91RVJihd/TXB77q1
github.com/docker/cli v28.0.4+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8= github.com/docker/cli v28.0.4+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8=
github.com/docker/distribution v2.8.3+incompatible h1:AtKxIZ36LoNK51+Z6RpzLpddBirtxJnzDrHLEKxTAYk= github.com/docker/distribution v2.8.3+incompatible h1:AtKxIZ36LoNK51+Z6RpzLpddBirtxJnzDrHLEKxTAYk=
github.com/docker/distribution v2.8.3+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w= github.com/docker/distribution v2.8.3+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w=
github.com/docker/docker v28.1.1+incompatible h1:49M11BFLsVO1gxY9UX9p/zwkE/rswggs8AdFmXQw51I= github.com/docker/docker v28.1.0+incompatible h1:4iqpcWQCt3Txcz7iWIb1U3SZ/n9ffo4U+ryY5/3eOp0=
github.com/docker/docker v28.1.1+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= github.com/docker/docker v28.1.0+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk=
github.com/docker/docker-credential-helpers v0.9.3 h1:gAm/VtF9wgqJMoxzT3Gj5p4AqIjCBS4wrsOh9yRqcz8= github.com/docker/docker-credential-helpers v0.9.3 h1:gAm/VtF9wgqJMoxzT3Gj5p4AqIjCBS4wrsOh9yRqcz8=
github.com/docker/docker-credential-helpers v0.9.3/go.mod h1:x+4Gbw9aGmChi3qTLZj8Dfn0TD20M/fuWy0E5+WDeCo= github.com/docker/docker-credential-helpers v0.9.3/go.mod h1:x+4Gbw9aGmChi3qTLZj8Dfn0TD20M/fuWy0E5+WDeCo=
github.com/docker/go-connections v0.5.0 h1:USnMq7hx7gwdVZq1L49hLXaFtUdTADjXGp+uj1Br63c= github.com/docker/go-connections v0.5.0 h1:USnMq7hx7gwdVZq1L49hLXaFtUdTADjXGp+uj1Br63c=
@ -318,8 +318,8 @@ github.com/mistifyio/go-zfs/v3 v3.0.1 h1:YaoXgBePoMA12+S1u/ddkv+QqxcfiZK4prI6HPn
github.com/mistifyio/go-zfs/v3 v3.0.1/go.mod h1:CzVgeB0RvF2EGzQnytKVvVSDwmKJXxkOTUGbNrTja/k= github.com/mistifyio/go-zfs/v3 v3.0.1/go.mod h1:CzVgeB0RvF2EGzQnytKVvVSDwmKJXxkOTUGbNrTja/k=
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
github.com/moby/buildkit v0.20.2 h1:qIeR47eQ1tzI1rwz0on3Xx2enRw/1CKjFhoONVcTlMA= github.com/moby/buildkit v0.21.0 h1:+z4vVqgt0spLrOSxi4DLedRbIh2gbNVlZ5q4rsnNp60=
github.com/moby/buildkit v0.20.2/go.mod h1:DhaF82FjwOElTftl0JUAJpH/SUIUx4UvcFncLeOtlDI= github.com/moby/buildkit v0.21.0/go.mod h1:mBq0D44uCyz2PdX8T/qym5LBbkBO3GGv0wqgX9ABYYw=
github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0= github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0=
github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo= github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo=
github.com/moby/go-archive v0.1.0 h1:Kk/5rdW/g+H8NHdJW2gsXyZ7UnzvJNOy6VKJqueWdcQ= github.com/moby/go-archive v0.1.0 h1:Kk/5rdW/g+H8NHdJW2gsXyZ7UnzvJNOy6VKJqueWdcQ=
@ -551,8 +551,8 @@ golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ss
golang.org/x/crypto v0.37.0 h1:kJNSjF/Xp7kU0iB2Z+9viTPMW4EqqsrywMXLJOOsXSE= golang.org/x/crypto v0.37.0 h1:kJNSjF/Xp7kU0iB2Z+9viTPMW4EqqsrywMXLJOOsXSE=
golang.org/x/crypto v0.37.0/go.mod h1:vg+k43peMZ0pUMhYmVAWysMK35e6ioLh3wB8ZCAfbVc= golang.org/x/crypto v0.37.0/go.mod h1:vg+k43peMZ0pUMhYmVAWysMK35e6ioLh3wB8ZCAfbVc=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20250128182459-e0ece0dbea4c h1:KL/ZBHXgKGVmuZBZ01Lt57yE5ws8ZPSkkihmEyq7FXc= golang.org/x/exp v0.0.0-20250408133849-7e4ce0ab07d0 h1:R84qjqJb5nVJMxqWYb3np9L5ZsaDtB+a39EqjV0JSUM=
golang.org/x/exp v0.0.0-20250128182459-e0ece0dbea4c/go.mod h1:tujkw807nyEEAamNbDrEGzRav+ilXA7PCRAd6xsmwiU= golang.org/x/exp v0.0.0-20250408133849-7e4ce0ab07d0/go.mod h1:S9Xr4PYopiDyqSyp5NjCrhFrqg6A5zA2E/iPHPhqnS8=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
@ -668,8 +668,8 @@ golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58= golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58=
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk= golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=
golang.org/x/tools v0.31.0 h1:0EedkvKDbh+qistFTd0Bcwe/YLh4vHwWEkiI0toFIBU= golang.org/x/tools v0.32.0 h1:Q7N1vhpkQv7ybVzLFtTjvQya2ewbwNDZzUgfXGqtMWU=
golang.org/x/tools v0.31.0/go.mod h1:naFTU+Cev749tSJRXJlna0T3WxKvb1kWEx15xA4SdmQ= golang.org/x/tools v0.32.0/go.mod h1:ZxrU41P/wAbZD8EDa6dDCa6XfpkhJ7HFMjHJXfBDu8s=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=

View File

@ -341,6 +341,7 @@ success_task:
- vendor - vendor
- cross_build - cross_build
- integration - integration
- integration_rootless
- in_podman - in_podman
container: container:

View File

@ -1,16 +1,29 @@
--- version: "2"
run: run:
build-tags: build-tags:
- apparmor - apparmor
- seccomp - seccomp
- selinux - selinux
# Don't exceed number of threads available when running under CI
concurrency: 4 formatters:
enable:
- gofumpt
linters: linters:
enable: enable:
- gofmt - nolintlint
- gofumpt
- revive - revive
- unconvert - unconvert
- unparam - unparam
- unused
- whitespace - whitespace
exclusions:
presets:
- comments
- std-error-handling
settings:
staticcheck:
checks:
- all
- -QF1008 # https://staticcheck.dev/docs/checks/#QF1008 Omit embedded fields from selector expression.

View File

@ -2,6 +2,135 @@
# Changelog # Changelog
## v1.40.0 (2025-04-17)
Bump c/storage to v1.58.0, c/image v5.35.0, c/common v0.63.0
fix(deps): update module github.com/docker/docker to v28.1.0+incompatible
fix(deps): update module github.com/containers/storage to v1.58.0
cirrus: make Total Success wait for rootless integration
chroot: use symbolic names when complaining about mount() errors
cli: hide the `completion` command instead of disabling it outright
Document rw and src options for --mount flag in buildah-run(1)
fix(deps): update module github.com/moby/buildkit to v0.21.0
build: add support for inherit-labels
chore(deps): update dependency golangci/golangci-lint to v2.1.0
.github: check_cirrus_cron work around github bug
stage_executor,getCreatedBy: expand buildArgs for sources correctly
Add a link to project governance and MAINTAINERS file
fix(deps): update github.com/containers/storage digest to b1d1b45
generateHostname: simplify
Use maps.Copy
Use slices.Concat
Use slices.Clone
Use slices.Contains
Use for range over integers
tests/testreport: don't copy os.Environ
Use any instead of interface{}
ci: add golangci-lint run with --tests=false
ci: add nolintlint, fix found issues
copier: rm nolint:unparam annotation
.golangci.yml: add unused linter
chroot: fix unused warnings
copier: fix unused warnings
tests/conformance: fix unused warning
ci: switch to golangci-lint v2
internal/mkcw: disable ST1003 warnings
tests/conformance: do not double import (fix ST1019)
cmd/buildah: don't double import (fix ST1019)
Do not capitalize error strings
cmd/buildah: do not capitalize error strings
tests/conformance: fix QF1012 warnings
tests/serve: fix QF1012 warning
Use strings.ReplaceAll to fix QF1004 warnings
Use switch to fix QF1003 warnings
Apply De Morgan's law to fix QF1001 warnings
Fix QF1007 staticcheck warnings
imagebuildah: fix revive warning
Rename max variable
tests/tools: install lint from binary, use renovate
fix(deps): update module github.com/containernetworking/cni to v1.3.0
Update Buildah issue template to new version and support podman build
fix(deps): update module golang.org/x/crypto to v0.37.0
stage_executor: reset platform in systemcontext for stages
fix(deps): update github.com/opencontainers/runtime-tools digest to 260e151
cmd/buildah: rm unused containerOutputUsingTemplate
cmd/buildah: rm unused getDateAndDigestAndSize
build: return ExecErrorCodeGeneric when git operation fails
add: report error while creating dir for URL source.
createPlatformContainer: drop MS_REMOUNT|MS_BIND
fix(deps): update module github.com/docker/docker to v28.0.3+incompatible
fix: bats won't fail on ! without cleverness
feat: use HistoryTimestamp, if set, for oci-archive entries
Allow extendedGlob to work with Windows paths
fix(deps): update module github.com/moby/buildkit to v0.20.2
fix(deps): update github.com/openshift/imagebuilder digest to e87e4e1
fix(deps): update module github.com/docker/docker to v28.0.2+incompatible
fix(deps): update module tags.cncf.io/container-device-interface to v1.0.1
chore(deps): update dependency containers/automation_images to v20250324
vendor: update github.com/opencontainers/selinux to v1.12.0
replace deprecated selinux/label calls
vendor: bump c/common to dbeb17e40c80
Use builtin arg defaults from imagebuilder
linux: accept unmask paths as glob values
vendor: update containers/common
Add --parents option for COPY in Dockerfiles
fix(deps): update module github.com/opencontainers/runc to v1.2.6
update go.sum from the previous commit
fix(deps): update module tags.cncf.io/container-device-interface to v1
chore(deps): update module golang.org/x/net to v0.36.0 [security]
packit: remove f40 from copr builds
cirrus: update to go 1.23 image
vendor bump to golang.org/x/crypto v0.36.0
cirrus: update PRIOR_FEDORA comment
github: remove cirrus rerun action
fix(deps): update module github.com/containers/common to v0.62.2
fix(deps): update module github.com/containers/image/v5 to v5.34.2
fix: close files properly when BuildDockerfiles exits
fix(deps): update module github.com/containers/storage to v1.57.2
stage_executor: history should include heredoc summary correctly
fix(deps): update module github.com/containers/common to v0.62.1
github: disable cron rerun action
fix(deps): update module github.com/moby/buildkit to v0.20.1
internal/mkcw.Archive(): use github.com/containers/storage/pkg/ioutils
[skip-ci] TMT: system tests
buildah-build.1.md: secret examples
fix(deps): update github.com/containers/luksy digest to 40bd943
fix(deps): update module github.com/opencontainers/image-spec to v1.1.1
fix(deps): update module github.com/containers/image/v5 to v5.34.1
Use UnparsedInstance.Manifest instead of ImageSource.GetManifest
fix(deps): update module github.com/opencontainers/runtime-spec to v1.2.1
tests/conformance/testdata/Dockerfile.add: update some URLs
Vendor imagebuilder
Fix source of OS, architecture and variant
chore(deps): update module github.com/go-jose/go-jose/v4 to v4.0.5 [security]
fix(deps): update module tags.cncf.io/container-device-interface to v0.8.1
fix(deps): update module github.com/moby/buildkit to v0.20.0
chroot createPlatformContainer: use MS_REMOUNT
conformance: make TestCommit and TestConformance parallel
cirrus: reduce task timeout
mkcw: mkcw_check_image use bats run_with_log
test: use /tmp as TMPDIR
heredoc: create temp subdirs for each build
test: heredoc remove python dependency from test
Support the containers.conf container_name_as_hostname option
fix(deps): update module github.com/opencontainers/runc to v1.2.5
fix(deps): update module github.com/spf13/cobra to v1.9.0
.cirrus: use more cores for smoke
Switch to the CNCF Code of Conduct
.cirrus: bump ci resources
fix(deps): update module golang.org/x/crypto to v0.33.0
Distinguish --mount=type=cache locations by ownership, too
fix(deps): update module golang.org/x/term to v0.29.0
.cirrus: run -race only on non-PR branch
unit: deparallize some tests
.cirrus: use multiple cpu for unit tests
Makefile: use -parallel for go test
unit_test: use Parallel test where possible
Update module golang.org/x/sys to v0.30.0
Update module golang.org/x/sync to v0.11.0
Update dependency containers/automation_images to v20250131
Bump to Buildah v1.40.0-dev
## v1.39.0 (2025-01-31) ## v1.39.0 (2025-01-31)
Bump c/storage v1.57.1, c/image 5.34.0, c/common v0.62.0 Bump c/storage v1.57.1, c/image 5.34.0, c/common v0.62.0

3
vendor/github.com/containers/buildah/GOVERNANCE.md generated vendored Normal file
View File

@ -0,0 +1,3 @@
## The Buildah Project Community Governance
The Buildah project, as part of Podman Container Tools, follows the [Podman Project Governance](https://github.com/containers/podman/blob/main/GOVERNANCE.md).

View File

@ -1,4 +0,0 @@
Dan Walsh <dwalsh@redhat.com> (@rhatdan)
Nalin Dahyabhai <nalin@redhat.com> (@nalind)
Tom Sweeney <tsweeney@redhat.com> (@tomsweeneyredhat)
Urvashi Mohnani <umohnani@redhat.com> (@umohnani8)

31
vendor/github.com/containers/buildah/MAINTAINERS.md generated vendored Normal file
View File

@ -0,0 +1,31 @@
# Buildah Maintainers
[GOVERNANCE.md](https://github.com/containers/podman/blob/main/GOVERNANCE.md)
describes the project's governance and the Project Roles used below.
## Maintainers
| Maintainer | GitHub ID | Project Roles | Affiliation |
|-------------------|----------------------------------------------------------|----------------------------------|----------------------------------------------|
| Brent Baude | [baude](https://github.com/baude) | Core Maintainer | [Red Hat](https://github.com/RedHatOfficial) |
| Nalin Dahyabhai | [nalind](https://github.com/nalind) | Core Maintainer | [Red Hat](https://github.com/RedHatOfficial) |
| Matthew Heon | [mheon](https://github.com/mheon) | Core Maintainer | [Red Hat](https://github.com/RedHatOfficial) |
| Paul Holzinger | [Luap99](https://github.com/Luap99) | Core Maintainer | [Red Hat](https://github.com/RedHatOfficial) |
| Giuseppe Scrivano | [giuseppe](https://github.com/giuseppe) | Core Maintainer | [Red Hat](https://github.com/RedHatOfficial) |
| Miloslav Trmač | [mtrmac](https://github.com/mtrmac) | Core Maintainer | [Red Hat](https://github.com/RedHatOfficial) |
| Neil Smith | [Neil-Smith](https://github.com/Neil-Smith) | Community Manager | [Red Hat](https://github.com/RedHatOfficial) |
| Tom Sweeney | [TomSweeneyRedHat](https://github.com/TomSweeneyRedHat/) | Maintainer and Community Manager | [Red Hat](https://github.com/RedHatOfficial) |
| Lokesh Mandvekar | [lsm5](https://github.com/lsm5) | Maintainer | [Red Hat](https://github.com/RedHatOfficial) |
| Dan Walsh | [rhatdan](https://github.com/rhatdan) | Maintainer | [Red Hat](https://github.com/RedHatOfficial) |
| Ashley Cui | [ashley-cui](https://github.com/ashley-cui) | Reviewer | [Red Hat](https://github.com/RedHatOfficial) |
| Aditya Rajan | [flouthoc](https://github.com/flouthoc) | Reviewer | [Red Hat](https://github.com/RedHatOfficial) |
| Jan Rodák | [Honny1](https://github.com/Honny1) | Reviewer | [Red Hat](https://github.com/RedHatOfficial) |
| Valentin Rothberg | [vrothberg](https://github.com/vrothberg) | Reviewer | [Red Hat](https://github.com/RedHatOfficial) |
## Alumni
None at present
## Credits
The structure of this document was based off of the equivalent one in the [CRI-O Project](https://github.com/cri-o/cri-o/blob/main/MAINTAINERS.md).

View File

@ -52,6 +52,9 @@ ifeq ($(BUILDDEBUG), 1)
override GOGCFLAGS += -N -l override GOGCFLAGS += -N -l
endif endif
# Managed by renovate.
export GOLANGCI_LINT_VERSION := 2.1.0
# make all BUILDDEBUG=1 # make all BUILDDEBUG=1
# Note: Uses the -N -l go compiler options to disable compiler optimizations # Note: Uses the -N -l go compiler options to disable compiler optimizations
# and inlining. Using these build options allows you to subsequently # and inlining. Using these build options allows you to subsequently
@ -192,6 +195,7 @@ vendor:
.PHONY: lint .PHONY: lint
lint: install.tools lint: install.tools
./tests/tools/build/golangci-lint run $(LINTFLAGS) ./tests/tools/build/golangci-lint run $(LINTFLAGS)
./tests/tools/build/golangci-lint run --tests=false $(LINTFLAGS)
# CAUTION: This is not a replacement for RPMs provided by your distro. # CAUTION: This is not a replacement for RPMs provided by your distro.
# Only intended to build and test the latest unreleased changes. # Only intended to build and test the latest unreleased changes.

View File

@ -1,15 +1,24 @@
approvers: approvers:
- TomSweeneyRedHat - baude
- giuseppe
- lsm5 - lsm5
- Luap99
- mheon
- mtrmac
- nalind - nalind
- rhatdan - rhatdan
- umohnani8 - TomSweeneyRedHat
reviewers: reviewers:
- ashley-cui - ashley-cui
- baude - baude
- edsantiago
- flouthoc - flouthoc
- giuseppe - giuseppe
- Honny1 - Honny1
- lsm5
- Luap99
- mheon - mheon
- mtrmac
- nalind
- rhatdan
- TomSweeneyRedHat
- vrothberg - vrothberg

View File

@ -454,10 +454,7 @@ func (b *Builder) Add(destination string, extract bool, options AddAndCopyOption
} }
// if the destination is a directory that doesn't yet exist, let's copy it. // if the destination is a directory that doesn't yet exist, let's copy it.
newDestDirFound := false newDestDirFound := (len(destStats) == 1 || len(destStats[0].Globbed) == 0) && destMustBeDirectory && !destCanBeFile
if (len(destStats) == 1 || len(destStats[0].Globbed) == 0) && destMustBeDirectory && !destCanBeFile {
newDestDirFound = true
}
if len(destStats) == 1 && len(destStats[0].Globbed) == 1 && destStats[0].Results[destStats[0].Globbed[0]].IsRegular { if len(destStats) == 1 && len(destStats[0].Globbed) == 1 && destStats[0].Results[destStats[0].Globbed[0]].IsRegular {
if destMustBeDirectory { if destMustBeDirectory {
@ -625,7 +622,7 @@ func (b *Builder) Add(destination string, extract bool, options AddAndCopyOption
} }
// Check for dockerignore-style exclusion of this item. // Check for dockerignore-style exclusion of this item.
if rel != "." { if rel != "." {
excluded, err := pm.Matches(filepath.ToSlash(rel)) // nolint:staticcheck excluded, err := pm.Matches(filepath.ToSlash(rel)) //nolint:staticcheck
if err != nil { if err != nil {
return fmt.Errorf("checking if %q(%q) is excluded: %w", globbed, rel, err) return fmt.Errorf("checking if %q(%q) is excluded: %w", globbed, rel, err)
} }

View File

@ -1,3 +1,131 @@
- Changelog for v1.40.0 (2025-04-17)
* Bump c/storage to v1.58.0, c/image v5.35.0, c/common v0.63.0
* fix(deps): update module github.com/docker/docker to v28.1.0+incompatible
* fix(deps): update module github.com/containers/storage to v1.58.0
* cirrus: make Total Success wait for rootless integration
* chroot: use symbolic names when complaining about mount() errors
* cli: hide the `completion` command instead of disabling it outright
* Document rw and src options for --mount flag in buildah-run(1)
* fix(deps): update module github.com/moby/buildkit to v0.21.0
* build: add support for inherit-labels
* chore(deps): update dependency golangci/golangci-lint to v2.1.0
* .github: check_cirrus_cron work around github bug
* stage_executor,getCreatedBy: expand buildArgs for sources correctly
* Add a link to project governance and MAINTAINERS file
* fix(deps): update github.com/containers/storage digest to b1d1b45
* generateHostname: simplify
* Use maps.Copy
* Use slices.Concat
* Use slices.Clone
* Use slices.Contains
* Use for range over integers
* tests/testreport: don't copy os.Environ
* Use any instead of interface{}
* ci: add golangci-lint run with --tests=false
* ci: add nolintlint, fix found issues
* copier: rm nolint:unparam annotation
* .golangci.yml: add unused linter
* chroot: fix unused warnings
* copier: fix unused warnings
* tests/conformance: fix unused warning
* ci: switch to golangci-lint v2
* internal/mkcw: disable ST1003 warnings
* tests/conformance: do not double import (fix ST1019)
* cmd/buildah: don't double import (fix ST1019)
* Do not capitalize error strings
* cmd/buildah: do not capitalize error strings
* tests/conformance: fix QF1012 warnings
* tests/serve: fix QF1012 warning
* Use strings.ReplaceAll to fix QF1004 warnings
* Use switch to fix QF1003 warnings
* Apply De Morgan's law to fix QF1001 warnings
* Fix QF1007 staticcheck warnings
* imagebuildah: fix revive warning
* Rename max variable
* tests/tools: install lint from binary, use renovate
* fix(deps): update module github.com/containernetworking/cni to v1.3.0
* Update Buildah issue template to new version and support podman build
* fix(deps): update module golang.org/x/crypto to v0.37.0
* stage_executor: reset platform in systemcontext for stages
* fix(deps): update github.com/opencontainers/runtime-tools digest to 260e151
* cmd/buildah: rm unused containerOutputUsingTemplate
* cmd/buildah: rm unused getDateAndDigestAndSize
* build: return ExecErrorCodeGeneric when git operation fails
* add: report error while creating dir for URL source.
* createPlatformContainer: drop MS_REMOUNT|MS_BIND
* fix(deps): update module github.com/docker/docker to v28.0.3+incompatible
* fix: bats won't fail on ! without cleverness
* feat: use HistoryTimestamp, if set, for oci-archive entries
* Allow extendedGlob to work with Windows paths
* fix(deps): update module github.com/moby/buildkit to v0.20.2
* fix(deps): update github.com/openshift/imagebuilder digest to e87e4e1
* fix(deps): update module github.com/docker/docker to v28.0.2+incompatible
* fix(deps): update module tags.cncf.io/container-device-interface to v1.0.1
* chore(deps): update dependency containers/automation_images to v20250324
* vendor: update github.com/opencontainers/selinux to v1.12.0
* replace deprecated selinux/label calls
* vendor: bump c/common to dbeb17e40c80
* Use builtin arg defaults from imagebuilder
* linux: accept unmask paths as glob values
* vendor: update containers/common
* Add --parents option for COPY in Dockerfiles
* fix(deps): update module github.com/opencontainers/runc to v1.2.6
* update go.sum from the previous commit
* fix(deps): update module tags.cncf.io/container-device-interface to v1
* chore(deps): update module golang.org/x/net to v0.36.0 [security]
* packit: remove f40 from copr builds
* cirrus: update to go 1.23 image
* vendor bump to golang.org/x/crypto v0.36.0
* cirrus: update PRIOR_FEDORA comment
* github: remove cirrus rerun action
* fix(deps): update module github.com/containers/common to v0.62.2
* fix(deps): update module github.com/containers/image/v5 to v5.34.2
* fix: close files properly when BuildDockerfiles exits
* fix(deps): update module github.com/containers/storage to v1.57.2
* stage_executor: history should include heredoc summary correctly
* fix(deps): update module github.com/containers/common to v0.62.1
* github: disable cron rerun action
* fix(deps): update module github.com/moby/buildkit to v0.20.1
* internal/mkcw.Archive(): use github.com/containers/storage/pkg/ioutils
* [skip-ci] TMT: system tests
* buildah-build.1.md: secret examples
* fix(deps): update github.com/containers/luksy digest to 40bd943
* fix(deps): update module github.com/opencontainers/image-spec to v1.1.1
* fix(deps): update module github.com/containers/image/v5 to v5.34.1
* Use UnparsedInstance.Manifest instead of ImageSource.GetManifest
* fix(deps): update module github.com/opencontainers/runtime-spec to v1.2.1
* tests/conformance/testdata/Dockerfile.add: update some URLs
* Vendor imagebuilder
* Fix source of OS, architecture and variant
* chore(deps): update module github.com/go-jose/go-jose/v4 to v4.0.5 [security]
* fix(deps): update module tags.cncf.io/container-device-interface to v0.8.1
* fix(deps): update module github.com/moby/buildkit to v0.20.0
* chroot createPlatformContainer: use MS_REMOUNT
* conformance: make TestCommit and TestConformance parallel
* cirrus: reduce task timeout
* mkcw: mkcw_check_image use bats run_with_log
* test: use /tmp as TMPDIR
* heredoc: create temp subdirs for each build
* test: heredoc remove python dependency from test
* Support the containers.conf container_name_as_hostname option
* fix(deps): update module github.com/opencontainers/runc to v1.2.5
* fix(deps): update module github.com/spf13/cobra to v1.9.0
* .cirrus: use more cores for smoke
* Switch to the CNCF Code of Conduct
* .cirrus: bump ci resources
* fix(deps): update module golang.org/x/crypto to v0.33.0
* Distinguish --mount=type=cache locations by ownership, too
* fix(deps): update module golang.org/x/term to v0.29.0
* .cirrus: run -race only on non-PR branch
* unit: deparallize some tests
* .cirrus: use multiple cpu for unit tests
* Makefile: use -parallel for go test
* unit_test: use Parallel test where possible
* Update module golang.org/x/sys to v0.30.0
* Update module golang.org/x/sync to v0.11.0
* Update dependency containers/automation_images to v20250131
* Bump to Buildah v1.40.0-dev
- Changelog for v1.39.0 (2025-01-31) - Changelog for v1.39.0 (2025-01-31)
* Bump c/storage v1.57.1, c/image 5.34.0, c/common v0.62.0 * Bump c/storage v1.57.1, c/image 5.34.0, c/common v0.62.0
* Update module github.com/containers/storage to v1.57.0 * Update module github.com/containers/storage to v1.57.0

View File

@ -8,6 +8,7 @@ import (
"os" "os"
"os/exec" "os/exec"
"path/filepath" "path/filepath"
"slices"
"strings" "strings"
"syscall" "syscall"
"time" "time"
@ -42,8 +43,82 @@ var (
"RLIMIT_STACK": unix.RLIMIT_STACK, "RLIMIT_STACK": unix.RLIMIT_STACK,
} }
rlimitsReverseMap = map[int]string{} rlimitsReverseMap = map[int]string{}
mountFlagMap = map[int]string{
unix.MS_ACTIVE: "MS_ACTIVE",
unix.MS_BIND: "MS_BIND",
unix.MS_BORN: "MS_BORN",
unix.MS_DIRSYNC: "MS_DIRSYNC",
unix.MS_KERNMOUNT: "MS_KERNMOUNT",
unix.MS_LAZYTIME: "MS_LAZYTIME",
unix.MS_MANDLOCK: "MS_MANDLOCK",
unix.MS_MOVE: "MS_MOVE",
unix.MS_NOATIME: "MS_NOATIME",
unix.MS_NODEV: "MS_NODEV",
unix.MS_NODIRATIME: "MS_NODIRATIME",
unix.MS_NOEXEC: "MS_NOEXEC",
unix.MS_NOREMOTELOCK: "MS_NOREMOTELOCK",
unix.MS_NOSEC: "MS_NOSEC",
unix.MS_NOSUID: "MS_NOSUID",
unix.MS_NOSYMFOLLOW: "MS_NOSYMFOLLOW",
unix.MS_NOUSER: "MS_NOUSER",
unix.MS_POSIXACL: "MS_POSIXACL",
unix.MS_PRIVATE: "MS_PRIVATE",
unix.MS_RDONLY: "MS_RDONLY",
unix.MS_REC: "MS_REC",
unix.MS_RELATIME: "MS_RELATIME",
unix.MS_REMOUNT: "MS_REMOUNT",
unix.MS_SHARED: "MS_SHARED",
unix.MS_SILENT: "MS_SILENT",
unix.MS_SLAVE: "MS_SLAVE",
unix.MS_STRICTATIME: "MS_STRICTATIME",
unix.MS_SUBMOUNT: "MS_SUBMOUNT",
unix.MS_SYNCHRONOUS: "MS_SYNCHRONOUS",
unix.MS_UNBINDABLE: "MS_UNBINDABLE",
}
statFlagMap = map[int]string{
unix.ST_MANDLOCK: "ST_MANDLOCK",
unix.ST_NOATIME: "ST_NOATIME",
unix.ST_NODEV: "ST_NODEV",
unix.ST_NODIRATIME: "ST_NODIRATIME",
unix.ST_NOEXEC: "ST_NOEXEC",
unix.ST_NOSUID: "ST_NOSUID",
unix.ST_RDONLY: "ST_RDONLY",
unix.ST_RELATIME: "ST_RELATIME",
unix.ST_SYNCHRONOUS: "ST_SYNCHRONOUS",
}
) )
func mountFlagNames(flags uintptr) []string {
var names []string
for flag, name := range mountFlagMap {
if int(flags)&flag == flag {
names = append(names, name)
flags = flags &^ (uintptr(flag))
}
}
if flags != 0 { // got some unknown leftovers
names = append(names, fmt.Sprintf("%#x", flags))
}
slices.Sort(names)
return names
}
func statFlagNames(flags uintptr) []string {
var names []string
flags = flags & ^uintptr(0x20) // mask off ST_VALID
for flag, name := range statFlagMap {
if int(flags)&flag == flag {
names = append(names, name)
flags = flags &^ (uintptr(flag))
}
}
if flags != 0 { // got some unknown leftovers
names = append(names, fmt.Sprintf("%#x", flags))
}
slices.Sort(names)
return names
}
type runUsingChrootSubprocOptions struct { type runUsingChrootSubprocOptions struct {
Spec *specs.Spec Spec *specs.Spec
BundlePath string BundlePath string
@ -61,14 +136,14 @@ func setPlatformUnshareOptions(spec *specs.Spec, cmd *unshare.Cmd) error {
uidmap, gidmap := spec.Linux.UIDMappings, spec.Linux.GIDMappings uidmap, gidmap := spec.Linux.UIDMappings, spec.Linux.GIDMappings
if len(uidmap) == 0 { if len(uidmap) == 0 {
// No UID mappings are configured for the container. Borrow our parent's mappings. // No UID mappings are configured for the container. Borrow our parent's mappings.
uidmap = append([]specs.LinuxIDMapping{}, hostUidmap...) uidmap = slices.Clone(hostUidmap)
for i := range uidmap { for i := range uidmap {
uidmap[i].HostID = uidmap[i].ContainerID uidmap[i].HostID = uidmap[i].ContainerID
} }
} }
if len(gidmap) == 0 { if len(gidmap) == 0 {
// No GID mappings are configured for the container. Borrow our parent's mappings. // No GID mappings are configured for the container. Borrow our parent's mappings.
gidmap = append([]specs.LinuxIDMapping{}, hostGidmap...) gidmap = slices.Clone(hostGidmap)
for i := range gidmap { for i := range gidmap {
gidmap[i].HostID = gidmap[i].ContainerID gidmap[i].HostID = gidmap[i].ContainerID
} }
@ -573,15 +648,15 @@ func setupChrootBindMounts(spec *specs.Spec, bundlePath string) (undoBinds func(
remountFlags |= uintptr(fs.Flags) & possibleImportantFlags remountFlags |= uintptr(fs.Flags) & possibleImportantFlags
} }
if err = unix.Mount(target, target, m.Type, remountFlags, ""); err != nil { if err = unix.Mount(target, target, m.Type, remountFlags, ""); err != nil {
return undoBinds, fmt.Errorf("remounting %q in mount namespace with flags %#x instead of %#x: %w", target, requestFlags, effectiveImportantFlags, err) return undoBinds, fmt.Errorf("remounting %q in mount namespace with flags %v instead of %v: %w", target, mountFlagNames(requestFlags), statFlagNames(effectiveImportantFlags), err)
} }
// Check if the desired flags stuck. // Check if the desired flags stuck.
if err = unix.Statfs(target, &fs); err != nil { if err = unix.Statfs(target, &fs); err != nil {
return undoBinds, fmt.Errorf("checking if directory %q was remounted with requested flags %#x instead of %#x: %w", target, requestFlags, effectiveImportantFlags, err) return undoBinds, fmt.Errorf("checking if directory %q was remounted with requested flags %v instead of %v: %w", target, mountFlagNames(requestFlags), statFlagNames(effectiveImportantFlags), err)
} }
newEffectiveImportantFlags := uintptr(fs.Flags) & importantFlags newEffectiveImportantFlags := uintptr(fs.Flags) & importantFlags
if newEffectiveImportantFlags != expectedImportantFlags { if newEffectiveImportantFlags != expectedImportantFlags {
return undoBinds, fmt.Errorf("unable to remount %q with requested flags %#x instead of %#x, just got %#x back", target, requestFlags, effectiveImportantFlags, newEffectiveImportantFlags) return undoBinds, fmt.Errorf("unable to remount %q with requested flags %v instead of %v, just got %v back", target, mountFlagNames(requestFlags), statFlagNames(effectiveImportantFlags), statFlagNames(newEffectiveImportantFlags))
} }
} }
} }

View File

@ -4,16 +4,12 @@ package chroot
import ( import (
"fmt" "fmt"
"os"
"github.com/containers/common/pkg/seccomp"
specs "github.com/opencontainers/runtime-spec/specs-go" specs "github.com/opencontainers/runtime-spec/specs-go"
libseccomp "github.com/seccomp/libseccomp-golang" libseccomp "github.com/seccomp/libseccomp-golang"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
) )
const seccompAvailable = true
// setSeccomp sets the seccomp filter for ourselves and any processes that we'll start. // setSeccomp sets the seccomp filter for ourselves and any processes that we'll start.
func setSeccomp(spec *specs.Spec) error { func setSeccomp(spec *specs.Spec) error {
logrus.Debugf("setting seccomp configuration") logrus.Debugf("setting seccomp configuration")
@ -178,27 +174,3 @@ func setSeccomp(spec *specs.Spec) error {
} }
return nil return nil
} }
func setupSeccomp(spec *specs.Spec, seccompProfilePath string) error {
switch seccompProfilePath {
case "unconfined":
spec.Linux.Seccomp = nil
case "":
seccompConfig, err := seccomp.GetDefaultProfile(spec)
if err != nil {
return fmt.Errorf("loading default seccomp profile failed: %w", err)
}
spec.Linux.Seccomp = seccompConfig
default:
seccompProfile, err := os.ReadFile(seccompProfilePath)
if err != nil {
return fmt.Errorf("opening seccomp profile failed: %w", err)
}
seccompConfig, err := seccomp.LoadProfile(string(seccompProfile), spec)
if err != nil {
return fmt.Errorf("loading seccomp profile (%s) failed: %w", seccompProfilePath, err)
}
spec.Linux.Seccomp = seccompConfig
}
return nil
}

View File

@ -8,19 +8,9 @@ import (
"github.com/opencontainers/runtime-spec/specs-go" "github.com/opencontainers/runtime-spec/specs-go"
) )
const seccompAvailable = false
func setSeccomp(spec *specs.Spec) error { func setSeccomp(spec *specs.Spec) error {
if spec.Linux.Seccomp != nil { if spec.Linux.Seccomp != nil {
return errors.New("configured a seccomp filter without seccomp support?") return errors.New("configured a seccomp filter without seccomp support?")
} }
return nil return nil
} }
func setupSeccomp(spec *specs.Spec, seccompProfilePath string) error {
if spec.Linux != nil {
// runtime-tools may have supplied us with a default filter
spec.Linux.Seccomp = nil
}
return nil
}

View File

@ -26,7 +26,7 @@ import (
// unmarshalConvertedConfig obtains the config blob of img valid for the wantedManifestMIMEType format // unmarshalConvertedConfig obtains the config blob of img valid for the wantedManifestMIMEType format
// (either as it exists, or converting the image if necessary), and unmarshals it into dest. // (either as it exists, or converting the image if necessary), and unmarshals it into dest.
// NOTE: The MIME type is of the _manifest_, not of the _config_ that is returned. // NOTE: The MIME type is of the _manifest_, not of the _config_ that is returned.
func unmarshalConvertedConfig(ctx context.Context, dest interface{}, img types.Image, wantedManifestMIMEType string) error { func unmarshalConvertedConfig(ctx context.Context, dest any, img types.Image, wantedManifestMIMEType string) error {
_, actualManifestMIMEType, err := img.Manifest(ctx) _, actualManifestMIMEType, err := img.Manifest(ctx)
if err != nil { if err != nil {
return fmt.Errorf("getting manifest MIME type for %q: %w", transports.ImageName(img.Reference()), err) return fmt.Errorf("getting manifest MIME type for %q: %w", transports.ImageName(img.Reference()), err)
@ -96,9 +96,7 @@ func (b *Builder) initConfig(ctx context.Context, sys *types.SystemContext, img
if b.ImageAnnotations == nil { if b.ImageAnnotations == nil {
b.ImageAnnotations = make(map[string]string, len(v1Manifest.Annotations)) b.ImageAnnotations = make(map[string]string, len(v1Manifest.Annotations))
} }
for k, v := range v1Manifest.Annotations { maps.Copy(b.ImageAnnotations, v1Manifest.Annotations)
b.ImageAnnotations[k] = v
}
} }
} }
} else { } else {

View File

@ -331,7 +331,7 @@ func Stat(root string, directory string, options StatOptions, globs []string) ([
Request: requestStat, Request: requestStat,
Root: root, Root: root,
Directory: directory, Directory: directory,
Globs: append([]string{}, globs...), Globs: slices.Clone(globs),
StatOptions: options, StatOptions: options,
} }
resp, err := copier(nil, nil, req) resp, err := copier(nil, nil, req)
@ -382,7 +382,7 @@ func Get(root string, directory string, options GetOptions, globs []string, bulk
Request: requestGet, Request: requestGet,
Root: root, Root: root,
Directory: directory, Directory: directory,
Globs: append([]string{}, globs...), Globs: slices.Clone(globs),
StatOptions: StatOptions{ StatOptions: StatOptions{
CheckForArchives: options.ExpandArchives, CheckForArchives: options.ExpandArchives,
}, },
@ -598,7 +598,7 @@ func copierWithoutSubprocess(bulkReader io.Reader, bulkWriter io.Writer, req req
req.preservedRoot = req.Root req.preservedRoot = req.Root
req.rootPrefix = string(os.PathSeparator) req.rootPrefix = string(os.PathSeparator)
req.preservedDirectory = req.Directory req.preservedDirectory = req.Directory
req.preservedGlobs = append([]string{}, req.Globs...) req.preservedGlobs = slices.Clone(req.Globs)
if !filepath.IsAbs(req.Directory) { if !filepath.IsAbs(req.Directory) {
req.Directory = filepath.Join(req.Root, cleanerReldirectory(req.Directory)) req.Directory = filepath.Join(req.Root, cleanerReldirectory(req.Directory))
} }
@ -701,9 +701,9 @@ func copierWithSubprocess(bulkReader io.Reader, bulkWriter io.Writer, req reques
bulkReaderRead = nil bulkReaderRead = nil
bulkWriterWrite.Close() bulkWriterWrite.Close()
bulkWriterWrite = nil bulkWriterWrite = nil
killAndReturn := func(err error, step string) (*response, error) { // nolint: unparam killAndReturn := func(err error, step string) error {
if err2 := cmd.Process.Kill(); err2 != nil { if err2 := cmd.Process.Kill(); err2 != nil {
return nil, fmt.Errorf("killing subprocess: %v; %s: %w", err2, step, err) return fmt.Errorf("killing subprocess: %v; %s: %w", err2, step, err)
} }
if errors.Is(err, io.ErrClosedPipe) || errors.Is(err, syscall.EPIPE) { if errors.Is(err, io.ErrClosedPipe) || errors.Is(err, syscall.EPIPE) {
err2 := cmd.Wait() err2 := cmd.Wait()
@ -711,22 +711,22 @@ func copierWithSubprocess(bulkReader io.Reader, bulkWriter io.Writer, req reques
err = fmt.Errorf("%s: %w", errorText, err) err = fmt.Errorf("%s: %w", errorText, err)
} }
if err2 != nil { if err2 != nil {
return nil, fmt.Errorf("waiting on subprocess: %v; %s: %w", err2, step, err) return fmt.Errorf("waiting on subprocess: %v; %s: %w", err2, step, err)
} }
} }
return nil, fmt.Errorf("%v: %w", step, err) return fmt.Errorf("%v: %w", step, err)
} }
if err = encoder.Encode(req); err != nil { if err = encoder.Encode(req); err != nil {
return killAndReturn(err, "error encoding work request for copier subprocess") return nil, killAndReturn(err, "error encoding work request for copier subprocess")
} }
if err = decoder.Decode(&resp); err != nil { if err = decoder.Decode(&resp); err != nil {
if errors.Is(err, io.EOF) && errorBuffer.Len() > 0 { if errors.Is(err, io.EOF) && errorBuffer.Len() > 0 {
return killAndReturn(errors.New(errorBuffer.String()), "error in copier subprocess") return nil, killAndReturn(errors.New(errorBuffer.String()), "error in copier subprocess")
} }
return killAndReturn(err, "error decoding response from copier subprocess") return nil, killAndReturn(err, "error decoding response from copier subprocess")
} }
if err = encoder.Encode(&request{Request: requestQuit}); err != nil { if err = encoder.Encode(&request{Request: requestQuit}); err != nil {
return killAndReturn(err, "error encoding quit request for copier subprocess") return nil, killAndReturn(err, "error encoding quit request for copier subprocess")
} }
stdinWrite.Close() stdinWrite.Close()
stdinWrite = nil stdinWrite = nil
@ -850,7 +850,7 @@ func copierMain() {
req.preservedRoot = req.Root req.preservedRoot = req.Root
req.rootPrefix = string(os.PathSeparator) req.rootPrefix = string(os.PathSeparator)
req.preservedDirectory = req.Directory req.preservedDirectory = req.Directory
req.preservedGlobs = append([]string{}, req.Globs...) req.preservedGlobs = slices.Clone(req.Globs)
if chrooted { if chrooted {
// We'll need to adjust some things now that the root // We'll need to adjust some things now that the root
// directory isn't what it was. Make the directory and // directory isn't what it was. Make the directory and
@ -975,7 +975,7 @@ func pathIsExcluded(root, path string, pm *fileutils.PatternMatcher) (string, bo
// Matches uses filepath.FromSlash() to convert candidates before // Matches uses filepath.FromSlash() to convert candidates before
// checking if they match the patterns it's been given, implying that // checking if they match the patterns it's been given, implying that
// it expects Unix-style paths. // it expects Unix-style paths.
matches, err := pm.Matches(filepath.ToSlash(rel)) // nolint:staticcheck matches, err := pm.Matches(filepath.ToSlash(rel)) //nolint:staticcheck
if err != nil { if err != nil {
return rel, false, fmt.Errorf("copier: error checking if %q is excluded: %w", rel, err) return rel, false, fmt.Errorf("copier: error checking if %q is excluded: %w", rel, err)
} }
@ -1009,7 +1009,7 @@ func resolvePath(root, path string, evaluateFinalComponent bool, pm *fileutils.P
} }
excluded = excluded || thisExcluded excluded = excluded || thisExcluded
if !excluded { if !excluded {
if target, err := os.Readlink(filepath.Join(workingPath, components[0])); err == nil && !(len(components) == 1 && !evaluateFinalComponent) { if target, err := os.Readlink(filepath.Join(workingPath, components[0])); err == nil && (len(components) != 1 || evaluateFinalComponent) {
followed++ followed++
if followed > maxLoopsFollowed { if followed > maxLoopsFollowed {
return "", &os.PathError{ return "", &os.PathError{
@ -1052,7 +1052,7 @@ func resolvePath(root, path string, evaluateFinalComponent bool, pm *fileutils.P
} }
func copierHandlerEval(req request) *response { func copierHandlerEval(req request) *response {
errorResponse := func(fmtspec string, args ...interface{}) *response { errorResponse := func(fmtspec string, args ...any) *response {
return &response{Error: fmt.Sprintf(fmtspec, args...), Eval: evalResponse{}} return &response{Error: fmt.Sprintf(fmtspec, args...), Eval: evalResponse{}}
} }
resolvedTarget, err := resolvePath(req.Root, req.Directory, true, nil) resolvedTarget, err := resolvePath(req.Root, req.Directory, true, nil)
@ -1063,7 +1063,7 @@ func copierHandlerEval(req request) *response {
} }
func copierHandlerStat(req request, pm *fileutils.PatternMatcher) *response { func copierHandlerStat(req request, pm *fileutils.PatternMatcher) *response {
errorResponse := func(fmtspec string, args ...interface{}) *response { errorResponse := func(fmtspec string, args ...any) *response {
return &response{Error: fmt.Sprintf(fmtspec, args...), Stat: statResponse{}} return &response{Error: fmt.Sprintf(fmtspec, args...), Stat: statResponse{}}
} }
if len(req.Globs) == 0 { if len(req.Globs) == 0 {
@ -1233,7 +1233,7 @@ func copierHandlerGet(bulkWriter io.Writer, req request, pm *fileutils.PatternMa
statRequest := req statRequest := req
statRequest.Request = requestStat statRequest.Request = requestStat
statResponse := copierHandlerStat(req, pm) statResponse := copierHandlerStat(req, pm)
errorResponse := func(fmtspec string, args ...interface{}) (*response, func() error, error) { errorResponse := func(fmtspec string, args ...any) (*response, func() error, error) {
return &response{Error: fmt.Sprintf(fmtspec, args...), Stat: statResponse.Stat, Get: getResponse{}}, nil, nil return &response{Error: fmt.Sprintf(fmtspec, args...), Stat: statResponse.Stat, Get: getResponse{}}, nil, nil
} }
if statResponse.Error != "" { if statResponse.Error != "" {
@ -1661,14 +1661,15 @@ func copierHandlerGetOne(srcfi os.FileInfo, symlinkTarget, name, contentPath str
return fmt.Errorf("getting fflags: %w", err) return fmt.Errorf("getting fflags: %w", err)
} }
var f *os.File var f *os.File
if hdr.Typeflag == tar.TypeReg { switch hdr.Typeflag {
case tar.TypeReg:
// open the file first so that we don't write a header for it if we can't actually read it // open the file first so that we don't write a header for it if we can't actually read it
f, err = os.Open(contentPath) f, err = os.Open(contentPath)
if err != nil { if err != nil {
return fmt.Errorf("opening file for adding its contents to archive: %w", err) return fmt.Errorf("opening file for adding its contents to archive: %w", err)
} }
defer f.Close() defer f.Close()
} else if hdr.Typeflag == tar.TypeDir { case tar.TypeDir:
// open the directory file first to make sure we can access it. // open the directory file first to make sure we can access it.
f, err = os.Open(contentPath) f, err = os.Open(contentPath)
if err != nil { if err != nil {
@ -1695,7 +1696,7 @@ func copierHandlerGetOne(srcfi os.FileInfo, symlinkTarget, name, contentPath str
} }
func copierHandlerPut(bulkReader io.Reader, req request, idMappings *idtools.IDMappings) (*response, func() error, error) { func copierHandlerPut(bulkReader io.Reader, req request, idMappings *idtools.IDMappings) (*response, func() error, error) {
errorResponse := func(fmtspec string, args ...interface{}) (*response, func() error, error) { errorResponse := func(fmtspec string, args ...any) (*response, func() error, error) {
return &response{Error: fmt.Sprintf(fmtspec, args...), Put: putResponse{}}, nil, nil return &response{Error: fmt.Sprintf(fmtspec, args...), Put: putResponse{}}, nil, nil
} }
dirUID, dirGID, defaultDirUID, defaultDirGID := 0, 0, 0, 0 dirUID, dirGID, defaultDirUID, defaultDirGID := 0, 0, 0, 0
@ -2080,7 +2081,7 @@ func copierHandlerPut(bulkReader io.Reader, req request, idMappings *idtools.IDM
// set xattrs, including some that might have been reset by chown() // set xattrs, including some that might have been reset by chown()
if !req.PutOptions.StripXattrs { if !req.PutOptions.StripXattrs {
xattrs := mapWithPrefixedKeysWithoutKeyPrefix(hdr.PAXRecords, xattrPAXRecordNamespace) xattrs := mapWithPrefixedKeysWithoutKeyPrefix(hdr.PAXRecords, xattrPAXRecordNamespace)
if err = Lsetxattrs(path, xattrs); err != nil { // nolint:staticcheck if err = Lsetxattrs(path, xattrs); err != nil {
if !req.PutOptions.IgnoreXattrErrors { if !req.PutOptions.IgnoreXattrErrors {
return fmt.Errorf("copier: put: error setting extended attributes on %q: %w", path, err) return fmt.Errorf("copier: put: error setting extended attributes on %q: %w", path, err)
} }
@ -2109,7 +2110,7 @@ func copierHandlerPut(bulkReader io.Reader, req request, idMappings *idtools.IDM
} }
func copierHandlerMkdir(req request, idMappings *idtools.IDMappings) (*response, func() error, error) { func copierHandlerMkdir(req request, idMappings *idtools.IDMappings) (*response, func() error, error) {
errorResponse := func(fmtspec string, args ...interface{}) (*response, func() error, error) { errorResponse := func(fmtspec string, args ...any) (*response, func() error, error) {
return &response{Error: fmt.Sprintf(fmtspec, args...), Mkdir: mkdirResponse{}}, nil, nil return &response{Error: fmt.Sprintf(fmtspec, args...), Mkdir: mkdirResponse{}}, nil, nil
} }
dirUID, dirGID := 0, 0 dirUID, dirGID := 0, 0
@ -2163,7 +2164,7 @@ func copierHandlerMkdir(req request, idMappings *idtools.IDMappings) (*response,
} }
func copierHandlerRemove(req request) *response { func copierHandlerRemove(req request) *response {
errorResponse := func(fmtspec string, args ...interface{}) *response { errorResponse := func(fmtspec string, args ...any) *response {
return &response{Error: fmt.Sprintf(fmtspec, args...), Remove: removeResponse{}} return &response{Error: fmt.Sprintf(fmtspec, args...), Remove: removeResponse{}}
} }
resolvedTarget, err := resolvePath(req.Root, req.Directory, false, nil) resolvedTarget, err := resolvePath(req.Root, req.Directory, false, nil)

View File

@ -84,8 +84,3 @@ func sameDevice(a, b os.FileInfo) bool {
} }
return uA.Dev == uB.Dev return uA.Dev == uB.Dev
} }
const (
testModeMask = int64(os.ModePerm)
testIgnoreSymlinkDates = false
)

View File

@ -81,8 +81,3 @@ func lutimes(isSymlink bool, path string, atime, mtime time.Time) error {
func sameDevice(a, b os.FileInfo) bool { func sameDevice(a, b os.FileInfo) bool {
return true return true
} }
const (
testModeMask = int64(0o600)
testIgnoreSymlinkDates = true
)

View File

@ -187,7 +187,7 @@ type BuildOptions struct {
// Log is a callback that will print a progress message. If no value // Log is a callback that will print a progress message. If no value
// is supplied, the message will be sent to Err (or os.Stderr, if Err // is supplied, the message will be sent to Err (or os.Stderr, if Err
// is nil) by default. // is nil) by default.
Log func(format string, args ...interface{}) Log func(format string, args ...any)
// In is connected to stdin for RUN instructions. // In is connected to stdin for RUN instructions.
In io.Reader In io.Reader
// Out is a place where non-error log messages are sent. // Out is a place where non-error log messages are sent.
@ -236,6 +236,9 @@ type BuildOptions struct {
// ID mapping options to use if we're setting up our own user namespace // ID mapping options to use if we're setting up our own user namespace
// when handling RUN instructions. // when handling RUN instructions.
IDMappingOptions *IDMappingOptions IDMappingOptions *IDMappingOptions
// InheritLabels controls whether or not built images will retain the labels
// which were set in their base images
InheritLabels types.OptionalBool
// AddCapabilities is a list of capabilities to add to the default set when // AddCapabilities is a list of capabilities to add to the default set when
// handling RUN instructions. // handling RUN instructions.
AddCapabilities []string AddCapabilities []string

View File

@ -29,7 +29,7 @@ const (
// identify working containers. // identify working containers.
Package = "buildah" Package = "buildah"
// Version for the Package. Also used by .packit.sh for Packit builds. // Version for the Package. Also used by .packit.sh for Packit builds.
Version = "1.40.0-dev" Version = "1.40.0"
// DefaultRuntime if containers.conf fails. // DefaultRuntime if containers.conf fails.
DefaultRuntime = "runc" DefaultRuntime = "runc"

View File

@ -164,7 +164,7 @@ type V1Image struct {
// V2Image stores the image configuration // V2Image stores the image configuration
type V2Image struct { type V2Image struct {
V1Image V1Image
Parent ID `json:"parent,omitempty"` // nolint:govet Parent ID `json:"parent,omitempty"`
RootFS *V2S2RootFS `json:"rootfs,omitempty"` RootFS *V2S2RootFS `json:"rootfs,omitempty"`
History []V2S2History `json:"history,omitempty"` History []V2S2History `json:"history,omitempty"`
OSVersion string `json:"os.version,omitempty"` OSVersion string `json:"os.version,omitempty"`

View File

@ -435,9 +435,7 @@ func buildDockerfilesOnce(ctx context.Context, store storage.Store, logger *logr
return "", nil, fmt.Errorf("creating build executor: %w", err) return "", nil, fmt.Errorf("creating build executor: %w", err)
} }
b := imagebuilder.NewBuilder(options.Args) b := imagebuilder.NewBuilder(options.Args)
for k, v := range builtinArgDefaults { maps.Copy(b.BuiltinArgDefaults, builtinArgDefaults)
b.BuiltinArgDefaults[k] = v
}
defaultContainerConfig, err := config.Default() defaultContainerConfig, err := config.Default()
if err != nil { if err != nil {
@ -451,7 +449,7 @@ func buildDockerfilesOnce(ctx context.Context, store storage.Store, logger *logr
if options.Target != "" { if options.Target != "" {
stagesTargeted, ok := stages.ThroughTarget(options.Target) stagesTargeted, ok := stages.ThroughTarget(options.Target)
if !ok { if !ok {
return "", nil, fmt.Errorf("The target %q was not found in the provided Dockerfile", options.Target) return "", nil, fmt.Errorf("the target %q was not found in the provided Dockerfile", options.Target)
} }
stages = stagesTargeted stages = stagesTargeted
} }

View File

@ -80,8 +80,9 @@ type Executor struct {
output string output string
outputFormat string outputFormat string
additionalTags []string additionalTags []string
log func(format string, args ...interface{}) // can be nil log func(format string, args ...any) // can be nil
in io.Reader in io.Reader
inheritLabels types.OptionalBool
out io.Writer out io.Writer
err io.Writer err io.Writer
signaturePolicyPath string signaturePolicyPath string
@ -261,6 +262,7 @@ func newExecutor(logger *logrus.Logger, logPrefix string, store storage.Store, o
err: options.Err, err: options.Err,
reportWriter: writer, reportWriter: writer,
isolation: options.Isolation, isolation: options.Isolation,
inheritLabels: options.InheritLabels,
namespaceOptions: options.NamespaceOptions, namespaceOptions: options.NamespaceOptions,
configureNetwork: options.ConfigureNetwork, configureNetwork: options.ConfigureNetwork,
cniPluginPath: options.CNIPluginPath, cniPluginPath: options.CNIPluginPath,
@ -372,9 +374,12 @@ func newExecutor(logger *logrus.Logger, logPrefix string, store storage.Store, o
// startStage creates a new stage executor that will be referenced whenever a // startStage creates a new stage executor that will be referenced whenever a
// COPY or ADD statement uses a --from=NAME flag. // COPY or ADD statement uses a --from=NAME flag.
func (b *Executor) startStage(ctx context.Context, stage *imagebuilder.Stage, stages imagebuilder.Stages, output string) *StageExecutor { func (b *Executor) startStage(ctx context.Context, stage *imagebuilder.Stage, stages imagebuilder.Stages, output string) *StageExecutor {
// create a copy of systemContext for each stage executor.
systemContext := *b.systemContext
stageExec := &StageExecutor{ stageExec := &StageExecutor{
ctx: ctx, ctx: ctx,
executor: b, executor: b,
systemContext: &systemContext,
log: b.log, log: b.log,
index: stage.Position, index: stage.Position,
stages: stages, stages: stages,
@ -508,7 +513,7 @@ func (b *Executor) buildStage(ctx context.Context, cleanupStages map[int]*StageE
// layers, its easier to reuse cached layers. // layers, its easier to reuse cached layers.
if len(b.labels) > 0 { if len(b.labels) > 0 {
var labelLine string var labelLine string
labels := append([]string{}, b.labels...) labels := slices.Clone(b.labels)
for _, labelSpec := range labels { for _, labelSpec := range labels {
key, value, _ := strings.Cut(labelSpec, "=") key, value, _ := strings.Cut(labelSpec, "=")
// check only for an empty key since docker allows empty values // check only for an empty key since docker allows empty values
@ -553,7 +558,7 @@ func (b *Executor) buildStage(ctx context.Context, cleanupStages map[int]*StageE
stageExecutor := b.startStage(ctx, &stage, stages, output) stageExecutor := b.startStage(ctx, &stage, stages, output)
if stageExecutor.log == nil { if stageExecutor.log == nil {
stepCounter := 0 stepCounter := 0
stageExecutor.log = func(format string, args ...interface{}) { stageExecutor.log = func(format string, args ...any) {
prefix := b.logPrefix prefix := b.logPrefix
if len(stages) > 1 { if len(stages) > 1 {
prefix += fmt.Sprintf("[%d/%d] ", stageIndex+1, len(stages)) prefix += fmt.Sprintf("[%d/%d] ", stageIndex+1, len(stages))

View File

@ -59,8 +59,9 @@ import (
// name to the image that it produces. // name to the image that it produces.
type StageExecutor struct { type StageExecutor struct {
ctx context.Context ctx context.Context
systemContext *types.SystemContext
executor *Executor executor *Executor
log func(format string, args ...interface{}) log func(format string, args ...any)
index int index int
stages imagebuilder.Stages stages imagebuilder.Stages
name string name string
@ -172,14 +173,7 @@ func (s *StageExecutor) Preserve(path string) error {
for cachedPath := range s.volumeCache { for cachedPath := range s.volumeCache {
// Walk our list of cached volumes, and check that they're // Walk our list of cached volumes, and check that they're
// still in the list of locations that we need to cache. // still in the list of locations that we need to cache.
found := false found := slices.Contains(s.volumes, cachedPath)
for _, volume := range s.volumes {
if volume == cachedPath {
// We need to keep this volume's cache.
found = true
break
}
}
if !found { if !found {
// We don't need to keep this volume's cache. Make a // We don't need to keep this volume's cache. Make a
// note to remove it. // note to remove it.
@ -584,8 +578,8 @@ func (s *StageExecutor) performCopy(excludes []string, copies ...imagebuilder.Co
// The values for these next two fields are ultimately // The values for these next two fields are ultimately
// based on command line flags with names that sound // based on command line flags with names that sound
// much more generic. // much more generic.
CertPath: s.executor.systemContext.DockerCertPath, CertPath: s.systemContext.DockerCertPath,
InsecureSkipTLSVerify: s.executor.systemContext.DockerInsecureSkipTLSVerify, InsecureSkipTLSVerify: s.systemContext.DockerInsecureSkipTLSVerify,
MaxRetries: s.executor.maxPullPushRetries, MaxRetries: s.executor.maxPullPushRetries,
RetryDelay: s.executor.retryPullPushDelay, RetryDelay: s.executor.retryPullPushDelay,
Parents: copy.Parents, Parents: copy.Parents,
@ -621,7 +615,7 @@ func (s *StageExecutor) runStageMountPoints(mountList []string) (map[string]inte
if strings.Contains(flag, "from") { if strings.Contains(flag, "from") {
tokens := strings.Split(flag, ",") tokens := strings.Split(flag, ",")
if len(tokens) < 2 { if len(tokens) < 2 {
return nil, fmt.Errorf("Invalid --mount command: %s", flag) return nil, fmt.Errorf("invalid --mount command: %s", flag)
} }
for _, token := range tokens { for _, token := range tokens {
key, val, hasVal := strings.Cut(token, "=") key, val, hasVal := strings.Cut(token, "=")
@ -711,8 +705,8 @@ func (s *StageExecutor) runStageMountPoints(mountList []string) (map[string]inte
MountPoint: otherStage.mountPoint, MountPoint: otherStage.mountPoint,
} }
break break
} else { }
// Treat the source's name as the name of an image. // Otherwise, treat the source's name as the name of an image.
mountPoint, err := s.getImageRootfs(s.ctx, from) mountPoint, err := s.getImageRootfs(s.ctx, from)
if err != nil { if err != nil {
return nil, fmt.Errorf("%s from=%s: no stage or image found with that name", flag, from) return nil, fmt.Errorf("%s from=%s: no stage or image found with that name", flag, from)
@ -722,8 +716,6 @@ func (s *StageExecutor) runStageMountPoints(mountList []string) (map[string]inte
DidExecute: true, DidExecute: true,
MountPoint: mountPoint, MountPoint: mountPoint,
} }
break
}
default: default:
continue continue
} }
@ -816,7 +808,7 @@ func (s *StageExecutor) Run(run imagebuilder.Run, config docker.Config) error {
defer devNull.Close() defer devNull.Close()
stdin = devNull stdin = devNull
} }
namespaceOptions := append([]define.NamespaceOption{}, s.executor.namespaceOptions...) namespaceOptions := slices.Clone(s.executor.namespaceOptions)
options := buildah.RunOptions{ options := buildah.RunOptions{
Args: s.executor.runtimeArgs, Args: s.executor.runtimeArgs,
Cmd: config.Cmd, Cmd: config.Cmd,
@ -841,7 +833,7 @@ func (s *StageExecutor) Run(run imagebuilder.Run, config docker.Config) error {
Stderr: s.executor.err, Stderr: s.executor.err,
Stdin: stdin, Stdin: stdin,
Stdout: s.executor.out, Stdout: s.executor.out,
SystemContext: s.executor.systemContext, SystemContext: s.systemContext,
Terminal: buildah.WithoutTerminal, Terminal: buildah.WithoutTerminal,
User: config.User, User: config.User,
WorkingDir: config.WorkingDir, WorkingDir: config.WorkingDir,
@ -966,19 +958,20 @@ func (s *StageExecutor) prepare(ctx context.Context, from string, initializeIBCo
} }
} }
builderSystemContext := s.executor.systemContext // In a multi-stage build where `FROM --platform=<>` was used then we must
// get platform string from stage // reset context for new stages so that new stages don't inherit unexpected
if stage.Builder.Platform != "" { // `--platform` from prior stages.
os, arch, variant, err := parse.Platform(stage.Builder.Platform) if stage.Builder.Platform != "" || (len(s.stages) > 1 && (s.systemContext.ArchitectureChoice == "" && s.systemContext.VariantChoice == "" && s.systemContext.OSChoice == "")) {
imageOS, imageArch, imageVariant, err := parse.Platform(stage.Builder.Platform)
if err != nil { if err != nil {
return nil, fmt.Errorf("unable to parse platform %q: %w", stage.Builder.Platform, err) return nil, fmt.Errorf("unable to parse platform %q: %w", stage.Builder.Platform, err)
} }
if arch != "" || variant != "" { if imageArch != "" || imageVariant != "" {
builderSystemContext.ArchitectureChoice = arch s.systemContext.ArchitectureChoice = imageArch
builderSystemContext.VariantChoice = variant s.systemContext.VariantChoice = imageVariant
} }
if os != "" { if imageOS != "" {
builderSystemContext.OSChoice = os s.systemContext.OSChoice = imageOS
} }
} }
@ -992,7 +985,7 @@ func (s *StageExecutor) prepare(ctx context.Context, from string, initializeIBCo
BlobDirectory: s.executor.blobDirectory, BlobDirectory: s.executor.blobDirectory,
SignaturePolicyPath: s.executor.signaturePolicyPath, SignaturePolicyPath: s.executor.signaturePolicyPath,
ReportWriter: s.executor.reportWriter, ReportWriter: s.executor.reportWriter,
SystemContext: builderSystemContext, SystemContext: s.systemContext,
Isolation: s.executor.isolation, Isolation: s.executor.isolation,
NamespaceOptions: s.executor.namespaceOptions, NamespaceOptions: s.executor.namespaceOptions,
ConfigureNetwork: s.executor.configureNetwork, ConfigureNetwork: s.executor.configureNetwork,
@ -1076,6 +1069,11 @@ func (s *StageExecutor) prepare(ctx context.Context, from string, initializeIBCo
RootFS: rootfs, RootFS: rootfs,
} }
dImage.Config = &dImage.ContainerConfig dImage.Config = &dImage.ContainerConfig
if s.executor.inheritLabels == types.OptionalBoolFalse {
// If user has selected `--inherit-labels=false` let's not
// inherit labels from base image.
dImage.Config.Labels = nil
}
err = ib.FromImage(&dImage, node) err = ib.FromImage(&dImage, node)
if err != nil { if err != nil {
if err2 := builder.Delete(); err2 != nil { if err2 := builder.Delete(); err2 != nil {
@ -1545,7 +1543,7 @@ func (s *StageExecutor) Execute(ctx context.Context, base string) (imgID string,
// we need to call ib.Run() to correctly put the args together before // we need to call ib.Run() to correctly put the args together before
// determining if a cached layer with the same build args already exists // determining if a cached layer with the same build args already exists
// and that is done in the if block below. // and that is done in the if block below.
if checkForLayers && step.Command != "arg" && !(s.executor.squash && lastInstruction && lastStage) && !avoidLookingCache { if checkForLayers && step.Command != "arg" && (!s.executor.squash || !lastInstruction || !lastStage) && !avoidLookingCache {
// For `COPY` and `ADD`, history entries include digests computed from // For `COPY` and `ADD`, history entries include digests computed from
// the content that's copied in. We need to compute that information so that // the content that's copied in. We need to compute that information so that
// it can be used to evaluate the cache, which means we need to go ahead // it can be used to evaluate the cache, which means we need to go ahead
@ -1879,6 +1877,11 @@ func (s *StageExecutor) getCreatedBy(node *parser.Node, addedContentSummary stri
if node == nil { if node == nil {
return "/bin/sh", nil return "/bin/sh", nil
} }
inheritLabels := ""
// If --inherit-label was manually set to false then update history.
if s.executor.inheritLabels == types.OptionalBoolFalse {
inheritLabels = "|inheritLabels=false"
}
switch strings.ToUpper(node.Value) { switch strings.ToUpper(node.Value) {
case "ARG": case "ARG":
for _, variable := range strings.Fields(node.Original) { for _, variable := range strings.Fields(node.Original) {
@ -1887,7 +1890,7 @@ func (s *StageExecutor) getCreatedBy(node *parser.Node, addedContentSummary stri
} }
} }
buildArgs := s.getBuildArgsKey() buildArgs := s.getBuildArgsKey()
return "/bin/sh -c #(nop) ARG " + buildArgs, nil return "/bin/sh -c #(nop) ARG " + buildArgs + inheritLabels, nil
case "RUN": case "RUN":
shArg := "" shArg := ""
buildArgs := s.getBuildArgsResolvedForRun() buildArgs := s.getBuildArgsResolvedForRun()
@ -1903,6 +1906,10 @@ func (s *StageExecutor) getCreatedBy(node *parser.Node, addedContentSummary stri
continue continue
} }
mountOptionSource = mountInfo.Source mountOptionSource = mountInfo.Source
mountOptionSource, err = imagebuilder.ProcessWord(mountOptionSource, s.stage.Builder.Arguments())
if err != nil {
return "", fmt.Errorf("getCreatedBy: while replacing arg variables with values for format %q: %w", mountOptionSource, err)
}
mountOptionFrom = mountInfo.From mountOptionFrom = mountInfo.From
// If source is not specified then default is '.' // If source is not specified then default is '.'
if mountOptionSource == "" { if mountOptionSource == "" {
@ -1963,16 +1970,16 @@ func (s *StageExecutor) getCreatedBy(node *parser.Node, addedContentSummary stri
if buildArgs != "" { if buildArgs != "" {
result = result + "|" + strconv.Itoa(len(strings.Split(buildArgs, " "))) + " " + buildArgs + " " result = result + "|" + strconv.Itoa(len(strings.Split(buildArgs, " "))) + " " + buildArgs + " "
} }
result = result + "/bin/sh -c " + shArg + heredoc + appendCheckSum result = result + "/bin/sh -c " + shArg + heredoc + appendCheckSum + inheritLabels
return result, nil return result, nil
case "ADD", "COPY": case "ADD", "COPY":
destination := node destination := node
for destination.Next != nil { for destination.Next != nil {
destination = destination.Next destination = destination.Next
} }
return "/bin/sh -c #(nop) " + strings.ToUpper(node.Value) + " " + addedContentSummary + " in " + destination.Value + " ", nil return "/bin/sh -c #(nop) " + strings.ToUpper(node.Value) + " " + addedContentSummary + " in " + destination.Value + " " + inheritLabels, nil
default: default:
return "/bin/sh -c #(nop) " + node.Original, nil return "/bin/sh -c #(nop) " + node.Original + inheritLabels, nil
} }
} }
@ -2058,7 +2065,7 @@ func (s *StageExecutor) tagExistingImage(ctx context.Context, cacheID, output st
return "", nil, err return "", nil, err
} }
policyContext, err := util.GetPolicyContext(s.executor.systemContext) policyContext, err := util.GetPolicyContext(s.systemContext)
if err != nil { if err != nil {
return "", nil, err return "", nil, err
} }
@ -2117,7 +2124,7 @@ func (s *StageExecutor) generateCacheKey(ctx context.Context, currNode *parser.N
if err != nil { if err != nil {
return "", fmt.Errorf("getting history of base image %q: %w", s.builder.FromImageID, err) return "", fmt.Errorf("getting history of base image %q: %w", s.builder.FromImageID, err)
} }
for i := 0; i < len(diffIDs); i++ { for i := range len(diffIDs) {
fmt.Fprintln(hash, diffIDs[i].String()) fmt.Fprintln(hash, diffIDs[i].String())
} }
} }
@ -2171,7 +2178,7 @@ func (s *StageExecutor) pushCache(ctx context.Context, src, cacheKey string) err
Compression: s.executor.compression, Compression: s.executor.compression,
SignaturePolicyPath: s.executor.signaturePolicyPath, SignaturePolicyPath: s.executor.signaturePolicyPath,
Store: s.executor.store, Store: s.executor.store,
SystemContext: s.executor.systemContext, SystemContext: s.systemContext,
BlobDirectory: s.executor.blobDirectory, BlobDirectory: s.executor.blobDirectory,
SignBy: s.executor.signBy, SignBy: s.executor.signBy,
MaxRetries: s.executor.maxPullPushRetries, MaxRetries: s.executor.maxPullPushRetries,
@ -2209,7 +2216,7 @@ func (s *StageExecutor) pullCache(ctx context.Context, cacheKey string) (referen
options := buildah.PullOptions{ options := buildah.PullOptions{
SignaturePolicyPath: s.executor.signaturePolicyPath, SignaturePolicyPath: s.executor.signaturePolicyPath,
Store: s.executor.store, Store: s.executor.store,
SystemContext: s.executor.systemContext, SystemContext: s.systemContext,
BlobDirectory: s.executor.blobDirectory, BlobDirectory: s.executor.blobDirectory,
MaxRetries: s.executor.maxPullPushRetries, MaxRetries: s.executor.maxPullPushRetries,
RetryDelay: s.executor.retryPullPushDelay, RetryDelay: s.executor.retryPullPushDelay,
@ -2382,7 +2389,7 @@ func (s *StageExecutor) commit(ctx context.Context, createdBy string, emptyLayer
s.builder.SetStopSignal(config.StopSignal) s.builder.SetStopSignal(config.StopSignal)
if config.Healthcheck != nil { if config.Healthcheck != nil {
s.builder.SetHealthcheck(&buildahdocker.HealthConfig{ s.builder.SetHealthcheck(&buildahdocker.HealthConfig{
Test: append([]string{}, config.Healthcheck.Test...), Test: slices.Clone(config.Healthcheck.Test),
Interval: config.Healthcheck.Interval, Interval: config.Healthcheck.Interval,
Timeout: config.Healthcheck.Timeout, Timeout: config.Healthcheck.Timeout,
StartPeriod: config.Healthcheck.StartPeriod, StartPeriod: config.Healthcheck.StartPeriod,
@ -2431,7 +2438,7 @@ func (s *StageExecutor) commit(ctx context.Context, createdBy string, emptyLayer
SignaturePolicyPath: s.executor.signaturePolicyPath, SignaturePolicyPath: s.executor.signaturePolicyPath,
ReportWriter: writer, ReportWriter: writer,
PreferredManifestType: s.executor.outputFormat, PreferredManifestType: s.executor.outputFormat,
SystemContext: s.executor.systemContext, SystemContext: s.systemContext,
Squash: squash, Squash: squash,
OmitHistory: s.executor.commonBuildOptions.OmitHistory, OmitHistory: s.executor.commonBuildOptions.OmitHistory,
EmptyLayer: emptyLayer, EmptyLayer: emptyLayer,

View File

@ -19,7 +19,7 @@ import (
func importBuilderDataFromImage(ctx context.Context, store storage.Store, systemContext *types.SystemContext, imageID, containerName, containerID string) (*Builder, error) { func importBuilderDataFromImage(ctx context.Context, store storage.Store, systemContext *types.SystemContext, imageID, containerName, containerID string) (*Builder, error) {
if imageID == "" { if imageID == "" {
return nil, errors.New("Internal error: imageID is empty in importBuilderDataFromImage") return nil, errors.New("internal error: imageID is empty in importBuilderDataFromImage")
} }
storeopts, err := storage.DefaultStoreOptions() storeopts, err := storage.DefaultStoreOptions()

View File

@ -23,7 +23,7 @@ import (
// InfoData holds the info type, i.e store, host etc and the data for each type // InfoData holds the info type, i.e store, host etc and the data for each type
type InfoData struct { type InfoData struct {
Type string Type string
Data map[string]interface{} Data map[string]any
} }
// Info returns the store and host information // Info returns the store and host information
@ -42,8 +42,8 @@ func Info(store storage.Store) ([]InfoData, error) {
return info, nil return info, nil
} }
func hostInfo() map[string]interface{} { func hostInfo() map[string]any {
info := map[string]interface{}{} info := map[string]any{}
ps := internalUtil.NormalizePlatform(v1.Platform{OS: runtime.GOOS, Architecture: runtime.GOARCH}) ps := internalUtil.NormalizePlatform(v1.Platform{OS: runtime.GOOS, Architecture: runtime.GOARCH})
info["os"] = ps.OS info["os"] = ps.OS
info["arch"] = ps.Architecture info["arch"] = ps.Architecture
@ -77,7 +77,7 @@ func hostInfo() map[string]interface{} {
info["SwapFree"] = mi.SwapFree info["SwapFree"] = mi.SwapFree
} }
hostDistributionInfo := getHostDistributionInfo() hostDistributionInfo := getHostDistributionInfo()
info["Distribution"] = map[string]interface{}{ info["Distribution"] = map[string]any{
"distribution": hostDistributionInfo["Distribution"], "distribution": hostDistributionInfo["Distribution"],
"version": hostDistributionInfo["Version"], "version": hostDistributionInfo["Version"],
} }
@ -128,9 +128,9 @@ func hostInfo() map[string]interface{} {
} }
// top-level "store" info // top-level "store" info
func storeInfo(store storage.Store) (map[string]interface{}, error) { func storeInfo(store storage.Store) (map[string]any, error) {
// lets say storage driver in use, number of images, number of containers // lets say storage driver in use, number of images, number of containers
info := map[string]interface{}{} info := map[string]any{}
info["GraphRoot"] = store.GraphRoot() info["GraphRoot"] = store.GraphRoot()
info["RunRoot"] = store.RunRoot() info["RunRoot"] = store.RunRoot()
info["GraphDriverName"] = store.GraphDriverName() info["GraphDriverName"] = store.GraphDriverName()
@ -148,7 +148,7 @@ func storeInfo(store storage.Store) (map[string]interface{}, error) {
if err != nil { if err != nil {
logrus.Error(err, "error getting number of images") logrus.Error(err, "error getting number of images")
} }
info["ImageStore"] = map[string]interface{}{ info["ImageStore"] = map[string]any{
"number": len(images), "number": len(images),
} }
@ -156,7 +156,7 @@ func storeInfo(store storage.Store) (map[string]interface{}, error) {
if err != nil { if err != nil {
logrus.Error(err, "error getting number of containers") logrus.Error(err, "error getting number of containers")
} }
info["ContainerStore"] = map[string]interface{}{ info["ContainerStore"] = map[string]any{
"number": len(containers), "number": len(containers),
} }

View File

@ -1,6 +1,7 @@
package config package config
import ( import (
"maps"
"slices" "slices"
"github.com/containers/image/v5/manifest" "github.com/containers/image/v5/manifest"
@ -25,9 +26,7 @@ func Schema2ConfigFromGoDockerclientConfig(config *dockerclient.Config) *manifes
} }
} }
labels := make(map[string]string) labels := make(map[string]string)
for k, v := range config.Labels { maps.Copy(labels, config.Labels)
labels[k] = v
}
volumes := make(map[string]struct{}) volumes := make(map[string]struct{})
for v := range config.Volumes { for v := range config.Volumes {
volumes[v] = struct{}{} volumes[v] = struct{}{}
@ -82,9 +81,7 @@ func GoDockerclientConfigFromSchema2Config(s2config *manifest.Schema2Config) *do
} }
} }
labels := make(map[string]string) labels := make(map[string]string)
for k, v := range s2config.Labels { maps.Copy(labels, s2config.Labels)
labels[k] = v
}
volumes := make(map[string]struct{}) volumes := make(map[string]struct{})
for v := range s2config.Volumes { for v := range s2config.Volumes {
volumes[v] = struct{}{} volumes[v] = struct{}{}
@ -101,17 +98,17 @@ func GoDockerclientConfigFromSchema2Config(s2config *manifest.Schema2Config) *do
Tty: s2config.Tty, Tty: s2config.Tty,
OpenStdin: s2config.OpenStdin, OpenStdin: s2config.OpenStdin,
StdinOnce: s2config.StdinOnce, StdinOnce: s2config.StdinOnce,
Env: append([]string{}, s2config.Env...), Env: slices.Clone(s2config.Env),
Cmd: append([]string{}, s2config.Cmd...), Cmd: slices.Clone(s2config.Cmd),
Healthcheck: healthCheck, Healthcheck: healthCheck,
ArgsEscaped: s2config.ArgsEscaped, ArgsEscaped: s2config.ArgsEscaped,
Image: s2config.Image, Image: s2config.Image,
Volumes: volumes, Volumes: volumes,
WorkingDir: s2config.WorkingDir, WorkingDir: s2config.WorkingDir,
Entrypoint: append([]string{}, s2config.Entrypoint...), Entrypoint: slices.Clone(s2config.Entrypoint),
NetworkDisabled: s2config.NetworkDisabled, NetworkDisabled: s2config.NetworkDisabled,
MacAddress: s2config.MacAddress, MacAddress: s2config.MacAddress,
OnBuild: append([]string{}, s2config.OnBuild...), OnBuild: slices.Clone(s2config.OnBuild),
Labels: labels, Labels: labels,
StopSignal: s2config.StopSignal, StopSignal: s2config.StopSignal,
Shell: s2config.Shell, Shell: s2config.Shell,

View File

@ -3,6 +3,7 @@ package config
import ( import (
"fmt" "fmt"
"os" "os"
"slices"
"strings" "strings"
"github.com/containers/buildah/docker" "github.com/containers/buildah/docker"
@ -24,9 +25,9 @@ func firstStringElseSecondString(first, second string) string {
// slice of strings if it has contents, else the second slice // slice of strings if it has contents, else the second slice
func firstSliceElseSecondSlice(first, second []string) []string { func firstSliceElseSecondSlice(first, second []string) []string {
if len(first) > 0 { if len(first) > 0 {
return append([]string{}, first...) return slices.Clone(first)
} }
return append([]string{}, second...) return slices.Clone(second)
} }
// firstSlicePairElseSecondSlicePair takes two pairs of string slices, and // firstSlicePairElseSecondSlicePair takes two pairs of string slices, and
@ -34,9 +35,9 @@ func firstSliceElseSecondSlice(first, second []string) []string {
// pair // pair
func firstSlicePairElseSecondSlicePair(firstA, firstB, secondA, secondB []string) ([]string, []string) { func firstSlicePairElseSecondSlicePair(firstA, firstB, secondA, secondB []string) ([]string, []string) {
if len(firstA) > 0 || len(firstB) > 0 { if len(firstA) > 0 || len(firstB) > 0 {
return append([]string{}, firstA...), append([]string{}, firstB...) return slices.Clone(firstA), slices.Clone(firstB)
} }
return append([]string{}, secondA...), append([]string{}, secondB...) return slices.Clone(secondA), slices.Clone(secondB)
} }
// mergeEnv combines variables from a and b into a single environment slice. if // mergeEnv combines variables from a and b into a single environment slice. if
@ -45,7 +46,7 @@ func firstSlicePairElseSecondSlicePair(firstA, firstB, secondA, secondB []string
func mergeEnv(a, b []string) []string { func mergeEnv(a, b []string) []string {
index := make(map[string]int) index := make(map[string]int)
results := make([]string, 0, len(a)+len(b)) results := make([]string, 0, len(a)+len(b))
for _, kv := range append(append([]string{}, a...), b...) { for _, kv := range slices.Concat(a, b) {
k, _, specifiesValue := strings.Cut(kv, "=") k, _, specifiesValue := strings.Cut(kv, "=")
if !specifiesValue { if !specifiesValue {
if value, ok := os.LookupEnv(kv); ok { if value, ok := os.LookupEnv(kv); ok {
@ -134,7 +135,7 @@ func Override(dconfig *docker.Config, oconfig *v1.ImageConfig, overrideChanges [
oconfig.Entrypoint, oconfig.Cmd = firstSlicePairElseSecondSlicePair(overrideConfig.Entrypoint, overrideConfig.Cmd, oconfig.Entrypoint, oconfig.Cmd) oconfig.Entrypoint, oconfig.Cmd = firstSlicePairElseSecondSlicePair(overrideConfig.Entrypoint, overrideConfig.Cmd, oconfig.Entrypoint, oconfig.Cmd)
if overrideConfig.Healthcheck != nil { if overrideConfig.Healthcheck != nil {
dconfig.Healthcheck = &docker.HealthConfig{ dconfig.Healthcheck = &docker.HealthConfig{
Test: append([]string{}, overrideConfig.Healthcheck.Test...), Test: slices.Clone(overrideConfig.Healthcheck.Test),
Interval: overrideConfig.Healthcheck.Interval, Interval: overrideConfig.Healthcheck.Interval,
Timeout: overrideConfig.Healthcheck.Timeout, Timeout: overrideConfig.Healthcheck.Timeout,
StartPeriod: overrideConfig.Healthcheck.StartPeriod, StartPeriod: overrideConfig.Healthcheck.StartPeriod,

View File

@ -26,17 +26,18 @@ type TeeConfigFlags struct {
// TeeConfigFlagBits are bits representing run-time expectations. // TeeConfigFlagBits are bits representing run-time expectations.
type TeeConfigFlagBits int type TeeConfigFlagBits int
//nolint:revive,staticcheck // Don't warn about bad naming.
const ( const (
SEV_CONFIG_NO_DEBUG TeeConfigFlagBits = 0b00000001 //revive:disable-line:var-naming no debugging of guests SEV_CONFIG_NO_DEBUG TeeConfigFlagBits = 0b00000001 // no debugging of guests
SEV_CONFIG_NO_KEY_SHARING TeeConfigFlagBits = 0b00000010 //revive:disable-line:var-naming no sharing keys between guests SEV_CONFIG_NO_KEY_SHARING TeeConfigFlagBits = 0b00000010 // no sharing keys between guests
SEV_CONFIG_ENCRYPTED_STATE TeeConfigFlagBits = 0b00000100 //revive:disable-line:var-naming requires SEV-ES SEV_CONFIG_ENCRYPTED_STATE TeeConfigFlagBits = 0b00000100 // requires SEV-ES
SEV_CONFIG_NO_SEND TeeConfigFlagBits = 0b00001000 //revive:disable-line:var-naming no transferring the guest to another platform SEV_CONFIG_NO_SEND TeeConfigFlagBits = 0b00001000 // no transferring the guest to another platform
SEV_CONFIG_DOMAIN TeeConfigFlagBits = 0b00010000 //revive:disable-line:var-naming no transferring the guest out of the domain (?) SEV_CONFIG_DOMAIN TeeConfigFlagBits = 0b00010000 // no transferring the guest out of the domain (?)
SEV_CONFIG_SEV TeeConfigFlagBits = 0b00100000 //revive:disable-line:var-naming no transferring the guest to non-SEV platforms SEV_CONFIG_SEV TeeConfigFlagBits = 0b00100000 // no transferring the guest to non-SEV platforms
SNP_CONFIG_SMT TeeConfigFlagBits = 0b00000001 //revive:disable-line:var-naming SMT is enabled on the host machine SNP_CONFIG_SMT TeeConfigFlagBits = 0b00000001 // SMT is enabled on the host machine
SNP_CONFIG_MANDATORY TeeConfigFlagBits = 0b00000010 //revive:disable-line:var-naming reserved bit which should always be set SNP_CONFIG_MANDATORY TeeConfigFlagBits = 0b00000010 // reserved bit which should always be set
SNP_CONFIG_MIGRATE_MA TeeConfigFlagBits = 0b00000100 //revive:disable-line:var-naming allowed to use a migration agent SNP_CONFIG_MIGRATE_MA TeeConfigFlagBits = 0b00000100 // allowed to use a migration agent
SNP_CONFIG_DEBUG TeeConfigFlagBits = 0b00001000 //revive:disable-line:var-naming allow debugging SNP_CONFIG_DEBUG TeeConfigFlagBits = 0b00001000 // allow debugging
) )
// TeeConfigFlagMinFW corresponds to a minimum version of the kernel+initrd // TeeConfigFlagMinFW corresponds to a minimum version of the kernel+initrd

View File

@ -28,7 +28,8 @@ type SnpWorkloadData struct {
Generation string `json:"gen"` // "milan" (naples=1, rome=2, milan=3, genoa/bergamo/siena=4, turin=5) Generation string `json:"gen"` // "milan" (naples=1, rome=2, milan=3, genoa/bergamo/siena=4, turin=5)
} }
//nolint:revive,staticcheck // Don't warn about bad naming.
const ( const (
// SEV_NO_ES is a known trusted execution environment type: AMD-SEV (secure encrypted virtualization without encrypted state, requires epyc 1000 "naples") // SEV_NO_ES is a known trusted execution environment type: AMD-SEV (secure encrypted virtualization without encrypted state, requires epyc 1000 "naples")
SEV_NO_ES define.TeeType = "sev_no_es" //revive:disable-line:var-naming SEV_NO_ES define.TeeType = "sev_no_es"
) )

View File

@ -28,18 +28,23 @@ type (
const ( const (
maxWorkloadConfigSize = 1024 * 1024 maxWorkloadConfigSize = 1024 * 1024
preferredPaddingBoundary = 4096 preferredPaddingBoundary = 4096
// SEV is a known trusted execution environment type: AMD-SEV
SEV = define.SEV
// SEV_NO_ES is a known trusted execution environment type: AMD-SEV without encrypted state
SEV_NO_ES = types.SEV_NO_ES //revive:disable-line:var-naming
// SNP is a known trusted execution environment type: AMD-SNP
SNP = define.SNP
// krun looks for its configuration JSON directly in a disk image if the last twelve bytes // krun looks for its configuration JSON directly in a disk image if the last twelve bytes
// of the disk image are this magic value followed by a little-endian 64-bit // of the disk image are this magic value followed by a little-endian 64-bit
// length-of-the-configuration // length-of-the-configuration
krunMagic = "KRUN" krunMagic = "KRUN"
) )
//nolint:revive,staticcheck
const (
// SEV is a known trusted execution environment type: AMD-SEV
SEV = define.SEV
// SEV_NO_ES is a known trusted execution environment type: AMD-SEV without encrypted state
SEV_NO_ES = types.SEV_NO_ES
// SNP is a known trusted execution environment type: AMD-SNP
SNP = define.SNP
)
// ReadWorkloadConfigFromImage reads the workload configuration from the // ReadWorkloadConfigFromImage reads the workload configuration from the
// specified disk image file // specified disk image file
func ReadWorkloadConfigFromImage(path string) (WorkloadConfig, error) { func ReadWorkloadConfigFromImage(path string) (WorkloadConfig, error) {

View File

@ -1,6 +1,10 @@
package sbom package sbom
import "github.com/containers/buildah/define" import (
"slices"
"github.com/containers/buildah/define"
)
// Preset returns a predefined SBOMScanOptions structure that has the passed-in // Preset returns a predefined SBOMScanOptions structure that has the passed-in
// name as one of its "Type" values. // name as one of its "Type" values.
@ -55,11 +59,9 @@ func Preset(name string) (preset *define.SBOMScanOptions, err error) {
}, },
} }
for _, preset := range presets { for _, preset := range presets {
for _, presetName := range preset.Type { if slices.Contains(preset.Type, name) {
if presetName == name {
return &preset, nil return &preset, nil
} }
} }
}
return nil, nil return nil, nil
} }

View File

@ -99,12 +99,10 @@ func newContainerIDMappingOptions(idmapOptions *define.IDMappingOptions) storage
func containerNameExist(name string, containers []storage.Container) bool { func containerNameExist(name string, containers []storage.Container) bool {
for _, container := range containers { for _, container := range containers {
for _, cname := range container.Names { if slices.Contains(container.Names, name) {
if cname == name {
return true return true
} }
} }
}
return false return false
} }
@ -246,11 +244,11 @@ func newBuilder(ctx context.Context, store storage.Store, options BuilderOptions
suffixDigitsModulo := 100 suffixDigitsModulo := 100
for { for {
var flags map[string]interface{} var flags map[string]any
// check if we have predefined ProcessLabel and MountLabel // check if we have predefined ProcessLabel and MountLabel
// this could be true if this is another stage in a build // this could be true if this is another stage in a build
if options.ProcessLabel != "" && options.MountLabel != "" { if options.ProcessLabel != "" && options.MountLabel != "" {
flags = map[string]interface{}{ flags = map[string]any{
"ProcessLabel": options.ProcessLabel, "ProcessLabel": options.ProcessLabel,
"MountLabel": options.MountLabel, "MountLabel": options.MountLabel,
} }

View File

@ -68,13 +68,11 @@ func GenBuildOptions(c *cobra.Command, inputArgs []string, iopts BuildOptions) (
tags = tags[1:] tags = tags[1:]
} }
if c.Flag("manifest").Changed { if c.Flag("manifest").Changed {
for _, tag := range tags { if slices.Contains(tags, iopts.Manifest) {
if tag == iopts.Manifest {
return options, nil, nil, errors.New("the same name must not be specified for both '--tag' and '--manifest'") return options, nil, nil, errors.New("the same name must not be specified for both '--tag' and '--manifest'")
} }
} }
} }
}
if err := auth.CheckAuthFile(iopts.BudResults.Authfile); err != nil { if err := auth.CheckAuthFile(iopts.BudResults.Authfile); err != nil {
return options, nil, nil, err return options, nil, nil, err
} }
@ -378,6 +376,7 @@ func GenBuildOptions(c *cobra.Command, inputArgs []string, iopts BuildOptions) (
IIDFile: iopts.Iidfile, IIDFile: iopts.Iidfile,
IgnoreFile: iopts.IgnoreFile, IgnoreFile: iopts.IgnoreFile,
In: stdin, In: stdin,
InheritLabels: types.NewOptionalBool(iopts.InheritLabels),
Isolation: isolation, Isolation: isolation,
Jobs: &iopts.Jobs, Jobs: &iopts.Jobs,
Labels: iopts.Label, Labels: iopts.Label,

View File

@ -6,6 +6,7 @@ package cli
import ( import (
"fmt" "fmt"
"maps"
"os" "os"
"runtime" "runtime"
"strings" "strings"
@ -71,6 +72,7 @@ type BudResults struct {
Format string Format string
From string From string
Iidfile string Iidfile string
InheritLabels bool
Label []string Label []string
LayerLabel []string LayerLabel []string
Logfile string Logfile string
@ -230,6 +232,7 @@ func GetBudFlags(flags *BudResults) pflag.FlagSet {
fs.StringVar(&flags.CertDir, "cert-dir", "", "use certificates at the specified path to access the registry") fs.StringVar(&flags.CertDir, "cert-dir", "", "use certificates at the specified path to access the registry")
fs.BoolVar(&flags.Compress, "compress", false, "this is a legacy option, which has no effect on the image") fs.BoolVar(&flags.Compress, "compress", false, "this is a legacy option, which has no effect on the image")
fs.BoolVar(&flags.CompatVolumes, "compat-volumes", false, "preserve the contents of VOLUMEs during RUN instructions") fs.BoolVar(&flags.CompatVolumes, "compat-volumes", false, "preserve the contents of VOLUMEs during RUN instructions")
fs.BoolVar(&flags.InheritLabels, "inherit-labels", true, "inherit the labels from the base image or base stages.")
fs.StringArrayVar(&flags.CPPFlags, "cpp-flag", []string{}, "set additional flag to pass to C preprocessor (cpp)") fs.StringArrayVar(&flags.CPPFlags, "cpp-flag", []string{}, "set additional flag to pass to C preprocessor (cpp)")
fs.StringVar(&flags.Creds, "creds", "", "use `[username[:password]]` for accessing the registry") fs.StringVar(&flags.Creds, "creds", "", "use `[username[:password]]` for accessing the registry")
fs.StringVarP(&flags.CWOptions, "cw", "", "", "confidential workload `options`") fs.StringVarP(&flags.CWOptions, "cw", "", "", "confidential workload `options`")
@ -455,13 +458,9 @@ func GetFromAndBudFlagsCompletions() commonComp.FlagCompletions {
// Add in the usernamespace and namespace flag completions // Add in the usernamespace and namespace flag completions
userNsComp := GetUserNSFlagsCompletions() userNsComp := GetUserNSFlagsCompletions()
for name, comp := range userNsComp { maps.Copy(flagCompletion, userNsComp)
flagCompletion[name] = comp
}
namespaceComp := GetNameSpaceFlagsCompletions() namespaceComp := GetNameSpaceFlagsCompletions()
for name, comp := range namespaceComp { maps.Copy(flagCompletion, namespaceComp)
flagCompletion[name] = comp
}
return flagCompletion return flagCompletion
} }

View File

@ -29,7 +29,7 @@ const (
) )
type config struct { type config struct {
params map[string]interface{} params map[string]any
} }
var ( var (
@ -39,11 +39,11 @@ var (
func NewConfig() *config { func NewConfig() *config {
return &config{ return &config{
params: make(map[string]interface{}), params: make(map[string]any),
} }
} }
func handleBoolSetting(key string, val bool) (string, interface{}) { func handleBoolSetting(key string, val bool) (string, any) {
// jail doesn't deal with booleans - it uses paired parameter // jail doesn't deal with booleans - it uses paired parameter
// names, e.g. "persist"/"nopersist". If the key contains '.', // names, e.g. "persist"/"nopersist". If the key contains '.',
// the "no" prefix is applied to the last element. // the "no" prefix is applied to the last element.
@ -55,7 +55,7 @@ func handleBoolSetting(key string, val bool) (string, interface{}) {
return key, nil return key, nil
} }
func (c *config) Set(key string, value interface{}) { func (c *config) Set(key string, value any) {
// Normalise integer types to int32 // Normalise integer types to int32
switch v := value.(type) { switch v := value.(type) {
case int: case int:

View File

@ -11,6 +11,7 @@ import (
"net" "net"
"os" "os"
"path/filepath" "path/filepath"
"slices"
"strconv" "strconv"
"strings" "strings"
"unicode" "unicode"
@ -705,11 +706,12 @@ func GetBuildOutput(buildOutput string) (define.BuildOutputOption, error) {
return define.BuildOutputOption{}, fmt.Errorf("duplicate %q not supported", arr[0]) return define.BuildOutputOption{}, fmt.Errorf("duplicate %q not supported", arr[0])
} }
typeSelected = true typeSelected = true
if arr[1] == "local" { switch arr[1] {
case "local":
isDir = true isDir = true
} else if arr[1] == "tar" { case "tar":
isDir = false isDir = false
} else { default:
return define.BuildOutputOption{}, fmt.Errorf("invalid type %q selected for build output options %q", arr[1], buildOutput) return define.BuildOutputOption{}, fmt.Errorf("invalid type %q selected for build output options %q", arr[1], buildOutput)
} }
case "dest": case "dest":
@ -851,7 +853,7 @@ func SBOMScanOptionsFromFlagSet(flags *pflag.FlagSet, _ func(name string) *pflag
if image != "" || len(commands) > 0 || mergeStrategy != "" { if image != "" || len(commands) > 0 || mergeStrategy != "" {
options = &define.SBOMScanOptions{ options = &define.SBOMScanOptions{
Image: image, Image: image,
Commands: append([]string{}, commands...), Commands: slices.Clone(commands),
MergeStrategy: define.SBOMMergeStrategy(mergeStrategy), MergeStrategy: define.SBOMMergeStrategy(mergeStrategy),
} }
} }

View File

@ -22,8 +22,8 @@ func get() (Rusage, error) {
Date: time.Now(), Date: time.Now(),
Utime: mkduration(rusage.Utime), Utime: mkduration(rusage.Utime),
Stime: mkduration(rusage.Stime), Stime: mkduration(rusage.Stime),
Inblock: int64(rusage.Inblock), // nolint: unconvert Inblock: int64(rusage.Inblock), //nolint:unconvert
Outblock: int64(rusage.Oublock), // nolint: unconvert Outblock: int64(rusage.Oublock), //nolint:unconvert
} }
return r, nil return r, nil
} }

View File

@ -38,7 +38,7 @@ func NewAgentServer(source *Source) (*AgentServer, error) {
} }
// newAgentServerKeyring creates a new agent from scratch and adds keys // newAgentServerKeyring creates a new agent from scratch and adds keys
func newAgentServerKeyring(keys []interface{}) (*AgentServer, error) { func newAgentServerKeyring(keys []any) (*AgentServer, error) {
a := agent.NewKeyring() a := agent.NewKeyring()
for _, k := range keys { for _, k := range keys {
if err := a.Add(agent.AddedKey{PrivateKey: k}); err != nil { if err := a.Add(agent.AddedKey{PrivateKey: k}); err != nil {
@ -191,12 +191,12 @@ func (a *readOnlyAgent) Extension(_ string, _ []byte) ([]byte, error) {
// The source of the forwarded agent can be from a socket on the host, or from individual key files // The source of the forwarded agent can be from a socket on the host, or from individual key files
type Source struct { type Source struct {
Socket string Socket string
Keys []interface{} Keys []any
} }
// NewSource takes paths and checks of they are keys or sockets, and creates a source // NewSource takes paths and checks of they are keys or sockets, and creates a source
func NewSource(paths []string) (*Source, error) { func NewSource(paths []string) (*Source, error) {
var keys []interface{} var keys []any
var socket string var socket string
if len(paths) == 0 { if len(paths) == 0 {
socket = os.Getenv("SSH_AUTH_SOCK") socket = os.Getenv("SSH_AUTH_SOCK")

View File

@ -181,14 +181,8 @@ func (b *Builder) addHostsEntries(file, imageRoot string, entries etchosts.HostE
// generateHostname creates a containers /etc/hostname file // generateHostname creates a containers /etc/hostname file
func (b *Builder) generateHostname(rdir, hostname string, chownOpts *idtools.IDPair) (string, error) { func (b *Builder) generateHostname(rdir, hostname string, chownOpts *idtools.IDPair) (string, error) {
var err error cfile := filepath.Join(rdir, "hostname")
hostnamePath := "/etc/hostname" if err := ioutils.AtomicWriteFile(cfile, append([]byte(hostname), '\n'), 0o644); err != nil {
var hostnameBuffer bytes.Buffer
hostnameBuffer.Write([]byte(fmt.Sprintf("%s\n", hostname)))
cfile := filepath.Join(rdir, filepath.Base(hostnamePath))
if err = ioutils.AtomicWriteFile(cfile, hostnameBuffer.Bytes(), 0o644); err != nil {
return "", fmt.Errorf("writing /etc/hostname into the container: %w", err) return "", fmt.Errorf("writing /etc/hostname into the container: %w", err)
} }
@ -198,7 +192,7 @@ func (b *Builder) generateHostname(rdir, hostname string, chownOpts *idtools.IDP
uid = chownOpts.UID uid = chownOpts.UID
gid = chownOpts.GID gid = chownOpts.GID
} }
if err = os.Chown(cfile, uid, gid); err != nil { if err := os.Chown(cfile, uid, gid); err != nil {
return "", err return "", err
} }
if err := relabel(cfile, b.MountLabel, false); err != nil { if err := relabel(cfile, b.MountLabel, false); err != nil {
@ -734,7 +728,7 @@ func runUsingRuntime(options RunOptions, configureNetwork bool, moreCreateArgs [
return wstatus, nil return wstatus, nil
} }
func runCollectOutput(logger *logrus.Logger, fds, closeBeforeReadingFds []int) string { //nolint:interfacer func runCollectOutput(logger *logrus.Logger, fds, closeBeforeReadingFds []int) string {
for _, fd := range closeBeforeReadingFds { for _, fd := range closeBeforeReadingFds {
unix.Close(fd) unix.Close(fd)
} }
@ -780,7 +774,7 @@ func runCollectOutput(logger *logrus.Logger, fds, closeBeforeReadingFds []int) s
return b.String() return b.String()
} }
func setNonblock(logger *logrus.Logger, fd int, description string, nonblocking bool) (bool, error) { //nolint:interfacer func setNonblock(logger *logrus.Logger, fd int, description string, nonblocking bool) (bool, error) {
mask, err := unix.FcntlInt(uintptr(fd), unix.F_GETFL, 0) mask, err := unix.FcntlInt(uintptr(fd), unix.F_GETFL, 0)
if err != nil { if err != nil {
return false, err return false, err
@ -870,13 +864,13 @@ func runCopyStdio(logger *logrus.Logger, stdio *sync.WaitGroup, copyPipes bool,
return return
} }
if blocked { if blocked {
defer setNonblock(logger, rfd, readDesc[rfd], false) // nolint:errcheck defer setNonblock(logger, rfd, readDesc[rfd], false) //nolint:errcheck
} }
setNonblock(logger, wfd, writeDesc[wfd], false) // nolint:errcheck setNonblock(logger, wfd, writeDesc[wfd], false) //nolint:errcheck
} }
if copyPipes { if copyPipes {
setNonblock(logger, stdioPipe[unix.Stdin][1], writeDesc[stdioPipe[unix.Stdin][1]], true) // nolint:errcheck setNonblock(logger, stdioPipe[unix.Stdin][1], writeDesc[stdioPipe[unix.Stdin][1]], true) //nolint:errcheck
} }
runCopyStdioPassData(copyPipes, stdioPipe, finishCopy, relayMap, relayBuffer, readDesc, writeDesc) runCopyStdioPassData(copyPipes, stdioPipe, finishCopy, relayMap, relayBuffer, readDesc, writeDesc)

View File

@ -6,6 +6,7 @@ import (
"context" "context"
"errors" "errors"
"fmt" "fmt"
"maps"
"os" "os"
"path/filepath" "path/filepath"
"slices" "slices"
@ -281,7 +282,7 @@ func (b *Builder) Run(command []string, options RunOptions) error {
} }
// Combine the working container's set of devices with the ones for just this run. // Combine the working container's set of devices with the ones for just this run.
deviceSpecs := append(append([]string{}, options.DeviceSpecs...), b.DeviceSpecs...) deviceSpecs := slices.Concat(options.DeviceSpecs, b.DeviceSpecs)
deviceSpecs, err = b.cdiSetupDevicesInSpec(deviceSpecs, options.CDIConfigDir, g.Config) // makes changes to more than just the device list deviceSpecs, err = b.cdiSetupDevicesInSpec(deviceSpecs, options.CDIConfigDir, g.Config) // makes changes to more than just the device list
if err != nil { if err != nil {
return err return err
@ -302,7 +303,7 @@ func (b *Builder) Run(command []string, options RunOptions) error {
// We are going to create bind mounts for devices // We are going to create bind mounts for devices
// but we need to make sure that we don't override // but we need to make sure that we don't override
// anything which is already in OCI spec. // anything which is already in OCI spec.
mounts := make(map[string]interface{}) mounts := make(map[string]any)
for _, m := range g.Mounts() { for _, m := range g.Mounts() {
mounts[m.Destination] = true mounts[m.Destination] = true
} }
@ -456,7 +457,7 @@ func (b *Builder) Run(command []string, options RunOptions) error {
} }
resolvFile := "" resolvFile := ""
if !slices.Contains(volumes, resolvconf.DefaultResolvConf) && options.ConfigureNetwork != define.NetworkDisabled && !(len(b.CommonBuildOpts.DNSServers) == 1 && strings.ToLower(b.CommonBuildOpts.DNSServers[0]) == "none") { if !slices.Contains(volumes, resolvconf.DefaultResolvConf) && options.ConfigureNetwork != define.NetworkDisabled && (len(b.CommonBuildOpts.DNSServers) != 1 || strings.ToLower(b.CommonBuildOpts.DNSServers[0]) != "none") {
resolvFile, err = b.createResolvConf(path, rootIDPair) resolvFile, err = b.createResolvConf(path, rootIDPair)
if err != nil { if err != nil {
return err return err
@ -586,9 +587,7 @@ func (b *Builder) setupOCIHooks(config *specs.Spec, hasVolumes bool) (map[string
if len(ociHooks) > 0 || config.Hooks != nil { if len(ociHooks) > 0 || config.Hooks != nil {
logrus.Warnf("Implicit hook directories are deprecated; set --hooks-dir=%q explicitly to continue to load ociHooks from this directory", hDir) logrus.Warnf("Implicit hook directories are deprecated; set --hooks-dir=%q explicitly to continue to load ociHooks from this directory", hDir)
} }
for i, hook := range ociHooks { maps.Copy(allHooks, ociHooks)
allHooks[i] = hook
}
} }
} else { } else {
manager, err := hooks.New(context.Background(), b.CommonBuildOpts.OCIHooksDir, []string{}) manager, err := hooks.New(context.Background(), b.CommonBuildOpts.OCIHooksDir, []string{})
@ -691,9 +690,9 @@ func setupSlirp4netnsNetwork(config *config.Config, netns, cid string, options,
} }
return func() { return func() {
syscall.Kill(res.Pid, syscall.SIGKILL) // nolint:errcheck syscall.Kill(res.Pid, syscall.SIGKILL) //nolint:errcheck
var status syscall.WaitStatus var status syscall.WaitStatus
syscall.Wait4(res.Pid, &status, 0, nil) // nolint:errcheck syscall.Wait4(res.Pid, &status, 0, nil) //nolint:errcheck
}, result, nil }, result, nil
} }
@ -1062,28 +1061,28 @@ func addRlimits(ulimit []string, g *generate.Generator, defaultUlimits []string)
g.AddProcessRlimits("RLIMIT_"+strings.ToUpper(ul.Name), uint64(ul.Hard), uint64(ul.Soft)) g.AddProcessRlimits("RLIMIT_"+strings.ToUpper(ul.Name), uint64(ul.Hard), uint64(ul.Soft))
} }
if !nofileSet { if !nofileSet {
max := define.RLimitDefaultValue lim := define.RLimitDefaultValue
var rlimit unix.Rlimit var rlimit unix.Rlimit
if err := unix.Getrlimit(unix.RLIMIT_NOFILE, &rlimit); err == nil { if err := unix.Getrlimit(unix.RLIMIT_NOFILE, &rlimit); err == nil {
if max < rlimit.Max || unshare.IsRootless() { if lim < rlimit.Max || unshare.IsRootless() {
max = rlimit.Max lim = rlimit.Max
} }
} else { } else {
logrus.Warnf("Failed to return RLIMIT_NOFILE ulimit %q", err) logrus.Warnf("Failed to return RLIMIT_NOFILE ulimit %q", err)
} }
g.AddProcessRlimits("RLIMIT_NOFILE", max, max) g.AddProcessRlimits("RLIMIT_NOFILE", lim, lim)
} }
if !nprocSet { if !nprocSet {
max := define.RLimitDefaultValue lim := define.RLimitDefaultValue
var rlimit unix.Rlimit var rlimit unix.Rlimit
if err := unix.Getrlimit(unix.RLIMIT_NPROC, &rlimit); err == nil { if err := unix.Getrlimit(unix.RLIMIT_NPROC, &rlimit); err == nil {
if max < rlimit.Max || unshare.IsRootless() { if lim < rlimit.Max || unshare.IsRootless() {
max = rlimit.Max lim = rlimit.Max
} }
} else { } else {
logrus.Warnf("Failed to return RLIMIT_NPROC ulimit %q", err) logrus.Warnf("Failed to return RLIMIT_NPROC ulimit %q", err)
} }
g.AddProcessRlimits("RLIMIT_NPROC", max, max) g.AddProcessRlimits("RLIMIT_NPROC", lim, lim)
} }
return nil return nil

View File

@ -107,7 +107,7 @@ func (b *Builder) sbomScan(ctx context.Context, options CommitOptions) (imageFil
// Start by assuming it's shell -c $whatever. // Start by assuming it's shell -c $whatever.
parsedCommand := []string{"/bin/sh", "-c", commandSpec} parsedCommand := []string{"/bin/sh", "-c", commandSpec}
if shell := scanBuilder.Shell(); len(shell) != 0 { if shell := scanBuilder.Shell(); len(shell) != 0 {
parsedCommand = append(append([]string{}, shell...), commandSpec) parsedCommand = append(slices.Clone(shell), commandSpec)
} }
if !strings.ContainsAny(commandSpec, "<>|") { // An imperfect check for shell redirection being used. if !strings.ContainsAny(commandSpec, "<>|") { // An imperfect check for shell redirection being used.
// If we can parse it ourselves, though, prefer to use that result, // If we can parse it ourselves, though, prefer to use that result,

View File

@ -335,13 +335,9 @@ func logIfNotErrno(err error, what string, ignores ...syscall.Errno) (logged boo
if err == nil { if err == nil {
return false return false
} }
if errno, isErrno := err.(syscall.Errno); isErrno { if errno, ok := err.(syscall.Errno); ok && slices.Contains(ignores, errno) {
for _, ignore := range ignores {
if errno == ignore {
return false return false
} }
}
}
logrus.Error(what) logrus.Error(what)
return true return true
} }

View File

@ -1,5 +1,5 @@
// FIXME(thaJeztah): remove once we are a module; the go:build directive prevents go from downgrading language version to go1.16: // FIXME(thaJeztah): remove once we are a module; the go:build directive prevents go from downgrading language version to go1.16:
//go:build go1.23 //go:build go1.22
package registry // import "github.com/docker/docker/api/types/registry" package registry // import "github.com/docker/docker/api/types/registry"

View File

@ -148,9 +148,10 @@ func parseDirective(key string, dt []byte, anyFormat bool) (string, string, []Ra
} }
// use json directive, and search for { "key": "..." } // use json directive, and search for { "key": "..." }
jsonDirective := map[string]string{} jsonDirective := map[string]any{}
if err := json.Unmarshal(dt, &jsonDirective); err == nil { if err := json.Unmarshal(dt, &jsonDirective); err == nil {
if v, ok := jsonDirective[key]; ok { if vAny, ok := jsonDirective[key]; ok {
if v, ok := vAny.(string); ok {
loc := []Range{{ loc := []Range{{
Start: Position{Line: line}, Start: Position{Line: line},
End: Position{Line: line}, End: Position{Line: line},
@ -158,6 +159,7 @@ func parseDirective(key string, dt []byte, anyFormat bool) (string, string, []Ra
return v, v, loc, true return v, v, loc, true
} }
} }
}
return "", "", nil, false return "", "", nil, false
} }

View File

@ -281,7 +281,7 @@ func parseJSON(rest string) (*Node, map[string]bool, error) {
return nil, nil, errDockerfileNotJSONArray return nil, nil, errDockerfileNotJSONArray
} }
var myJSON []interface{} var myJSON []any
if err := json.Unmarshal([]byte(rest), &myJSON); err != nil { if err := json.Unmarshal([]byte(rest), &myJSON); err != nil {
return nil, nil, err return nil, nil, err
} }

View File

@ -220,7 +220,7 @@ func init() {
// based on the command and command arguments. A Node is created from the // based on the command and command arguments. A Node is created from the
// result of the dispatch. // result of the dispatch.
func newNodeFromLine(line string, d *directives, comments []string) (*Node, error) { func newNodeFromLine(line string, d *directives, comments []string) (*Node, error) {
cmd, flags, args, err := splitCommand(line) cmd, flags, args, err := splitCommand(line, d)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -7,7 +7,7 @@ import (
// splitCommand takes a single line of text and parses out the cmd and args, // splitCommand takes a single line of text and parses out the cmd and args,
// which are used for dispatching to more exact parsing functions. // which are used for dispatching to more exact parsing functions.
func splitCommand(line string) (string, []string, string, error) { func splitCommand(line string, d *directives) (string, []string, string, error) {
var args string var args string
var flags []string var flags []string
@ -16,7 +16,7 @@ func splitCommand(line string) (string, []string, string, error) {
if len(cmdline) == 2 { if len(cmdline) == 2 {
var err error var err error
args, flags, err = extractBuilderFlags(cmdline[1]) args, flags, err = extractBuilderFlags(cmdline[1], d)
if err != nil { if err != nil {
return "", nil, "", err return "", nil, "", err
} }
@ -25,7 +25,7 @@ func splitCommand(line string) (string, []string, string, error) {
return cmdline[0], flags, strings.TrimSpace(args), nil return cmdline[0], flags, strings.TrimSpace(args), nil
} }
func extractBuilderFlags(line string) (string, []string, error) { func extractBuilderFlags(line string, d *directives) (string, []string, error) {
// Parses the BuilderFlags and returns the remaining part of the line // Parses the BuilderFlags and returns the remaining part of the line
const ( const (
@ -87,7 +87,7 @@ func extractBuilderFlags(line string) (string, []string, error) {
phase = inQuote phase = inQuote
continue continue
} }
if ch == '\\' { if ch == d.escapeToken {
if pos+1 == len(line) { if pos+1 == len(line) {
continue // just skip \ at end continue // just skip \ at end
} }
@ -104,7 +104,7 @@ func extractBuilderFlags(line string) (string, []string, error) {
phase = inWord phase = inWord
continue continue
} }
if ch == '\\' { if ch == d.escapeToken {
if pos+1 == len(line) { if pos+1 == len(line) {
phase = inWord phase = inWord
continue // just skip \ at end continue // just skip \ at end

View File

@ -10,6 +10,7 @@
// builds a list of push/pop events and their node type. Subsequent // builds a list of push/pop events and their node type. Subsequent
// method calls that request a traversal scan this list, rather than walk // method calls that request a traversal scan this list, rather than walk
// the AST, and perform type filtering using efficient bit sets. // the AST, and perform type filtering using efficient bit sets.
// This representation is sometimes called a "balanced parenthesis tree."
// //
// Experiments suggest the inspector's traversals are about 2.5x faster // Experiments suggest the inspector's traversals are about 2.5x faster
// than ast.Inspect, but it may take around 5 traversals for this // than ast.Inspect, but it may take around 5 traversals for this
@ -50,6 +51,7 @@ type Inspector struct {
//go:linkname events //go:linkname events
func events(in *Inspector) []event { return in.events } func events(in *Inspector) []event { return in.events }
//go:linkname packEdgeKindAndIndex
func packEdgeKindAndIndex(ek edge.Kind, index int) int32 { func packEdgeKindAndIndex(ek edge.Kind, index int) int32 {
return int32(uint32(index+1)<<7 | uint32(ek)) return int32(uint32(index+1)<<7 | uint32(ek))
} }

14
vendor/modules.txt vendored
View File

@ -110,8 +110,8 @@ github.com/containernetworking/cni/pkg/version
# github.com/containernetworking/plugins v1.6.2 # github.com/containernetworking/plugins v1.6.2
## explicit; go 1.23 ## explicit; go 1.23
github.com/containernetworking/plugins/pkg/ns github.com/containernetworking/plugins/pkg/ns
# github.com/containers/buildah v1.39.1-0.20250401180830-32d78c69be17 # github.com/containers/buildah v1.40.0
## explicit; go 1.23.0 ## explicit; go 1.23.3
github.com/containers/buildah github.com/containers/buildah
github.com/containers/buildah/bind github.com/containers/buildah/bind
github.com/containers/buildah/chroot github.com/containers/buildah/chroot
@ -428,7 +428,7 @@ github.com/distribution/reference
## explicit ## explicit
github.com/docker/distribution/registry/api/errcode github.com/docker/distribution/registry/api/errcode
github.com/docker/distribution/registry/api/v2 github.com/docker/distribution/registry/api/v2
# github.com/docker/docker v28.1.1+incompatible # github.com/docker/docker v28.1.0+incompatible
## explicit ## explicit
github.com/docker/docker/api github.com/docker/docker/api
github.com/docker/docker/api/types github.com/docker/docker/api/types
@ -706,8 +706,8 @@ github.com/mistifyio/go-zfs/v3
# github.com/mitchellh/mapstructure v1.5.0 # github.com/mitchellh/mapstructure v1.5.0
## explicit; go 1.14 ## explicit; go 1.14
github.com/mitchellh/mapstructure github.com/mitchellh/mapstructure
# github.com/moby/buildkit v0.20.2 # github.com/moby/buildkit v0.21.0
## explicit; go 1.22.0 ## explicit; go 1.23.0
github.com/moby/buildkit/frontend/dockerfile/command github.com/moby/buildkit/frontend/dockerfile/command
github.com/moby/buildkit/frontend/dockerfile/parser github.com/moby/buildkit/frontend/dockerfile/parser
github.com/moby/buildkit/frontend/dockerfile/shell github.com/moby/buildkit/frontend/dockerfile/shell
@ -1103,8 +1103,6 @@ golang.org/x/crypto/ssh/internal/bcrypt_pbkdf
golang.org/x/crypto/ssh/knownhosts golang.org/x/crypto/ssh/knownhosts
golang.org/x/crypto/twofish golang.org/x/crypto/twofish
golang.org/x/crypto/xts golang.org/x/crypto/xts
# golang.org/x/exp v0.0.0-20250128182459-e0ece0dbea4c
## explicit; go 1.22.0
# golang.org/x/mod v0.24.0 # golang.org/x/mod v0.24.0
## explicit; go 1.23.0 ## explicit; go 1.23.0
golang.org/x/mod/semver golang.org/x/mod/semver
@ -1168,7 +1166,7 @@ golang.org/x/text/unicode/norm
# golang.org/x/time v0.11.0 # golang.org/x/time v0.11.0
## explicit; go 1.23.0 ## explicit; go 1.23.0
golang.org/x/time/rate golang.org/x/time/rate
# golang.org/x/tools v0.31.0 # golang.org/x/tools v0.32.0
## explicit; go 1.23.0 ## explicit; go 1.23.0
golang.org/x/tools/cover golang.org/x/tools/cover
golang.org/x/tools/go/ast/inspector golang.org/x/tools/go/ast/inspector