diff --git a/api/v1/clusterextension_types.go b/api/v1/clusterextension_types.go index e331ec63e..6de62b0e1 100644 --- a/api/v1/clusterextension_types.go +++ b/api/v1/clusterextension_types.go @@ -98,10 +98,13 @@ type ClusterExtensionSpec struct { // +optional Install *ClusterExtensionInstallConfig `json:"install,omitempty"` - // config contains optional configuration values applied during rendering of the - // ClusterExtension's manifests. Values can be specified inline. + // config is an optional field used to specify bundle specific configuration + // used to configure the bundle. Configuration is bundle specific and a bundle may provide + // a configuration schema. When not specified, the default configuration of the resolved bundle will be used. // - // config is optional. When not specified, the default configuration of the resolved bundle will be used. + // config is validated against a configuration schema provided by the resolved bundle. If the bundle does not provide + // a configuration schema the final manifests will be derived on a best-effort basis. More information on how + // to configure the bundle should be found in its end-user documentation. // // // +optional @@ -174,6 +177,8 @@ type ClusterExtensionConfig struct { // ClusterExtension. // // inline must be set if configType is 'Inline'. + // inline accepts arbitrary JSON/YAML objects. + // inline is validation at runtime against the schema provided by the bundle if a schema is provided. // // +kubebuilder:validation:Type=object // +optional diff --git a/commitchecker.yaml b/commitchecker.yaml index 8fec18e87..752b7004b 100644 --- a/commitchecker.yaml +++ b/commitchecker.yaml @@ -1,4 +1,4 @@ -expectedMergeBase: 292c0dbc236747e57f77fd914830a865e87fad6b +expectedMergeBase: 926d57e1e6559f7ac0ef69a47b3d50d96975ec38 upstreamBranch: main upstreamOrg: operator-framework upstreamRepo: operator-controller diff --git a/docs/api-reference/olmv1-api-reference.md b/docs/api-reference/olmv1-api-reference.md index 1b1ad6656..b21e40452 100644 --- a/docs/api-reference/olmv1-api-reference.md +++ b/docs/api-reference/olmv1-api-reference.md @@ -254,7 +254,7 @@ _Appears in:_ | Field | Description | Default | Validation | | --- | --- | --- | --- | | `configType` _[ClusterExtensionConfigType](#clusterextensionconfigtype)_ | configType is a required reference to the type of configuration source.

Allowed values are "Inline"

When this field is set to "Inline", the cluster extension configuration is defined inline within the
ClusterExtension resource. | | Enum: [Inline]
Required: \{\}
| -| `inline` _[JSON](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.31/#json-v1-apiextensions-k8s-io)_ | inline contains JSON or YAML values specified directly in the
ClusterExtension.

inline must be set if configType is 'Inline'. | | Type: object
| +| `inline` _[JSON](https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.31/#json-v1-apiextensions-k8s-io)_ | inline contains JSON or YAML values specified directly in the
ClusterExtension.

inline must be set if configType is 'Inline'.
inline accepts arbitrary JSON/YAML objects.
inline is validation at runtime against the schema provided by the bundle if a schema is provided. | | Type: object
| #### ClusterExtensionConfigType @@ -343,7 +343,7 @@ _Appears in:_ | `serviceAccount` _[ServiceAccountReference](#serviceaccountreference)_ | serviceAccount is a reference to a ServiceAccount used to perform all interactions
with the cluster that are required to manage the extension.
The ServiceAccount must be configured with the necessary permissions to perform these interactions.
The ServiceAccount must exist in the namespace referenced in the spec.
serviceAccount is required. | | Required: \{\}
| | `source` _[SourceConfig](#sourceconfig)_ | source is a required field which selects the installation source of content
for this ClusterExtension. Selection is performed by setting the sourceType.

Catalog is currently the only implemented sourceType, and setting the
sourcetype to "Catalog" requires the catalog field to also be defined.

Below is a minimal example of a source definition (in yaml):

source:
sourceType: Catalog
catalog:
packageName: example-package | | Required: \{\}
| | `install` _[ClusterExtensionInstallConfig](#clusterextensioninstallconfig)_ | install is an optional field used to configure the installation options
for the ClusterExtension such as the pre-flight check configuration. | | | -| `config` _[ClusterExtensionConfig](#clusterextensionconfig)_ | config contains optional configuration values applied during rendering of the
ClusterExtension's manifests. Values can be specified inline.

config is optional. When not specified, the default configuration of the resolved bundle will be used.

| | | +| `config` _[ClusterExtensionConfig](#clusterextensionconfig)_ | config is an optional field used to specify bundle specific configuration
used to configure the bundle. Configuration is bundle specific and a bundle may provide
a configuration schema. When not specified, the default configuration of the resolved bundle will be used.

config is validated against a configuration schema provided by the resolved bundle. If the bundle does not provide
a configuration schema the final manifests will be derived on a best-effort basis. More information on how
to configure the bundle should be found in its end-user documentation.

| | | #### ClusterExtensionStatus diff --git a/docs/draft/howto/enable-webhook-support.md b/docs/draft/howto/enable-webhook-support.md index 2ab856bf0..f5c7de776 100644 --- a/docs/draft/howto/enable-webhook-support.md +++ b/docs/draft/howto/enable-webhook-support.md @@ -1,12 +1,11 @@ ## Installation of Bundles containing Webhooks !!! note -This feature is still in *alpha*. Either the `WebhookProviderCertManager`, or the `WebhookProviderOpenshiftServiceCA`, feature-gate -must be enabled to make use of it. See the instructions below on how to enable the feature-gate. +OLMv1 supports the installation of bundles containing webhooks by default. +By default, OLM v1 uses the community Cert Manager package for admission webhook via the feature-gate flag `WebhookProviderCertManager`. To use the OpenShift Service CA provider, set the `--feature-gates=WebhookProviderOpenshiftServiceCA=true` flag at startup. -OLMv1 currently does not support the installation of bundles containing webhooks. The webhook support feature enables this capability. -Webhooks, or more concretely Admission Webhooks, are part of Kuberntes' [Dynamic Admission Control](https://kubernetes.io/docs/reference/access-authn-authz/extensible-admission-controllers/) -feature. Webhooks run as services called by the kube-apiservice in due course of processing a resource related request. They can be used to validate resources, ensure reasonable default values, +Admission webhooks are part of the Kubernetes suite of [Dynamic Admission Control](https://kubernetes.io/docs/reference/access-authn-authz/extensible-admission-controllers/) +plugins. Webhooks run as services called by the kube-apiservice in due course of processing a resource related request. They can be used to validate resources, ensure reasonable default values, are set, or aid in the migration to new CustomResourceDefinition schema. The communication with the webhook service is secured by TLS. In OLMv1, the TLS certificate is managed by a certificate provider. Currently, two certificate providers are supported: CertManager and Openshift-ServiceCA. The certificate provider to use given by the feature-gate: @@ -15,14 +14,12 @@ certificate provider. Currently, two certificate providers are supported: CertMa As CertManager is already installed with OLMv1, we suggest using `WebhookProviderCertManager`. -### Run OLM v1with Experimental Features Enabled +### Run OLM v1 with Webhook Support -```terminal title=Enable Experimental Features in a New Kind Cluster -make run-experimental +```terminal title=Start the controller with webhook support +make run ``` -This will enable only the `WebhookProviderCertManager` feature-gate, which works with cert-manager. - Then, ```terminal title=Wait for rollout to complete diff --git a/docs/draft/tutorials/explore-available-content-metas-endpoint.md b/docs/draft/tutorials/explore-available-content-metas-endpoint.md index 70cb87424..f17271d3e 100644 --- a/docs/draft/tutorials/explore-available-content-metas-endpoint.md +++ b/docs/draft/tutorials/explore-available-content-metas-endpoint.md @@ -92,7 +92,7 @@ Then you can query the catalog by using `curl` commands and the `jq` CLI tool to ``` !!! important - Currently, OLM 1.0 does not support the installation of extensions that use webhooks or that target a single or specified set of namespaces. + OLM 1.0 supports installing extensions that define webhooks. Targeting a single or specified set of namespaces requires enabling the `SingleOwnNamespaceInstallSupport` feature-gate. 3. Return list of packages which support `AllNamespaces` install mode, do not use webhooks, and where the channel head version uses `olm.csv.metadata` format: diff --git a/docs/project/olmv1_limitations.md b/docs/project/olmv1_limitations.md index 26e2340ff..01ce9436d 100644 --- a/docs/project/olmv1_limitations.md +++ b/docs/project/olmv1_limitations.md @@ -8,8 +8,7 @@ hide: Currently, OLM v1 only supports installing operators packaged in [OLM v0 bundles](https://olm.operatorframework.io/docs/tasks/creating-operator-bundle/) , also known as `registry+v1` bundles. Additionally, the bundled operator, or cluster extension: -* **must** support installation via the `AllNamespaces` install mode. -* **must not** use webhooks. +* **must** support installation via the `AllNamespaces` install mode * **must not** declare dependencies using any of the following file-based catalog properties: * `olm.gvk.required` * `olm.package.required` diff --git a/docs/tutorials/explore-available-content.md b/docs/tutorials/explore-available-content.md index 0a1f46809..36e3cf883 100644 --- a/docs/tutorials/explore-available-content.md +++ b/docs/tutorials/explore-available-content.md @@ -92,7 +92,7 @@ Then you can query the catalog by using `curl` commands and the `jq` CLI tool to ``` !!! important - Currently, OLM 1.0 does not support the installation of extensions that use webhooks or that target a single or specified set of namespaces. + OLM 1.0 supports installing extensions that define webhooks. Targeting a single or specified set of namespaces requires enabling the `SingleOwnNamespaceInstallSupport` feature-gate. 3. Return list of packages that support `AllNamespaces` install mode and do not use webhooks: diff --git a/go.mod b/go.mod index 8b94dc19a..6da4ac25c 100644 --- a/go.mod +++ b/go.mod @@ -15,7 +15,7 @@ require ( github.com/google/go-containerregistry v0.20.6 github.com/google/renameio/v2 v2.0.0 github.com/gorilla/handlers v1.5.2 - github.com/klauspost/compress v1.18.0 + github.com/klauspost/compress v1.18.1 github.com/opencontainers/go-digest v1.0.0 github.com/opencontainers/image-spec v1.1.1 github.com/operator-framework/api v0.35.0 @@ -26,7 +26,7 @@ require ( github.com/spf13/cobra v1.10.1 github.com/spf13/pflag v1.0.10 github.com/stretchr/testify v1.11.1 - go.podman.io/image/v5 v5.37.0 + go.podman.io/image/v5 v5.38.0 golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b golang.org/x/mod v0.29.0 golang.org/x/sync v0.17.0 @@ -89,10 +89,10 @@ require ( github.com/cyphar/filepath-securejoin v0.4.1 // indirect github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/distribution/reference v0.6.0 // indirect - github.com/docker/cli v28.4.0+incompatible // indirect + github.com/docker/cli v28.5.1+incompatible // indirect github.com/docker/distribution v2.8.3+incompatible // indirect - github.com/docker/docker v28.3.3+incompatible // indirect - github.com/docker/docker-credential-helpers v0.9.3 // indirect + github.com/docker/docker v28.5.1+incompatible // indirect + github.com/docker/docker-credential-helpers v0.9.4 // indirect github.com/docker/go-connections v0.6.0 // indirect github.com/docker/go-units v0.5.0 // indirect github.com/emicklei/go-restful/v3 v3.13.0 // indirect @@ -221,12 +221,12 @@ require ( go.opentelemetry.io/otel/trace v1.38.0 // indirect go.opentelemetry.io/proto/otlp v1.7.0 // indirect go.podman.io/common v0.65.0 // indirect - go.podman.io/storage v1.60.0 // indirect + go.podman.io/storage v1.61.0 // indirect go.yaml.in/yaml/v2 v2.4.3 // indirect go.yaml.in/yaml/v3 v3.0.4 // indirect golang.org/x/crypto v0.43.0 // indirect golang.org/x/net v0.46.0 // indirect - golang.org/x/oauth2 v0.31.0 // indirect + golang.org/x/oauth2 v0.32.0 // indirect golang.org/x/sys v0.37.0 // indirect golang.org/x/term v0.36.0 // indirect golang.org/x/text v0.30.0 // indirect diff --git a/go.sum b/go.sum index fed918467..8b2845753 100644 --- a/go.sum +++ b/go.sum @@ -104,14 +104,14 @@ github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5Qvfr github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E= github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxKI= github.com/dlclark/regexp2 v1.11.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= -github.com/docker/cli v28.4.0+incompatible h1:RBcf3Kjw2pMtwui5V0DIMdyeab8glEw5QY0UUU4C9kY= -github.com/docker/cli v28.4.0+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8= +github.com/docker/cli v28.5.1+incompatible h1:ESutzBALAD6qyCLqbQSEf1a/U8Ybms5agw59yGVc+yY= +github.com/docker/cli v28.5.1+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/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w= -github.com/docker/docker v28.3.3+incompatible h1:Dypm25kh4rmk49v1eiVbsAtpAsYURjYkaKubwuBdxEI= -github.com/docker/docker v28.3.3+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/go.mod h1:x+4Gbw9aGmChi3qTLZj8Dfn0TD20M/fuWy0E5+WDeCo= +github.com/docker/docker v28.5.1+incompatible h1:Bm8DchhSD2J6PsFzxC35TZo4TLGR2PdW/E69rU45NhM= +github.com/docker/docker v28.5.1+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= +github.com/docker/docker-credential-helpers v0.9.4 h1:76ItO69/AP/V4yT9V4uuuItG0B1N8hvt0T0c0NN/DzI= +github.com/docker/docker-credential-helpers v0.9.4/go.mod h1:v1S+hepowrQXITkEfw6o4+BMbGot02wiKpzWhGUZK6c= github.com/docker/go-connections v0.6.0 h1:LlMG9azAe1TqfR7sO+NJttz1gy6KO7VJBh+pMmjSD94= github.com/docker/go-connections v0.6.0/go.mod h1:AahvXYshr6JgfUJGdDCs2b5EZG/vmaMAntpSFH5BFKE= github.com/docker/go-events v0.0.0-20250114142523-c867878c5e32 h1:EHZfspsnLAz8Hzccd67D5abwLiqoqym2jz/jOS39mCk= @@ -300,8 +300,8 @@ github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnr github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= -github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo= -github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ= +github.com/klauspost/compress v1.18.1 h1:bcSGx7UbpBqMChDtsF28Lw6v/G94LPrrbMbdC3JH2co= +github.com/klauspost/compress v1.18.1/go.mod h1:ZQFFVG+MdnR0P+l6wpXgIL4NTtwiKIdBnrBd8Nrxr+0= github.com/klauspost/pgzip v1.2.6 h1:8RXeL5crjEUFnR2/Sn6GJNWtSQ3Dk8pq4CL3jvdDyjU= github.com/klauspost/pgzip v1.2.6/go.mod h1:Ch1tH69qFZu15pkjo5kYi6mth2Zzwzt50oCQKQE9RUs= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= @@ -555,10 +555,10 @@ go.opentelemetry.io/proto/otlp v1.7.0 h1:jX1VolD6nHuFzOYso2E73H85i92Mv8JQYk0K9vz go.opentelemetry.io/proto/otlp v1.7.0/go.mod h1:fSKjH6YJ7HDlwzltzyMj036AJ3ejJLCgCSHGj4efDDo= go.podman.io/common v0.65.0 h1:8JNl25U4VpKDkFHSymSPm4te7ZQHJbfAB/l2FqtmYEg= go.podman.io/common v0.65.0/go.mod h1:+lJu8KHeoDQsD9HDdiFaMaOUiqPLQnK406WuLnqM7Z0= -go.podman.io/image/v5 v5.37.0 h1:yzgQybwuWIIeK63hu+mQqna/wOh96XD5cpVc6j8Dg5M= -go.podman.io/image/v5 v5.37.0/go.mod h1:+s2Sx5dia/jVeT8tI3r2NAPrARMiDdbEq3QPIQogx3I= -go.podman.io/storage v1.60.0 h1:bWNSrR58nxg39VNFDSx3m0AswbvyzPGOo5XsUfomTao= -go.podman.io/storage v1.60.0/go.mod h1:NK+rsWJVuQeCM7ifv7cxD3abegWxwtW/3OkuSUJJoE4= +go.podman.io/image/v5 v5.38.0 h1:aUKrCANkPvze1bnhLJsaubcfz0d9v/bSDLnwsXJm6G4= +go.podman.io/image/v5 v5.38.0/go.mod h1:hSIoIUzgBnmc4DjoIdzk63aloqVbD7QXDMkSE/cvG90= +go.podman.io/storage v1.61.0 h1:5hD/oyRYt1f1gxgvect+8syZBQhGhV28dCw2+CZpx0Q= +go.podman.io/storage v1.61.0/go.mod h1:A3UBK0XypjNZ6pghRhuxg62+2NIm5lcUGv/7XyMhMUI= go.uber.org/automaxprocs v1.6.0 h1:O3y2/QNTOdbF+e/dpXNNW7Rx2hZ4sTIPyybbxyNqTUs= go.uber.org/automaxprocs v1.6.0/go.mod h1:ifeIMSnPZuznNm6jmdzmU3/bfk01Fe2fotchwEFJ8r8= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= @@ -615,8 +615,8 @@ golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM= golang.org/x/net v0.46.0 h1:giFlY12I07fugqwPuWJi68oOnpfqFnJIJzaIIm2JVV4= golang.org/x/net v0.46.0/go.mod h1:Q9BGdFy1y4nkUwiLvT5qtyhAnEHgnQ/zd8PfU6nc210= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= -golang.org/x/oauth2 v0.31.0 h1:8Fq0yVZLh4j4YA47vHKFTa9Ew5XIrCP8LC6UeNZnLxo= -golang.org/x/oauth2 v0.31.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA= +golang.org/x/oauth2 v0.32.0 h1:jsCblLleRMDrxMN29H3z/k1KliIvpLgCkE6R8FXXNgY= +golang.org/x/oauth2 v0.32.0/go.mod h1:lzm5WQJQwKZ3nwavOZ3IS5Aulzxi68dUSgRHujetwEA= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= diff --git a/helm/experimental.yaml b/helm/experimental.yaml index ae98c0803..b14b1b303 100644 --- a/helm/experimental.yaml +++ b/helm/experimental.yaml @@ -9,7 +9,6 @@ options: operatorController: features: enabled: - - WebhookProviderCertManager - SingleOwnNamespaceInstallSupport - PreflightPermissions - HelmChartSupport diff --git a/helm/olmv1/base/operator-controller/crd/experimental/olm.operatorframework.io_clusterextensions.yaml b/helm/olmv1/base/operator-controller/crd/experimental/olm.operatorframework.io_clusterextensions.yaml index 4cae796a6..1038b7fdf 100644 --- a/helm/olmv1/base/operator-controller/crd/experimental/olm.operatorframework.io_clusterextensions.yaml +++ b/helm/olmv1/base/operator-controller/crd/experimental/olm.operatorframework.io_clusterextensions.yaml @@ -59,10 +59,13 @@ spec: properties: config: description: |- - config contains optional configuration values applied during rendering of the - ClusterExtension's manifests. Values can be specified inline. + config is an optional field used to specify bundle specific configuration + used to configure the bundle. Configuration is bundle specific and a bundle may provide + a configuration schema. When not specified, the default configuration of the resolved bundle will be used. - config is optional. When not specified, the default configuration of the resolved bundle will be used. + config is validated against a configuration schema provided by the resolved bundle. If the bundle does not provide + a configuration schema the final manifests will be derived on a best-effort basis. More information on how + to configure the bundle should be found in its end-user documentation. properties: configType: description: |- @@ -81,6 +84,8 @@ spec: ClusterExtension. inline must be set if configType is 'Inline'. + inline accepts arbitrary JSON/YAML objects. + inline is validation at runtime against the schema provided by the bundle if a schema is provided. type: object x-kubernetes-preserve-unknown-fields: true required: diff --git a/helm/tilt.yaml b/helm/tilt.yaml index 3dbc373c7..aaed7c71f 100644 --- a/helm/tilt.yaml +++ b/helm/tilt.yaml @@ -14,7 +14,6 @@ options: operatorController: features: enabled: - - WebhookProviderCertManager - SingleOwnNamespaceInstallSupport - PreflightPermissions - HelmChartSupport diff --git a/internal/operator-controller/applier/provider.go b/internal/operator-controller/applier/provider.go index ed1a1c5ec..f425e7415 100644 --- a/internal/operator-controller/applier/provider.go +++ b/internal/operator-controller/applier/provider.go @@ -8,12 +8,12 @@ import ( "helm.sh/helm/v3/pkg/chart" "k8s.io/apimachinery/pkg/util/sets" - "k8s.io/apimachinery/pkg/util/validation" "sigs.k8s.io/controller-runtime/pkg/client" "github.com/operator-framework/api/pkg/operators/v1alpha1" ocv1 "github.com/operator-framework/operator-controller/api/v1" + "github.com/operator-framework/operator-controller/internal/operator-controller/rukpak/bundle" "github.com/operator-framework/operator-controller/internal/operator-controller/rukpak/bundle/source" "github.com/operator-framework/operator-controller/internal/operator-controller/rukpak/render" ) @@ -68,43 +68,18 @@ func (r *RegistryV1ManifestProvider) Get(bundleFS fs.FS, ext *ocv1.ClusterExtens render.WithCertificateProvider(r.CertificateProvider), } - watchNamespace, err := r.getWatchNamespace(ext) - if err != nil { - return nil, err - } - - if watchNamespace != "" { - opts = append(opts, render.WithTargetNamespaces(watchNamespace)) - } - - return r.BundleRenderer.Render(rv1, ext.Spec.Namespace, opts...) -} - -// getWatchNamespace determines the watch namespace the ClusterExtension should use based on the -// configuration in .spec.config.Inline. Only active if SingleOwnNamespace support is enabled. -func (r *RegistryV1ManifestProvider) getWatchNamespace(ext *ocv1.ClusterExtension) (string, error) { - if !r.IsSingleOwnNamespaceEnabled { - return "", nil - } - - var watchNamespace string - if ext.Spec.Config != nil && ext.Spec.Config.Inline != nil { - cfg := struct { - WatchNamespace string `json:"watchNamespace"` - }{} - if err := json.Unmarshal(ext.Spec.Config.Inline.Raw, &cfg); err != nil { - return "", fmt.Errorf("invalid bundle configuration: %w", err) + if r.IsSingleOwnNamespaceEnabled && ext.Spec.Config != nil && ext.Spec.Config.ConfigType == ocv1.ClusterExtensionConfigTypeInline { + bundleConfig, err := bundle.UnmarshallConfig(ext.Spec.Config.Inline.Raw, rv1, ext.Spec.Namespace) + if err != nil { + return nil, fmt.Errorf("invalid bundle configuration: %w", err) } - watchNamespace = cfg.WatchNamespace - } else { - return "", nil - } - if errs := validation.IsDNS1123Subdomain(watchNamespace); len(errs) > 0 { - return "", fmt.Errorf("invalid watch namespace '%s': namespace must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character", watchNamespace) + if bundleConfig != nil && bundleConfig.WatchNamespace != nil { + opts = append(opts, render.WithTargetNamespaces(*bundleConfig.WatchNamespace)) + } } - return watchNamespace, nil + return r.BundleRenderer.Render(rv1, ext.Spec.Namespace, opts...) } // RegistryV1HelmChartProvider creates a Helm-Chart from a registry+v1 bundle and its associated ClusterExtension diff --git a/internal/operator-controller/applier/provider_test.go b/internal/operator-controller/applier/provider_test.go index 1816bdd33..b1a6cd4f4 100644 --- a/internal/operator-controller/applier/provider_test.go +++ b/internal/operator-controller/applier/provider_test.go @@ -64,6 +64,42 @@ func Test_RegistryV1ManifestProvider_Integration(t *testing.T) { require.Contains(t, err.Error(), "some error") }) + t.Run("surfaces bundle config unmarshall errors", func(t *testing.T) { + provider := applier.RegistryV1ManifestProvider{ + BundleRenderer: render.BundleRenderer{ + ResourceGenerators: []render.ResourceGenerator{ + func(rv1 *bundle.RegistryV1, opts render.Options) ([]client.Object, error) { + return nil, nil + }, + }, + }, + // must be true for now as we only unmarshal configuration when this feature is on + // once we go GA and remove IsSingleOwnNamespaceEnabled it's ok to just delete this + IsSingleOwnNamespaceEnabled: true, + } + + // The contents of the bundle are not important for this tesy, only that it be a valid bundle + // to avoid errors in the deserialization process + bundleFS := bundlefs.Builder().WithPackageName("test"). + WithCSV(clusterserviceversion.Builder().WithInstallModeSupportFor(v1alpha1.InstallModeTypeSingleNamespace).Build()).Build() + + ext := &ocv1.ClusterExtension{ + Spec: ocv1.ClusterExtensionSpec{ + Namespace: "install-namespace", + Config: &ocv1.ClusterExtensionConfig{ + ConfigType: ocv1.ClusterExtensionConfigTypeInline, + Inline: &apiextensionsv1.JSON{ + Raw: []byte(`{"watchNamespace": "install-namespace"}`), + }, + }, + }, + } + + _, err := provider.Get(bundleFS, ext) + require.Error(t, err) + require.Contains(t, err.Error(), "invalid bundle configuration") + }) + t.Run("returns rendered manifests", func(t *testing.T) { provider := applier.RegistryV1ManifestProvider{ BundleRenderer: registryv1.Renderer, @@ -205,6 +241,54 @@ func Test_RegistryV1ManifestProvider_SingleOwnNamespaceSupport(t *testing.T) { require.Equal(t, "unsupported bundle: bundle does not support AllNamespaces install mode", err.Error()) }) + t.Run("rejects bundles without AllNamespaces install mode and with SingleNamespace support when Single/OwnNamespace install mode support is enabled", func(t *testing.T) { + expectedWatchNamespace := "some-namespace" + provider := applier.RegistryV1ManifestProvider{ + BundleRenderer: render.BundleRenderer{ + ResourceGenerators: []render.ResourceGenerator{ + func(rv1 *bundle.RegistryV1, opts render.Options) ([]client.Object, error) { + t.Log("ensure watch namespace is appropriately configured") + require.Equal(t, []string{expectedWatchNamespace}, opts.TargetNamespaces) + return nil, nil + }, + }, + }, + IsSingleOwnNamespaceEnabled: false, + } + + bundleFS := bundlefs.Builder().WithPackageName("test"). + WithCSV(clusterserviceversion.Builder().WithInstallModeSupportFor(v1alpha1.InstallModeTypeSingleNamespace).Build()).Build() + + _, err := provider.Get(bundleFS, &ocv1.ClusterExtension{ + Spec: ocv1.ClusterExtensionSpec{ + Namespace: "install-namespace", + Config: &ocv1.ClusterExtensionConfig{ + ConfigType: ocv1.ClusterExtensionConfigTypeInline, + Inline: &apiextensionsv1.JSON{ + Raw: []byte(`{"watchNamespace": "` + expectedWatchNamespace + `"}`), + }, + }, + }, + }) + require.Error(t, err) + require.Contains(t, err.Error(), "unsupported bundle") + }) + + t.Run("rejects bundles without AllNamespaces install mode and with OwnNamespace support when Single/OwnNamespace install mode support is disabled", func(t *testing.T) { + provider := applier.RegistryV1ManifestProvider{ + IsSingleOwnNamespaceEnabled: false, + } + bundleFS := bundlefs.Builder().WithPackageName("test"). + WithCSV(clusterserviceversion.Builder().WithInstallModeSupportFor(v1alpha1.InstallModeTypeOwnNamespace).Build()).Build() + _, err := provider.Get(bundleFS, &ocv1.ClusterExtension{ + Spec: ocv1.ClusterExtensionSpec{ + Namespace: "install-namespace", + }, + }) + require.Error(t, err) + require.Contains(t, err.Error(), "unsupported bundle") + }) + t.Run("accepts bundles without AllNamespaces install mode and with SingleNamespace support when Single/OwnNamespace install mode support is enabled", func(t *testing.T) { expectedWatchNamespace := "some-namespace" provider := applier.RegistryV1ManifestProvider{ diff --git a/internal/operator-controller/controllers/clusterextension_admission_test.go b/internal/operator-controller/controllers/clusterextension_admission_test.go index 7e1fb930c..38c6c60d4 100644 --- a/internal/operator-controller/controllers/clusterextension_admission_test.go +++ b/internal/operator-controller/controllers/clusterextension_admission_test.go @@ -6,6 +6,7 @@ import ( "testing" "github.com/stretchr/testify/require" + apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ocv1 "github.com/operator-framework/operator-controller/api/v1" @@ -448,6 +449,54 @@ func TestClusterExtensionAdmissionInstall(t *testing.T) { } } +func Test_ClusterExtensionAdmissionInlineConfig(t *testing.T) { + t.Parallel() + for _, tc := range []struct { + name string + configBytes []byte + errMsg string + }{ + { + name: "rejects valid json that is not of an object type", + configBytes: []byte(`true`), + errMsg: "spec.config.inline in body must be of type object", + }, + { + name: "accepts valid json object", + configBytes: []byte(`{"key": "value"}`), + }, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + cl := newClient(t) + err := cl.Create(context.Background(), buildClusterExtension(ocv1.ClusterExtensionSpec{ + Source: ocv1.SourceConfig{ + SourceType: "Catalog", + Catalog: &ocv1.CatalogFilter{ + PackageName: "package", + }, + }, + Namespace: "default", + ServiceAccount: ocv1.ServiceAccountReference{ + Name: "default", + }, + Config: &ocv1.ClusterExtensionConfig{ + ConfigType: ocv1.ClusterExtensionConfigTypeInline, + Inline: &apiextensionsv1.JSON{ + Raw: tc.configBytes, + }, + }, + })) + if tc.errMsg == "" { + require.NoError(t, err, "unexpected error for inline bundle configuration %q: %w", string(tc.configBytes), err) + } else { + require.Error(t, err) + require.Contains(t, err.Error(), tc.errMsg) + } + }) + } +} + func buildClusterExtension(spec ocv1.ClusterExtensionSpec) *ocv1.ClusterExtension { return &ocv1.ClusterExtension{ ObjectMeta: metav1.ObjectMeta{ diff --git a/internal/operator-controller/features/features.go b/internal/operator-controller/features/features.go index 1abdf0a18..4926ff853 100644 --- a/internal/operator-controller/features/features.go +++ b/internal/operator-controller/features/features.go @@ -51,8 +51,8 @@ var operatorControllerFeatureGates = map[featuregate.Feature]featuregate.Feature // mutating, and/or conversion webhooks with CertManager // as the certificate provider. WebhookProviderCertManager: { - Default: false, - PreRelease: featuregate.Alpha, + Default: true, + PreRelease: featuregate.GA, LockToDefault: false, }, @@ -61,8 +61,8 @@ var operatorControllerFeatureGates = map[featuregate.Feature]featuregate.Feature // mutating, and/or conversion webhooks with Openshift Service CA // as the certificate provider. WebhookProviderOpenshiftServiceCA: { - Default: false, - PreRelease: featuregate.Alpha, + Default: true, + PreRelease: featuregate.GA, LockToDefault: false, }, diff --git a/internal/operator-controller/rukpak/bundle/config.go b/internal/operator-controller/rukpak/bundle/config.go new file mode 100644 index 000000000..c65a2311a --- /dev/null +++ b/internal/operator-controller/rukpak/bundle/config.go @@ -0,0 +1,125 @@ +package bundle + +import ( + "encoding/json" + "errors" + "fmt" + "strings" + + "k8s.io/apimachinery/pkg/util/sets" + "k8s.io/apimachinery/pkg/util/validation" + "sigs.k8s.io/yaml" + + "github.com/operator-framework/api/pkg/operators/v1alpha1" +) + +type Config struct { + WatchNamespace *string `json:"watchNamespace"` +} + +// UnmarshallConfig returns a deserialized and validated *bundle.Config based on bytes and validated +// against rv1 and the desired install namespaces. It will error if: +// - rv is nil +// - bytes is not a valid YAML/JSON object +// - bytes is a valid YAML/JSON object but does not follow the registry+v1 schema +// if bytes is nil a nil bundle.Config is returned +func UnmarshallConfig(bytes []byte, rv1 RegistryV1, installNamespace string) (*Config, error) { + if bytes == nil { + return nil, nil + } + + bundleConfig := &Config{} + if err := yaml.UnmarshalStrict(bytes, bundleConfig); err != nil { + return nil, fmt.Errorf("error unmarshalling registry+v1 configuration: %w", formatUnmarshallError(err)) + } + + // collect bundle install modes + bundleInstallModeSet := sets.New(rv1.CSV.Spec.InstallModes...) + + if err := validateConfig(bundleConfig, installNamespace, bundleInstallModeSet); err != nil { + return nil, fmt.Errorf("error unmarshalling registry+v1 configuration: %w", err) + } + + return bundleConfig, nil +} + +// validateConfig validates a *bundle.Config against the bundle's supported install modes and the user-give installNamespace. +func validateConfig(config *Config, installNamespace string, bundleInstallModeSet sets.Set[v1alpha1.InstallMode]) error { + // no config, no problem + if config == nil { + return nil + } + + // if the bundle does not support the watchNamespace configuration and it is set, treat it like any unknown field + if config.WatchNamespace != nil && !isWatchNamespaceConfigSupported(bundleInstallModeSet) { + return errors.New(`unknown field "watchNamespace"`) + } + + // if watchNamespace is required then ensure that it is set + if config.WatchNamespace == nil && isWatchNamespaceConfigRequired(bundleInstallModeSet) { + return errors.New(`required field "watchNamespace" is missing`) + } + + // if watchNamespace is set then ensure it is a valid namespace + if config.WatchNamespace != nil { + if errs := validation.IsDNS1123Subdomain(*config.WatchNamespace); len(errs) > 0 { + return fmt.Errorf("invalid 'watchNamespace' %q: namespace must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character", *config.WatchNamespace) + } + } + + // only accept install namespace if OwnNamespace install mode is supported + if config.WatchNamespace != nil && *config.WatchNamespace == installNamespace && + !bundleInstallModeSet.Has(v1alpha1.InstallMode{Type: v1alpha1.InstallModeTypeOwnNamespace, Supported: true}) { + return fmt.Errorf("invalid 'watchNamespace' %q: must not be install namespace (%s)", *config.WatchNamespace, installNamespace) + } + + // only accept non-install namespace is SingleNamespace is supported + if config.WatchNamespace != nil && *config.WatchNamespace != installNamespace && + !bundleInstallModeSet.Has(v1alpha1.InstallMode{Type: v1alpha1.InstallModeTypeSingleNamespace, Supported: true}) { + return fmt.Errorf("invalid 'watchNamespace' %q: must be install namespace (%s)", *config.WatchNamespace, installNamespace) + } + + return nil +} + +// isWatchNamespaceConfigSupported returns true when the bundle exposes a watchNamespace configuration. This happens when: +// - SingleNamespace install more is supported, or +// - OwnNamespace and AllNamespaces install modes are supported +func isWatchNamespaceConfigSupported(bundleInstallModeSet sets.Set[v1alpha1.InstallMode]) bool { + return bundleInstallModeSet.Has(v1alpha1.InstallMode{Type: v1alpha1.InstallModeTypeSingleNamespace, Supported: true}) || + bundleInstallModeSet.HasAll( + v1alpha1.InstallMode{Type: v1alpha1.InstallModeTypeOwnNamespace, Supported: true}, + v1alpha1.InstallMode{Type: v1alpha1.InstallModeTypeAllNamespaces, Supported: true}) +} + +// isWatchNamespaceConfigRequired returns true if the watchNamespace configuration is required. This happens when +// AllNamespaces install mode is not supported and SingleNamespace is supported +func isWatchNamespaceConfigRequired(bundleInstallModeSet sets.Set[v1alpha1.InstallMode]) bool { + return !bundleInstallModeSet.Has(v1alpha1.InstallMode{Type: v1alpha1.InstallModeTypeAllNamespaces, Supported: true}) && + bundleInstallModeSet.Has(v1alpha1.InstallMode{Type: v1alpha1.InstallModeTypeSingleNamespace, Supported: true}) +} + +// formatUnmarshallError format JSON unmarshal errors to be more readable +func formatUnmarshallError(err error) error { + var unmarshalErr *json.UnmarshalTypeError + if errors.As(err, &unmarshalErr) { + if unmarshalErr.Field == "" { + return errors.New("input is not a valid JSON object") + } else { + return fmt.Errorf("invalid value type for field %q: expected %q but got %q", unmarshalErr.Field, unmarshalErr.Type.String(), unmarshalErr.Value) + } + } + + // unwrap error until the core and process it + for { + unwrapped := errors.Unwrap(err) + if unwrapped == nil { + // usually the errors present in the form json: or yaml: + // we want to extract if we can + errMessageComponents := strings.Split(err.Error(), ":") + coreErrMessage := strings.TrimSpace(errMessageComponents[len(errMessageComponents)-1]) + return errors.New(coreErrMessage) + } + err = unwrapped + } +} diff --git a/internal/operator-controller/rukpak/bundle/config_test.go b/internal/operator-controller/rukpak/bundle/config_test.go new file mode 100644 index 000000000..10494f651 --- /dev/null +++ b/internal/operator-controller/rukpak/bundle/config_test.go @@ -0,0 +1,259 @@ +package bundle_test + +import ( + "testing" + + "github.com/stretchr/testify/require" + "k8s.io/utils/ptr" + + "github.com/operator-framework/api/pkg/operators/v1alpha1" + + "github.com/operator-framework/operator-controller/internal/operator-controller/rukpak/bundle" + "github.com/operator-framework/operator-controller/internal/operator-controller/rukpak/util/testing/clusterserviceversion" +) + +func Test_UnmarshallConfig(t *testing.T) { + for _, tc := range []struct { + name string + rawConfig []byte + supportedInstallModes []v1alpha1.InstallModeType + installNamespace string + expectedErrMessage string + expectedConfig *bundle.Config + }{ + { + name: "accepts nil raw config", + rawConfig: nil, + expectedConfig: nil, + }, + { + name: "accepts json config", + supportedInstallModes: []v1alpha1.InstallModeType{v1alpha1.InstallModeTypeSingleNamespace}, + rawConfig: []byte(`{"watchNamespace": "some-namespace"}`), + expectedConfig: &bundle.Config{ + WatchNamespace: ptr.To("some-namespace"), + }, + }, + { + name: "accepts yaml config", + supportedInstallModes: []v1alpha1.InstallModeType{v1alpha1.InstallModeTypeSingleNamespace}, + rawConfig: []byte(`watchNamespace: some-namespace`), + expectedConfig: &bundle.Config{ + WatchNamespace: ptr.To("some-namespace"), + }, + }, + { + name: "rejects invalid json", + supportedInstallModes: []v1alpha1.InstallModeType{v1alpha1.InstallModeTypeSingleNamespace}, + rawConfig: []byte(`{"hello`), + expectedErrMessage: `error unmarshalling registry+v1 configuration: found unexpected end of stream`, + }, + { + name: "rejects valid json that isn't of object type", + supportedInstallModes: []v1alpha1.InstallModeType{v1alpha1.InstallModeTypeSingleNamespace}, + rawConfig: []byte(`true`), + expectedErrMessage: `error unmarshalling registry+v1 configuration: input is not a valid JSON object`, + }, + { + name: "rejects additional fields", + supportedInstallModes: []v1alpha1.InstallModeType{v1alpha1.InstallModeTypeSingleNamespace}, + rawConfig: []byte(`somekey: somevalue`), + expectedErrMessage: `error unmarshalling registry+v1 configuration: unknown field "somekey"`, + }, + { + name: "rejects valid json but invalid registry+v1", + supportedInstallModes: []v1alpha1.InstallModeType{v1alpha1.InstallModeTypeSingleNamespace}, + rawConfig: []byte(`{"watchNamespace": {"hello": "there"}}`), + expectedErrMessage: `error unmarshalling registry+v1 configuration: invalid value type for field "watchNamespace": expected "string" but got "object"`, + }, + { + name: "rejects bad namespace format", + supportedInstallModes: []v1alpha1.InstallModeType{v1alpha1.InstallModeTypeSingleNamespace}, + rawConfig: []byte(`{"watchNamespace": "bad-Namespace-"}`), + expectedErrMessage: "invalid 'watchNamespace' \"bad-Namespace-\": namespace must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character", + }, + { + name: "rejects with unknown field when install modes {AllNamespaces}", + supportedInstallModes: []v1alpha1.InstallModeType{v1alpha1.InstallModeTypeAllNamespaces}, + rawConfig: []byte(`{"watchNamespace": "some-namespace"}`), + expectedErrMessage: "unknown field \"watchNamespace\"", + }, + { + name: "rejects with unknown field when install modes {MultiNamespace}", + supportedInstallModes: []v1alpha1.InstallModeType{v1alpha1.InstallModeTypeMultiNamespace}, + rawConfig: []byte(`{"watchNamespace": "some-namespace"}`), + expectedErrMessage: "unknown field \"watchNamespace\"", + }, + { + name: "reject with unknown field when install modes {AllNamespaces, MultiNamespace}", + supportedInstallModes: []v1alpha1.InstallModeType{v1alpha1.InstallModeTypeAllNamespaces, v1alpha1.InstallModeTypeMultiNamespace}, + rawConfig: []byte(`{"watchNamespace": "some-namespace"}`), + expectedErrMessage: "unknown field \"watchNamespace\"", + }, + { + name: "reject with unknown field when install modes {OwnNamespace}", + supportedInstallModes: []v1alpha1.InstallModeType{v1alpha1.InstallModeTypeOwnNamespace}, + rawConfig: []byte(`{"watchNamespace": "some-namespace"}`), + expectedErrMessage: "unknown field \"watchNamespace\"", + }, + { + name: "reject with unknown field when install modes {MultiNamespace, OwnNamespace}", + supportedInstallModes: []v1alpha1.InstallModeType{v1alpha1.InstallModeTypeMultiNamespace, v1alpha1.InstallModeTypeOwnNamespace}, + rawConfig: []byte(`{"watchNamespace": "some-namespace"}`), + expectedErrMessage: "unknown field \"watchNamespace\"", + }, + { + name: "accepts when install modes {SingleNamespace} and watchNamespace != install namespace", + supportedInstallModes: []v1alpha1.InstallModeType{v1alpha1.InstallModeTypeSingleNamespace}, + rawConfig: []byte(`{"watchNamespace": "some-namespace"}`), + expectedConfig: &bundle.Config{ + WatchNamespace: ptr.To("some-namespace"), + }, + }, + { + name: "accepts when install modes {AllNamespaces, SingleNamespace} and watchNamespace != install namespace", + supportedInstallModes: []v1alpha1.InstallModeType{v1alpha1.InstallModeTypeAllNamespaces, v1alpha1.InstallModeTypeSingleNamespace}, + rawConfig: []byte(`{"watchNamespace": "some-namespace"}`), + expectedConfig: &bundle.Config{ + WatchNamespace: ptr.To("some-namespace"), + }, + }, + { + name: "accepts when install modes {MultiNamespace, SingleNamespace} and watchNamespace != install namespace", + supportedInstallModes: []v1alpha1.InstallModeType{v1alpha1.InstallModeTypeMultiNamespace, v1alpha1.InstallModeTypeSingleNamespace}, + rawConfig: []byte(`{"watchNamespace": "some-namespace"}`), + expectedConfig: &bundle.Config{ + WatchNamespace: ptr.To("some-namespace"), + }, + }, + { + name: "accepts when install modes {OwnNamespace, SingleNamespace} and watchNamespace != install namespace", + supportedInstallModes: []v1alpha1.InstallModeType{v1alpha1.InstallModeTypeOwnNamespace, v1alpha1.InstallModeTypeSingleNamespace}, + rawConfig: []byte(`{"watchNamespace": "some-namespace"}`), + installNamespace: "not-namespace", + expectedConfig: &bundle.Config{ + WatchNamespace: ptr.To("some-namespace"), + }, + }, + { + name: "rejects when install modes {SingleNamespace} and watchNamespace == install namespace", + supportedInstallModes: []v1alpha1.InstallModeType{v1alpha1.InstallModeTypeSingleNamespace}, + rawConfig: []byte(`{"watchNamespace": "some-namespace"}`), + installNamespace: "some-namespace", + expectedErrMessage: "invalid 'watchNamespace' \"some-namespace\": must not be install namespace (some-namespace)", + }, + { + name: "rejects when install modes {AllNamespaces, SingleNamespace} and watchNamespace == install namespace", + supportedInstallModes: []v1alpha1.InstallModeType{v1alpha1.InstallModeTypeAllNamespaces, v1alpha1.InstallModeTypeSingleNamespace}, + rawConfig: []byte(`{"watchNamespace": "some-namespace"}`), + installNamespace: "some-namespace", + expectedErrMessage: "invalid 'watchNamespace' \"some-namespace\": must not be install namespace (some-namespace)", + }, + { + name: "rejects when install modes {MultiNamespace, SingleNamespace} and watchNamespace == install namespace", + supportedInstallModes: []v1alpha1.InstallModeType{v1alpha1.InstallModeTypeMultiNamespace, v1alpha1.InstallModeTypeSingleNamespace}, + rawConfig: []byte(`{"watchNamespace": "some-namespace"}`), + installNamespace: "some-namespace", + expectedErrMessage: "invalid 'watchNamespace' \"some-namespace\": must not be install namespace (some-namespace)", + }, + { + name: "accepts when install modes {AllNamespaces, OwnNamespace} and watchNamespace == install namespace", + supportedInstallModes: []v1alpha1.InstallModeType{v1alpha1.InstallModeTypeAllNamespaces, v1alpha1.InstallModeTypeOwnNamespace}, + rawConfig: []byte(`{"watchNamespace": "some-namespace"}`), + installNamespace: "some-namespace", + expectedConfig: &bundle.Config{ + WatchNamespace: ptr.To("some-namespace"), + }, + }, + { + name: "accepts when install modes {OwnNamespace, SingleNamespace} and watchNamespace == install namespace", + supportedInstallModes: []v1alpha1.InstallModeType{v1alpha1.InstallModeTypeOwnNamespace, v1alpha1.InstallModeTypeSingleNamespace}, + rawConfig: []byte(`{"watchNamespace": "some-namespace"}`), + installNamespace: "some-namespace", + expectedConfig: &bundle.Config{ + WatchNamespace: ptr.To("some-namespace"), + }, + }, + { + name: "rejects when install modes {AllNamespaces, OwnNamespace} and watchNamespace != install namespace", + supportedInstallModes: []v1alpha1.InstallModeType{v1alpha1.InstallModeTypeAllNamespaces, v1alpha1.InstallModeTypeOwnNamespace}, + rawConfig: []byte(`{"watchNamespace": "some-namespace"}`), + installNamespace: "not-some-namespace", + expectedErrMessage: "invalid 'watchNamespace' \"some-namespace\": must be install namespace (not-some-namespace)", + }, + { + name: "rejects with required field error when install modes {SingleNamespace} and watchNamespace is nil", + supportedInstallModes: []v1alpha1.InstallModeType{v1alpha1.InstallModeTypeSingleNamespace}, + rawConfig: []byte(`{"watchNamespace": null}`), + installNamespace: "not-some-namespace", + expectedErrMessage: "required field \"watchNamespace\" is missing", + }, + { + name: "rejects with required field error when install modes {SingleNamespace, OwnNamespace} and watchNamespace is nil", + supportedInstallModes: []v1alpha1.InstallModeType{v1alpha1.InstallModeTypeSingleNamespace, v1alpha1.InstallModeTypeOwnNamespace}, + rawConfig: []byte(`{"watchNamespace": null}`), + installNamespace: "not-some-namespace", + expectedErrMessage: "required field \"watchNamespace\" is missing", + }, + { + name: "rejects with required field error when install modes {SingleNamespace, MultiNamespace} and watchNamespace is nil", + supportedInstallModes: []v1alpha1.InstallModeType{v1alpha1.InstallModeTypeSingleNamespace, v1alpha1.InstallModeTypeMultiNamespace}, + rawConfig: []byte(`{"watchNamespace": null}`), + installNamespace: "not-some-namespace", + expectedErrMessage: "required field \"watchNamespace\" is missing", + }, + { + name: "rejects with required field error when install modes {SingleNamespace, OwnNamespace, MultiNamespace} and watchNamespace is nil", + supportedInstallModes: []v1alpha1.InstallModeType{v1alpha1.InstallModeTypeSingleNamespace, v1alpha1.InstallModeTypeOwnNamespace, v1alpha1.InstallModeTypeMultiNamespace}, + rawConfig: []byte(`{"watchNamespace": null}`), + installNamespace: "not-some-namespace", + expectedErrMessage: "required field \"watchNamespace\" is missing", + }, + { + name: "accepts null watchNamespace when install modes {AllNamespaces, OwnNamespace} and watchNamespace is nil", + supportedInstallModes: []v1alpha1.InstallModeType{v1alpha1.InstallModeTypeAllNamespaces, v1alpha1.InstallModeTypeOwnNamespace}, + rawConfig: []byte(`{"watchNamespace": null}`), + installNamespace: "not-some-namespace", + expectedConfig: &bundle.Config{ + WatchNamespace: nil, + }, + }, + { + name: "accepts null watchNamespace when install modes {AllNamespaces, OwnNamespace, MultiNamespace} and watchNamespace is nil", + supportedInstallModes: []v1alpha1.InstallModeType{v1alpha1.InstallModeTypeAllNamespaces, v1alpha1.InstallModeTypeOwnNamespace, v1alpha1.InstallModeTypeMultiNamespace}, + rawConfig: []byte(`{"watchNamespace": null}`), + installNamespace: "not-some-namespace", + expectedConfig: &bundle.Config{ + WatchNamespace: nil, + }, + }, + { + name: "rejects with format error when install modes are {SingleNamespace, OwnNamespace} and watchNamespace is ''", + supportedInstallModes: []v1alpha1.InstallModeType{v1alpha1.InstallModeTypeSingleNamespace, v1alpha1.InstallModeTypeOwnNamespace}, + rawConfig: []byte(`{"watchNamespace": ""}`), + installNamespace: "not-some-namespace", + expectedErrMessage: "invalid 'watchNamespace' \"\": namespace must consist of lower case alphanumeric characters", + }, + } { + t.Run(tc.name, func(t *testing.T) { + var rv1 bundle.RegistryV1 + if tc.supportedInstallModes != nil { + rv1 = bundle.RegistryV1{ + CSV: clusterserviceversion.Builder(). + WithName("test-operator"). + WithInstallModeSupportFor(tc.supportedInstallModes...). + Build(), + } + } + + config, err := bundle.UnmarshallConfig(tc.rawConfig, rv1, tc.installNamespace) + require.Equal(t, tc.expectedConfig, config) + if tc.expectedErrMessage != "" { + require.Error(t, err) + require.Contains(t, err.Error(), tc.expectedErrMessage) + } else { + require.NoError(t, err) + } + }) + } +} diff --git a/internal/operator-controller/rukpak/render/fake.go b/internal/operator-controller/rukpak/render/fake.go new file mode 100644 index 000000000..c8213d78a --- /dev/null +++ b/internal/operator-controller/rukpak/render/fake.go @@ -0,0 +1,24 @@ +package render + +import ( + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +type FakeCertProvider struct { + InjectCABundleFn func(obj client.Object, cfg CertificateProvisionerConfig) error + AdditionalObjectsFn func(cfg CertificateProvisionerConfig) ([]unstructured.Unstructured, error) + GetCertSecretInfoFn func(cfg CertificateProvisionerConfig) CertSecretInfo +} + +func (f FakeCertProvider) InjectCABundle(obj client.Object, cfg CertificateProvisionerConfig) error { + return f.InjectCABundleFn(obj, cfg) +} + +func (f FakeCertProvider) AdditionalObjects(cfg CertificateProvisionerConfig) ([]unstructured.Unstructured, error) { + return f.AdditionalObjectsFn(cfg) +} + +func (f FakeCertProvider) GetCertSecretInfo(cfg CertificateProvisionerConfig) CertSecretInfo { + return f.GetCertSecretInfoFn(cfg) +} diff --git a/manifests/experimental-e2e.yaml b/manifests/experimental-e2e.yaml index 39ff01d61..1efa8b8d9 100644 --- a/manifests/experimental-e2e.yaml +++ b/manifests/experimental-e2e.yaml @@ -864,10 +864,13 @@ spec: properties: config: description: |- - config contains optional configuration values applied during rendering of the - ClusterExtension's manifests. Values can be specified inline. + config is an optional field used to specify bundle specific configuration + used to configure the bundle. Configuration is bundle specific and a bundle may provide + a configuration schema. When not specified, the default configuration of the resolved bundle will be used. - config is optional. When not specified, the default configuration of the resolved bundle will be used. + config is validated against a configuration schema provided by the resolved bundle. If the bundle does not provide + a configuration schema the final manifests will be derived on a best-effort basis. More information on how + to configure the bundle should be found in its end-user documentation. properties: configType: description: |- @@ -886,6 +889,8 @@ spec: ClusterExtension. inline must be set if configType is 'Inline'. + inline accepts arbitrary JSON/YAML objects. + inline is validation at runtime against the schema provided by the bundle if a schema is provided. type: object x-kubernetes-preserve-unknown-fields: true required: @@ -2183,7 +2188,6 @@ spec: - --health-probe-bind-address=:8081 - --metrics-bind-address=:8443 - --leader-elect - - --feature-gates=WebhookProviderCertManager=true - --feature-gates=SingleOwnNamespaceInstallSupport=true - --feature-gates=PreflightPermissions=true - --feature-gates=HelmChartSupport=true diff --git a/manifests/experimental.yaml b/manifests/experimental.yaml index 86bba145d..664f8599c 100644 --- a/manifests/experimental.yaml +++ b/manifests/experimental.yaml @@ -829,10 +829,13 @@ spec: properties: config: description: |- - config contains optional configuration values applied during rendering of the - ClusterExtension's manifests. Values can be specified inline. + config is an optional field used to specify bundle specific configuration + used to configure the bundle. Configuration is bundle specific and a bundle may provide + a configuration schema. When not specified, the default configuration of the resolved bundle will be used. - config is optional. When not specified, the default configuration of the resolved bundle will be used. + config is validated against a configuration schema provided by the resolved bundle. If the bundle does not provide + a configuration schema the final manifests will be derived on a best-effort basis. More information on how + to configure the bundle should be found in its end-user documentation. properties: configType: description: |- @@ -851,6 +854,8 @@ spec: ClusterExtension. inline must be set if configType is 'Inline'. + inline accepts arbitrary JSON/YAML objects. + inline is validation at runtime against the schema provided by the bundle if a schema is provided. type: object x-kubernetes-preserve-unknown-fields: true required: @@ -2096,7 +2101,6 @@ spec: - --health-probe-bind-address=:8081 - --metrics-bind-address=:8443 - --leader-elect - - --feature-gates=WebhookProviderCertManager=true - --feature-gates=SingleOwnNamespaceInstallSupport=true - --feature-gates=PreflightPermissions=true - --feature-gates=HelmChartSupport=true diff --git a/openshift/operator-controller/manifests-experimental.yaml b/openshift/operator-controller/manifests-experimental.yaml index a64dab908..3e9327535 100644 --- a/openshift/operator-controller/manifests-experimental.yaml +++ b/openshift/operator-controller/manifests-experimental.yaml @@ -352,10 +352,13 @@ spec: properties: config: description: |- - config contains optional configuration values applied during rendering of the - ClusterExtension's manifests. Values can be specified inline. + config is an optional field used to specify bundle specific configuration + used to configure the bundle. Configuration is bundle specific and a bundle may provide + a configuration schema. When not specified, the default configuration of the resolved bundle will be used. - config is optional. When not specified, the default configuration of the resolved bundle will be used. + config is validated against a configuration schema provided by the resolved bundle. If the bundle does not provide + a configuration schema the final manifests will be derived on a best-effort basis. More information on how + to configure the bundle should be found in its end-user documentation. properties: configType: description: |- @@ -374,6 +377,8 @@ spec: ClusterExtension. inline must be set if configType is 'Inline'. + inline accepts arbitrary JSON/YAML objects. + inline is validation at runtime against the schema provided by the bundle if a schema is provided. type: object x-kubernetes-preserve-unknown-fields: true required: diff --git a/requirements.txt b/requirements.txt index b94e422c1..de4e5f983 100644 --- a/requirements.txt +++ b/requirements.txt @@ -27,7 +27,7 @@ python-dateutil==2.9.0.post0 PyYAML==6.0.3 pyyaml_env_tag==1.1 readtime==3.0.0 -regex==2025.9.18 +regex==2025.10.23 requests==2.32.5 six==1.17.0 soupsieve==2.8 diff --git a/test/e2e/webhook_support_test.go b/test/e2e/webhook_support_test.go new file mode 100644 index 000000000..0809efb54 --- /dev/null +++ b/test/e2e/webhook_support_test.go @@ -0,0 +1,240 @@ +package e2e + +import ( + "context" + "fmt" + "os" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + appsv1 "k8s.io/api/apps/v1" + corev1 "k8s.io/api/core/v1" + rbacv1 "k8s.io/api/rbac/v1" + apimeta "k8s.io/apimachinery/pkg/api/meta" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/types" + "k8s.io/client-go/dynamic" + "k8s.io/utils/ptr" + + ocv1 "github.com/operator-framework/operator-controller/api/v1" + utils "github.com/operator-framework/operator-controller/internal/shared/util/testutils" +) + +var dynamicClient dynamic.Interface + +func TestNoop(t *testing.T) { + t.Log("Running experimental-e2e tests") + defer utils.CollectTestArtifacts(t, artifactName, c, cfg) +} + +func TestWebhookSupport(t *testing.T) { + t.Log("Test support for bundles with webhooks") + defer utils.CollectTestArtifacts(t, artifactName, c, cfg) + + if dynamicClient == nil { + var err error + dynamicClient, err = dynamic.NewForConfig(cfg) + require.NoError(t, err) + } + + t.Log("By creating install namespace, and necessary rbac resources") + namespace := corev1.Namespace{ + ObjectMeta: metav1.ObjectMeta{ + Name: "webhook-operator", + }, + } + require.NoError(t, c.Create(t.Context(), &namespace)) + t.Cleanup(func() { + require.NoError(t, c.Delete(context.Background(), &namespace)) + }) + + serviceAccount := corev1.ServiceAccount{ + ObjectMeta: metav1.ObjectMeta{ + Name: "webhook-operator-installer", + Namespace: namespace.GetName(), + }, + } + require.NoError(t, c.Create(t.Context(), &serviceAccount)) + t.Cleanup(func() { + require.NoError(t, c.Delete(context.Background(), &serviceAccount)) + }) + + clusterRoleBinding := &rbacv1.ClusterRoleBinding{ + ObjectMeta: metav1.ObjectMeta{ + Name: "webhook-operator-installer", + }, + Subjects: []rbacv1.Subject{ + { + Kind: "ServiceAccount", + APIGroup: corev1.GroupName, + Name: serviceAccount.GetName(), + Namespace: serviceAccount.GetNamespace(), + }, + }, + RoleRef: rbacv1.RoleRef{ + APIGroup: rbacv1.GroupName, + Kind: "ClusterRole", + Name: "cluster-admin", + }, + } + require.NoError(t, c.Create(t.Context(), clusterRoleBinding)) + t.Cleanup(func() { + require.NoError(t, c.Delete(context.Background(), clusterRoleBinding)) + }) + + t.Log("By creating the webhook-operator ClusterCatalog") + extensionCatalog := &ocv1.ClusterCatalog{ + ObjectMeta: metav1.ObjectMeta{ + Name: "webhook-operator-catalog", + }, + Spec: ocv1.ClusterCatalogSpec{ + Source: ocv1.CatalogSource{ + Type: ocv1.SourceTypeImage, + Image: &ocv1.ImageSource{ + Ref: fmt.Sprintf("%s/e2e/test-catalog:v1", os.Getenv("CLUSTER_REGISTRY_HOST")), + PollIntervalMinutes: ptr.To(1), + }, + }, + }, + } + require.NoError(t, c.Create(t.Context(), extensionCatalog)) + t.Cleanup(func() { + require.NoError(t, c.Delete(context.Background(), extensionCatalog)) + }) + + t.Log("By waiting for the catalog to serve its metadata") + require.EventuallyWithT(t, func(ct *assert.CollectT) { + require.NoError(ct, c.Get(context.Background(), types.NamespacedName{Name: extensionCatalog.GetName()}, extensionCatalog)) + cond := apimeta.FindStatusCondition(extensionCatalog.Status.Conditions, ocv1.TypeServing) + require.NotNil(ct, cond) + require.Equal(ct, metav1.ConditionTrue, cond.Status) + require.Equal(ct, ocv1.ReasonAvailable, cond.Reason) + }, pollDuration, pollInterval) + + t.Log("By installing the webhook-operator ClusterExtension") + clusterExtension := &ocv1.ClusterExtension{ + ObjectMeta: metav1.ObjectMeta{ + Name: "webhook-operator-extension", + }, + Spec: ocv1.ClusterExtensionSpec{ + Source: ocv1.SourceConfig{ + SourceType: "Catalog", + Catalog: &ocv1.CatalogFilter{ + PackageName: "webhook-operator", + Selector: &metav1.LabelSelector{ + MatchLabels: map[string]string{"olm.operatorframework.io/metadata.name": extensionCatalog.Name}, + }, + }, + }, + Namespace: namespace.GetName(), + ServiceAccount: ocv1.ServiceAccountReference{ + Name: serviceAccount.GetName(), + }, + }, + } + require.NoError(t, c.Create(t.Context(), clusterExtension)) + t.Cleanup(func() { + require.NoError(t, c.Delete(context.Background(), clusterExtension)) + }) + + t.Log("By waiting for webhook-operator extension to be installed successfully") + require.EventuallyWithT(t, func(ct *assert.CollectT) { + require.NoError(ct, c.Get(t.Context(), types.NamespacedName{Name: clusterExtension.Name}, clusterExtension)) + cond := apimeta.FindStatusCondition(clusterExtension.Status.Conditions, ocv1.TypeInstalled) + require.NotNil(ct, cond) + require.Equal(ct, metav1.ConditionTrue, cond.Status) + require.Equal(ct, ocv1.ReasonSucceeded, cond.Reason) + require.Contains(ct, cond.Message, "Installed bundle") + require.NotNil(ct, clusterExtension.Status.Install) + require.NotEmpty(ct, clusterExtension.Status.Install.Bundle) + }, pollDuration, pollInterval) + + t.Log("By waiting for webhook-operator deployment to be available") + require.EventuallyWithT(t, func(ct *assert.CollectT) { + deployment := &appsv1.Deployment{} + require.NoError(ct, c.Get(t.Context(), types.NamespacedName{Namespace: namespace.GetName(), Name: "webhook-operator-controller-manager"}, deployment)) + available := false + for _, cond := range deployment.Status.Conditions { + if cond.Type == appsv1.DeploymentAvailable { + available = cond.Status == corev1.ConditionTrue + } + } + require.True(ct, available) + }, pollDuration, pollInterval) + + v1Gvr := schema.GroupVersionResource{ + Group: "webhook.operators.coreos.io", + Version: "v1", + Resource: "webhooktests", + } + v1Client := dynamicClient.Resource(v1Gvr).Namespace(namespace.GetName()) + + t.Log("By eventually seeing that invalid CR creation is rejected by the validating webhook") + require.EventuallyWithT(t, func(ct *assert.CollectT) { + obj := getWebhookOperatorResource("invalid-test-cr", namespace.GetName(), false) + _, err := v1Client.Create(t.Context(), obj, metav1.CreateOptions{}) + require.Error(ct, err) + require.Contains(ct, err.Error(), "Invalid value: false: Spec.Valid must be true") + }, pollDuration, pollInterval) + + var ( + res *unstructured.Unstructured + err error + obj = getWebhookOperatorResource("valid-test-cr", namespace.GetName(), true) + ) + + t.Log("By eventually creating a valid CR") + require.EventuallyWithT(t, func(ct *assert.CollectT) { + res, err = v1Client.Create(t.Context(), obj, metav1.CreateOptions{}) + require.NoError(ct, err) + }, pollDuration, pollInterval) + t.Cleanup(func() { + require.NoError(t, v1Client.Delete(context.Background(), obj.GetName(), metav1.DeleteOptions{})) + }) + + require.Equal(t, map[string]interface{}{ + "valid": true, + "mutate": true, + }, res.Object["spec"]) + + t.Log("By checking a valid CR is converted to v2 by the conversion webhook") + v2Gvr := schema.GroupVersionResource{ + Group: "webhook.operators.coreos.io", + Version: "v2", + Resource: "webhooktests", + } + v2Client := dynamicClient.Resource(v2Gvr).Namespace(namespace.GetName()) + + t.Log("By eventually getting the valid CR with a v2 client") + require.EventuallyWithT(t, func(ct *assert.CollectT) { + res, err = v2Client.Get(t.Context(), obj.GetName(), metav1.GetOptions{}) + require.NoError(ct, err) + }, pollDuration, pollInterval) + + t.Log("and verifying that the CR is correctly converted") + require.Equal(t, map[string]interface{}{ + "conversion": map[string]interface{}{ + "valid": true, + "mutate": true, + }, + }, res.Object["spec"]) +} + +func getWebhookOperatorResource(name string, namespace string, valid bool) *unstructured.Unstructured { + return &unstructured.Unstructured{ + Object: map[string]interface{}{ + "apiVersion": "webhook.operators.coreos.io/v1", + "kind": "webhooktests", + "metadata": map[string]interface{}{ + "name": name, + "namespace": namespace, + }, + "spec": map[string]interface{}{ + "valid": valid, + }, + }, + } +} diff --git a/test/experimental-e2e/experimental_e2e_test.go b/test/experimental-e2e/single_namespace_support_test.go similarity index 55% rename from test/experimental-e2e/experimental_e2e_test.go rename to test/experimental-e2e/single_namespace_support_test.go index fca2511f7..d1ca13465 100644 --- a/test/experimental-e2e/experimental_e2e_test.go +++ b/test/experimental-e2e/single_namespace_support_test.go @@ -15,11 +15,8 @@ import ( apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" apimeta "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" utilruntime "k8s.io/apimachinery/pkg/util/runtime" - "k8s.io/client-go/dynamic" "k8s.io/client-go/rest" "k8s.io/utils/ptr" ctrl "sigs.k8s.io/controller-runtime" @@ -38,9 +35,8 @@ const ( ) var ( - cfg *rest.Config - c client.Client - dynamicClient dynamic.Interface + cfg *rest.Config + c client.Client ) func TestMain(m *testing.M) { @@ -51,9 +47,6 @@ func TestMain(m *testing.M) { c, err = client.New(cfg, client.Options{Scheme: scheme.Scheme}) utilruntime.Must(err) - dynamicClient, err = dynamic.NewForConfig(cfg) - utilruntime.Must(err) - os.Exit(m.Run()) } @@ -62,193 +55,6 @@ func TestNoop(t *testing.T) { defer utils.CollectTestArtifacts(t, artifactName, c, cfg) } -func TestWebhookSupport(t *testing.T) { - t.Log("Test support for bundles with webhooks") - defer utils.CollectTestArtifacts(t, artifactName, c, cfg) - - t.Log("By creating install namespace, and necessary rbac resources") - namespace := corev1.Namespace{ - ObjectMeta: metav1.ObjectMeta{ - Name: "webhook-operator", - }, - } - require.NoError(t, c.Create(t.Context(), &namespace)) - t.Cleanup(func() { - require.NoError(t, c.Delete(context.Background(), &namespace)) - }) - - serviceAccount := corev1.ServiceAccount{ - ObjectMeta: metav1.ObjectMeta{ - Name: "webhook-operator-installer", - Namespace: namespace.GetName(), - }, - } - require.NoError(t, c.Create(t.Context(), &serviceAccount)) - t.Cleanup(func() { - require.NoError(t, c.Delete(context.Background(), &serviceAccount)) - }) - - clusterRoleBinding := &rbacv1.ClusterRoleBinding{ - ObjectMeta: metav1.ObjectMeta{ - Name: "webhook-operator-installer", - }, - Subjects: []rbacv1.Subject{ - { - Kind: "ServiceAccount", - APIGroup: corev1.GroupName, - Name: serviceAccount.GetName(), - Namespace: serviceAccount.GetNamespace(), - }, - }, - RoleRef: rbacv1.RoleRef{ - APIGroup: rbacv1.GroupName, - Kind: "ClusterRole", - Name: "cluster-admin", - }, - } - require.NoError(t, c.Create(t.Context(), clusterRoleBinding)) - t.Cleanup(func() { - require.NoError(t, c.Delete(context.Background(), clusterRoleBinding)) - }) - - t.Log("By creating the webhook-operator ClusterCatalog") - extensionCatalog := &ocv1.ClusterCatalog{ - ObjectMeta: metav1.ObjectMeta{ - Name: "webhook-operator-catalog", - }, - Spec: ocv1.ClusterCatalogSpec{ - Source: ocv1.CatalogSource{ - Type: ocv1.SourceTypeImage, - Image: &ocv1.ImageSource{ - Ref: fmt.Sprintf("%s/e2e/test-catalog:v1", os.Getenv("CLUSTER_REGISTRY_HOST")), - PollIntervalMinutes: ptr.To(1), - }, - }, - }, - } - require.NoError(t, c.Create(t.Context(), extensionCatalog)) - t.Cleanup(func() { - require.NoError(t, c.Delete(context.Background(), extensionCatalog)) - }) - - t.Log("By waiting for the catalog to serve its metadata") - require.EventuallyWithT(t, func(ct *assert.CollectT) { - require.NoError(ct, c.Get(context.Background(), types.NamespacedName{Name: extensionCatalog.GetName()}, extensionCatalog)) - cond := apimeta.FindStatusCondition(extensionCatalog.Status.Conditions, ocv1.TypeServing) - require.NotNil(ct, cond) - require.Equal(ct, metav1.ConditionTrue, cond.Status) - require.Equal(ct, ocv1.ReasonAvailable, cond.Reason) - }, pollDuration, pollInterval) - - t.Log("By installing the webhook-operator ClusterExtension") - clusterExtension := &ocv1.ClusterExtension{ - ObjectMeta: metav1.ObjectMeta{ - Name: "webhook-operator-extension", - }, - Spec: ocv1.ClusterExtensionSpec{ - Source: ocv1.SourceConfig{ - SourceType: "Catalog", - Catalog: &ocv1.CatalogFilter{ - PackageName: "webhook-operator", - Selector: &metav1.LabelSelector{ - MatchLabels: map[string]string{"olm.operatorframework.io/metadata.name": extensionCatalog.Name}, - }, - }, - }, - Namespace: namespace.GetName(), - ServiceAccount: ocv1.ServiceAccountReference{ - Name: serviceAccount.GetName(), - }, - }, - } - require.NoError(t, c.Create(t.Context(), clusterExtension)) - t.Cleanup(func() { - require.NoError(t, c.Delete(context.Background(), clusterExtension)) - }) - - t.Log("By waiting for webhook-operator extension to be installed successfully") - require.EventuallyWithT(t, func(ct *assert.CollectT) { - require.NoError(ct, c.Get(t.Context(), types.NamespacedName{Name: clusterExtension.Name}, clusterExtension)) - cond := apimeta.FindStatusCondition(clusterExtension.Status.Conditions, ocv1.TypeInstalled) - require.NotNil(ct, cond) - require.Equal(ct, metav1.ConditionTrue, cond.Status) - require.Equal(ct, ocv1.ReasonSucceeded, cond.Reason) - require.Contains(ct, cond.Message, "Installed bundle") - require.NotNil(ct, clusterExtension.Status.Install) - require.NotEmpty(ct, clusterExtension.Status.Install.Bundle) - }, pollDuration, pollInterval) - - t.Log("By waiting for webhook-operator deployment to be available") - require.EventuallyWithT(t, func(ct *assert.CollectT) { - deployment := &appsv1.Deployment{} - require.NoError(ct, c.Get(t.Context(), types.NamespacedName{Namespace: namespace.GetName(), Name: "webhook-operator-controller-manager"}, deployment)) - available := false - for _, cond := range deployment.Status.Conditions { - if cond.Type == appsv1.DeploymentAvailable { - available = cond.Status == corev1.ConditionTrue - } - } - require.True(ct, available) - }, pollDuration, pollInterval) - - v1Gvr := schema.GroupVersionResource{ - Group: "webhook.operators.coreos.io", - Version: "v1", - Resource: "webhooktests", - } - v1Client := dynamicClient.Resource(v1Gvr).Namespace(namespace.GetName()) - - t.Log("By eventually seeing that invalid CR creation is rejected by the validating webhook") - require.EventuallyWithT(t, func(ct *assert.CollectT) { - obj := getWebhookOperatorResource("invalid-test-cr", namespace.GetName(), false) - _, err := v1Client.Create(t.Context(), obj, metav1.CreateOptions{}) - require.Error(ct, err) - require.Contains(ct, err.Error(), "Invalid value: false: Spec.Valid must be true") - }, pollDuration, pollInterval) - - var ( - res *unstructured.Unstructured - err error - obj = getWebhookOperatorResource("valid-test-cr", namespace.GetName(), true) - ) - - t.Log("By eventually creating a valid CR") - require.EventuallyWithT(t, func(ct *assert.CollectT) { - res, err = v1Client.Create(t.Context(), obj, metav1.CreateOptions{}) - require.NoError(ct, err) - }, pollDuration, pollInterval) - t.Cleanup(func() { - require.NoError(t, v1Client.Delete(context.Background(), obj.GetName(), metav1.DeleteOptions{})) - }) - - require.Equal(t, map[string]interface{}{ - "valid": true, - "mutate": true, - }, res.Object["spec"]) - - t.Log("By checking a valid CR is converted to v2 by the conversion webhook") - v2Gvr := schema.GroupVersionResource{ - Group: "webhook.operators.coreos.io", - Version: "v2", - Resource: "webhooktests", - } - v2Client := dynamicClient.Resource(v2Gvr).Namespace(namespace.GetName()) - - t.Log("By eventually getting the valid CR with a v2 client") - require.EventuallyWithT(t, func(ct *assert.CollectT) { - res, err = v2Client.Get(t.Context(), obj.GetName(), metav1.GetOptions{}) - require.NoError(ct, err) - }, pollDuration, pollInterval) - - t.Log("and verifying that the CR is correctly converted") - require.Equal(t, map[string]interface{}{ - "conversion": map[string]interface{}{ - "valid": true, - "mutate": true, - }, - }, res.Object["spec"]) -} - func TestClusterExtensionConfigSupport(t *testing.T) { t.Log("Test support for cluster extension config") defer utils.CollectTestArtifacts(t, artifactName, c, cfg) @@ -443,19 +249,3 @@ func TestClusterExtensionVersionUpdate(t *testing.T) { require.Len(ct, cerList.Items, 2) }, pollDuration, pollInterval) } - -func getWebhookOperatorResource(name string, namespace string, valid bool) *unstructured.Unstructured { - return &unstructured.Unstructured{ - Object: map[string]interface{}{ - "apiVersion": "webhook.operators.coreos.io/v1", - "kind": "webhooktests", - "metadata": map[string]interface{}{ - "name": name, - "namespace": namespace, - }, - "spec": map[string]interface{}{ - "valid": valid, - }, - }, - } -} diff --git a/vendor/github.com/docker/cli/cli/config/memorystore/store.go b/vendor/github.com/docker/cli/cli/config/memorystore/store.go index 199083464..267e1e343 100644 --- a/vendor/github.com/docker/cli/cli/config/memorystore/store.go +++ b/vendor/github.com/docker/cli/cli/config/memorystore/store.go @@ -3,7 +3,6 @@ package memorystore import ( - "errors" "fmt" "maps" "os" @@ -13,12 +12,17 @@ import ( "github.com/docker/cli/cli/config/types" ) -var errValueNotFound = errors.New("value not found") +// notFoundErr is the error returned when a plugin could not be found. +type notFoundErr string -func IsErrValueNotFound(err error) bool { - return errors.Is(err, errValueNotFound) +func (notFoundErr) NotFound() {} + +func (e notFoundErr) Error() string { + return string(e) } +var errValueNotFound notFoundErr = "value not found" + type Config struct { lock sync.RWMutex memoryCredentials map[string]types.AuthConfig diff --git a/vendor/github.com/klauspost/compress/flate/deflate.go b/vendor/github.com/klauspost/compress/flate/deflate.go index af53fb860..4e92f5998 100644 --- a/vendor/github.com/klauspost/compress/flate/deflate.go +++ b/vendor/github.com/klauspost/compress/flate/deflate.go @@ -6,11 +6,12 @@ package flate import ( - "encoding/binary" "errors" "fmt" "io" "math" + + "github.com/klauspost/compress/internal/le" ) const ( @@ -234,12 +235,9 @@ func (d *compressor) fillWindow(b []byte) { // Calculate 256 hashes at the time (more L1 cache hits) loops := (n + 256 - minMatchLength) / 256 - for j := 0; j < loops; j++ { + for j := range loops { startindex := j * 256 - end := startindex + 256 + minMatchLength - 1 - if end > n { - end = n - } + end := min(startindex+256+minMatchLength-1, n) tocheck := d.window[startindex:end] dstSize := len(tocheck) - minMatchLength + 1 @@ -269,18 +267,12 @@ func (d *compressor) fillWindow(b []byte) { // We only look at chainCount possibilities before giving up. // pos = s.index, prevHead = s.chainHead-s.hashOffset, prevLength=minMatchLength-1, lookahead func (d *compressor) findMatch(pos int, prevHead int, lookahead int) (length, offset int, ok bool) { - minMatchLook := maxMatchLength - if lookahead < minMatchLook { - minMatchLook = lookahead - } + minMatchLook := min(lookahead, maxMatchLength) win := d.window[0 : pos+minMatchLook] // We quit when we get a match that's at least nice long - nice := len(win) - pos - if d.nice < nice { - nice = d.nice - } + nice := min(d.nice, len(win)-pos) // If we've got a match that's good enough, only look in 1/4 the chain. tries := d.chain @@ -288,10 +280,7 @@ func (d *compressor) findMatch(pos int, prevHead int, lookahead int) (length, of wEnd := win[pos+length] wPos := win[pos:] - minIndex := pos - windowSize - if minIndex < 0 { - minIndex = 0 - } + minIndex := max(pos-windowSize, 0) offset = 0 if d.chain < 100 { @@ -374,7 +363,7 @@ func (d *compressor) writeStoredBlock(buf []byte) error { // of the supplied slice. // The caller must ensure that len(b) >= 4. func hash4(b []byte) uint32 { - return hash4u(binary.LittleEndian.Uint32(b), hashBits) + return hash4u(le.Load32(b, 0), hashBits) } // hash4 returns the hash of u to fit in a hash table with h bits. @@ -389,7 +378,7 @@ func bulkHash4(b []byte, dst []uint32) { if len(b) < 4 { return } - hb := binary.LittleEndian.Uint32(b) + hb := le.Load32(b, 0) dst[0] = hash4u(hb, hashBits) end := len(b) - 4 + 1 @@ -480,10 +469,7 @@ func (d *compressor) deflateLazy() { prevOffset := s.offset s.length = minMatchLength - 1 s.offset = 0 - minIndex := s.index - windowSize - if minIndex < 0 { - minIndex = 0 - } + minIndex := max(s.index-windowSize, 0) if s.chainHead-s.hashOffset >= minIndex && lookahead > prevLength && prevLength < d.lazy { if newLength, newOffset, ok := d.findMatch(s.index, s.chainHead-s.hashOffset, lookahead); ok { @@ -503,10 +489,7 @@ func (d *compressor) deflateLazy() { if prevLength < maxMatchLength-checkOff { prevIndex := s.index - 1 if prevIndex+prevLength < s.maxInsertIndex { - end := lookahead - if lookahead > maxMatchLength+checkOff { - end = maxMatchLength + checkOff - } + end := min(lookahead, maxMatchLength+checkOff) end += prevIndex // Hash at match end. @@ -603,15 +586,9 @@ func (d *compressor) deflateLazy() { // table. newIndex := s.index + prevLength - 1 // Calculate missing hashes - end := newIndex - if end > s.maxInsertIndex { - end = s.maxInsertIndex - } + end := min(newIndex, s.maxInsertIndex) end += minMatchLength - 1 - startindex := s.index + 1 - if startindex > s.maxInsertIndex { - startindex = s.maxInsertIndex - } + startindex := min(s.index+1, s.maxInsertIndex) tocheck := d.window[startindex:end] dstSize := len(tocheck) - minMatchLength + 1 if dstSize > 0 { diff --git a/vendor/github.com/klauspost/compress/flate/dict_decoder.go b/vendor/github.com/klauspost/compress/flate/dict_decoder.go index bb36351a5..cb855abc4 100644 --- a/vendor/github.com/klauspost/compress/flate/dict_decoder.go +++ b/vendor/github.com/klauspost/compress/flate/dict_decoder.go @@ -104,10 +104,7 @@ func (dd *dictDecoder) writeCopy(dist, length int) int { dstBase := dd.wrPos dstPos := dstBase srcPos := dstPos - dist - endPos := dstPos + length - if endPos > len(dd.hist) { - endPos = len(dd.hist) - } + endPos := min(dstPos+length, len(dd.hist)) // Copy non-overlapping section after destination position. // diff --git a/vendor/github.com/klauspost/compress/flate/fast_encoder.go b/vendor/github.com/klauspost/compress/flate/fast_encoder.go index 0e8b1630c..791c9dcbf 100644 --- a/vendor/github.com/klauspost/compress/flate/fast_encoder.go +++ b/vendor/github.com/klauspost/compress/flate/fast_encoder.go @@ -7,7 +7,6 @@ package flate import ( "fmt" - "math/bits" "github.com/klauspost/compress/internal/le" ) @@ -151,29 +150,9 @@ func (e *fastGen) matchlen(s, t int, src []byte) int32 { panic(fmt.Sprint(s, "-", t, "(", s-t, ") > maxMatchLength (", maxMatchOffset, ")")) } } - s1 := min(s+maxMatchLength-4, len(src)) - left := s1 - s - n := int32(0) - for left >= 8 { - diff := le.Load64(src, s) ^ le.Load64(src, t) - if diff != 0 { - return n + int32(bits.TrailingZeros64(diff)>>3) - } - s += 8 - t += 8 - n += 8 - left -= 8 - } - - a := src[s:s1] + a := src[s:min(s+maxMatchLength-4, len(src))] b := src[t:] - for i := range a { - if a[i] != b[i] { - break - } - n++ - } - return n + return int32(matchLen(a, b)) } // matchlenLong will return the match length between offsets and t in src. @@ -193,29 +172,7 @@ func (e *fastGen) matchlenLong(s, t int, src []byte) int32 { panic(fmt.Sprint(s, "-", t, "(", s-t, ") > maxMatchLength (", maxMatchOffset, ")")) } } - // Extend the match to be as long as possible. - left := len(src) - s - n := int32(0) - for left >= 8 { - diff := le.Load64(src, s) ^ le.Load64(src, t) - if diff != 0 { - return n + int32(bits.TrailingZeros64(diff)>>3) - } - s += 8 - t += 8 - n += 8 - left -= 8 - } - - a := src[s:] - b := src[t:] - for i := range a { - if a[i] != b[i] { - break - } - n++ - } - return n + return int32(matchLen(src[s:], src[t:])) } // Reset the encoding table. diff --git a/vendor/github.com/klauspost/compress/flate/huffman_bit_writer.go b/vendor/github.com/klauspost/compress/flate/huffman_bit_writer.go index afdc8c053..03a179697 100644 --- a/vendor/github.com/klauspost/compress/flate/huffman_bit_writer.go +++ b/vendor/github.com/klauspost/compress/flate/huffman_bit_writer.go @@ -211,7 +211,9 @@ func (w *huffmanBitWriter) flush() { n++ } w.bits = 0 - w.write(w.bytes[:n]) + if n > 0 { + w.write(w.bytes[:n]) + } w.nbytes = 0 } @@ -303,10 +305,7 @@ func (w *huffmanBitWriter) generateCodegen(numLiterals int, numOffsets int, litE w.codegenFreq[size]++ count-- for count >= 3 { - n := 6 - if n > count { - n = count - } + n := min(6, count) codegen[outIndex] = 16 outIndex++ codegen[outIndex] = uint8(n - 3) @@ -316,10 +315,7 @@ func (w *huffmanBitWriter) generateCodegen(numLiterals int, numOffsets int, litE } } else { for count >= 11 { - n := 138 - if n > count { - n = count - } + n := min(138, count) codegen[outIndex] = 18 outIndex++ codegen[outIndex] = uint8(n - 11) @@ -438,8 +434,8 @@ func (w *huffmanBitWriter) writeOutBits() { w.nbits -= 48 n := w.nbytes - // We over-write, but faster... - le.Store64(w.bytes[n:], bits) + // We overwrite, but faster... + le.Store64(w.bytes[:], n, bits) n += 6 if n >= bufferFlushSize { @@ -472,7 +468,7 @@ func (w *huffmanBitWriter) writeDynamicHeader(numLiterals int, numOffsets int, n w.writeBits(int32(numOffsets-1), 5) w.writeBits(int32(numCodegens-4), 4) - for i := 0; i < numCodegens; i++ { + for i := range numCodegens { value := uint(w.codegenEncoding.codes[codegenOrder[i]].len()) w.writeBits(int32(value), 3) } @@ -650,7 +646,7 @@ func (w *huffmanBitWriter) writeBlockDynamic(tokens *tokens, eof bool, input []b w.lastHeader = 0 } - numLiterals, numOffsets := w.indexTokens(tokens, !sync) + numLiterals, numOffsets := w.indexTokens(tokens, fillReuse && !sync) extraBits := 0 ssize, storable := w.storedSize(input) @@ -855,8 +851,7 @@ func (w *huffmanBitWriter) writeTokens(tokens []token, leCodes, oeCodes []hcode) bits |= c.code64() << (nbits & 63) nbits += c.len() if nbits >= 48 { - le.Store64(w.bytes[nbytes:], bits) - //*(*uint64)(unsafe.Pointer(&w.bytes[nbytes])) = bits + le.Store64(w.bytes[:], nbytes, bits) bits >>= 48 nbits -= 48 nbytes += 6 @@ -883,8 +878,7 @@ func (w *huffmanBitWriter) writeTokens(tokens []token, leCodes, oeCodes []hcode) bits |= c.code64() << (nbits & 63) nbits += c.len() if nbits >= 48 { - le.Store64(w.bytes[nbytes:], bits) - //*(*uint64)(unsafe.Pointer(&w.bytes[nbytes])) = bits + le.Store64(w.bytes[:], nbytes, bits) bits >>= 48 nbits -= 48 nbytes += 6 @@ -906,8 +900,7 @@ func (w *huffmanBitWriter) writeTokens(tokens []token, leCodes, oeCodes []hcode) bits |= uint64(extraLength) << (nbits & 63) nbits += extraLengthBits if nbits >= 48 { - le.Store64(w.bytes[nbytes:], bits) - //*(*uint64)(unsafe.Pointer(&w.bytes[nbytes])) = bits + le.Store64(w.bytes[:], nbytes, bits) bits >>= 48 nbits -= 48 nbytes += 6 @@ -932,8 +925,7 @@ func (w *huffmanBitWriter) writeTokens(tokens []token, leCodes, oeCodes []hcode) bits |= c.code64() << (nbits & 63) nbits += c.len() if nbits >= 48 { - le.Store64(w.bytes[nbytes:], bits) - //*(*uint64)(unsafe.Pointer(&w.bytes[nbytes])) = bits + le.Store64(w.bytes[:], nbytes, bits) bits >>= 48 nbits -= 48 nbytes += 6 @@ -954,8 +946,7 @@ func (w *huffmanBitWriter) writeTokens(tokens []token, leCodes, oeCodes []hcode) bits |= uint64((offset-(offsetComb>>8))&matchOffsetOnlyMask) << (nbits & 63) nbits += uint8(offsetComb) if nbits >= 48 { - le.Store64(w.bytes[nbytes:], bits) - //*(*uint64)(unsafe.Pointer(&w.bytes[nbytes])) = bits + le.Store64(w.bytes[:], nbytes, bits) bits >>= 48 nbits -= 48 nbytes += 6 @@ -1108,7 +1099,7 @@ func (w *huffmanBitWriter) writeBlockHuff(eof bool, input []byte, sync bool) { // We must have at least 48 bits free. if nbits >= 8 { n := nbits >> 3 - le.Store64(w.bytes[nbytes:], bits) + le.Store64(w.bytes[:], nbytes, bits) bits >>= (n * 8) & 63 nbits -= n * 8 nbytes += n @@ -1137,8 +1128,7 @@ func (w *huffmanBitWriter) writeBlockHuff(eof bool, input []byte, sync bool) { // Remaining... for _, t := range input { if nbits >= 48 { - le.Store64(w.bytes[nbytes:], bits) - //*(*uint64)(unsafe.Pointer(&w.bytes[nbytes])) = bits + le.Store64(w.bytes[:], nbytes, bits) bits >>= 48 nbits -= 48 nbytes += 6 diff --git a/vendor/github.com/klauspost/compress/flate/huffman_code.go b/vendor/github.com/klauspost/compress/flate/huffman_code.go index be7b58b47..5f901bd0f 100644 --- a/vendor/github.com/klauspost/compress/flate/huffman_code.go +++ b/vendor/github.com/klauspost/compress/flate/huffman_code.go @@ -91,7 +91,7 @@ func generateFixedLiteralEncoding() *huffmanEncoder { h := newHuffmanEncoder(literalCount) codes := h.codes var ch uint16 - for ch = 0; ch < literalCount; ch++ { + for ch = range uint16(literalCount) { var bits uint16 var size uint8 switch { diff --git a/vendor/github.com/klauspost/compress/flate/inflate.go b/vendor/github.com/klauspost/compress/flate/inflate.go index 0d7b437f1..6e90126db 100644 --- a/vendor/github.com/klauspost/compress/flate/inflate.go +++ b/vendor/github.com/klauspost/compress/flate/inflate.go @@ -485,7 +485,7 @@ func (f *decompressor) readHuffman() error { f.nb -= 5 + 5 + 4 // (HCLEN+4)*3 bits: code lengths in the magic codeOrder order. - for i := 0; i < nclen; i++ { + for i := range nclen { for f.nb < 3 { if err := f.moreBits(); err != nil { return err @@ -776,7 +776,7 @@ func fixedHuffmanDecoderInit() { fixedOnce.Do(func() { // These come from the RFC section 3.2.6. var bits [288]int - for i := 0; i < 144; i++ { + for i := range 144 { bits[i] = 8 } for i := 144; i < 256; i++ { diff --git a/vendor/github.com/klauspost/compress/flate/level5.go b/vendor/github.com/klauspost/compress/flate/level5.go index 6e5c21502..a22ad7d12 100644 --- a/vendor/github.com/klauspost/compress/flate/level5.go +++ b/vendor/github.com/klauspost/compress/flate/level5.go @@ -677,10 +677,7 @@ func (e *fastEncL5Window) matchlen(s, t int32, src []byte) int32 { panic(fmt.Sprint(s, "-", t, "(", s-t, ") > maxMatchLength (", maxMatchOffset, ")")) } } - s1 := int(s) + maxMatchLength - 4 - if s1 > len(src) { - s1 = len(src) - } + s1 := min(int(s)+maxMatchLength-4, len(src)) // Extend the match to be as long as possible. return int32(matchLen(src[s:s1], src[t:])) diff --git a/vendor/github.com/klauspost/compress/flate/stateless.go b/vendor/github.com/klauspost/compress/flate/stateless.go index 13b9b100d..90b74f7ac 100644 --- a/vendor/github.com/klauspost/compress/flate/stateless.go +++ b/vendor/github.com/klauspost/compress/flate/stateless.go @@ -56,7 +56,7 @@ func NewStatelessWriter(dst io.Writer) io.WriteCloser { // bitWriterPool contains bit writers that can be reused. var bitWriterPool = sync.Pool{ - New: func() interface{} { + New: func() any { return newHuffmanBitWriter(nil) }, } @@ -184,7 +184,7 @@ func statelessEnc(dst *tokens, src []byte, startAt int16) { // Index until startAt if startAt > 0 { cv := load3232(src, 0) - for i := int16(0); i < startAt; i++ { + for i := range startAt { table[hashSL(cv)] = tableEntry{offset: i} cv = (cv >> 8) | (uint32(src[i+4]) << 24) } diff --git a/vendor/github.com/klauspost/compress/fse/bitwriter.go b/vendor/github.com/klauspost/compress/fse/bitwriter.go index e82fa3bb7..d58b3fe42 100644 --- a/vendor/github.com/klauspost/compress/fse/bitwriter.go +++ b/vendor/github.com/klauspost/compress/fse/bitwriter.go @@ -143,7 +143,7 @@ func (b *bitWriter) flush32() { // flushAlign will flush remaining full bytes and align to next byte boundary. func (b *bitWriter) flushAlign() { nbBytes := (b.nBits + 7) >> 3 - for i := uint8(0); i < nbBytes; i++ { + for i := range nbBytes { b.out = append(b.out, byte(b.bitContainer>>(i*8))) } b.nBits = 0 diff --git a/vendor/github.com/klauspost/compress/fse/compress.go b/vendor/github.com/klauspost/compress/fse/compress.go index 074018d8f..8c8baa4fc 100644 --- a/vendor/github.com/klauspost/compress/fse/compress.go +++ b/vendor/github.com/klauspost/compress/fse/compress.go @@ -396,7 +396,7 @@ func (s *Scratch) buildCTable() error { if v > largeLimit { s.zeroBits = true } - for nbOccurrences := int16(0); nbOccurrences < v; nbOccurrences++ { + for range v { tableSymbol[position] = symbol position = (position + step) & tableMask for position > highThreshold { diff --git a/vendor/github.com/klauspost/compress/gzhttp/compress.go b/vendor/github.com/klauspost/compress/gzhttp/compress.go index 52e3077ec..d621a3e91 100644 --- a/vendor/github.com/klauspost/compress/gzhttp/compress.go +++ b/vendor/github.com/klauspost/compress/gzhttp/compress.go @@ -103,10 +103,7 @@ func (w *GzipResponseWriter) Write(b []byte) (int, error) { // Save the write into a buffer for later use in GZIP responseWriter // (if content is long enough) or at close with regular responseWriter. - wantBuf := 512 - if w.minSize > wantBuf { - wantBuf = w.minSize - } + wantBuf := max(w.minSize, 512) if w.jitterBuffer > 0 && w.jitterBuffer > wantBuf { wantBuf = w.jitterBuffer } @@ -455,7 +452,7 @@ func GzipHandler(h http.Handler) http.HandlerFunc { return defaultWrapper(h) } -var grwPool = sync.Pool{New: func() interface{} { return &GzipResponseWriter{} }} +var grwPool = sync.Pool{New: func() any { return &GzipResponseWriter{} }} // NewWrapper returns a reusable wrapper with the supplied options. func NewWrapper(opts ...option) (func(http.Handler) http.HandlerFunc, error) { @@ -890,8 +887,8 @@ func parseCoding(s string) (coding string, qvalue float64, err error) { if n == 0 { coding = strings.ToLower(part) - } else if strings.HasPrefix(part, "q=") { - qvalue, err = strconv.ParseFloat(strings.TrimPrefix(part, "q="), 64) + } else if after, ok := strings.CutPrefix(part, "q="); ok { + qvalue, err = strconv.ParseFloat(after, 64) if qvalue < 0.0 { qvalue = 0.0 diff --git a/vendor/github.com/klauspost/compress/gzhttp/transport.go b/vendor/github.com/klauspost/compress/gzhttp/transport.go index 3914a06e0..d4720a44e 100644 --- a/vendor/github.com/klauspost/compress/gzhttp/transport.go +++ b/vendor/github.com/klauspost/compress/gzhttp/transport.go @@ -196,10 +196,10 @@ func lower(b byte) byte { var zstdReaderPool sync.Pool // zstdReader wraps a response body so it can lazily -// call gzip.NewReader on the first call to Read +// call zstd.NewReader on the first call to Read type zstdReader struct { body io.ReadCloser // underlying HTTP/1 response body framing - zr *zstd.Decoder // lazily-initialized gzip reader + zr *zstd.Decoder // lazily-initialized zstd reader zerr error // any error from zstd.NewReader; sticky } @@ -208,14 +208,12 @@ func (zr *zstdReader) Read(p []byte) (n int, err error) { return 0, zr.zerr } if zr.zr == nil { - if zr.zerr == nil { - reader, ok := zstdReaderPool.Get().(*zstd.Decoder) - if ok { - zr.zerr = reader.Reset(zr.body) - zr.zr = reader - } else { - zr.zr, zr.zerr = zstd.NewReader(zr.body, zstd.WithDecoderLowmem(true), zstd.WithDecoderMaxWindow(32<<20), zstd.WithDecoderConcurrency(1)) - } + reader, ok := zstdReaderPool.Get().(*zstd.Decoder) + if ok { + zr.zerr = reader.Reset(zr.body) + zr.zr = reader + } else { + zr.zr, zr.zerr = zstd.NewReader(zr.body, zstd.WithDecoderLowmem(true), zstd.WithDecoderMaxWindow(32<<20), zstd.WithDecoderConcurrency(1)) } if zr.zerr != nil { return 0, zr.zerr diff --git a/vendor/github.com/klauspost/compress/gzhttp/writer/gzkp/gzkp.go b/vendor/github.com/klauspost/compress/gzhttp/writer/gzkp/gzkp.go index 1930af12e..5db2f7c43 100644 --- a/vendor/github.com/klauspost/compress/gzhttp/writer/gzkp/gzkp.go +++ b/vendor/github.com/klauspost/compress/gzhttp/writer/gzkp/gzkp.go @@ -35,7 +35,7 @@ func poolIndex(level int) int { func addLevelPool(level int) { gzipWriterPools[poolIndex(level)] = &sync.Pool{ - New: func() interface{} { + New: func() any { // NewWriterLevel only returns error on a bad level, we are guaranteeing // that this will be a valid level so it is okay to ignore the returned // error. diff --git a/vendor/github.com/klauspost/compress/huff0/bitwriter.go b/vendor/github.com/klauspost/compress/huff0/bitwriter.go index 0ebc9aaac..41db94cde 100644 --- a/vendor/github.com/klauspost/compress/huff0/bitwriter.go +++ b/vendor/github.com/klauspost/compress/huff0/bitwriter.go @@ -85,7 +85,7 @@ func (b *bitWriter) flush32() { // flushAlign will flush remaining full bytes and align to next byte boundary. func (b *bitWriter) flushAlign() { nbBytes := (b.nBits + 7) >> 3 - for i := uint8(0); i < nbBytes; i++ { + for i := range nbBytes { b.out = append(b.out, byte(b.bitContainer>>(i*8))) } b.nBits = 0 diff --git a/vendor/github.com/klauspost/compress/huff0/compress.go b/vendor/github.com/klauspost/compress/huff0/compress.go index 84aa3d12f..a97cf1b5d 100644 --- a/vendor/github.com/klauspost/compress/huff0/compress.go +++ b/vendor/github.com/klauspost/compress/huff0/compress.go @@ -276,7 +276,7 @@ func (s *Scratch) compress4X(src []byte) ([]byte, error) { offsetIdx := len(s.Out) s.Out = append(s.Out, sixZeros[:]...) - for i := 0; i < 4; i++ { + for i := range 4 { toDo := src if len(toDo) > segmentSize { toDo = toDo[:segmentSize] @@ -312,7 +312,7 @@ func (s *Scratch) compress4Xp(src []byte) ([]byte, error) { segmentSize := (len(src) + 3) / 4 var wg sync.WaitGroup wg.Add(4) - for i := 0; i < 4; i++ { + for i := range 4 { toDo := src if len(toDo) > segmentSize { toDo = toDo[:segmentSize] @@ -326,7 +326,7 @@ func (s *Scratch) compress4Xp(src []byte) ([]byte, error) { }(i) } wg.Wait() - for i := 0; i < 4; i++ { + for i := range 4 { o := s.tmpOut[i] if len(o) > math.MaxUint16 { // We cannot store the size in the jump table diff --git a/vendor/github.com/klauspost/compress/huff0/decompress.go b/vendor/github.com/klauspost/compress/huff0/decompress.go index 0f56b02d7..7d0efa881 100644 --- a/vendor/github.com/klauspost/compress/huff0/decompress.go +++ b/vendor/github.com/klauspost/compress/huff0/decompress.go @@ -626,7 +626,7 @@ func (d *Decoder) decompress4X8bit(dst, src []byte) ([]byte, error) { var br [4]bitReaderBytes start := 6 - for i := 0; i < 3; i++ { + for i := range 3 { length := int(src[i*2]) | (int(src[i*2+1]) << 8) if start+length >= len(src) { return nil, errors.New("truncated input (or invalid offset)") @@ -798,10 +798,7 @@ func (d *Decoder) decompress4X8bit(dst, src []byte) ([]byte, error) { remainBytes := dstEvery - (decoded / 4) for i := range br { offset := dstEvery * i - endsAt := offset + remainBytes - if endsAt > len(out) { - endsAt = len(out) - } + endsAt := min(offset+remainBytes, len(out)) br := &br[i] bitsLeft := br.remaining() for bitsLeft > 0 { @@ -864,7 +861,7 @@ func (d *Decoder) decompress4X8bit(dst, src []byte) ([]byte, error) { func (d *Decoder) decompress4X8bitExactly(dst, src []byte) ([]byte, error) { var br [4]bitReaderBytes start := 6 - for i := 0; i < 3; i++ { + for i := range 3 { length := int(src[i*2]) | (int(src[i*2+1]) << 8) if start+length >= len(src) { return nil, errors.New("truncated input (or invalid offset)") @@ -1035,10 +1032,7 @@ func (d *Decoder) decompress4X8bitExactly(dst, src []byte) ([]byte, error) { remainBytes := dstEvery - (decoded / 4) for i := range br { offset := dstEvery * i - endsAt := offset + remainBytes - if endsAt > len(out) { - endsAt = len(out) - } + endsAt := min(offset+remainBytes, len(out)) br := &br[i] bitsLeft := br.remaining() for bitsLeft > 0 { diff --git a/vendor/github.com/klauspost/compress/huff0/decompress_amd64.go b/vendor/github.com/klauspost/compress/huff0/decompress_amd64.go index ba7e8e6b0..99ddd4af9 100644 --- a/vendor/github.com/klauspost/compress/huff0/decompress_amd64.go +++ b/vendor/github.com/klauspost/compress/huff0/decompress_amd64.go @@ -58,7 +58,7 @@ func (d *Decoder) Decompress4X(dst, src []byte) ([]byte, error) { var br [4]bitReaderShifted // Decode "jump table" start := 6 - for i := 0; i < 3; i++ { + for i := range 3 { length := int(src[i*2]) | (int(src[i*2+1]) << 8) if start+length >= len(src) { return nil, errors.New("truncated input (or invalid offset)") @@ -109,10 +109,7 @@ func (d *Decoder) Decompress4X(dst, src []byte) ([]byte, error) { remainBytes := dstEvery - (decoded / 4) for i := range br { offset := dstEvery * i - endsAt := offset + remainBytes - if endsAt > len(out) { - endsAt = len(out) - } + endsAt := min(offset+remainBytes, len(out)) br := &br[i] bitsLeft := br.remaining() for bitsLeft > 0 { diff --git a/vendor/github.com/klauspost/compress/huff0/huff0.go b/vendor/github.com/klauspost/compress/huff0/huff0.go index 77ecd68e0..67d9e05b6 100644 --- a/vendor/github.com/klauspost/compress/huff0/huff0.go +++ b/vendor/github.com/klauspost/compress/huff0/huff0.go @@ -201,7 +201,7 @@ func (c cTable) write(s *Scratch) error { for i := range hist[:16] { hist[i] = 0 } - for n := uint8(0); n < maxSymbolValue; n++ { + for n := range maxSymbolValue { v := bitsToWeight[c[n].nBits] & 15 huffWeight[n] = v hist[v]++ @@ -271,7 +271,7 @@ func (c cTable) estTableSize(s *Scratch) (sz int, err error) { for i := range hist[:16] { hist[i] = 0 } - for n := uint8(0); n < maxSymbolValue; n++ { + for n := range maxSymbolValue { v := bitsToWeight[c[n].nBits] & 15 huffWeight[n] = v hist[v]++ diff --git a/vendor/github.com/klauspost/compress/internal/le/unsafe_disabled.go b/vendor/github.com/klauspost/compress/internal/le/unsafe_disabled.go index 0cfb5c0e2..4f2a0d8c5 100644 --- a/vendor/github.com/klauspost/compress/internal/le/unsafe_disabled.go +++ b/vendor/github.com/klauspost/compress/internal/le/unsafe_disabled.go @@ -37,6 +37,6 @@ func Store32(b []byte, v uint32) { } // Store64 will store v at b. -func Store64(b []byte, v uint64) { - binary.LittleEndian.PutUint64(b, v) +func Store64[I Indexer](b []byte, i I, v uint64) { + binary.LittleEndian.PutUint64(b[i:], v) } diff --git a/vendor/github.com/klauspost/compress/internal/le/unsafe_enabled.go b/vendor/github.com/klauspost/compress/internal/le/unsafe_enabled.go index ada45cd90..218a38bc4 100644 --- a/vendor/github.com/klauspost/compress/internal/le/unsafe_enabled.go +++ b/vendor/github.com/klauspost/compress/internal/le/unsafe_enabled.go @@ -38,18 +38,15 @@ func Load64[I Indexer](b []byte, i I) uint64 { // Store16 will store v at b. func Store16(b []byte, v uint16) { - //binary.LittleEndian.PutUint16(b, v) *(*uint16)(unsafe.Pointer(unsafe.SliceData(b))) = v } // Store32 will store v at b. func Store32(b []byte, v uint32) { - //binary.LittleEndian.PutUint32(b, v) *(*uint32)(unsafe.Pointer(unsafe.SliceData(b))) = v } -// Store64 will store v at b. -func Store64(b []byte, v uint64) { - //binary.LittleEndian.PutUint64(b, v) - *(*uint64)(unsafe.Pointer(unsafe.SliceData(b))) = v +// Store64 will store v at b[i:]. +func Store64[I Indexer](b []byte, i I, v uint64) { + *(*uint64)(unsafe.Add(unsafe.Pointer(unsafe.SliceData(b)), i)) = v } diff --git a/vendor/github.com/klauspost/compress/internal/snapref/decode.go b/vendor/github.com/klauspost/compress/internal/snapref/decode.go index 40796a49d..a2c82fcd2 100644 --- a/vendor/github.com/klauspost/compress/internal/snapref/decode.go +++ b/vendor/github.com/klauspost/compress/internal/snapref/decode.go @@ -209,7 +209,7 @@ func (r *Reader) fill() error { if !r.readFull(r.buf[:len(magicBody)], false) { return r.err } - for i := 0; i < len(magicBody); i++ { + for i := range len(magicBody) { if r.buf[i] != magicBody[i] { r.err = ErrCorrupt return r.err diff --git a/vendor/github.com/klauspost/compress/internal/snapref/encode.go b/vendor/github.com/klauspost/compress/internal/snapref/encode.go index 13c6040a5..860a99416 100644 --- a/vendor/github.com/klauspost/compress/internal/snapref/encode.go +++ b/vendor/github.com/klauspost/compress/internal/snapref/encode.go @@ -20,8 +20,10 @@ import ( func Encode(dst, src []byte) []byte { if n := MaxEncodedLen(len(src)); n < 0 { panic(ErrTooLarge) - } else if len(dst) < n { + } else if cap(dst) < n { dst = make([]byte, n) + } else { + dst = dst[:n] } // The block starts with the varint-encoded length of the decompressed bytes. diff --git a/vendor/github.com/klauspost/compress/zstd/bitwriter.go b/vendor/github.com/klauspost/compress/zstd/bitwriter.go index 1952f175b..b22b297e6 100644 --- a/vendor/github.com/klauspost/compress/zstd/bitwriter.go +++ b/vendor/github.com/klauspost/compress/zstd/bitwriter.go @@ -88,7 +88,7 @@ func (b *bitWriter) flush32() { // flushAlign will flush remaining full bytes and align to next byte boundary. func (b *bitWriter) flushAlign() { nbBytes := (b.nBits + 7) >> 3 - for i := uint8(0); i < nbBytes; i++ { + for i := range nbBytes { b.out = append(b.out, byte(b.bitContainer>>(i*8))) } b.nBits = 0 diff --git a/vendor/github.com/klauspost/compress/zstd/blockdec.go b/vendor/github.com/klauspost/compress/zstd/blockdec.go index 0dd742fd2..2329e996f 100644 --- a/vendor/github.com/klauspost/compress/zstd/blockdec.go +++ b/vendor/github.com/klauspost/compress/zstd/blockdec.go @@ -54,11 +54,11 @@ const ( ) var ( - huffDecoderPool = sync.Pool{New: func() interface{} { + huffDecoderPool = sync.Pool{New: func() any { return &huff0.Scratch{} }} - fseDecoderPool = sync.Pool{New: func() interface{} { + fseDecoderPool = sync.Pool{New: func() any { return &fseDecoder{} }} ) @@ -553,7 +553,7 @@ func (b *blockDec) prepareSequences(in []byte, hist *history) (err error) { if compMode&3 != 0 { return errors.New("corrupt block: reserved bits not zero") } - for i := uint(0); i < 3; i++ { + for i := range uint(3) { mode := seqCompMode((compMode >> (6 - i*2)) & 3) if debugDecoder { println("Table", tableIndex(i), "is", mode) diff --git a/vendor/github.com/klauspost/compress/zstd/decoder.go b/vendor/github.com/klauspost/compress/zstd/decoder.go index ea2a19376..30df5513d 100644 --- a/vendor/github.com/klauspost/compress/zstd/decoder.go +++ b/vendor/github.com/klauspost/compress/zstd/decoder.go @@ -373,11 +373,9 @@ func (d *Decoder) DecodeAll(input, dst []byte) ([]byte, error) { if cap(dst) == 0 && !d.o.limitToCap { // Allocate len(input) * 2 by default if nothing is provided // and we didn't get frame content size. - size := len(input) * 2 - // Cap to 1 MB. - if size > 1<<20 { - size = 1 << 20 - } + size := min( + // Cap to 1 MB. + len(input)*2, 1<<20) if uint64(size) > d.o.maxDecodedSize { size = int(d.o.maxDecodedSize) } diff --git a/vendor/github.com/klauspost/compress/zstd/dict.go b/vendor/github.com/klauspost/compress/zstd/dict.go index b7b83164b..2ffbfdf37 100644 --- a/vendor/github.com/klauspost/compress/zstd/dict.go +++ b/vendor/github.com/klauspost/compress/zstd/dict.go @@ -194,17 +194,17 @@ func BuildDict(o BuildDictOptions) ([]byte, error) { hist := o.History contents := o.Contents debug := o.DebugOut != nil - println := func(args ...interface{}) { + println := func(args ...any) { if o.DebugOut != nil { fmt.Fprintln(o.DebugOut, args...) } } - printf := func(s string, args ...interface{}) { + printf := func(s string, args ...any) { if o.DebugOut != nil { fmt.Fprintf(o.DebugOut, s, args...) } } - print := func(args ...interface{}) { + print := func(args ...any) { if o.DebugOut != nil { fmt.Fprint(o.DebugOut, args...) } @@ -424,16 +424,10 @@ func BuildDict(o BuildDictOptions) ([]byte, error) { } // Literal table - avgSize := litTotal - if avgSize > huff0.BlockSizeMax/2 { - avgSize = huff0.BlockSizeMax / 2 - } + avgSize := min(litTotal, huff0.BlockSizeMax/2) huffBuff := make([]byte, 0, avgSize) // Target size - div := litTotal / avgSize - if div < 1 { - div = 1 - } + div := max(litTotal/avgSize, 1) if debug { println("Huffman weights:") } @@ -454,7 +448,7 @@ func BuildDict(o BuildDictOptions) ([]byte, error) { huffBuff = append(huffBuff, 255) } scratch := &huff0.Scratch{TableLog: 11} - for tries := 0; tries < 255; tries++ { + for tries := range 255 { scratch = &huff0.Scratch{TableLog: 11} _, _, err = huff0.Compress1X(huffBuff, scratch) if err == nil { @@ -471,7 +465,7 @@ func BuildDict(o BuildDictOptions) ([]byte, error) { // Bail out.... Just generate something huffBuff = append(huffBuff, bytes.Repeat([]byte{255}, 10000)...) - for i := 0; i < 128; i++ { + for i := range 128 { huffBuff = append(huffBuff, byte(i)) } continue diff --git a/vendor/github.com/klauspost/compress/zstd/enc_base.go b/vendor/github.com/klauspost/compress/zstd/enc_base.go index 7d250c67f..c1192ec38 100644 --- a/vendor/github.com/klauspost/compress/zstd/enc_base.go +++ b/vendor/github.com/klauspost/compress/zstd/enc_base.go @@ -8,7 +8,7 @@ import ( ) const ( - dictShardBits = 6 + dictShardBits = 7 ) type fastBase struct { @@ -41,11 +41,9 @@ func (e *fastBase) AppendCRC(dst []byte) []byte { // or a window size small enough to contain the input size, if > 0. func (e *fastBase) WindowSize(size int64) int32 { if size > 0 && size < int64(e.maxMatchOff) { - b := int32(1) << uint(bits.Len(uint(size))) - // Keep minimum window. - if b < 1024 { - b = 1024 - } + b := max( + // Keep minimum window. + int32(1)< tMin && s > nextEmit && src[offset-1] == src[s-1] && l < maxMatchLength { s-- offset-- @@ -382,10 +377,7 @@ encodeLoop: nextEmit = s // Index skipped... - end := s - if s > sLimit+4 { - end = sLimit + 4 - } + end := min(s, sLimit+4) off := index0 + e.cur for index0 < end { cv0 := load6432(src, index0) @@ -444,10 +436,7 @@ encodeLoop: nextEmit = s // Index old s + 1 -> s - 1 or sLimit - end := s - if s > sLimit-4 { - end = sLimit - 4 - } + end := min(s, sLimit-4) off := index0 + e.cur for index0 < end { diff --git a/vendor/github.com/klauspost/compress/zstd/enc_better.go b/vendor/github.com/klauspost/compress/zstd/enc_better.go index 84a79fde7..85dcd28c3 100644 --- a/vendor/github.com/klauspost/compress/zstd/enc_better.go +++ b/vendor/github.com/klauspost/compress/zstd/enc_better.go @@ -190,10 +190,7 @@ encodeLoop: // and have to do special offset treatment. startLimit := nextEmit + 1 - tMin := s - e.maxMatchOff - if tMin < 0 { - tMin = 0 - } + tMin := max(s-e.maxMatchOff, 0) for repIndex > tMin && start > startLimit && src[repIndex-1] == src[start-1] && seq.matchLen < maxMatchLength-zstdMinMatch-1 { repIndex-- start-- @@ -252,10 +249,7 @@ encodeLoop: // and have to do special offset treatment. startLimit := nextEmit + 1 - tMin := s - e.maxMatchOff - if tMin < 0 { - tMin = 0 - } + tMin := max(s-e.maxMatchOff, 0) for repIndex > tMin && start > startLimit && src[repIndex-1] == src[start-1] && seq.matchLen < maxMatchLength-zstdMinMatch-1 { repIndex-- start-- @@ -480,10 +474,7 @@ encodeLoop: l := matched // Extend backwards - tMin := s - e.maxMatchOff - if tMin < 0 { - tMin = 0 - } + tMin := max(s-e.maxMatchOff, 0) for t > tMin && s > nextEmit && src[t-1] == src[s-1] && l < maxMatchLength { s-- t-- @@ -719,10 +710,7 @@ encodeLoop: // and have to do special offset treatment. startLimit := nextEmit + 1 - tMin := s - e.maxMatchOff - if tMin < 0 { - tMin = 0 - } + tMin := max(s-e.maxMatchOff, 0) for repIndex > tMin && start > startLimit && src[repIndex-1] == src[start-1] && seq.matchLen < maxMatchLength-zstdMinMatch-1 { repIndex-- start-- @@ -783,10 +771,7 @@ encodeLoop: // and have to do special offset treatment. startLimit := nextEmit + 1 - tMin := s - e.maxMatchOff - if tMin < 0 { - tMin = 0 - } + tMin := max(s-e.maxMatchOff, 0) for repIndex > tMin && start > startLimit && src[repIndex-1] == src[start-1] && seq.matchLen < maxMatchLength-zstdMinMatch-1 { repIndex-- start-- @@ -1005,10 +990,7 @@ encodeLoop: l := matched // Extend backwards - tMin := s - e.maxMatchOff - if tMin < 0 { - tMin = 0 - } + tMin := max(s-e.maxMatchOff, 0) for t > tMin && s > nextEmit && src[t-1] == src[s-1] && l < maxMatchLength { s-- t-- diff --git a/vendor/github.com/klauspost/compress/zstd/enc_dfast.go b/vendor/github.com/klauspost/compress/zstd/enc_dfast.go index d36be7bd8..cf8cad00d 100644 --- a/vendor/github.com/klauspost/compress/zstd/enc_dfast.go +++ b/vendor/github.com/klauspost/compress/zstd/enc_dfast.go @@ -13,7 +13,7 @@ const ( dFastLongLen = 8 // Bytes used for table hash dLongTableShardCnt = 1 << (dFastLongTableBits - dictShardBits) // Number of shards in the table - dLongTableShardSize = dFastLongTableSize / tableShardCnt // Size of an individual shard + dLongTableShardSize = dFastLongTableSize / dLongTableShardCnt // Size of an individual shard dFastShortTableBits = tableBits // Bits used in the short match table dFastShortTableSize = 1 << dFastShortTableBits // Size of the table @@ -149,10 +149,7 @@ encodeLoop: // and have to do special offset treatment. startLimit := nextEmit + 1 - tMin := s - e.maxMatchOff - if tMin < 0 { - tMin = 0 - } + tMin := max(s-e.maxMatchOff, 0) for repIndex > tMin && start > startLimit && src[repIndex-1] == src[start-1] && seq.matchLen < maxMatchLength-zstdMinMatch-1 { repIndex-- start-- @@ -266,10 +263,7 @@ encodeLoop: l := e.matchlen(s+4, t+4, src) + 4 // Extend backwards - tMin := s - e.maxMatchOff - if tMin < 0 { - tMin = 0 - } + tMin := max(s-e.maxMatchOff, 0) for t > tMin && s > nextEmit && src[t-1] == src[s-1] && l < maxMatchLength { s-- t-- @@ -462,10 +456,7 @@ encodeLoop: // and have to do special offset treatment. startLimit := nextEmit + 1 - tMin := s - e.maxMatchOff - if tMin < 0 { - tMin = 0 - } + tMin := max(s-e.maxMatchOff, 0) for repIndex > tMin && start > startLimit && src[repIndex-1] == src[start-1] { repIndex-- start-- @@ -576,10 +567,7 @@ encodeLoop: l := int32(matchLen(src[s+4:], src[t+4:])) + 4 // Extend backwards - tMin := s - e.maxMatchOff - if tMin < 0 { - tMin = 0 - } + tMin := max(s-e.maxMatchOff, 0) for t > tMin && s > nextEmit && src[t-1] == src[s-1] { s-- t-- @@ -809,10 +797,7 @@ encodeLoop: // and have to do special offset treatment. startLimit := nextEmit + 1 - tMin := s - e.maxMatchOff - if tMin < 0 { - tMin = 0 - } + tMin := max(s-e.maxMatchOff, 0) for repIndex > tMin && start > startLimit && src[repIndex-1] == src[start-1] && seq.matchLen < maxMatchLength-zstdMinMatch-1 { repIndex-- start-- @@ -927,10 +912,7 @@ encodeLoop: l := e.matchlen(s+4, t+4, src) + 4 // Extend backwards - tMin := s - e.maxMatchOff - if tMin < 0 { - tMin = 0 - } + tMin := max(s-e.maxMatchOff, 0) for t > tMin && s > nextEmit && src[t-1] == src[s-1] && l < maxMatchLength { s-- t-- diff --git a/vendor/github.com/klauspost/compress/zstd/enc_fast.go b/vendor/github.com/klauspost/compress/zstd/enc_fast.go index f45a3da7d..9180a3a58 100644 --- a/vendor/github.com/klauspost/compress/zstd/enc_fast.go +++ b/vendor/github.com/klauspost/compress/zstd/enc_fast.go @@ -143,10 +143,7 @@ encodeLoop: // and have to do special offset treatment. startLimit := nextEmit + 1 - sMin := s - e.maxMatchOff - if sMin < 0 { - sMin = 0 - } + sMin := max(s-e.maxMatchOff, 0) for repIndex > sMin && start > startLimit && src[repIndex-1] == src[start-1] && seq.matchLen < maxMatchLength-zstdMinMatch { repIndex-- start-- @@ -223,10 +220,7 @@ encodeLoop: l := e.matchlen(s+4, t+4, src) + 4 // Extend backwards - tMin := s - e.maxMatchOff - if tMin < 0 { - tMin = 0 - } + tMin := max(s-e.maxMatchOff, 0) for t > tMin && s > nextEmit && src[t-1] == src[s-1] && l < maxMatchLength { s-- t-- @@ -387,10 +381,7 @@ encodeLoop: // and have to do special offset treatment. startLimit := nextEmit + 1 - sMin := s - e.maxMatchOff - if sMin < 0 { - sMin = 0 - } + sMin := max(s-e.maxMatchOff, 0) for repIndex > sMin && start > startLimit && src[repIndex-1] == src[start-1] { repIndex-- start-- @@ -469,10 +460,7 @@ encodeLoop: l := e.matchlen(s+4, t+4, src) + 4 // Extend backwards - tMin := s - e.maxMatchOff - if tMin < 0 { - tMin = 0 - } + tMin := max(s-e.maxMatchOff, 0) for t > tMin && s > nextEmit && src[t-1] == src[s-1] { s-- t-- @@ -655,10 +643,7 @@ encodeLoop: // and have to do special offset treatment. startLimit := nextEmit + 1 - sMin := s - e.maxMatchOff - if sMin < 0 { - sMin = 0 - } + sMin := max(s-e.maxMatchOff, 0) for repIndex > sMin && start > startLimit && src[repIndex-1] == src[start-1] && seq.matchLen < maxMatchLength-zstdMinMatch { repIndex-- start-- @@ -735,10 +720,7 @@ encodeLoop: l := e.matchlen(s+4, t+4, src) + 4 // Extend backwards - tMin := s - e.maxMatchOff - if tMin < 0 { - tMin = 0 - } + tMin := max(s-e.maxMatchOff, 0) for t > tMin && s > nextEmit && src[t-1] == src[s-1] && l < maxMatchLength { s-- t-- diff --git a/vendor/github.com/klauspost/compress/zstd/framedec.go b/vendor/github.com/klauspost/compress/zstd/framedec.go index e47af66e7..d88f067e5 100644 --- a/vendor/github.com/klauspost/compress/zstd/framedec.go +++ b/vendor/github.com/klauspost/compress/zstd/framedec.go @@ -238,10 +238,7 @@ func (d *frameDec) reset(br byteBuffer) error { if d.WindowSize == 0 && d.SingleSegment { // We may not need window in this case. - d.WindowSize = d.FrameContentSize - if d.WindowSize < MinWindowSize { - d.WindowSize = MinWindowSize - } + d.WindowSize = max(d.FrameContentSize, MinWindowSize) if d.WindowSize > d.o.maxDecodedSize { if debugDecoder { printf("window size %d > max %d\n", d.WindowSize, d.o.maxWindowSize) diff --git a/vendor/github.com/klauspost/compress/zstd/fse_encoder.go b/vendor/github.com/klauspost/compress/zstd/fse_encoder.go index ab26326a8..3a0f4e7fb 100644 --- a/vendor/github.com/klauspost/compress/zstd/fse_encoder.go +++ b/vendor/github.com/klauspost/compress/zstd/fse_encoder.go @@ -149,7 +149,7 @@ func (s *fseEncoder) buildCTable() error { if v > largeLimit { s.zeroBits = true } - for nbOccurrences := int16(0); nbOccurrences < v; nbOccurrences++ { + for range v { tableSymbol[position] = symbol position = (position + step) & tableMask for position > highThreshold { diff --git a/vendor/github.com/klauspost/compress/zstd/seqdec.go b/vendor/github.com/klauspost/compress/zstd/seqdec.go index 9a7de82f9..0bfb0e43c 100644 --- a/vendor/github.com/klauspost/compress/zstd/seqdec.go +++ b/vendor/github.com/klauspost/compress/zstd/seqdec.go @@ -231,10 +231,7 @@ func (s *sequenceDecs) decodeSync(hist []byte) error { llTable, mlTable, ofTable := s.litLengths.fse.dt[:maxTablesize], s.matchLengths.fse.dt[:maxTablesize], s.offsets.fse.dt[:maxTablesize] llState, mlState, ofState := s.litLengths.state.state, s.matchLengths.state.state, s.offsets.state.state out := s.out - maxBlockSize := maxCompressedBlockSize - if s.windowSize < maxBlockSize { - maxBlockSize = s.windowSize - } + maxBlockSize := min(s.windowSize, maxCompressedBlockSize) if debugDecoder { println("decodeSync: decoding", seqs, "sequences", br.remain(), "bits remain on stream") diff --git a/vendor/github.com/klauspost/compress/zstd/seqdec_amd64.go b/vendor/github.com/klauspost/compress/zstd/seqdec_amd64.go index c59f17e07..1f8c3cec2 100644 --- a/vendor/github.com/klauspost/compress/zstd/seqdec_amd64.go +++ b/vendor/github.com/klauspost/compress/zstd/seqdec_amd64.go @@ -79,10 +79,7 @@ func (s *sequenceDecs) decodeSyncSimple(hist []byte) (bool, error) { br := s.br - maxBlockSize := maxCompressedBlockSize - if s.windowSize < maxBlockSize { - maxBlockSize = s.windowSize - } + maxBlockSize := min(s.windowSize, maxCompressedBlockSize) ctx := decodeSyncAsmContext{ llTable: s.litLengths.fse.dt[:maxTablesize], @@ -237,10 +234,7 @@ func sequenceDecs_decode_56_bmi2(s *sequenceDecs, br *bitReader, ctx *decodeAsmC func (s *sequenceDecs) decode(seqs []seqVals) error { br := s.br - maxBlockSize := maxCompressedBlockSize - if s.windowSize < maxBlockSize { - maxBlockSize = s.windowSize - } + maxBlockSize := min(s.windowSize, maxCompressedBlockSize) ctx := decodeAsmContext{ llTable: s.litLengths.fse.dt[:maxTablesize], diff --git a/vendor/github.com/klauspost/compress/zstd/simple_go124.go b/vendor/github.com/klauspost/compress/zstd/simple_go124.go new file mode 100644 index 000000000..2efc0497b --- /dev/null +++ b/vendor/github.com/klauspost/compress/zstd/simple_go124.go @@ -0,0 +1,56 @@ +// Copyright 2025+ Klaus Post. All rights reserved. +// License information can be found in the LICENSE file. + +//go:build go1.24 + +package zstd + +import ( + "errors" + "runtime" + "sync" + "weak" +) + +var weakMu sync.Mutex +var simpleEnc weak.Pointer[Encoder] +var simpleDec weak.Pointer[Decoder] + +// EncodeTo appends the encoded data from src to dst. +func EncodeTo(dst []byte, src []byte) []byte { + weakMu.Lock() + enc := simpleEnc.Value() + if enc == nil { + var err error + enc, err = NewWriter(nil, WithEncoderConcurrency(runtime.NumCPU()), WithWindowSize(1<<20), WithLowerEncoderMem(true), WithZeroFrames(true)) + if err != nil { + panic("failed to create simple encoder: " + err.Error()) + } + simpleEnc = weak.Make(enc) + } + weakMu.Unlock() + + return enc.EncodeAll(src, dst) +} + +// DecodeTo appends the decoded data from src to dst. +// The maximum decoded size is 1GiB, +// not including what may already be in dst. +func DecodeTo(dst []byte, src []byte) ([]byte, error) { + weakMu.Lock() + dec := simpleDec.Value() + if dec == nil { + var err error + dec, err = NewReader(nil, WithDecoderConcurrency(runtime.NumCPU()), WithDecoderLowmem(true), WithDecoderMaxMemory(1<<30)) + if err != nil { + weakMu.Unlock() + return nil, errors.New("failed to create simple decoder: " + err.Error()) + } + runtime.SetFinalizer(dec, func(d *Decoder) { + d.Close() + }) + simpleDec = weak.Make(dec) + } + weakMu.Unlock() + return dec.DecodeAll(src, dst) +} diff --git a/vendor/github.com/klauspost/compress/zstd/snappy.go b/vendor/github.com/klauspost/compress/zstd/snappy.go index a17381b8f..336c28893 100644 --- a/vendor/github.com/klauspost/compress/zstd/snappy.go +++ b/vendor/github.com/klauspost/compress/zstd/snappy.go @@ -257,7 +257,7 @@ func (r *SnappyConverter) Convert(in io.Reader, w io.Writer) (int64, error) { if !r.readFull(r.buf[:len(snappyMagicBody)], false) { return written, r.err } - for i := 0; i < len(snappyMagicBody); i++ { + for i := range len(snappyMagicBody) { if r.buf[i] != snappyMagicBody[i] { println("r.buf[i] != snappyMagicBody[i]", r.buf[i], snappyMagicBody[i], i) r.err = ErrSnappyCorrupt diff --git a/vendor/github.com/klauspost/compress/zstd/zip.go b/vendor/github.com/klauspost/compress/zstd/zip.go index 29c15c8c4..3198d7189 100644 --- a/vendor/github.com/klauspost/compress/zstd/zip.go +++ b/vendor/github.com/klauspost/compress/zstd/zip.go @@ -19,7 +19,7 @@ const ZipMethodWinZip = 93 const ZipMethodPKWare = 20 // zipReaderPool is the default reader pool. -var zipReaderPool = sync.Pool{New: func() interface{} { +var zipReaderPool = sync.Pool{New: func() any { z, err := NewReader(nil, WithDecoderLowmem(true), WithDecoderMaxWindow(128<<20), WithDecoderConcurrency(1)) if err != nil { panic(err) diff --git a/vendor/github.com/klauspost/compress/zstd/zstd.go b/vendor/github.com/klauspost/compress/zstd/zstd.go index 6252b46ae..1a869710d 100644 --- a/vendor/github.com/klauspost/compress/zstd/zstd.go +++ b/vendor/github.com/klauspost/compress/zstd/zstd.go @@ -98,13 +98,13 @@ var ( ErrDecoderNilInput = errors.New("nil input provided as reader") ) -func println(a ...interface{}) { +func println(a ...any) { if debug || debugDecoder || debugEncoder { log.Println(a...) } } -func printf(format string, a ...interface{}) { +func printf(format string, a ...any) { if debug || debugDecoder || debugEncoder { log.Printf(format, a...) } diff --git a/vendor/go.podman.io/image/v5/copy/compression.go b/vendor/go.podman.io/image/v5/copy/compression.go index 0ecc85186..e3e523029 100644 --- a/vendor/go.podman.io/image/v5/copy/compression.go +++ b/vendor/go.podman.io/image/v5/copy/compression.go @@ -27,9 +27,10 @@ var ( // expectedBaseCompressionFormats is used to check if a blob with a specified media type is compressed // using the algorithm that the media type says it should be compressed with expectedBaseCompressionFormats = map[string]*compressiontypes.Algorithm{ - imgspecv1.MediaTypeImageLayerGzip: &compression.Gzip, - imgspecv1.MediaTypeImageLayerZstd: &compression.Zstd, - manifest.DockerV2Schema2LayerMediaType: &compression.Gzip, + imgspecv1.MediaTypeImageLayerGzip: &compression.Gzip, + imgspecv1.MediaTypeImageLayerZstd: &compression.Zstd, + manifest.DockerV2Schema2LayerMediaType: &compression.Gzip, + manifest.DockerV2SchemaLayerMediaTypeZstd: &compression.Zstd, } ) diff --git a/vendor/go.podman.io/image/v5/docker/docker_client.go b/vendor/go.podman.io/image/v5/docker/docker_client.go index a83e19a36..1c0d67105 100644 --- a/vendor/go.podman.io/image/v5/docker/docker_client.go +++ b/vendor/go.podman.io/image/v5/docker/docker_client.go @@ -1066,6 +1066,8 @@ func (c *dockerClient) getBlob(ctx context.Context, ref dockerReference, info ty cache.RecordKnownLocation(ref.Transport(), bicTransportScope(ref), info.Digest, newBICLocationReference(ref)) blobSize, err := getBlobSize(res) if err != nil { + // See above, we don't guarantee returning a size + logrus.Debugf("failed to get blob size: %v", err) blobSize = -1 } diff --git a/vendor/go.podman.io/image/v5/internal/image/docker_schema2.go b/vendor/go.podman.io/image/v5/internal/image/docker_schema2.go index 9305524a0..1586d6790 100644 --- a/vendor/go.podman.io/image/v5/internal/image/docker_schema2.go +++ b/vendor/go.podman.io/image/v5/internal/image/docker_schema2.go @@ -233,6 +233,8 @@ func (m *manifestSchema2) convertToManifestOCI1(ctx context.Context, _ *types.Ma layers[idx].MediaType = imgspecv1.MediaTypeImageLayer case manifest.DockerV2Schema2LayerMediaType: layers[idx].MediaType = imgspecv1.MediaTypeImageLayerGzip + case manifest.DockerV2SchemaLayerMediaTypeZstd: + layers[idx].MediaType = imgspecv1.MediaTypeImageLayerZstd default: return nil, fmt.Errorf("Unknown media type during manifest conversion: %q", m.m.LayersDescriptors[idx].MediaType) } diff --git a/vendor/go.podman.io/image/v5/internal/image/oci.go b/vendor/go.podman.io/image/v5/internal/image/oci.go index 8b73b91ff..56a1a6d64 100644 --- a/vendor/go.podman.io/image/v5/internal/image/oci.go +++ b/vendor/go.podman.io/image/v5/internal/image/oci.go @@ -288,7 +288,7 @@ func (m *manifestOCI1) convertToManifestSchema2(_ context.Context, options *type case imgspecv1.MediaTypeImageLayerGzip: layers[idx].MediaType = manifest.DockerV2Schema2LayerMediaType case imgspecv1.MediaTypeImageLayerZstd: - return nil, fmt.Errorf("Error during manifest conversion: %q: zstd compression is not supported for docker images", layers[idx].MediaType) + return nil, fmt.Errorf("Error during manifest conversion: %q: zstd compression is not officially supported for docker images", layers[idx].MediaType) case ociencspec.MediaTypeLayerEnc, ociencspec.MediaTypeLayerGzipEnc, ociencspec.MediaTypeLayerZstdEnc, ociencspec.MediaTypeLayerNonDistributableEnc, ociencspec.MediaTypeLayerNonDistributableGzipEnc, ociencspec.MediaTypeLayerNonDistributableZstdEnc: return nil, fmt.Errorf("during manifest conversion: encrypted layers (%q) are not supported in docker images", layers[idx].MediaType) diff --git a/vendor/go.podman.io/image/v5/internal/manifest/manifest.go b/vendor/go.podman.io/image/v5/internal/manifest/manifest.go index 7dfe77844..687b37fb0 100644 --- a/vendor/go.podman.io/image/v5/internal/manifest/manifest.go +++ b/vendor/go.podman.io/image/v5/internal/manifest/manifest.go @@ -26,6 +26,8 @@ const ( DockerV2Schema2LayerMediaType = "application/vnd.docker.image.rootfs.diff.tar.gzip" // DockerV2SchemaLayerMediaTypeUncompressed is the mediaType used for uncompressed layers. DockerV2SchemaLayerMediaTypeUncompressed = "application/vnd.docker.image.rootfs.diff.tar" + // DockerV2Schema2LayerMediaType is the MIME type used for schema 2 layers. + DockerV2SchemaLayerMediaTypeZstd = "application/vnd.docker.image.rootfs.diff.tar.zstd" // DockerV2ListMediaType MIME type represents Docker manifest schema 2 list DockerV2ListMediaType = "application/vnd.docker.distribution.manifest.list.v2+json" // DockerV2Schema2ForeignLayerMediaType is the MIME type used for schema 2 foreign layers. diff --git a/vendor/go.podman.io/image/v5/manifest/manifest.go b/vendor/go.podman.io/image/v5/manifest/manifest.go index 45118fa4e..ed489a5a6 100644 --- a/vendor/go.podman.io/image/v5/manifest/manifest.go +++ b/vendor/go.podman.io/image/v5/manifest/manifest.go @@ -26,6 +26,9 @@ const ( DockerV2Schema2LayerMediaType = manifest.DockerV2Schema2LayerMediaType // DockerV2SchemaLayerMediaTypeUncompressed is the mediaType used for uncompressed layers. DockerV2SchemaLayerMediaTypeUncompressed = manifest.DockerV2SchemaLayerMediaTypeUncompressed + // DockerV2SchemaLayerMediaTypeZstd is the mediaType used for zstd layers. + // Warning: This mediaType is not officially supported in https://github.com/distribution/distribution/blob/main/docs/content/spec/manifest-v2-2.md but some images may exhibit it. Support is partial. + DockerV2SchemaLayerMediaTypeZstd = manifest.DockerV2SchemaLayerMediaTypeZstd // DockerV2ListMediaType MIME type represents Docker manifest schema 2 list DockerV2ListMediaType = manifest.DockerV2ListMediaType // DockerV2Schema2ForeignLayerMediaType is the MIME type used for schema 2 foreign layers. @@ -41,7 +44,7 @@ type NonImageArtifactError = manifest.NonImageArtifactError // SupportedSchema2MediaType checks if the specified string is a supported Docker v2s2 media type. func SupportedSchema2MediaType(m string) error { switch m { - case DockerV2ListMediaType, DockerV2Schema1MediaType, DockerV2Schema1SignedMediaType, DockerV2Schema2ConfigMediaType, DockerV2Schema2ForeignLayerMediaType, DockerV2Schema2ForeignLayerMediaTypeGzip, DockerV2Schema2LayerMediaType, DockerV2Schema2MediaType, DockerV2SchemaLayerMediaTypeUncompressed: + case DockerV2ListMediaType, DockerV2Schema1MediaType, DockerV2Schema1SignedMediaType, DockerV2Schema2ConfigMediaType, DockerV2Schema2ForeignLayerMediaType, DockerV2Schema2ForeignLayerMediaTypeGzip, DockerV2Schema2LayerMediaType, DockerV2Schema2MediaType, DockerV2SchemaLayerMediaTypeUncompressed, DockerV2SchemaLayerMediaTypeZstd: return nil default: return fmt.Errorf("unsupported docker v2s2 media type: %q", m) diff --git a/vendor/go.podman.io/image/v5/version/version.go b/vendor/go.podman.io/image/v5/version/version.go index e577735ee..71a957fc6 100644 --- a/vendor/go.podman.io/image/v5/version/version.go +++ b/vendor/go.podman.io/image/v5/version/version.go @@ -6,7 +6,7 @@ const ( // VersionMajor is for an API incompatible changes VersionMajor = 5 // VersionMinor is for functionality in a backwards-compatible manner - VersionMinor = 37 + VersionMinor = 38 // VersionPatch is for backwards-compatible bug fixes VersionPatch = 0 diff --git a/vendor/go.podman.io/storage/pkg/archive/archive.go b/vendor/go.podman.io/storage/pkg/archive/archive.go index 5f8647af7..5cdd75130 100644 --- a/vendor/go.podman.io/storage/pkg/archive/archive.go +++ b/vendor/go.podman.io/storage/pkg/archive/archive.go @@ -417,9 +417,7 @@ func FileInfoHeader(name string, fi os.FileInfo, link string) (*tar.Header, erro return nil, fmt.Errorf("tar: cannot canonicalize path: %w", err) } hdr.Name = name - if err := setHeaderForSpecialDevice(hdr, name, fi.Sys()); err != nil { - return nil, err - } + setHeaderForSpecialDevice(hdr, name, fi.Sys()) return hdr, nil } diff --git a/vendor/go.podman.io/storage/pkg/archive/archive_linux.go b/vendor/go.podman.io/storage/pkg/archive/archive_linux.go index fd7123bab..4613ee32f 100644 --- a/vendor/go.podman.io/storage/pkg/archive/archive_linux.go +++ b/vendor/go.podman.io/storage/pkg/archive/archive_linux.go @@ -30,7 +30,7 @@ type overlayWhiteoutConverter struct { rolayers []string } -func (o overlayWhiteoutConverter) ConvertWrite(hdr *tar.Header, path string, fi os.FileInfo) (wo *tar.Header, err error) { +func (o overlayWhiteoutConverter) ConvertWrite(hdr *tar.Header, path string, fi os.FileInfo) (*tar.Header, error) { // convert whiteouts to AUFS format if fi.Mode()&os.ModeCharDevice != 0 && hdr.Devmajor == 0 && hdr.Devminor == 0 { // we just rename the file and make it normal @@ -73,7 +73,7 @@ func (o overlayWhiteoutConverter) ConvertWrite(hdr *tar.Header, path string, fi // add a whiteout for this item in this layer. // create a header for the whiteout file // it should inherit some properties from the parent, but be a regular file - wo = &tar.Header{ + wo := &tar.Header{ Typeflag: tar.TypeReg, Mode: hdr.Mode & int64(os.ModePerm), Name: filepath.Join(hdr.Name, WhiteoutOpaqueDir), @@ -85,7 +85,7 @@ func (o overlayWhiteoutConverter) ConvertWrite(hdr *tar.Header, path string, fi AccessTime: hdr.AccessTime, ChangeTime: hdr.ChangeTime, } - break + return wo, nil } for dir := filepath.Dir(hdr.Name); dir != "" && dir != "." && dir != string(os.PathSeparator); dir = filepath.Dir(dir) { // Check for whiteout for a parent directory in a parent layer. @@ -109,7 +109,7 @@ func (o overlayWhiteoutConverter) ConvertWrite(hdr *tar.Header, path string, fi } } - return + return nil, nil } func (overlayWhiteoutConverter) ConvertReadWithHandler(hdr *tar.Header, path string, handler TarWhiteoutHandler) (bool, error) { diff --git a/vendor/go.podman.io/storage/pkg/archive/archive_other.go b/vendor/go.podman.io/storage/pkg/archive/archive_other.go index b342ff75e..f7c7352fd 100644 --- a/vendor/go.podman.io/storage/pkg/archive/archive_other.go +++ b/vendor/go.podman.io/storage/pkg/archive/archive_other.go @@ -2,7 +2,7 @@ package archive -func GetWhiteoutConverter(format WhiteoutFormat, data interface{}) TarWhiteoutConverter { +func GetWhiteoutConverter(format WhiteoutFormat, data any) TarWhiteoutConverter { return nil } diff --git a/vendor/go.podman.io/storage/pkg/archive/archive_unix.go b/vendor/go.podman.io/storage/pkg/archive/archive_unix.go index 2d9d68de2..b09b06443 100644 --- a/vendor/go.podman.io/storage/pkg/archive/archive_unix.go +++ b/vendor/go.podman.io/storage/pkg/archive/archive_unix.go @@ -32,8 +32,10 @@ func statUnix(fi os.FileInfo, hdr *tar.Header) error { if s.Mode&unix.S_IFBLK != 0 || s.Mode&unix.S_IFCHR != 0 { - hdr.Devmajor = int64(unix.Major(uint64(s.Rdev))) //nolint: unconvert - hdr.Devminor = int64(unix.Minor(uint64(s.Rdev))) //nolint: unconvert + // _nolint_: Whether this conversion is required is hardware- and OS-dependent: the value might be uint64 on Linux, int32 on macOS. + // So, this might trigger either "uncovert" (if the conversion is unnecessary) or "nolintlint" (if it is required) + hdr.Devmajor = int64(unix.Major(uint64(s.Rdev))) //nolint:unconvert,nolintlint + hdr.Devminor = int64(unix.Minor(uint64(s.Rdev))) //nolint:unconvert,nolintlint } return nil @@ -67,19 +69,19 @@ func chmodTarEntry(perm os.FileMode) os.FileMode { return perm // noop for unix as golang APIs provide perm bits correctly } -func setHeaderForSpecialDevice(hdr *tar.Header, name string, stat any) (err error) { +func setHeaderForSpecialDevice(hdr *tar.Header, name string, stat any) { s, ok := stat.(*syscall.Stat_t) if ok { // Currently go does not fill in the major/minors if s.Mode&unix.S_IFBLK != 0 || s.Mode&unix.S_IFCHR != 0 { - hdr.Devmajor = int64(major(uint64(s.Rdev))) //nolint: unconvert - hdr.Devminor = int64(minor(uint64(s.Rdev))) //nolint: unconvert + // _nolint_: Whether this conversion is required is hardware- and OS-dependent: the value might be uint64 on Linux, int32 on macOS. + // So, this might trigger either "uncovert" (if the conversion is unnecessary) or "nolintlint" (if it is required) + hdr.Devmajor = int64(major(uint64(s.Rdev))) //nolint: unconvert,nolintlint + hdr.Devminor = int64(minor(uint64(s.Rdev))) //nolint: unconvert,nolintlint } } - - return } func getInodeFromStat(stat any) (inode uint64) { @@ -89,7 +91,7 @@ func getInodeFromStat(stat any) (inode uint64) { inode = s.Ino } - return + return inode } func getFileUIDGID(stat any) (idtools.IDPair, error) { diff --git a/vendor/go.podman.io/storage/pkg/archive/archive_windows.go b/vendor/go.podman.io/storage/pkg/archive/archive_windows.go index 1183f4a28..2c84e9ea5 100644 --- a/vendor/go.podman.io/storage/pkg/archive/archive_windows.go +++ b/vendor/go.podman.io/storage/pkg/archive/archive_windows.go @@ -52,14 +52,13 @@ func chmodTarEntry(perm os.FileMode) os.FileMode { return noPermPart | permPart } -func setHeaderForSpecialDevice(hdr *tar.Header, name string, stat interface{}) (err error) { +func setHeaderForSpecialDevice(hdr *tar.Header, name string, stat interface{}) { // do nothing. no notion of Rdev, Nlink in stat on Windows - return } -func getInodeFromStat(stat interface{}) (inode uint64) { +func getInodeFromStat(stat interface{}) uint64 { // do nothing. no notion of Inode in stat on Windows - return + return 0 } // handleTarTypeBlockCharFifo is an OS-specific helper function used by diff --git a/vendor/go.podman.io/storage/pkg/archive/changes.go b/vendor/go.podman.io/storage/pkg/archive/changes.go index 051ab6952..a60c20dd3 100644 --- a/vendor/go.podman.io/storage/pkg/archive/changes.go +++ b/vendor/go.podman.io/storage/pkg/archive/changes.go @@ -86,12 +86,12 @@ func Changes(layers []string, rw string) ([]Change, error) { return changes(layers, rw, aufsDeletedFile, aufsMetadataSkip, aufsWhiteoutPresent) } -func aufsMetadataSkip(path string) (skip bool, err error) { - skip, err = filepath.Match(string(os.PathSeparator)+WhiteoutMetaPrefix+"*", path) +func aufsMetadataSkip(path string) (bool, error) { + skip, err := filepath.Match(string(os.PathSeparator)+WhiteoutMetaPrefix+"*", path) if err != nil { skip = true } - return + return skip, err } func aufsDeletedFile(root, path string, fi os.FileInfo) (string, error) { @@ -281,8 +281,7 @@ func (info *FileInfo) LookUp(path string) *FileInfo { return info } - pathElements := strings.Split(path, string(os.PathSeparator)) - for _, elem := range pathElements { + for elem := range strings.SplitSeq(path, string(os.PathSeparator)) { if elem != "" { child := parent.children[elem] if child == nil { diff --git a/vendor/go.podman.io/storage/pkg/archive/changes_windows.go b/vendor/go.podman.io/storage/pkg/archive/changes_windows.go index 947ec2d22..997ee574e 100644 --- a/vendor/go.podman.io/storage/pkg/archive/changes_windows.go +++ b/vendor/go.podman.io/storage/pkg/archive/changes_windows.go @@ -20,8 +20,8 @@ func (info *FileInfo) isDir() bool { return info.parent == nil || info.stat.Mode().IsDir() } -func getIno(fi os.FileInfo) (inode uint64) { - return +func getIno(fi os.FileInfo) uint64 { + return 0 } func hasHardlinks(fi os.FileInfo) bool { diff --git a/vendor/go.podman.io/storage/pkg/archive/copy.go b/vendor/go.podman.io/storage/pkg/archive/copy.go index 308f132d5..3f91c72b9 100644 --- a/vendor/go.podman.io/storage/pkg/archive/copy.go +++ b/vendor/go.podman.io/storage/pkg/archive/copy.go @@ -93,13 +93,13 @@ func TarResource(sourceInfo CopyInfo) (content io.ReadCloser, err error) { // TarResourceRebase is like TarResource but renames the first path element of // items in the resulting tar archive to match the given rebaseName if not "". -func TarResourceRebase(sourcePath, rebaseName string) (content io.ReadCloser, err error) { +func TarResourceRebase(sourcePath, rebaseName string) (io.ReadCloser, error) { sourcePath = normalizePath(sourcePath) - if err = fileutils.Lexists(sourcePath); err != nil { + if err := fileutils.Lexists(sourcePath); err != nil { // Catches the case where the source does not exist or is not a // directory if asserted to be a directory, as this also causes an // error. - return + return nil, err } // Separate the source path between its directory and @@ -411,7 +411,7 @@ func ResolveHostSourcePath(path string, followLink bool) (resolvedPath, rebaseNa if followLink { resolvedPath, err = filepath.EvalSymlinks(path) if err != nil { - return + return "", "", err } resolvedPath, rebaseName = GetRebaseName(path, resolvedPath) @@ -422,7 +422,7 @@ func ResolveHostSourcePath(path string, followLink bool) (resolvedPath, rebaseNa var resolvedDirPath string resolvedDirPath, err = filepath.EvalSymlinks(dirPath) if err != nil { - return + return "", "", err } // resolvedDirPath will have been cleaned (no trailing path separators) so // we can manually join it with the base path element. diff --git a/vendor/go.podman.io/storage/pkg/archive/fflags_bsd.go b/vendor/go.podman.io/storage/pkg/archive/fflags_bsd.go index 829c95ef1..7584b14ce 100644 --- a/vendor/go.podman.io/storage/pkg/archive/fflags_bsd.go +++ b/vendor/go.podman.io/storage/pkg/archive/fflags_bsd.go @@ -77,7 +77,7 @@ var ( func parseFileFlags(fflags string) (uint32, uint32, error) { var set, clear uint32 = 0, 0 - for _, fflag := range strings.Split(fflags, ",") { + for fflag := range strings.SplitSeq(fflags, ",") { isClear := false if clean, ok := strings.CutPrefix(fflag, "no"); ok { isClear = true diff --git a/vendor/go.podman.io/storage/pkg/archive/time_linux.go b/vendor/go.podman.io/storage/pkg/archive/time_linux.go index 3448569b1..a5233c09f 100644 --- a/vendor/go.podman.io/storage/pkg/archive/time_linux.go +++ b/vendor/go.podman.io/storage/pkg/archive/time_linux.go @@ -10,7 +10,7 @@ func timeToTimespec(time time.Time) (ts syscall.Timespec) { // Return UTIME_OMIT special value ts.Sec = 0 ts.Nsec = ((1 << 30) - 2) - return + return ts } return syscall.NsecToTimespec(time.UnixNano()) } diff --git a/vendor/go.podman.io/storage/pkg/archive/wrap.go b/vendor/go.podman.io/storage/pkg/archive/wrap.go index 903befd76..f8a97254e 100644 --- a/vendor/go.podman.io/storage/pkg/archive/wrap.go +++ b/vendor/go.podman.io/storage/pkg/archive/wrap.go @@ -45,8 +45,8 @@ func Generate(input ...string) (io.Reader, error) { return buf, nil } -func parseStringPairs(input ...string) (output [][2]string) { - output = make([][2]string, 0, len(input)/2+1) +func parseStringPairs(input ...string) [][2]string { + output := make([][2]string, 0, len(input)/2+1) for i := 0; i < len(input); i += 2 { var pair [2]string pair[0] = input[i] @@ -55,5 +55,5 @@ func parseStringPairs(input ...string) (output [][2]string) { } output = append(output, pair) } - return + return output } diff --git a/vendor/go.podman.io/storage/pkg/chunked/compressor/compressor.go b/vendor/go.podman.io/storage/pkg/chunked/compressor/compressor.go index 23bcbda51..ef26a812b 100644 --- a/vendor/go.podman.io/storage/pkg/chunked/compressor/compressor.go +++ b/vendor/go.podman.io/storage/pkg/chunked/compressor/compressor.go @@ -173,7 +173,7 @@ func (rc *rollingChecksumReader) Read(b []byte) (bool, int, error) { return false, -1, err } if holeLen > 0 { - for j := int64(0); j < holeLen; j++ { + for range holeLen { rc.rollsum.Roll(0) } rc.pendingHole = holeLen diff --git a/vendor/go.podman.io/storage/pkg/chunked/internal/minimal/compression.go b/vendor/go.podman.io/storage/pkg/chunked/internal/minimal/compression.go index 256365759..c3fcf71a7 100644 --- a/vendor/go.podman.io/storage/pkg/chunked/internal/minimal/compression.go +++ b/vendor/go.podman.io/storage/pkg/chunked/internal/minimal/compression.go @@ -146,7 +146,9 @@ const ( // TarSplitChecksumKey is no longer used and is replaced by the TOC.TarSplitDigest field instead. // The value is retained here as a constant as a historical reference for older zstd:chunked images. - // TarSplitChecksumKey = "io.github.containers.zstd-chunked.tarsplit-checksum" + // + // Deprecated: This field should never be relied on - use the digest in the TOC instead. + TarSplitChecksumKey = "io.github.containers.zstd-chunked.tarsplit-checksum" // ManifestTypeCRFS is a manifest file compatible with the CRFS TOC file. ManifestTypeCRFS = 1 diff --git a/vendor/go.podman.io/storage/pkg/chunked/toc/toc.go b/vendor/go.podman.io/storage/pkg/chunked/toc/toc.go index 7059b5406..fafa40e60 100644 --- a/vendor/go.podman.io/storage/pkg/chunked/toc/toc.go +++ b/vendor/go.podman.io/storage/pkg/chunked/toc/toc.go @@ -7,6 +7,20 @@ import ( "go.podman.io/storage/pkg/chunked/internal/minimal" ) +// ChunkedAnnotations contains various annotations that might be set or used by the pkg/chunked-supported +// compression formats. +// +// This set does not define their semantics in detail as a public API. +// The _only_ intended use of this set is: code that _changes_ layer compression to a format +// which is not chunked can/should remove these annotations. +var ChunkedAnnotations = map[string]struct{}{ + minimal.ManifestChecksumKey: {}, + minimal.ManifestInfoKey: {}, + minimal.TarSplitInfoKey: {}, + minimal.TarSplitChecksumKey: {}, //nolint:staticcheck // The field is deprecated, so removing it when changing compressionn is all the more desirable. + tocJSONDigestAnnotation: {}, +} + // tocJSONDigestAnnotation is the annotation key for the digest of the estargz // TOC JSON. // It is defined in github.com/containerd/stargz-snapshotter/estargz as TOCJSONDigestAnnotation diff --git a/vendor/go.podman.io/storage/pkg/fileutils/fileutils.go b/vendor/go.podman.io/storage/pkg/fileutils/fileutils.go index 85ce2d526..434979825 100644 --- a/vendor/go.podman.io/storage/pkg/fileutils/fileutils.go +++ b/vendor/go.podman.io/storage/pkg/fileutils/fileutils.go @@ -51,7 +51,6 @@ func NewPatternMatcher(patterns []string) (*PatternMatcher, error) { return nil, err } newp.cleanedPattern = p - newp.dirs = strings.Split(p, string(os.PathSeparator)) pm.patterns = append(pm.patterns, newp) } return pm, nil @@ -168,7 +167,6 @@ func (pm *PatternMatcher) Patterns() []*Pattern { // Pattern defines a single regexp used to filter file paths. type Pattern struct { cleanedPattern string - dirs []string regexp *regexp.Regexp exclusion bool } diff --git a/vendor/go.podman.io/storage/pkg/idtools/idtools_unix.go b/vendor/go.podman.io/storage/pkg/idtools/idtools_unix.go index 817b59aed..e7c264367 100644 --- a/vendor/go.podman.io/storage/pkg/idtools/idtools_unix.go +++ b/vendor/go.podman.io/storage/pkg/idtools/idtools_unix.go @@ -8,7 +8,6 @@ import ( "io" "os" "path/filepath" - "strings" "sync" "syscall" @@ -112,7 +111,7 @@ func LookupUser(username string) (user.User, error) { return usr, nil } // local files lookup failed; attempt to call `getent` to query configured passwd dbs - usr, err = getentUser(fmt.Sprintf("%s %s", "passwd", username)) + usr, err = getentUser(username) if err != nil { return user.User{}, err } @@ -128,11 +127,11 @@ func LookupUID(uid int) (user.User, error) { return usr, nil } // local files lookup failed; attempt to call `getent` to query configured passwd dbs - return getentUser(fmt.Sprintf("%s %d", "passwd", uid)) + return getentUser(fmt.Sprintf("%d", uid)) } -func getentUser(args string) (user.User, error) { - reader, err := callGetent(args) +func getentUser(key string) (user.User, error) { + reader, err := callGetent("passwd", key) if err != nil { return user.User{}, err } @@ -141,7 +140,7 @@ func getentUser(args string) (user.User, error) { return user.User{}, err } if len(users) == 0 { - return user.User{}, fmt.Errorf("getent failed to find passwd entry for %q", strings.Split(args, " ")[1]) + return user.User{}, fmt.Errorf("getent failed to find passwd entry for %q", key) } return users[0], nil } @@ -155,7 +154,7 @@ func LookupGroup(groupname string) (user.Group, error) { return group, nil } // local files lookup failed; attempt to call `getent` to query configured group dbs - return getentGroup(fmt.Sprintf("%s %s", "group", groupname)) + return getentGroup(groupname) } // LookupGID uses traditional local system files lookup (from libcontainer/user) on a group ID, @@ -167,11 +166,11 @@ func LookupGID(gid int) (user.Group, error) { return group, nil } // local files lookup failed; attempt to call `getent` to query configured group dbs - return getentGroup(fmt.Sprintf("%s %d", "group", gid)) + return getentGroup(fmt.Sprintf("%d", gid)) } -func getentGroup(args string) (user.Group, error) { - reader, err := callGetent(args) +func getentGroup(key string) (user.Group, error) { + reader, err := callGetent("group", key) if err != nil { return user.Group{}, err } @@ -180,18 +179,18 @@ func getentGroup(args string) (user.Group, error) { return user.Group{}, err } if len(groups) == 0 { - return user.Group{}, fmt.Errorf("getent failed to find groups entry for %q", strings.Split(args, " ")[1]) + return user.Group{}, fmt.Errorf("getent failed to find groups entry for %q", key) } return groups[0], nil } -func callGetent(args string) (io.Reader, error) { +func callGetent(db, key string) (io.Reader, error) { entOnce.Do(func() { getentCmd, _ = resolveBinary("getent") }) // if no `getent` command on host, can't do anything else if getentCmd == "" { return nil, fmt.Errorf("") } - out, err := execCmd(getentCmd, args) + out, err := execCmd(getentCmd, db, key) if err != nil { exitCode, errC := system.GetExitCode(err) if errC != nil { @@ -201,8 +200,7 @@ func callGetent(args string) (io.Reader, error) { case 1: return nil, fmt.Errorf("getent reported invalid parameters/database unknown") case 2: - terms := strings.Split(args, " ") - return nil, fmt.Errorf("getent unable to find entry %q in %s database", terms[1], terms[0]) + return nil, fmt.Errorf("getent unable to find entry %q in %s database", key, db) case 3: return nil, fmt.Errorf("getent database doesn't support enumeration") default: diff --git a/vendor/go.podman.io/storage/pkg/idtools/usergroupadd_linux.go b/vendor/go.podman.io/storage/pkg/idtools/usergroupadd_linux.go index d2ff4466c..ee80ce6a7 100644 --- a/vendor/go.podman.io/storage/pkg/idtools/usergroupadd_linux.go +++ b/vendor/go.podman.io/storage/pkg/idtools/usergroupadd_linux.go @@ -2,6 +2,7 @@ package idtools import ( "fmt" + "slices" "sort" "strconv" "strings" @@ -17,19 +18,12 @@ import ( var ( once sync.Once - userCommand string - - cmdTemplates = map[string]string{ - "adduser": "--system --shell /bin/false --no-create-home --disabled-login --disabled-password --group %s", - "useradd": "-r -s /bin/false %s", - "usermod": "-%s %d-%d %s", - } + userCommand []string // command, args…, to be finished by adding an user name idOutRegexp = regexp.Delayed(`uid=([0-9]+).*gid=([0-9]+)`) // default length for a UID/GID subordinate range defaultRangeLen = 65536 defaultRangeStart = 100000 - userMod = "usermod" ) // AddNamespaceRangesUser takes a username and uses the standard system @@ -72,16 +66,16 @@ func addUser(userName string) error { once.Do(func() { // set up which commands are used for adding users/groups dependent on distro if _, err := resolveBinary("adduser"); err == nil { - userCommand = "adduser" + userCommand = []string{"adduser", "--system", "--shell", "/bin/false", "--no-create-home", "--disabled-login", "--disabled-password", "--group"} } else if _, err := resolveBinary("useradd"); err == nil { - userCommand = "useradd" + userCommand = []string{"useradd", "-r", "-s", "/bin/false"} } }) - if userCommand == "" { + if userCommand == nil { return fmt.Errorf("cannot add user; no useradd/adduser binary found") } - args := fmt.Sprintf(cmdTemplates[userCommand], userName) - out, err := execCmd(userCommand, args) + args := append(slices.Clone(userCommand), userName) + out, err := execCmd(args[0], args[1:]...) if err != nil { return fmt.Errorf("failed to add user with error: %w; output: %q", err, string(out)) } @@ -101,7 +95,7 @@ func createSubordinateRanges(name string) error { if err != nil { return fmt.Errorf("can't find available subuid range: %w", err) } - out, err := execCmd(userMod, fmt.Sprintf(cmdTemplates[userMod], "v", startID, startID+defaultRangeLen-1, name)) + out, err := execCmd("usermod", "-v", fmt.Sprintf("%d-%d", startID, startID+defaultRangeLen-1), name) if err != nil { return fmt.Errorf("unable to add subuid range to user: %q; output: %s, err: %w", name, out, err) } @@ -117,7 +111,7 @@ func createSubordinateRanges(name string) error { if err != nil { return fmt.Errorf("can't find available subgid range: %w", err) } - out, err := execCmd(userMod, fmt.Sprintf(cmdTemplates[userMod], "w", startID, startID+defaultRangeLen-1, name)) + out, err := execCmd("usermod", "-w", fmt.Sprintf("%d-%d", startID, startID+defaultRangeLen-1), name) if err != nil { return fmt.Errorf("unable to add subgid range to user: %q; output: %s, err: %w", name, out, err) } diff --git a/vendor/go.podman.io/storage/pkg/idtools/utils_unix.go b/vendor/go.podman.io/storage/pkg/idtools/utils_unix.go index f34462a23..10606fba8 100644 --- a/vendor/go.podman.io/storage/pkg/idtools/utils_unix.go +++ b/vendor/go.podman.io/storage/pkg/idtools/utils_unix.go @@ -6,7 +6,6 @@ import ( "fmt" "os/exec" "path/filepath" - "strings" ) func resolveBinary(binname string) (string, error) { @@ -26,7 +25,7 @@ func resolveBinary(binname string) (string, error) { return "", fmt.Errorf("binary %q does not resolve to a binary of that name in $PATH (%q)", binname, resolvedPath) } -func execCmd(cmd, args string) ([]byte, error) { - execCmd := exec.Command(cmd, strings.Split(args, " ")...) +func execCmd(cmd string, args ...string) ([]byte, error) { + execCmd := exec.Command(cmd, args...) return execCmd.CombinedOutput() } diff --git a/vendor/go.podman.io/storage/pkg/ioutils/bytespipe.go b/vendor/go.podman.io/storage/pkg/ioutils/bytespipe.go index cf6058035..47ab34507 100644 --- a/vendor/go.podman.io/storage/pkg/ioutils/bytespipe.go +++ b/vendor/go.podman.io/storage/pkg/ioutils/bytespipe.go @@ -121,7 +121,8 @@ func (bp *BytesPipe) Close() error { // Read reads bytes from BytesPipe. // Data could be read only once. -func (bp *BytesPipe) Read(p []byte) (n int, err error) { +func (bp *BytesPipe) Read(p []byte) (int, error) { + var n int bp.mu.Lock() if bp.bufLen == 0 { if bp.closeErr != nil { @@ -158,7 +159,7 @@ func (bp *BytesPipe) Read(p []byte) (n int, err error) { bp.wait.Broadcast() bp.mu.Unlock() - return + return n, nil } func returnBuffer(b *fixedBuffer) { diff --git a/vendor/go.podman.io/storage/pkg/ioutils/readers.go b/vendor/go.podman.io/storage/pkg/ioutils/readers.go index 146e1a5ff..aed1cb033 100644 --- a/vendor/go.podman.io/storage/pkg/ioutils/readers.go +++ b/vendor/go.podman.io/storage/pkg/ioutils/readers.go @@ -83,7 +83,7 @@ func (r *OnEOFReader) Read(p []byte) (n int, err error) { if err == io.EOF { r.runFunc() } - return + return n, err } // Close closes the file and run the function. diff --git a/vendor/go.podman.io/storage/pkg/ioutils/writers.go b/vendor/go.podman.io/storage/pkg/ioutils/writers.go index 0b6d0a7a6..2a8007e44 100644 --- a/vendor/go.podman.io/storage/pkg/ioutils/writers.go +++ b/vendor/go.podman.io/storage/pkg/ioutils/writers.go @@ -59,8 +59,8 @@ func NewWriteCounter(w io.Writer) *WriteCounter { } } -func (wc *WriteCounter) Write(p []byte) (count int, err error) { - count, err = wc.Writer.Write(p) +func (wc *WriteCounter) Write(p []byte) (int, error) { + count, err := wc.Writer.Write(p) wc.Count += int64(count) - return + return count, err } diff --git a/vendor/go.podman.io/storage/pkg/mount/flags.go b/vendor/go.podman.io/storage/pkg/mount/flags.go index 40a229932..9325e2597 100644 --- a/vendor/go.podman.io/storage/pkg/mount/flags.go +++ b/vendor/go.podman.io/storage/pkg/mount/flags.go @@ -119,7 +119,7 @@ func ParseOptions(options string) (int, string) { data []string ) - for _, o := range strings.Split(options, ",") { + for o := range strings.SplitSeq(options, ",") { // If the option does not exist in the flags table or the flag // is not supported on the platform, // then it is a data value for a specific fs type @@ -139,7 +139,7 @@ func ParseOptions(options string) (int, string) { // ParseTmpfsOptions parse fstab type mount options into flags and data func ParseTmpfsOptions(options string) (int, string, error) { flags, data := ParseOptions(options) - for _, o := range strings.Split(data, ",") { + for o := range strings.SplitSeq(data, ",") { opt, _, _ := strings.Cut(o, "=") if !validFlags[opt] { return 0, "", fmt.Errorf("invalid tmpfs option %q", opt) diff --git a/vendor/go.podman.io/storage/pkg/mount/mounter_freebsd.go b/vendor/go.podman.io/storage/pkg/mount/mounter_freebsd.go index 61d6d1c59..1c99ff461 100644 --- a/vendor/go.podman.io/storage/pkg/mount/mounter_freebsd.go +++ b/vendor/go.podman.io/storage/pkg/mount/mounter_freebsd.go @@ -33,8 +33,7 @@ func mount(device, target, mType string, flag uintptr, data string) error { options := []string{"fspath", target} if data != "" { - xs := strings.Split(data, ",") - for _, x := range xs { + for x := range strings.SplitSeq(data, ",") { if x == "bind" { isNullFS = true continue diff --git a/vendor/go.podman.io/storage/pkg/pools/pools.go b/vendor/go.podman.io/storage/pkg/pools/pools.go index 78b729c2e..1179d9b93 100644 --- a/vendor/go.podman.io/storage/pkg/pools/pools.go +++ b/vendor/go.podman.io/storage/pkg/pools/pools.go @@ -59,11 +59,11 @@ func (bufPool *BufioReaderPool) Put(b *bufio.Reader) { } // Copy is a convenience wrapper which uses a buffer to avoid allocation in io.Copy. -func Copy(dst io.Writer, src io.Reader) (written int64, err error) { +func Copy(dst io.Writer, src io.Reader) (int64, error) { buf := BufioReader32KPool.Get(src) - written, err = io.Copy(dst, buf) + written, err := io.Copy(dst, buf) BufioReader32KPool.Put(buf) - return + return written, err } // NewReadCloserWrapper returns a wrapper which puts the bufio.Reader back diff --git a/vendor/go.podman.io/storage/pkg/system/exitcode.go b/vendor/go.podman.io/storage/pkg/system/exitcode.go index 60f0514b1..4d7b5c880 100644 --- a/vendor/go.podman.io/storage/pkg/system/exitcode.go +++ b/vendor/go.podman.io/storage/pkg/system/exitcode.go @@ -29,5 +29,5 @@ func ProcessExitCode(err error) (exitCode int) { exitCode = 127 } } - return + return exitCode } diff --git a/vendor/go.podman.io/storage/pkg/system/stat_netbsd.go b/vendor/go.podman.io/storage/pkg/system/stat_netbsd.go index 715f05b93..57850a883 100644 --- a/vendor/go.podman.io/storage/pkg/system/stat_netbsd.go +++ b/vendor/go.podman.io/storage/pkg/system/stat_netbsd.go @@ -4,10 +4,12 @@ import "syscall" // fromStatT converts a syscall.Stat_t type to a system.Stat_t type func fromStatT(s *syscall.Stat_t) (*StatT, error) { - return &StatT{size: s.Size, + return &StatT{ + size: s.Size, mode: uint32(s.Mode), uid: s.Uid, gid: s.Gid, rdev: uint64(s.Rdev), - mtim: s.Mtimespec}, nil + mtim: s.Mtimespec, + }, nil } diff --git a/vendor/go.podman.io/storage/pkg/system/xattrs_darwin.go b/vendor/go.podman.io/storage/pkg/system/xattrs_darwin.go index 27ada2083..d574e9e61 100644 --- a/vendor/go.podman.io/storage/pkg/system/xattrs_darwin.go +++ b/vendor/go.podman.io/storage/pkg/system/xattrs_darwin.go @@ -74,7 +74,7 @@ func Llistxattr(path string) ([]string, error) { } var attrs []string - for _, token := range bytes.Split(dest[:sz], []byte{0}) { + for token := range bytes.SplitSeq(dest[:sz], []byte{0}) { if len(token) > 0 { attrs = append(attrs, string(token)) } diff --git a/vendor/go.podman.io/storage/pkg/system/xattrs_freebsd.go b/vendor/go.podman.io/storage/pkg/system/xattrs_freebsd.go index 5d653976e..f62f5f745 100644 --- a/vendor/go.podman.io/storage/pkg/system/xattrs_freebsd.go +++ b/vendor/go.podman.io/storage/pkg/system/xattrs_freebsd.go @@ -17,12 +17,10 @@ const ( EOVERFLOW unix.Errno = unix.EOVERFLOW ) -var ( - namespaceMap = map[string]int{ - "user": EXTATTR_NAMESPACE_USER, - "system": EXTATTR_NAMESPACE_SYSTEM, - } -) +var namespaceMap = map[string]int{ + "user": EXTATTR_NAMESPACE_USER, + "system": EXTATTR_NAMESPACE_SYSTEM, +} func xattrToExtattr(xattr string) (namespace int, extattr string, err error) { namespaceName, extattr, found := strings.Cut(xattr, ".") diff --git a/vendor/go.podman.io/storage/pkg/system/xattrs_linux.go b/vendor/go.podman.io/storage/pkg/system/xattrs_linux.go index 12462cca3..3322707a4 100644 --- a/vendor/go.podman.io/storage/pkg/system/xattrs_linux.go +++ b/vendor/go.podman.io/storage/pkg/system/xattrs_linux.go @@ -77,7 +77,7 @@ func Llistxattr(path string) ([]string, error) { } var attrs []string - for _, token := range bytes.Split(dest[:sz], []byte{0}) { + for token := range bytes.SplitSeq(dest[:sz], []byte{0}) { if len(token) > 0 { attrs = append(attrs, string(token)) } diff --git a/vendor/golang.org/x/oauth2/oauth2.go b/vendor/golang.org/x/oauth2/oauth2.go index de34feb84..3e3b63069 100644 --- a/vendor/golang.org/x/oauth2/oauth2.go +++ b/vendor/golang.org/x/oauth2/oauth2.go @@ -9,7 +9,6 @@ package oauth2 // import "golang.org/x/oauth2" import ( - "bytes" "context" "errors" "net/http" @@ -158,7 +157,7 @@ func SetAuthURLParam(key, value string) AuthCodeOption { // PKCE), https://www.oauth.com/oauth2-servers/pkce/ and // https://www.ietf.org/archive/id/draft-ietf-oauth-v2-1-09.html#name-cross-site-request-forgery (describing both approaches) func (c *Config) AuthCodeURL(state string, opts ...AuthCodeOption) string { - var buf bytes.Buffer + var buf strings.Builder buf.WriteString(c.Endpoint.AuthURL) v := url.Values{ "response_type": {"code"}, diff --git a/vendor/modules.txt b/vendor/modules.txt index ba5793e45..d2184a149 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -212,7 +212,7 @@ github.com/davecgh/go-spew/spew # github.com/distribution/reference v0.6.0 ## explicit; go 1.20 github.com/distribution/reference -# github.com/docker/cli v28.4.0+incompatible +# github.com/docker/cli v28.5.1+incompatible ## explicit github.com/docker/cli/cli/config github.com/docker/cli/cli/config/configfile @@ -224,10 +224,10 @@ github.com/docker/cli/cli/config/types github.com/docker/distribution/registry/api/errcode github.com/docker/distribution/registry/api/v2 github.com/docker/distribution/registry/client/auth/challenge -# github.com/docker/docker v28.3.3+incompatible +# github.com/docker/docker v28.5.1+incompatible ## explicit github.com/docker/docker/api/types/versions -# github.com/docker/docker-credential-helpers v0.9.3 +# github.com/docker/docker-credential-helpers v0.9.4 ## explicit; go 1.21 github.com/docker/docker-credential-helpers/client github.com/docker/docker-credential-helpers/credentials @@ -506,8 +506,8 @@ github.com/josharian/intern # github.com/json-iterator/go v1.1.12 ## explicit; go 1.12 github.com/json-iterator/go -# github.com/klauspost/compress v1.18.0 -## explicit; go 1.22 +# github.com/klauspost/compress v1.18.1 +## explicit; go 1.23 github.com/klauspost/compress github.com/klauspost/compress/flate github.com/klauspost/compress/fse @@ -886,8 +886,8 @@ go.podman.io/common/pkg/auth go.podman.io/common/pkg/capabilities go.podman.io/common/pkg/completion go.podman.io/common/pkg/password -# go.podman.io/image/v5 v5.37.0 -## explicit; go 1.23.3 +# go.podman.io/image/v5 v5.38.0 +## explicit; go 1.24.0 go.podman.io/image/v5/copy go.podman.io/image/v5/directory/explicitfilepath go.podman.io/image/v5/docker @@ -942,8 +942,8 @@ go.podman.io/image/v5/signature/simplesigning go.podman.io/image/v5/transports go.podman.io/image/v5/types go.podman.io/image/v5/version -# go.podman.io/storage v1.60.0 -## explicit; go 1.23.3 +# go.podman.io/storage v1.61.0 +## explicit; go 1.24.0 go.podman.io/storage/internal/rawfilelock go.podman.io/storage/pkg/archive go.podman.io/storage/pkg/chunked/compressor @@ -1015,7 +1015,7 @@ golang.org/x/net/internal/timeseries golang.org/x/net/proxy golang.org/x/net/trace golang.org/x/net/websocket -# golang.org/x/oauth2 v0.31.0 +# golang.org/x/oauth2 v0.32.0 ## explicit; go 1.24.0 golang.org/x/oauth2 golang.org/x/oauth2/internal