diff --git a/cmd/cosign/policy_webhook/main.go b/cmd/cosign/policy_webhook/main.go index 54a90fa6dcd..72fbbd7924a 100644 --- a/cmd/cosign/policy_webhook/main.go +++ b/cmd/cosign/policy_webhook/main.go @@ -28,11 +28,14 @@ import ( "knative.dev/pkg/webhook" "knative.dev/pkg/webhook/certificates" "knative.dev/pkg/webhook/resourcesemantics" + "knative.dev/pkg/webhook/resourcesemantics/conversion" "knative.dev/pkg/webhook/resourcesemantics/defaulting" "knative.dev/pkg/webhook/resourcesemantics/validation" "sigs.k8s.io/release-utils/version" + "github.com/sigstore/cosign/pkg/apis/cosigned" "github.com/sigstore/cosign/pkg/apis/cosigned/v1alpha1" + "github.com/sigstore/cosign/pkg/apis/cosigned/v1beta1" "github.com/sigstore/cosign/pkg/reconciler/clusterimagepolicy" // Register the provider-specific plugins @@ -61,6 +64,13 @@ var ( validatingWebhookName = flag.String("validating-webhook-name", "validating.clusterimagepolicy.sigstore.dev", "The name of the validating webhook configuration as well as the webhook name that is automatically configured, if exists, with different rules and client settings setting how the admission requests to be dispatched to policy-webhook.") ) +var types = map[schema.GroupVersionKind]resourcesemantics.GenericCRD{ + // v1alpha1 + v1alpha1.SchemeGroupVersion.WithKind("ClusterImagePolicy"): &v1alpha1.ClusterImagePolicy{}, + // v1beta1 + v1beta1.SchemeGroupVersion.WithKind("ClusterImagePolicy"): &v1beta1.ClusterImagePolicy{}, +} + func main() { opts := webhook.Options{ ServiceName: "policy-webhook", @@ -81,6 +91,7 @@ func main() { clusterimagepolicy.NewController, NewPolicyValidatingAdmissionController, NewPolicyMutatingAdmissionController, + newConversionController, ) } @@ -89,9 +100,7 @@ func NewPolicyValidatingAdmissionController(ctx context.Context, cmw configmap.W ctx, *validatingWebhookName, "/validating", - map[schema.GroupVersionKind]resourcesemantics.GenericCRD{ - v1alpha1.SchemeGroupVersion.WithKind("ClusterImagePolicy"): &v1alpha1.ClusterImagePolicy{}, - }, + types, func(ctx context.Context) context.Context { return ctx }, @@ -104,12 +113,40 @@ func NewPolicyMutatingAdmissionController(ctx context.Context, cmw configmap.Wat ctx, *mutatingWebhookName, "/defaulting", - map[schema.GroupVersionKind]resourcesemantics.GenericCRD{ - v1alpha1.SchemeGroupVersion.WithKind("ClusterImagePolicy"): &v1alpha1.ClusterImagePolicy{}, - }, + types, func(ctx context.Context) context.Context { return ctx }, true, ) } + +func newConversionController(ctx context.Context, cmw configmap.Watcher) *controller.Impl { + // nolint: revive + var ( + v1alpha1GroupVersion = v1alpha1.SchemeGroupVersion.Version + v1beta1GroupVersion = v1beta1.SchemeGroupVersion.Version + ) + + return conversion.NewConversionController(ctx, + // The path on which to serve the webhook + "/resource-conversion", + + // Specify the types of custom resource definitions that should be converted + map[schema.GroupKind]conversion.GroupKindConversion{ + v1beta1.Kind("ClusterImagePolicy"): { + DefinitionName: cosigned.ClusterImagePolicyResource.String(), + HubVersion: v1alpha1GroupVersion, + Zygotes: map[string]conversion.ConvertibleObject{ + v1alpha1GroupVersion: &v1alpha1.ClusterImagePolicy{}, + v1beta1GroupVersion: &v1beta1.ClusterImagePolicy{}, + }, + }, + }, + + // A function that infuses the context passed to ConvertTo/ConvertFrom/SetDefaults with custom metadata + func(ctx context.Context) context.Context { + return ctx + }, + ) +} diff --git a/config/200-clusterrole.yaml b/config/200-clusterrole.yaml index c97fec636c8..44813272250 100644 --- a/config/200-clusterrole.yaml +++ b/config/200-clusterrole.yaml @@ -37,16 +37,15 @@ rules: # which requires we can Get the system namespace. resourceNames: ["cosign-system"] - # TODO: We will need this once we have conversion webhooks. - # # Allow the reconciliation of exactly our CRDs. - # # This is needed for us to patch in conversion webhook information. - # - apiGroups: ["apiextensions.k8s.io"] - # resources: ["customresourcedefinitions"] - # verbs: ["list", "watch"] - # - apiGroups: ["apiextensions.k8s.io"] - # resources: ["customresourcedefinitions"] - # verbs: ["get", "update"] - # resourceNames: ["clusterimagepolicies.cosigned.sigstore.dev"] + # Allow the reconciliation of exactly our CRDs. + # This is needed for us to patch in conversion webhook information. + - apiGroups: ["apiextensions.k8s.io"] + resources: ["customresourcedefinitions"] + verbs: ["list", "watch"] + - apiGroups: ["apiextensions.k8s.io"] + resources: ["customresourcedefinitions"] + verbs: ["get", "update"] + resourceNames: ["clusterimagepolicies.cosigned.sigstore.dev"] # Allow reconciliation of the ClusterImagePolic CRDs. - apiGroups: ["cosigned.sigstore.dev", "validating.clusterimagepolicy.sigstore.dev", "defaulting.clusterimagepolicy.sigstore.dev"] diff --git a/config/300-clusterimagepolicy.yaml b/config/300-clusterimagepolicy.yaml index e924048f74f..a8bbb17adc1 100644 --- a/config/300-clusterimagepolicy.yaml +++ b/config/300-clusterimagepolicy.yaml @@ -175,3 +175,150 @@ spec: type: string url: type: string + - name: v1beta1 + served: true + storage: false + schema: + openAPIV3Schema: + type: object + properties: + spec: + description: Spec holds the desired state of the ClusterImagePolicy (from the client). + type: object + properties: + authorities: + type: array + items: + type: object + properties: + attestations: + type: array + items: + type: object + properties: + name: + description: Name of the attestation. These can then be referenced at the CIP level policy. + type: string + policy: + type: object + properties: + configMapRef: + type: object + properties: + name: + description: Name is unique within a namespace to reference a configmap resource. + type: string + namespace: + description: Namespace defines the space within which the configmap name must be unique. + type: string + data: + type: string + type: + description: Which kind of policy this is, currently only rego or cue are supported. Furthermore, only cue is tested :) + type: string + url: + type: string + predicateType: + description: Which predicate type to verify. Matches cosign verify-attestation options. + type: string + ctlog: + type: object + properties: + url: + type: string + key: + type: object + properties: + data: + description: Data contains the inline public key + type: string + kms: + description: KMS contains the KMS url of the public key + type: string + secretRef: + type: object + properties: + name: + description: Name is unique within a namespace to reference a secret resource. + type: string + namespace: + description: Namespace defines the space within which the secret name must be unique. + type: string + keyless: + type: object + properties: + ca-cert: + type: object + properties: + data: + description: Data contains the inline public key + type: string + kms: + description: KMS contains the KMS url of the public key + type: string + secretRef: + type: object + properties: + name: + description: Name is unique within a namespace to reference a secret resource. + type: string + namespace: + description: Namespace defines the space within which the secret name must be unique. + type: string + identities: + type: array + items: + type: object + properties: + issuer: + type: string + subject: + type: string + url: + type: string + name: + description: Name is the name for this authority. Used by the CIP Policy validator to be able to reference matching signature or attestation verifications. If not specified, the name will be authority- + type: string + source: + type: array + items: + type: object + properties: + oci: + type: string + signaturePullSecrets: + description: SignaturePullSecrets is an optional list of references to secrets in the same namespace as the deploying resource for pulling any of the signatures used by this Source. + type: array + items: + type: object + properties: + name: + description: 'Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names' + type: string + images: + type: array + items: + type: object + properties: + glob: + type: string + policy: + description: Policy is an optional policy that can be applied against all the successfully validated Authorities. If no authorities pass, this does not even get evaluated, as the Policy is considered failed. + type: object + properties: + configMapRef: + type: object + properties: + name: + description: Name is unique within a namespace to reference a configmap resource. + type: string + namespace: + description: Namespace defines the space within which the configmap name must be unique. + type: string + data: + type: string + type: + description: Which kind of policy this is, currently only rego or cue are supported. Furthermore, only cue is tested :) + type: string + url: + type: string diff --git a/hack/update-codegen.sh b/hack/update-codegen.sh index f8c9c05ab2d..323c687c204 100755 --- a/hack/update-codegen.sh +++ b/hack/update-codegen.sh @@ -45,7 +45,7 @@ group "Kubernetes Codegen" # instead of the $GOPATH directly. For normal projects this can be dropped. ${CODEGEN_PKG}/generate-groups.sh "deepcopy,client,informer,lister" \ github.com/sigstore/cosign/pkg/client github.com/sigstore/cosign/pkg/apis \ - "cosigned:v1alpha1" \ + "cosigned:v1alpha1 cosigned:v1beta1" \ --go-header-file ${REPO_ROOT_DIR}/hack/boilerplate/boilerplate.go.txt group "Knative Codegen" @@ -53,7 +53,7 @@ group "Knative Codegen" # Knative Injection ${KNATIVE_CODEGEN_PKG}/hack/generate-knative.sh "injection" \ github.com/sigstore/cosign/pkg/client github.com/sigstore/cosign/pkg/apis \ - "cosigned:v1alpha1" \ + "cosigned:v1alpha1 cosigned:v1beta1" \ --go-header-file ${REPO_ROOT_DIR}/hack/boilerplate/boilerplate.go.txt group "Update CRD Schema" diff --git a/pkg/apis/cosigned/register.go b/pkg/apis/cosigned/register.go index 7414b7fee97..c4f2dcf5567 100644 --- a/pkg/apis/cosigned/register.go +++ b/pkg/apis/cosigned/register.go @@ -14,7 +14,17 @@ package cosigned +import "k8s.io/apimachinery/pkg/runtime/schema" + const ( // GroupName is the name of the API group. GroupName = "cosigned.sigstore.dev" ) + +var ( + // ClusterImagePolicyResource represents a ClusterImagePolicy + ClusterImagePolicyResource = schema.GroupResource{ + Group: GroupName, + Resource: "clusterimagepolicies", + } +) diff --git a/pkg/apis/cosigned/v1alpha1/clusterimagepolicy_conversion.go b/pkg/apis/cosigned/v1alpha1/clusterimagepolicy_conversion.go new file mode 100644 index 00000000000..18ff95216eb --- /dev/null +++ b/pkg/apis/cosigned/v1alpha1/clusterimagepolicy_conversion.go @@ -0,0 +1,192 @@ +// Copyright 2022 The Sigstore Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package v1alpha1 + +import ( + "context" + "fmt" + + "github.com/sigstore/cosign/pkg/apis/cosigned/v1beta1" + v1 "k8s.io/api/core/v1" + "knative.dev/pkg/apis" +) + +var _ apis.Convertible = (*ClusterImagePolicy)(nil) + +// ConvertTo implements api.Convertible +func (c *ClusterImagePolicy) ConvertTo(ctx context.Context, obj apis.Convertible) error { + switch sink := obj.(type) { + case *v1beta1.ClusterImagePolicy: + sink.ObjectMeta = c.ObjectMeta + return c.Spec.ConvertTo(ctx, &sink.Spec) + default: + return fmt.Errorf("unknown version, got: %T", sink) + } +} + +// ConvertFrom implements api.Convertible +func (c *ClusterImagePolicy) ConvertFrom(ctx context.Context, obj apis.Convertible) error { + switch source := obj.(type) { + case *v1beta1.ClusterImagePolicy: + c.ObjectMeta = source.ObjectMeta + return c.Spec.ConvertFrom(ctx, &source.Spec) + default: + return fmt.Errorf("unknown version, got: %T", c) + } +} + +func (spec *ClusterImagePolicySpec) ConvertTo(ctx context.Context, sink *v1beta1.ClusterImagePolicySpec) error { + for _, image := range spec.Images { + sink.Images = append(sink.Images, v1beta1.ImagePattern{Glob: image.Glob}) + } + for _, authority := range spec.Authorities { + v1beta1Authority := v1beta1.Authority{} + err := authority.ConvertTo(ctx, &v1beta1Authority) + if err != nil { + return err + } + sink.Authorities = append(sink.Authorities, v1beta1Authority) + } + return nil +} + +func (authority *Authority) ConvertTo(ctx context.Context, sink *v1beta1.Authority) error { + sink.Name = authority.Name + if authority.CTLog != nil && authority.CTLog.URL != nil { + sink.CTLog = &v1beta1.TLog{URL: authority.CTLog.URL.DeepCopy()} + } + for _, source := range authority.Sources { + v1beta1Source := v1beta1.Source{} + v1beta1Source.OCI = source.OCI + for _, sps := range source.SignaturePullSecrets { + v1beta1Source.SignaturePullSecrets = append(v1beta1Source.SignaturePullSecrets, v1.LocalObjectReference{Name: sps.Name}) + } + sink.Sources = append(sink.Sources, v1beta1Source) + } + for _, att := range authority.Attestations { + v1beta1Att := v1beta1.Attestation{} + v1beta1Att.Name = att.Name + v1beta1Att.PredicateType = att.PredicateType + if att.Policy != nil { + v1beta1Att.Policy = &v1beta1.Policy{ + Type: att.Policy.Type, + Data: att.Policy.Data, + } + v1beta1Att.Policy.URL = att.Policy.URL.DeepCopy() + if att.Policy.ConfigMapRef != nil { + v1beta1Att.Policy.ConfigMapRef = &v1beta1.ConfigMapReference{ + Name: att.Policy.ConfigMapRef.Name, + Namespace: att.Policy.ConfigMapRef.Namespace, + } + } + } + sink.Attestations = append(sink.Attestations, v1beta1Att) + } + if authority.Key != nil { + sink.Key = &v1beta1.KeyRef{} + authority.Key.ConvertTo(ctx, sink.Key) + } + if authority.Keyless != nil { + sink.Keyless = &v1beta1.KeylessRef{ + URL: authority.Keyless.URL.DeepCopy(), + } + for _, id := range authority.Keyless.Identities { + sink.Keyless.Identities = append(sink.Keyless.Identities, v1beta1.Identity{Issuer: id.Issuer, Subject: id.Subject}) + } + if authority.Keyless.CACert != nil { + sink.Keyless.CACert = &v1beta1.KeyRef{} + authority.Keyless.CACert.ConvertTo(ctx, sink.Keyless.CACert) + } + } + return nil +} + +func (key *KeyRef) ConvertTo(ctx context.Context, sink *v1beta1.KeyRef) { + sink.SecretRef = key.SecretRef.DeepCopy() + sink.Data = key.Data + sink.KMS = key.KMS +} + +func (spec *ClusterImagePolicySpec) ConvertFrom(ctx context.Context, source *v1beta1.ClusterImagePolicySpec) error { + for _, image := range source.Images { + spec.Images = append(spec.Images, ImagePattern{Glob: image.Glob}) + } + for i := range source.Authorities { + authority := Authority{} + err := authority.ConvertFrom(ctx, &source.Authorities[i]) + if err != nil { + return err + } + spec.Authorities = append(spec.Authorities, authority) + } + return nil +} + +func (authority *Authority) ConvertFrom(ctx context.Context, source *v1beta1.Authority) error { + authority.Name = source.Name + if source.CTLog != nil && source.CTLog.URL != nil { + authority.CTLog = &TLog{URL: source.CTLog.URL.DeepCopy()} + } + for _, s := range source.Sources { + src := Source{} + src.OCI = s.OCI + for _, sps := range s.SignaturePullSecrets { + src.SignaturePullSecrets = append(src.SignaturePullSecrets, v1.LocalObjectReference{Name: sps.Name}) + } + authority.Sources = append(authority.Sources, src) + } + for _, att := range source.Attestations { + attestation := Attestation{} + attestation.Name = att.Name + attestation.PredicateType = att.PredicateType + if att.Policy != nil { + attestation.Policy = &Policy{ + Type: att.Policy.Type, + Data: att.Policy.Data, + } + attestation.Policy.URL = att.Policy.URL.DeepCopy() + if att.Policy.ConfigMapRef != nil { + attestation.Policy.ConfigMapRef = &ConfigMapReference{ + Name: att.Policy.ConfigMapRef.Name, + Namespace: att.Policy.ConfigMapRef.Namespace, + } + } + } + authority.Attestations = append(authority.Attestations, attestation) + } + if source.Key != nil { + authority.Key = &KeyRef{} + authority.Key.ConvertFrom(ctx, source.Key) + } + if source.Keyless != nil { + authority.Keyless = &KeylessRef{ + URL: source.Keyless.URL.DeepCopy(), + } + for _, id := range source.Keyless.Identities { + authority.Keyless.Identities = append(authority.Keyless.Identities, Identity{Issuer: id.Issuer, Subject: id.Subject}) + } + if source.Keyless.CACert != nil { + authority.Keyless.CACert = &KeyRef{} + authority.Keyless.CACert.ConvertFrom(ctx, source.Keyless.CACert) + } + } + return nil +} + +func (key *KeyRef) ConvertFrom(ctx context.Context, source *v1beta1.KeyRef) { + key.SecretRef = source.SecretRef.DeepCopy() + key.Data = source.Data + key.KMS = source.KMS +} diff --git a/pkg/apis/cosigned/v1alpha1/clusterimagepolicy_conversion_test.go b/pkg/apis/cosigned/v1alpha1/clusterimagepolicy_conversion_test.go new file mode 100644 index 00000000000..775730d2dcb --- /dev/null +++ b/pkg/apis/cosigned/v1alpha1/clusterimagepolicy_conversion_test.go @@ -0,0 +1,130 @@ +// Copyright 2022 The Sigstore Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package v1alpha1 + +import ( + "context" + "testing" + + "github.com/google/go-cmp/cmp" + v1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + "github.com/sigstore/cosign/pkg/apis/cosigned/v1beta1" +) + +// Test v1alpha1 -> v1beta1 -> v1alpha1 +func TestConversionRoundTripV1alpha1(t *testing.T) { + tests := []struct { + name string + in *ClusterImagePolicy + }{{name: "key and keyless", + in: &ClusterImagePolicy{ + ObjectMeta: metav1.ObjectMeta{ + Name: "test-cip", + }, + Spec: ClusterImagePolicySpec{ + Images: []ImagePattern{{Glob: "*"}}, + Authorities: []Authority{ + {Key: &KeyRef{ + SecretRef: &v1.SecretReference{Name: "mysecret"}}}, + {Keyless: &KeylessRef{ + Identities: []Identity{{Subject: "subject", Issuer: "issuer"}}, + CACert: &KeyRef{KMS: "kms", Data: "data", SecretRef: &v1.SecretReference{Name: "secret"}}, + }}, + }, + }, + }, + }, {name: "source and attestations", + in: &ClusterImagePolicy{ + ObjectMeta: metav1.ObjectMeta{ + Name: "test-cip", + }, + Spec: ClusterImagePolicySpec{ + Images: []ImagePattern{{Glob: "*"}}, + Authorities: []Authority{ + {Key: &KeyRef{ + SecretRef: &v1.SecretReference{Name: "mysecret"}}}, + {Sources: []Source{{ + OCI: "registry.example.com", + SignaturePullSecrets: []v1.LocalObjectReference{{Name: "sps-secret"}}}}}, + {Attestations: []Attestation{{ + Name: "attestation-0", + PredicateType: "vuln", + Policy: &Policy{ + Type: "cue", + Data: "cue language goes here", + }, + }}}, + }, + }, + }, + }} + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + ver := &v1beta1.ClusterImagePolicy{} + if err := test.in.ConvertTo(context.Background(), ver); err != nil { + t.Error("ConvertTo() =", err) + } + got := &ClusterImagePolicy{} + if err := got.ConvertFrom(context.Background(), ver); err != nil { + t.Error("ConvertFrom() =", err) + } + + if diff := cmp.Diff(test.in, got); diff != "" { + t.Error("roundtrip (-want, +got) =", diff) + } + }) + } +} + +// Test v1beta1 -> v1alpha1 -> v1beta1 +func TestConversionRoundTripV1beta1(t *testing.T) { + tests := []struct { + name string + in *v1beta1.ClusterImagePolicy + }{{name: "simple configuration", + in: &v1beta1.ClusterImagePolicy{ + ObjectMeta: metav1.ObjectMeta{ + Name: "test-cip", + }, + Spec: v1beta1.ClusterImagePolicySpec{ + Images: []v1beta1.ImagePattern{{Glob: "*"}}, + }, + }, + }, {name: "another", + in: &v1beta1.ClusterImagePolicy{ + ObjectMeta: metav1.ObjectMeta{ + Name: "test-cip", + }, + }, + }} + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + ver := &ClusterImagePolicy{} + if err := ver.ConvertFrom(context.Background(), test.in); err != nil { + t.Error("ConvertDown() =", err) + } + got := &v1beta1.ClusterImagePolicy{} + if err := ver.ConvertTo(context.Background(), got); err != nil { + t.Error("ConvertUp() =", err) + } + + if diff := cmp.Diff(test.in, got); diff != "" { + t.Error("roundtrip (-want, +got) =", diff) + } + }) + } +} diff --git a/pkg/apis/cosigned/v1alpha1/clusterimagepolicy_types.go b/pkg/apis/cosigned/v1alpha1/clusterimagepolicy_types.go index dbff4aa63ef..682f368512f 100644 --- a/pkg/apis/cosigned/v1alpha1/clusterimagepolicy_types.go +++ b/pkg/apis/cosigned/v1alpha1/clusterimagepolicy_types.go @@ -65,8 +65,7 @@ type ClusterImagePolicySpec struct { // If multiple patterns match a particular image, then ALL of // those authorities must be satisfied for the image to be admitted. type ImagePattern struct { - // +optional - Glob string `json:"glob,omitempty"` + Glob string `json:"glob"` } // The authorities block defines the rules for discovering and diff --git a/pkg/apis/cosigned/v1alpha1/clusterimagepolicy_validation.go b/pkg/apis/cosigned/v1alpha1/clusterimagepolicy_validation.go index c979a9d61bf..7881a9c816d 100644 --- a/pkg/apis/cosigned/v1alpha1/clusterimagepolicy_validation.go +++ b/pkg/apis/cosigned/v1alpha1/clusterimagepolicy_validation.go @@ -53,10 +53,7 @@ func (image *ImagePattern) Validate(ctx context.Context) *apis.FieldError { errs = errs.Also(apis.ErrMissingField("glob")) } - if image.Glob != "" { - errs = errs.Also(ValidateGlob(image.Glob).ViaField("glob")) - } - + errs = errs.Also(ValidateGlob(image.Glob).ViaField("glob")) return errs } diff --git a/pkg/apis/cosigned/v1beta1/clusterimagepolicy_conversion.go b/pkg/apis/cosigned/v1beta1/clusterimagepolicy_conversion.go new file mode 100644 index 00000000000..9a1da9c39ea --- /dev/null +++ b/pkg/apis/cosigned/v1beta1/clusterimagepolicy_conversion.go @@ -0,0 +1,34 @@ +// Copyright 2022 The Sigstore Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package v1beta1 + +import ( + "context" + "fmt" + + "knative.dev/pkg/apis" +) + +var _ apis.Convertible = (*ClusterImagePolicy)(nil) + +// ConvertTo implements api.Convertible +func (c *ClusterImagePolicy) ConvertTo(ctx context.Context, sink apis.Convertible) error { + return fmt.Errorf("v1beta1 is the highest known version, got: %T", sink) +} + +// ConvertFrom implements api.Convertible +func (c *ClusterImagePolicy) ConvertFrom(ctx context.Context, source apis.Convertible) error { + return fmt.Errorf("v1beta1 is the highest know version, got: %T", source) +} diff --git a/pkg/apis/cosigned/v1beta1/clusterimagepolicy_conversion_test.go b/pkg/apis/cosigned/v1beta1/clusterimagepolicy_conversion_test.go new file mode 100644 index 00000000000..2af5a89933b --- /dev/null +++ b/pkg/apis/cosigned/v1beta1/clusterimagepolicy_conversion_test.go @@ -0,0 +1,44 @@ +// Copyright 2022 The Sigstore Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package v1beta1 + +import ( + "context" + "fmt" + "testing" + + "knative.dev/pkg/apis" +) + +type BadOne struct{} + +func (ct *BadOne) ConvertTo(ctx context.Context, sink apis.Convertible) error { + return fmt.Errorf("v1beta1 is the highest known version, got: %T", sink) +} +func (ct *BadOne) ConvertFrom(ctx context.Context, source apis.Convertible) error { + return fmt.Errorf("v1beta1 is the highest know version, got: %T", source) +} + +func TestClusterTaskConversionBadType(t *testing.T) { + good, bad := &ClusterImagePolicy{}, &BadOne{} + + if err := good.ConvertTo(context.Background(), bad); err == nil { + t.Errorf("ConvertTo() = %#v, wanted error", bad) + } + + if err := good.ConvertFrom(context.Background(), bad); err == nil { + t.Errorf("ConvertFrom() = %#v, wanted error", good) + } +} diff --git a/pkg/apis/cosigned/v1beta1/clusterimagepolicy_defaults.go b/pkg/apis/cosigned/v1beta1/clusterimagepolicy_defaults.go new file mode 100644 index 00000000000..bb23d3d4558 --- /dev/null +++ b/pkg/apis/cosigned/v1beta1/clusterimagepolicy_defaults.go @@ -0,0 +1,33 @@ +// Copyright 2022 The Sigstore Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package v1beta1 + +import ( + "context" + "fmt" +) + +// SetDefaults implements apis.Defaultable +func (c *ClusterImagePolicy) SetDefaults(ctx context.Context) { + c.Spec.SetDefaults(ctx) +} + +func (spec *ClusterImagePolicySpec) SetDefaults(ctx context.Context) { + for i, authority := range spec.Authorities { + if authority.Name == "" { + spec.Authorities[i].Name = fmt.Sprintf("authority-%d", i) + } + } +} diff --git a/pkg/apis/cosigned/v1beta1/clusterimagepolicy_defaults_test.go b/pkg/apis/cosigned/v1beta1/clusterimagepolicy_defaults_test.go new file mode 100644 index 00000000000..86318c5d340 --- /dev/null +++ b/pkg/apis/cosigned/v1beta1/clusterimagepolicy_defaults_test.go @@ -0,0 +1,63 @@ +// Copyright 2022 The Sigstore Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package v1beta1 + +import ( + "context" + + "testing" + + "knative.dev/pkg/apis" +) + +func TestNameDefaulting(t *testing.T) { + tests := []struct { + in *ClusterImagePolicy + wantNames []string + }{ + {in: cipWithNames([]string{""}), + wantNames: []string{"authority-0"}, + }, + {in: cipWithNames([]string{"", "vuln-scan"}), + wantNames: []string{"authority-0", "vuln-scan"}, + }, + {in: cipWithNames([]string{"vuln-scan", ""}), + wantNames: []string{"vuln-scan", "authority-1"}, + }, + {in: cipWithNames([]string{"first", "second"}), + wantNames: []string{"first", "second"}, + }} + for _, tc := range tests { + tc.in.SetDefaults(context.TODO()) + if len(tc.in.Spec.Authorities) != len(tc.wantNames) { + t.Fatalf("Mismatch number of wantNames: %d vs authorities: %d", len(tc.wantNames), len(tc.in.Spec.Authorities)) + } + for i, wantName := range tc.wantNames { + if tc.in.Spec.Authorities[i].Name != wantName { + t.Errorf("Wanted name: %s got %s", wantName, tc.in.Spec.Authorities[i].Name) + } + } + } +} + +func cipWithNames(names []string) *ClusterImagePolicy { + cip := &ClusterImagePolicy{ + Spec: ClusterImagePolicySpec{}, + } + for _, name := range names { + cip.Spec.Authorities = append(cip.Spec.Authorities, Authority{Name: name, Keyless: &KeylessRef{URL: &apis.URL{Host: "tests.example.com"}}}) + } + return cip +} diff --git a/pkg/apis/cosigned/v1beta1/clusterimagepolicy_types.go b/pkg/apis/cosigned/v1beta1/clusterimagepolicy_types.go new file mode 100644 index 00000000000..3840189755d --- /dev/null +++ b/pkg/apis/cosigned/v1beta1/clusterimagepolicy_types.go @@ -0,0 +1,197 @@ +// Copyright 2022 The Sigstore Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package v1beta1 + +import ( + v1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime/schema" + "knative.dev/pkg/apis" + "knative.dev/pkg/kmeta" +) + +// ClusterImagePolicy defines the images that go through verification +// and the authorities used for verification +// +// +genclient +// +genclient:nonNamespaced +// +genclient:noStatus +// +genreconciler:krshapedlogic=false + +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object +type ClusterImagePolicy struct { + metav1.TypeMeta `json:",inline"` + metav1.ObjectMeta `json:"metadata"` + + // Spec holds the desired state of the ClusterImagePolicy (from the client). + Spec ClusterImagePolicySpec `json:"spec"` +} + +var ( + _ apis.Validatable = (*ClusterImagePolicy)(nil) + _ apis.Defaultable = (*ClusterImagePolicy)(nil) + _ kmeta.OwnerRefable = (*ClusterImagePolicy)(nil) +) + +// GetGroupVersionKind implements kmeta.OwnerRefable +func (c *ClusterImagePolicy) GetGroupVersionKind() schema.GroupVersionKind { + return SchemeGroupVersion.WithKind("ClusterImagePolicy") +} + +// ClusterImagePolicySpec defines a list of images that should be verified +type ClusterImagePolicySpec struct { + Images []ImagePattern `json:"images"` + Authorities []Authority `json:"authorities"` + // Policy is an optional policy that can be applied against all the + // successfully validated Authorities. If no authorities pass, this does + // not even get evaluated, as the Policy is considered failed. + // +optional + Policy *Policy `json:"policy,omitempty"` +} + +// ImagePattern defines a pattern and its associated authorties +// If multiple patterns match a particular image, then ALL of +// those authorities must be satisfied for the image to be admitted. +type ImagePattern struct { + Glob string `json:"glob"` +} + +// The authorities block defines the rules for discovering and +// validating signatures. Signatures are +// cryptographically verified using one of the "key" or "keyless" +// fields. +// When multiple authorities are specified, any of them may be used +// to source the valid signature we are looking for to admit an +// image. + +type Authority struct { + // Name is the name for this authority. Used by the CIP Policy + // validator to be able to reference matching signature or attestation + // verifications. + // If not specified, the name will be authority- + Name string `json:"name"` + // +optional + Key *KeyRef `json:"key,omitempty"` + // +optional + Keyless *KeylessRef `json:"keyless,omitempty"` + // +optional + Sources []Source `json:"source,omitempty"` + // +optional + CTLog *TLog `json:"ctlog,omitempty"` + // +optional + Attestations []Attestation `json:"attestations,omitempty"` +} + +// This references a public verification key stored in +// a secret in the cosign-system namespace. +// A KeyRef must specify only one of SecretRef, Data or KMS +type KeyRef struct { + // +optional + SecretRef *v1.SecretReference `json:"secretRef,omitempty"` + // Data contains the inline public key + // +optional + Data string `json:"data,omitempty"` + // KMS contains the KMS url of the public key + // +optional + KMS string `json:"kms,omitempty"` +} + +// Source specifies the location of the signature +type Source struct { + // +optional + OCI string `json:"oci,omitempty"` + // SignaturePullSecrets is an optional list of references to secrets in the + // same namespace as the deploying resource for pulling any of the signatures + // used by this Source. + // +optional + SignaturePullSecrets []v1.LocalObjectReference `json:"signaturePullSecrets,omitempty"` +} + +// TLog specifies the URL to a transparency log that holds +// the signature and public key information +type TLog struct { + // +optional + URL *apis.URL `json:"url,omitempty"` +} + +// KeylessRef contains location of the validating certificate and the identities +// against which to verify. KeylessRef will contain either the URL to the verifying +// certificate, or it will contain the certificate data inline or in a secret. +type KeylessRef struct { + // +optional + URL *apis.URL `json:"url,omitempty"` + // +optional + Identities []Identity `json:"identities,omitempty"` + // +optional + CACert *KeyRef `json:"ca-cert,omitempty"` +} + +// Attestation defines the type of attestation to validate and optionally +// apply a policy decision to it. Authority block is used to verify the +// specified attestation types, and if Policy is specified, then it's applied +// only after the validation of the Attestation signature has been verified. +type Attestation struct { + // Name of the attestation. These can then be referenced at the CIP level + // policy. + Name string `json:"name"` + // Which predicate type to verify. Matches cosign verify-attestation options. + PredicateType string `json:"predicateType"` + // +optional + Policy *Policy `json:"policy,omitempty"` +} + +// Policy specifies a policy to use for Attestation validation. +// Exactly one of Data, URL, or ConfigMapReference must be specified. +type Policy struct { + // Which kind of policy this is, currently only rego or cue are supported. + // Furthermore, only cue is tested :) + Type string `json:"type"` + // +optional + Data string `json:"data,omitempty"` + // +optional + URL *apis.URL `json:"url,omitempty"` + // +optional + ConfigMapRef *ConfigMapReference `json:"configMapRef,omitempty"` +} + +// ConfigMapReference is cut&paste from SecretReference, but for the life of me +// couldn't find one in the public types. If there's one, use it. +type ConfigMapReference struct { + // Name is unique within a namespace to reference a configmap resource. + // +optional + Name string `json:"name,omitempty"` + // Namespace defines the space within which the configmap name must be unique. + // +optional + Namespace string `json:"namespace,omitempty"` +} + +// Identity may contain the issuer and/or the subject found in the transparency log. +// Either field supports a pattern glob. +type Identity struct { + // +optional + Issuer string `json:"issuer,omitempty"` + // +optional + Subject string `json:"subject,omitempty"` +} + +// ClusterImagePolicyList is a list of ClusterImagePolicy resources +// +// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object +type ClusterImagePolicyList struct { + metav1.TypeMeta `json:",inline"` + metav1.ListMeta `json:"metadata"` + + Items []ClusterImagePolicy `json:"items"` +} diff --git a/pkg/apis/cosigned/v1beta1/clusterimagepolicy_validation.go b/pkg/apis/cosigned/v1beta1/clusterimagepolicy_validation.go new file mode 100644 index 00000000000..86a05e664ea --- /dev/null +++ b/pkg/apis/cosigned/v1beta1/clusterimagepolicy_validation.go @@ -0,0 +1,213 @@ +// Copyright 2022 The Sigstore Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package v1beta1 + +import ( + "context" + "fmt" + "path/filepath" + "regexp" + + "github.com/sigstore/cosign/pkg/apis/utils" + "knative.dev/pkg/apis" +) + +// Validate implements apis.Validatable +func (c *ClusterImagePolicy) Validate(ctx context.Context) *apis.FieldError { + return c.Spec.Validate(ctx).ViaField("spec") +} + +func (spec *ClusterImagePolicySpec) Validate(ctx context.Context) (errors *apis.FieldError) { + if len(spec.Images) == 0 { + errors = errors.Also(apis.ErrMissingField("images")) + } + for i, image := range spec.Images { + errors = errors.Also(image.Validate(ctx).ViaFieldIndex("images", i)) + } + if len(spec.Authorities) == 0 { + errors = errors.Also(apis.ErrMissingField("authorities")) + } + for i, authority := range spec.Authorities { + errors = errors.Also(authority.Validate(ctx).ViaFieldIndex("authorities", i)) + } + errors = errors.Also(spec.Policy.Validate(ctx)) + + return +} + +func (image *ImagePattern) Validate(ctx context.Context) *apis.FieldError { + var errs *apis.FieldError + if image.Glob == "" { + errs = errs.Also(apis.ErrMissingField("glob")) + } + + errs = errs.Also(ValidateGlob(image.Glob).ViaField("glob")) + + return errs +} + +func (authority *Authority) Validate(ctx context.Context) *apis.FieldError { + var errs *apis.FieldError + if authority.Key == nil && authority.Keyless == nil { + errs = errs.Also(apis.ErrMissingOneOf("key", "keyless")) + } + if authority.Key != nil && authority.Keyless != nil { + errs = errs.Also(apis.ErrMultipleOneOf("key", "keyless")) + } + + if authority.Key != nil { + errs = errs.Also(authority.Key.Validate(ctx).ViaField("key")) + } + if authority.Keyless != nil { + errs = errs.Also(authority.Keyless.Validate(ctx).ViaField("keyless")) + } + + for i, source := range authority.Sources { + errs = errs.Also(source.Validate(ctx).ViaFieldIndex("source", i)) + } + + for _, att := range authority.Attestations { + errs = errs.Also(att.Validate(ctx).ViaField("attestations")) + } + + return errs +} + +func (key *KeyRef) Validate(ctx context.Context) *apis.FieldError { + var errs *apis.FieldError + + if key.Data == "" && key.KMS == "" && key.SecretRef == nil { + errs = errs.Also(apis.ErrMissingOneOf("data", "kms", "secretref")) + } + + if key.Data != "" { + if key.KMS != "" || key.SecretRef != nil { + errs = errs.Also(apis.ErrMultipleOneOf("data", "kms", "secretref")) + } + validPubkey := utils.IsValidKey([]byte(key.Data)) + if !validPubkey { + errs = errs.Also( + apis.ErrInvalidValue(key.Data, "data"), + ) + } + } else if key.KMS != "" && key.SecretRef != nil { + errs = errs.Also(apis.ErrMultipleOneOf("data", "kms", "secretref")) + } + return errs +} + +func (keyless *KeylessRef) Validate(ctx context.Context) *apis.FieldError { + var errs *apis.FieldError + if keyless.URL == nil && keyless.Identities == nil && keyless.CACert == nil { + errs = errs.Also(apis.ErrMissingOneOf("url", "identities", "ca-cert")) + } + + // TODO: Are these really mutually exclusive? + if keyless.URL != nil && keyless.CACert != nil { + errs = errs.Also(apis.ErrMultipleOneOf("url", "ca-cert")) + } + + if keyless.Identities != nil && len(keyless.Identities) == 0 { + errs = errs.Also(apis.ErrMissingField("identities")) + } + + for i, identity := range keyless.Identities { + errs = errs.Also(identity.Validate(ctx).ViaFieldIndex("identities", i)) + } + return errs +} + +func (source *Source) Validate(ctx context.Context) *apis.FieldError { + var errs *apis.FieldError + if source.OCI == "" { + errs = errs.Also(apis.ErrMissingField("oci")) + } + + if len(source.SignaturePullSecrets) > 0 { + for i, secret := range source.SignaturePullSecrets { + if secret.Name == "" { + errs = errs.Also(apis.ErrMissingField("name")).ViaFieldIndex("signaturePullSecrets", i) + } + } + } + return errs +} + +func (a *Attestation) Validate(ctx context.Context) *apis.FieldError { + var errs *apis.FieldError + if a.Name == "" { + errs = errs.Also(apis.ErrMissingField("name")) + } + if a.PredicateType == "" { + errs = errs.Also(apis.ErrMissingField("predicateType")) + } else if a.PredicateType != "custom" && a.PredicateType != "slsaprovenance" && a.PredicateType != "spdx" && a.PredicateType != "link" && a.PredicateType != "vuln" { + // TODO(vaikas): The above should be using something like: + // if _, ok := options.PredicateTypeMap[a.PrecicateType]; !ok { + // But it causes an import loop. That refactor can be part of + // another PR. + errs = errs.Also(apis.ErrInvalidValue(a.PredicateType, "predicateType", "unsupported precicate type")) + } + errs = errs.Also(a.Policy.Validate(ctx).ViaField("policy")) + return errs +} + +func (p *Policy) Validate(ctx context.Context) *apis.FieldError { + if p == nil { + return nil + } + var errs *apis.FieldError + if p.Type != "cue" { + errs = errs.Also(apis.ErrInvalidValue(p.Type, "type", "only cue is supported at the moment")) + } + if p.Data == "" { + errs = errs.Also(apis.ErrMissingField("data")) + } + // TODO(vaikas): How to validate the cue / rego bytes here (data). + return errs +} + +func (identity *Identity) Validate(ctx context.Context) *apis.FieldError { + var errs *apis.FieldError + if identity.Issuer == "" && identity.Subject == "" { + errs = errs.Also(apis.ErrMissingOneOf("issuer", "subject")) + } + if identity.Issuer != "" { + errs = errs.Also(ValidateRegex(identity.Issuer).ViaField("issuer")) + } + if identity.Subject != "" { + errs = errs.Also(ValidateRegex(identity.Subject).ViaField("subject")) + } + return errs +} + +// ValidateGlob glob compilation by testing against empty string +func ValidateGlob(glob string) *apis.FieldError { + _, err := filepath.Match(glob, "") + if err != nil { + return apis.ErrInvalidValue(glob, apis.CurrentField, fmt.Sprintf("glob is invalid: %v", err)) + } + + return nil +} + +func ValidateRegex(regex string) *apis.FieldError { + // It's a regexp, so pull out the regex + _, err := regexp.Compile(regex) + if err != nil { + return apis.ErrInvalidValue(regex, apis.CurrentField, fmt.Sprintf("regex is invalid: %v", err)) + } + + return nil +} diff --git a/pkg/apis/cosigned/v1beta1/clusterimagepolicy_validation_test.go b/pkg/apis/cosigned/v1beta1/clusterimagepolicy_validation_test.go new file mode 100644 index 00000000000..3dad6b9b51d --- /dev/null +++ b/pkg/apis/cosigned/v1beta1/clusterimagepolicy_validation_test.go @@ -0,0 +1,678 @@ +// Copyright 2022 The Sigstore Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package v1beta1 + +import ( + "context" + "testing" + + "github.com/stretchr/testify/require" + v1 "k8s.io/api/core/v1" + "knative.dev/pkg/apis" +) + +func TestImagePatternValidation(t *testing.T) { + tests := []struct { + name string + expectErr bool + errorString string + policy ClusterImagePolicy + }{ + { + name: "Should fail when glob is not present", + expectErr: true, + errorString: "missing field(s): spec.authorities, spec.images[0].glob", + policy: ClusterImagePolicy{ + Spec: ClusterImagePolicySpec{ + Images: []ImagePattern{ + {}, + }, + }, + }, + }, + { + name: "Glob should fail with invalid glob", + expectErr: true, + errorString: "invalid value: [: spec.images[0].glob\nglob is invalid: syntax error in pattern\nmissing field(s): spec.authorities", + policy: ClusterImagePolicy{ + Spec: ClusterImagePolicySpec{ + Images: []ImagePattern{ + { + Glob: "[", + }, + }, + }, + }, + }, + { + name: "missing image and authorities in the spec", + expectErr: true, + errorString: "missing field(s): spec.authorities, spec.images", + policy: ClusterImagePolicy{ + Spec: ClusterImagePolicySpec{}, + }, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + err := test.policy.Validate(context.TODO()) + if test.expectErr { + require.NotNil(t, err) + require.EqualError(t, err, test.errorString) + } else { + require.Nil(t, err) + } + }) + } +} + +func TestKeyValidation(t *testing.T) { + tests := []struct { + name string + expectErr bool + errorString string + policy ClusterImagePolicy + }{ + { + name: "Should fail when key has multiple properties", + expectErr: true, + errorString: "expected exactly one, got both: spec.authorities[0].key.data, spec.authorities[0].key.kms, spec.authorities[0].key.secretref", + policy: ClusterImagePolicy{ + Spec: ClusterImagePolicySpec{ + Images: []ImagePattern{ + { + Glob: "myglob", + }, + }, + Authorities: []Authority{ + { + Key: &KeyRef{ + Data: "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEaEOVJCFtduYr3xqTxeRWSW32CY/s\nTBNZj4oIUPl8JvhVPJ1TKDPlNcuT4YphSt6t3yOmMvkdQbCj8broX6vijw==\n-----END PUBLIC KEY-----", + KMS: "kms://key/path", + }, + }, + }, + }, + }, + }, + { + name: "Should fail when key has mixed valid and invalid data", + expectErr: true, + errorString: "invalid value: -----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEaEOVJCFtduYr3xqTxeRWSW32CY/s\nTBNZj4oIUPl8JvhVPJ1TKDPlNcuT4YphSt6t3yOmMvkdQbCj8broX6vijw==\n-----END PUBLIC KEY-----\n---somedata---: spec.authorities[0].key.data", + policy: ClusterImagePolicy{ + Spec: ClusterImagePolicySpec{ + Images: []ImagePattern{ + { + Glob: "myglob", + }, + }, + Authorities: []Authority{ + { + Key: &KeyRef{ + Data: "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEaEOVJCFtduYr3xqTxeRWSW32CY/s\nTBNZj4oIUPl8JvhVPJ1TKDPlNcuT4YphSt6t3yOmMvkdQbCj8broX6vijw==\n-----END PUBLIC KEY-----\n---somedata---", + }, + }, + }, + }, + }, + }, + { + name: "Should fail when key has malformed pubkey data", + expectErr: true, + errorString: "invalid value: ---some key data----: spec.authorities[0].key.data", + policy: ClusterImagePolicy{ + Spec: ClusterImagePolicySpec{ + Images: []ImagePattern{ + { + Glob: "myglob", + }, + }, + Authorities: []Authority{ + { + Key: &KeyRef{ + Data: "---some key data----", + }, + }, + }, + }, + }, + }, + { + name: "Should fail when key is empty", + expectErr: true, + errorString: "expected exactly one, got neither: spec.authorities[0].key.data, spec.authorities[0].key.kms, spec.authorities[0].key.secretref", + policy: ClusterImagePolicy{ + Spec: ClusterImagePolicySpec{ + Images: []ImagePattern{ + { + Glob: "myglob*", + }, + }, + Authorities: []Authority{ + { + Key: &KeyRef{}, + }, + }, + }, + }, + }, + { + name: "Should pass when key has only one property: %v", + errorString: "", + policy: ClusterImagePolicy{ + Spec: ClusterImagePolicySpec{ + Images: []ImagePattern{ + { + Glob: "yepanotherglob", + }, + }, + Authorities: []Authority{ + { + Key: &KeyRef{ + KMS: "kms://key/path", + }, + }, + }, + }, + }, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + err := test.policy.Validate(context.TODO()) + if test.expectErr { + require.NotNil(t, err) + require.EqualError(t, err, test.errorString) + } else { + require.Nil(t, err) + } + }) + } +} + +func TestKeylessValidation(t *testing.T) { + tests := []struct { + name string + expectErr bool + errorString string + policy ClusterImagePolicy + }{ + { + name: "Should fail when keyless is empty", + expectErr: true, + errorString: "expected exactly one, got neither: spec.authorities[0].keyless.ca-cert, spec.authorities[0].keyless.identities, spec.authorities[0].keyless.url", + policy: ClusterImagePolicy{ + Spec: ClusterImagePolicySpec{ + Images: []ImagePattern{ + { + Glob: "globbityglob", + }, + }, + Authorities: []Authority{ + { + Keyless: &KeylessRef{}, + }, + }, + }, + }, + }, + { + name: "Should fail when keyless has multiple properties", + expectErr: true, + errorString: "expected exactly one, got both: spec.authorities[0].keyless.ca-cert, spec.authorities[0].keyless.url", + policy: ClusterImagePolicy{ + Spec: ClusterImagePolicySpec{ + Images: []ImagePattern{ + { + Glob: "globbityglob", + }, + }, + Authorities: []Authority{ + { + Keyless: &KeylessRef{ + URL: &apis.URL{ + Host: "myhost", + }, + CACert: &KeyRef{ + Data: "---certificate---", + }, + }, + }, + }, + }, + }, + }, + { + name: "Should pass when a valid keyless ref is specified", + expectErr: false, + policy: ClusterImagePolicy{ + Spec: ClusterImagePolicySpec{ + Images: []ImagePattern{ + { + Glob: "globbityglob", + }, + }, + Authorities: []Authority{ + { + Keyless: &KeylessRef{ + URL: &apis.URL{ + Host: "myhost", + }, + }, + }, + }, + }, + }, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + err := test.policy.Validate(context.TODO()) + if test.expectErr { + require.NotNil(t, err) + require.EqualError(t, err, test.errorString) + } else { + require.Nil(t, err) + } + }) + } +} + +func TestAuthoritiesValidation(t *testing.T) { + tests := []struct { + name string + expectErr bool + errorString string + policy ClusterImagePolicy + }{ + { + name: "Should fail when keyless is empty", + expectErr: true, + errorString: "expected exactly one, got both: spec.authorities[0].key, spec.authorities[0].keyless\nexpected exactly one, got neither: spec.authorities[0].key.data, spec.authorities[0].key.kms, spec.authorities[0].key.secretref, spec.authorities[0].keyless.ca-cert, spec.authorities[0].keyless.identities, spec.authorities[0].keyless.url", + policy: ClusterImagePolicy{ + Spec: ClusterImagePolicySpec{ + Images: []ImagePattern{ + { + Glob: "globbityglob", + }, + }, + Authorities: []Authority{ + { + Key: &KeyRef{}, + Keyless: &KeylessRef{}, + }, + }, + }, + }, + }, + { + name: "Should fail when keyless is empty", + expectErr: true, + errorString: "missing field(s): spec.authorities", + policy: ClusterImagePolicy{ + Spec: ClusterImagePolicySpec{ + Images: []ImagePattern{ + { + Glob: "globbityglob", + }, + }, + Authorities: []Authority{}, + }, + }, + }, + { + name: "Should pass when source oci is present", + expectErr: false, + policy: ClusterImagePolicy{ + Spec: ClusterImagePolicySpec{ + Images: []ImagePattern{{Glob: "*"}}, + Authorities: []Authority{ + { + Key: &KeyRef{KMS: "kms://key/path"}, + Sources: []Source{{OCI: "registry.example.com"}}, + }, + }, + }, + }, + }, + { + name: "Should fail when source oci is empty", + expectErr: true, + errorString: "missing field(s): spec.authorities[0].source[0].oci", + policy: ClusterImagePolicy{ + Spec: ClusterImagePolicySpec{ + Images: []ImagePattern{{Glob: "*"}}, + Authorities: []Authority{ + { + Key: &KeyRef{KMS: "kms://key/path"}, + Sources: []Source{{OCI: ""}}, + }, + }, + }, + }, + }, + { + name: "Should pass with multiple source oci is present", + expectErr: false, + policy: ClusterImagePolicy{ + Spec: ClusterImagePolicySpec{ + Images: []ImagePattern{{Glob: "*"}}, + Authorities: []Authority{ + { + Key: &KeyRef{KMS: "kms://key/path"}, + Sources: []Source{ + {OCI: "registry1"}, + {OCI: "registry2"}, + }, + }, + }, + }, + }, + }, + { + name: "Should pass with multiple source oci is present", + expectErr: false, + policy: ClusterImagePolicy{ + Spec: ClusterImagePolicySpec{ + Images: []ImagePattern{{Glob: "*"}}, + Authorities: []Authority{ + { + Key: &KeyRef{KMS: "kms://key/path"}, + Sources: []Source{ + {OCI: "registry1"}, + {OCI: "registry2"}, + }, + }, + }, + }, + }, + }, + { + name: "Should pass with attestations present", + expectErr: false, + policy: ClusterImagePolicy{ + Spec: ClusterImagePolicySpec{ + Images: []ImagePattern{{Glob: "*"}}, + Authorities: []Authority{ + { + Key: &KeyRef{KMS: "kms://key/path"}, + Attestations: []Attestation{ + {Name: "first", PredicateType: "vuln"}, + {Name: "second", PredicateType: "custom", Policy: &Policy{ + Type: "cue", + Data: `predicateType: "cosign.sigstore.dev/attestation/vuln/v1"`, + }, + }, + }, + }, + }, + }, + }, + }, + { + name: "Should fail with signaturePullSecret name empty", + expectErr: true, + errorString: "missing field(s): spec.authorities[0].source[0].signaturePullSecrets[0].name", + policy: ClusterImagePolicy{ + Spec: ClusterImagePolicySpec{ + Images: []ImagePattern{{Glob: "*"}}, + Authorities: []Authority{ + { + Key: &KeyRef{KMS: "kms://key/path"}, + Sources: []Source{ + { + OCI: "registry1", + SignaturePullSecrets: []v1.LocalObjectReference{ + {Name: ""}, + }, + }, + }, + }, + }, + }, + }, + }, + { + name: "Should pass with signaturePullSecret name filled", + expectErr: false, + policy: ClusterImagePolicy{ + Spec: ClusterImagePolicySpec{ + Images: []ImagePattern{{Glob: "*"}}, + Authorities: []Authority{ + { + Key: &KeyRef{KMS: "kms://key/path"}, + Sources: []Source{ + { + OCI: "registry1", + SignaturePullSecrets: []v1.LocalObjectReference{ + {Name: "testPullSecrets"}, + }, + }, + }, + }, + }, + }, + }, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + err := test.policy.Validate(context.TODO()) + if test.expectErr { + require.NotNil(t, err) + require.EqualError(t, err, test.errorString) + } else { + require.Nil(t, err) + } + }) + } +} + +func TestAttestationsValidation(t *testing.T) { + tests := []struct { + name string + expectErr bool + errorString string + attestation Attestation + }{{ + name: "vuln", + attestation: Attestation{Name: "first", PredicateType: "vuln"}, + }, { + name: "missing name", + attestation: Attestation{PredicateType: "vuln"}, + expectErr: true, + errorString: "missing field(s): name", + }, { + name: "missing predicatetype", + attestation: Attestation{Name: "first"}, + expectErr: true, + errorString: "missing field(s): predicateType", + }, { + name: "invalid predicatetype", + attestation: Attestation{Name: "first", PredicateType: "notsupported"}, + expectErr: true, + errorString: "invalid value: notsupported: predicateType\nunsupported precicate type", + }, { + name: "custom with invalid policy type", + attestation: Attestation{Name: "second", PredicateType: "custom", + Policy: &Policy{ + Type: "not-cue", + Data: `predicateType: "cosign.sigstore.dev/attestation/vuln/v1"`, + }, + }, + expectErr: true, + errorString: "invalid value: not-cue: policy.type\nonly cue is supported at the moment", + }, { + name: "custom with missing policy data", + attestation: Attestation{Name: "second", PredicateType: "custom", + Policy: &Policy{ + Type: "cue", + }, + }, + expectErr: true, + errorString: "missing field(s): policy.data", + }, { + name: "custom with policy", + attestation: Attestation{Name: "second", PredicateType: "custom", + Policy: &Policy{ + Type: "cue", + Data: `predicateType: "cosign.sigstore.dev/attestation/vuln/v1"`, + }, + }, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + err := test.attestation.Validate(context.TODO()) + if test.expectErr { + require.NotNil(t, err) + require.EqualError(t, err, test.errorString) + } else { + require.Nil(t, err) + } + }) + } +} +func TestIdentitiesValidation(t *testing.T) { + tests := []struct { + name string + expectErr bool + errorString string + policy ClusterImagePolicy + }{ + { + name: "Should fail when identities is empty", + expectErr: true, + errorString: "missing field(s): spec.authorities[0].keyless.identities", + policy: ClusterImagePolicy{ + Spec: ClusterImagePolicySpec{ + Images: []ImagePattern{ + { + Glob: "globbityglob", + }, + }, + Authorities: []Authority{ + { + Keyless: &KeylessRef{ + Identities: []Identity{}, + }, + }, + }, + }, + }, + }, + { + name: "Should fail when issuer has invalid regex", + expectErr: true, + errorString: "invalid value: ****: spec.authorities[0].keyless.identities[0].issuer\nregex is invalid: error parsing regexp: missing argument to repetition operator: `*`", + policy: ClusterImagePolicy{ + Spec: ClusterImagePolicySpec{ + Images: []ImagePattern{ + { + Glob: "globbityglob", + }, + }, + Authorities: []Authority{ + { + Keyless: &KeylessRef{ + Identities: []Identity{{Issuer: "****"}}, + }, + }, + }, + }, + }, + }, + { + name: "Should fail when subject has invalid regex", + expectErr: true, + errorString: "invalid value: ****: spec.authorities[0].keyless.identities[0].subject\nregex is invalid: error parsing regexp: missing argument to repetition operator: `*`", + policy: ClusterImagePolicy{ + Spec: ClusterImagePolicySpec{ + Images: []ImagePattern{ + { + Glob: "globbityglob", + }, + }, + Authorities: []Authority{ + { + Keyless: &KeylessRef{ + Identities: []Identity{{Subject: "****"}}, + }, + }, + }, + }, + }, + }, + { + name: "Should pass when subject and issuer have valid regex", + policy: ClusterImagePolicy{ + Spec: ClusterImagePolicySpec{ + Images: []ImagePattern{ + { + Glob: "globbityglob", + }, + }, + Authorities: []Authority{ + { + Keyless: &KeylessRef{ + Identities: []Identity{{Subject: ".*subject.*", Issuer: ".*issuer.*"}}, + }, + }, + }, + }, + }, + }, + { + name: "Should pass when identities is valid", + expectErr: false, + policy: ClusterImagePolicy{ + Spec: ClusterImagePolicySpec{ + Images: []ImagePattern{ + { + Glob: "globbityglob", + }, + }, + Authorities: []Authority{ + { + Keyless: &KeylessRef{ + Identities: []Identity{ + { + Issuer: "some issuer", + }, + }, + }, + }, + }, + }, + }, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + err := test.policy.Validate(context.TODO()) + if test.expectErr { + require.NotNil(t, err) + require.EqualError(t, err, test.errorString) + } else { + require.Nil(t, err) + } + }) + } +} diff --git a/pkg/apis/cosigned/v1beta1/doc.go b/pkg/apis/cosigned/v1beta1/doc.go new file mode 100644 index 00000000000..56d342553c7 --- /dev/null +++ b/pkg/apis/cosigned/v1beta1/doc.go @@ -0,0 +1,17 @@ +// Copyright 2022 The Sigstore Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// +k8s:deepcopy-gen=package +// +groupName=cosigned.sigstore.dev +package v1beta1 diff --git a/pkg/apis/cosigned/v1beta1/register.go b/pkg/apis/cosigned/v1beta1/register.go new file mode 100644 index 00000000000..8dfb06ec6d1 --- /dev/null +++ b/pkg/apis/cosigned/v1beta1/register.go @@ -0,0 +1,53 @@ +// Copyright 2022 The Sigstore Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package v1beta1 + +import ( + "github.com/sigstore/cosign/pkg/apis/cosigned" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" +) + +// SchemeGroupVersion is group version used to register these objects +var SchemeGroupVersion = schema.GroupVersion{Group: cosigned.GroupName, Version: "v1beta1"} + +// Kind takes an unqualified kind and returns back a Group qualified GroupKind +func Kind(kind string) schema.GroupKind { + return SchemeGroupVersion.WithKind(kind).GroupKind() +} + +// Resource takes an unqualified resource and returns a Group qualified GroupResource +func Resource(resource string) schema.GroupResource { + return SchemeGroupVersion.WithResource(resource).GroupResource() +} + +var ( + // SchemeBuilder builds a scheme with the types known to the package. + SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes) + // AddToScheme adds the types known to this package to an existing schema. + AddToScheme = SchemeBuilder.AddToScheme +) + +// Adds the list of known types to Scheme. +func addKnownTypes(scheme *runtime.Scheme) error { + scheme.AddKnownTypes(SchemeGroupVersion, + &ClusterImagePolicy{}, + &ClusterImagePolicyList{}, + ) + metav1.AddToGroupVersion(scheme, SchemeGroupVersion) + return nil +} diff --git a/pkg/apis/cosigned/v1beta1/zz_generated.deepcopy.go b/pkg/apis/cosigned/v1beta1/zz_generated.deepcopy.go new file mode 100644 index 00000000000..36ef3dc67d9 --- /dev/null +++ b/pkg/apis/cosigned/v1beta1/zz_generated.deepcopy.go @@ -0,0 +1,353 @@ +//go:build !ignore_autogenerated +// +build !ignore_autogenerated + +// Copyright 2022 The Sigstore Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Code generated by deepcopy-gen. DO NOT EDIT. + +package v1beta1 + +import ( + v1 "k8s.io/api/core/v1" + runtime "k8s.io/apimachinery/pkg/runtime" + apis "knative.dev/pkg/apis" +) + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Attestation) DeepCopyInto(out *Attestation) { + *out = *in + if in.Policy != nil { + in, out := &in.Policy, &out.Policy + *out = new(Policy) + (*in).DeepCopyInto(*out) + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Attestation. +func (in *Attestation) DeepCopy() *Attestation { + if in == nil { + return nil + } + out := new(Attestation) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Authority) DeepCopyInto(out *Authority) { + *out = *in + if in.Key != nil { + in, out := &in.Key, &out.Key + *out = new(KeyRef) + (*in).DeepCopyInto(*out) + } + if in.Keyless != nil { + in, out := &in.Keyless, &out.Keyless + *out = new(KeylessRef) + (*in).DeepCopyInto(*out) + } + if in.Sources != nil { + in, out := &in.Sources, &out.Sources + *out = make([]Source, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.CTLog != nil { + in, out := &in.CTLog, &out.CTLog + *out = new(TLog) + (*in).DeepCopyInto(*out) + } + if in.Attestations != nil { + in, out := &in.Attestations, &out.Attestations + *out = make([]Attestation, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Authority. +func (in *Authority) DeepCopy() *Authority { + if in == nil { + return nil + } + out := new(Authority) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ClusterImagePolicy) DeepCopyInto(out *ClusterImagePolicy) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterImagePolicy. +func (in *ClusterImagePolicy) DeepCopy() *ClusterImagePolicy { + if in == nil { + return nil + } + out := new(ClusterImagePolicy) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ClusterImagePolicy) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ClusterImagePolicyList) DeepCopyInto(out *ClusterImagePolicyList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]ClusterImagePolicy, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterImagePolicyList. +func (in *ClusterImagePolicyList) DeepCopy() *ClusterImagePolicyList { + if in == nil { + return nil + } + out := new(ClusterImagePolicyList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ClusterImagePolicyList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ClusterImagePolicySpec) DeepCopyInto(out *ClusterImagePolicySpec) { + *out = *in + if in.Images != nil { + in, out := &in.Images, &out.Images + *out = make([]ImagePattern, len(*in)) + copy(*out, *in) + } + if in.Authorities != nil { + in, out := &in.Authorities, &out.Authorities + *out = make([]Authority, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.Policy != nil { + in, out := &in.Policy, &out.Policy + *out = new(Policy) + (*in).DeepCopyInto(*out) + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClusterImagePolicySpec. +func (in *ClusterImagePolicySpec) DeepCopy() *ClusterImagePolicySpec { + if in == nil { + return nil + } + out := new(ClusterImagePolicySpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ConfigMapReference) DeepCopyInto(out *ConfigMapReference) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ConfigMapReference. +func (in *ConfigMapReference) DeepCopy() *ConfigMapReference { + if in == nil { + return nil + } + out := new(ConfigMapReference) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Identity) DeepCopyInto(out *Identity) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Identity. +func (in *Identity) DeepCopy() *Identity { + if in == nil { + return nil + } + out := new(Identity) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ImagePattern) DeepCopyInto(out *ImagePattern) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ImagePattern. +func (in *ImagePattern) DeepCopy() *ImagePattern { + if in == nil { + return nil + } + out := new(ImagePattern) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *KeyRef) DeepCopyInto(out *KeyRef) { + *out = *in + if in.SecretRef != nil { + in, out := &in.SecretRef, &out.SecretRef + *out = new(v1.SecretReference) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new KeyRef. +func (in *KeyRef) DeepCopy() *KeyRef { + if in == nil { + return nil + } + out := new(KeyRef) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *KeylessRef) DeepCopyInto(out *KeylessRef) { + *out = *in + if in.URL != nil { + in, out := &in.URL, &out.URL + *out = new(apis.URL) + (*in).DeepCopyInto(*out) + } + if in.Identities != nil { + in, out := &in.Identities, &out.Identities + *out = make([]Identity, len(*in)) + copy(*out, *in) + } + if in.CACert != nil { + in, out := &in.CACert, &out.CACert + *out = new(KeyRef) + (*in).DeepCopyInto(*out) + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new KeylessRef. +func (in *KeylessRef) DeepCopy() *KeylessRef { + if in == nil { + return nil + } + out := new(KeylessRef) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Policy) DeepCopyInto(out *Policy) { + *out = *in + if in.URL != nil { + in, out := &in.URL, &out.URL + *out = new(apis.URL) + (*in).DeepCopyInto(*out) + } + if in.ConfigMapRef != nil { + in, out := &in.ConfigMapRef, &out.ConfigMapRef + *out = new(ConfigMapReference) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Policy. +func (in *Policy) DeepCopy() *Policy { + if in == nil { + return nil + } + out := new(Policy) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Source) DeepCopyInto(out *Source) { + *out = *in + if in.SignaturePullSecrets != nil { + in, out := &in.SignaturePullSecrets, &out.SignaturePullSecrets + *out = make([]v1.LocalObjectReference, len(*in)) + copy(*out, *in) + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Source. +func (in *Source) DeepCopy() *Source { + if in == nil { + return nil + } + out := new(Source) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *TLog) DeepCopyInto(out *TLog) { + *out = *in + if in.URL != nil { + in, out := &in.URL, &out.URL + *out = new(apis.URL) + (*in).DeepCopyInto(*out) + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new TLog. +func (in *TLog) DeepCopy() *TLog { + if in == nil { + return nil + } + out := new(TLog) + in.DeepCopyInto(out) + return out +} diff --git a/pkg/client/clientset/versioned/clientset.go b/pkg/client/clientset/versioned/clientset.go index 9b3e1a1f1c0..e023fa11ed2 100644 --- a/pkg/client/clientset/versioned/clientset.go +++ b/pkg/client/clientset/versioned/clientset.go @@ -21,6 +21,7 @@ import ( "net/http" cosignedv1alpha1 "github.com/sigstore/cosign/pkg/client/clientset/versioned/typed/cosigned/v1alpha1" + cosignedv1beta1 "github.com/sigstore/cosign/pkg/client/clientset/versioned/typed/cosigned/v1beta1" discovery "k8s.io/client-go/discovery" rest "k8s.io/client-go/rest" flowcontrol "k8s.io/client-go/util/flowcontrol" @@ -29,6 +30,7 @@ import ( type Interface interface { Discovery() discovery.DiscoveryInterface CosignedV1alpha1() cosignedv1alpha1.CosignedV1alpha1Interface + CosignedV1beta1() cosignedv1beta1.CosignedV1beta1Interface } // Clientset contains the clients for groups. Each group has exactly one @@ -36,6 +38,7 @@ type Interface interface { type Clientset struct { *discovery.DiscoveryClient cosignedV1alpha1 *cosignedv1alpha1.CosignedV1alpha1Client + cosignedV1beta1 *cosignedv1beta1.CosignedV1beta1Client } // CosignedV1alpha1 retrieves the CosignedV1alpha1Client @@ -43,6 +46,11 @@ func (c *Clientset) CosignedV1alpha1() cosignedv1alpha1.CosignedV1alpha1Interfac return c.cosignedV1alpha1 } +// CosignedV1beta1 retrieves the CosignedV1beta1Client +func (c *Clientset) CosignedV1beta1() cosignedv1beta1.CosignedV1beta1Interface { + return c.cosignedV1beta1 +} + // Discovery retrieves the DiscoveryClient func (c *Clientset) Discovery() discovery.DiscoveryInterface { if c == nil { @@ -91,6 +99,10 @@ func NewForConfigAndClient(c *rest.Config, httpClient *http.Client) (*Clientset, if err != nil { return nil, err } + cs.cosignedV1beta1, err = cosignedv1beta1.NewForConfigAndClient(&configShallowCopy, httpClient) + if err != nil { + return nil, err + } cs.DiscoveryClient, err = discovery.NewDiscoveryClientForConfigAndClient(&configShallowCopy, httpClient) if err != nil { @@ -113,6 +125,7 @@ func NewForConfigOrDie(c *rest.Config) *Clientset { func New(c rest.Interface) *Clientset { var cs Clientset cs.cosignedV1alpha1 = cosignedv1alpha1.New(c) + cs.cosignedV1beta1 = cosignedv1beta1.New(c) cs.DiscoveryClient = discovery.NewDiscoveryClient(c) return &cs diff --git a/pkg/client/clientset/versioned/fake/clientset_generated.go b/pkg/client/clientset/versioned/fake/clientset_generated.go index 52edbeb40c2..19f931ae9b6 100644 --- a/pkg/client/clientset/versioned/fake/clientset_generated.go +++ b/pkg/client/clientset/versioned/fake/clientset_generated.go @@ -20,6 +20,8 @@ import ( clientset "github.com/sigstore/cosign/pkg/client/clientset/versioned" cosignedv1alpha1 "github.com/sigstore/cosign/pkg/client/clientset/versioned/typed/cosigned/v1alpha1" fakecosignedv1alpha1 "github.com/sigstore/cosign/pkg/client/clientset/versioned/typed/cosigned/v1alpha1/fake" + cosignedv1beta1 "github.com/sigstore/cosign/pkg/client/clientset/versioned/typed/cosigned/v1beta1" + fakecosignedv1beta1 "github.com/sigstore/cosign/pkg/client/clientset/versioned/typed/cosigned/v1beta1/fake" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/watch" "k8s.io/client-go/discovery" @@ -81,3 +83,8 @@ var ( func (c *Clientset) CosignedV1alpha1() cosignedv1alpha1.CosignedV1alpha1Interface { return &fakecosignedv1alpha1.FakeCosignedV1alpha1{Fake: &c.Fake} } + +// CosignedV1beta1 retrieves the CosignedV1beta1Client +func (c *Clientset) CosignedV1beta1() cosignedv1beta1.CosignedV1beta1Interface { + return &fakecosignedv1beta1.FakeCosignedV1beta1{Fake: &c.Fake} +} diff --git a/pkg/client/clientset/versioned/fake/register.go b/pkg/client/clientset/versioned/fake/register.go index 5ff7eae9ecf..cd26fda450b 100644 --- a/pkg/client/clientset/versioned/fake/register.go +++ b/pkg/client/clientset/versioned/fake/register.go @@ -18,6 +18,7 @@ package fake import ( cosignedv1alpha1 "github.com/sigstore/cosign/pkg/apis/cosigned/v1alpha1" + cosignedv1beta1 "github.com/sigstore/cosign/pkg/apis/cosigned/v1beta1" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" schema "k8s.io/apimachinery/pkg/runtime/schema" @@ -30,6 +31,7 @@ var codecs = serializer.NewCodecFactory(scheme) var localSchemeBuilder = runtime.SchemeBuilder{ cosignedv1alpha1.AddToScheme, + cosignedv1beta1.AddToScheme, } // AddToScheme adds all types of this clientset into the given scheme. This allows composition diff --git a/pkg/client/clientset/versioned/scheme/register.go b/pkg/client/clientset/versioned/scheme/register.go index 10c21904aee..cfe12d5ee5f 100644 --- a/pkg/client/clientset/versioned/scheme/register.go +++ b/pkg/client/clientset/versioned/scheme/register.go @@ -18,6 +18,7 @@ package scheme import ( cosignedv1alpha1 "github.com/sigstore/cosign/pkg/apis/cosigned/v1alpha1" + cosignedv1beta1 "github.com/sigstore/cosign/pkg/apis/cosigned/v1beta1" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" schema "k8s.io/apimachinery/pkg/runtime/schema" @@ -30,6 +31,7 @@ var Codecs = serializer.NewCodecFactory(Scheme) var ParameterCodec = runtime.NewParameterCodec(Scheme) var localSchemeBuilder = runtime.SchemeBuilder{ cosignedv1alpha1.AddToScheme, + cosignedv1beta1.AddToScheme, } // AddToScheme adds all types of this clientset into the given scheme. This allows composition diff --git a/pkg/client/clientset/versioned/typed/cosigned/v1beta1/clusterimagepolicy.go b/pkg/client/clientset/versioned/typed/cosigned/v1beta1/clusterimagepolicy.go new file mode 100644 index 00000000000..82e50d66f2e --- /dev/null +++ b/pkg/client/clientset/versioned/typed/cosigned/v1beta1/clusterimagepolicy.go @@ -0,0 +1,166 @@ +// Copyright 2022 The Sigstore Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Code generated by client-gen. DO NOT EDIT. + +package v1beta1 + +import ( + "context" + "time" + + v1beta1 "github.com/sigstore/cosign/pkg/apis/cosigned/v1beta1" + scheme "github.com/sigstore/cosign/pkg/client/clientset/versioned/scheme" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + rest "k8s.io/client-go/rest" +) + +// ClusterImagePoliciesGetter has a method to return a ClusterImagePolicyInterface. +// A group's client should implement this interface. +type ClusterImagePoliciesGetter interface { + ClusterImagePolicies() ClusterImagePolicyInterface +} + +// ClusterImagePolicyInterface has methods to work with ClusterImagePolicy resources. +type ClusterImagePolicyInterface interface { + Create(ctx context.Context, clusterImagePolicy *v1beta1.ClusterImagePolicy, opts v1.CreateOptions) (*v1beta1.ClusterImagePolicy, error) + Update(ctx context.Context, clusterImagePolicy *v1beta1.ClusterImagePolicy, opts v1.UpdateOptions) (*v1beta1.ClusterImagePolicy, error) + Delete(ctx context.Context, name string, opts v1.DeleteOptions) error + DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error + Get(ctx context.Context, name string, opts v1.GetOptions) (*v1beta1.ClusterImagePolicy, error) + List(ctx context.Context, opts v1.ListOptions) (*v1beta1.ClusterImagePolicyList, error) + Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) + Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.ClusterImagePolicy, err error) + ClusterImagePolicyExpansion +} + +// clusterImagePolicies implements ClusterImagePolicyInterface +type clusterImagePolicies struct { + client rest.Interface +} + +// newClusterImagePolicies returns a ClusterImagePolicies +func newClusterImagePolicies(c *CosignedV1beta1Client) *clusterImagePolicies { + return &clusterImagePolicies{ + client: c.RESTClient(), + } +} + +// Get takes name of the clusterImagePolicy, and returns the corresponding clusterImagePolicy object, and an error if there is any. +func (c *clusterImagePolicies) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.ClusterImagePolicy, err error) { + result = &v1beta1.ClusterImagePolicy{} + err = c.client.Get(). + Resource("clusterimagepolicies"). + Name(name). + VersionedParams(&options, scheme.ParameterCodec). + Do(ctx). + Into(result) + return +} + +// List takes label and field selectors, and returns the list of ClusterImagePolicies that match those selectors. +func (c *clusterImagePolicies) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.ClusterImagePolicyList, err error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + result = &v1beta1.ClusterImagePolicyList{} + err = c.client.Get(). + Resource("clusterimagepolicies"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Do(ctx). + Into(result) + return +} + +// Watch returns a watch.Interface that watches the requested clusterImagePolicies. +func (c *clusterImagePolicies) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + opts.Watch = true + return c.client.Get(). + Resource("clusterimagepolicies"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Watch(ctx) +} + +// Create takes the representation of a clusterImagePolicy and creates it. Returns the server's representation of the clusterImagePolicy, and an error, if there is any. +func (c *clusterImagePolicies) Create(ctx context.Context, clusterImagePolicy *v1beta1.ClusterImagePolicy, opts v1.CreateOptions) (result *v1beta1.ClusterImagePolicy, err error) { + result = &v1beta1.ClusterImagePolicy{} + err = c.client.Post(). + Resource("clusterimagepolicies"). + VersionedParams(&opts, scheme.ParameterCodec). + Body(clusterImagePolicy). + Do(ctx). + Into(result) + return +} + +// Update takes the representation of a clusterImagePolicy and updates it. Returns the server's representation of the clusterImagePolicy, and an error, if there is any. +func (c *clusterImagePolicies) Update(ctx context.Context, clusterImagePolicy *v1beta1.ClusterImagePolicy, opts v1.UpdateOptions) (result *v1beta1.ClusterImagePolicy, err error) { + result = &v1beta1.ClusterImagePolicy{} + err = c.client.Put(). + Resource("clusterimagepolicies"). + Name(clusterImagePolicy.Name). + VersionedParams(&opts, scheme.ParameterCodec). + Body(clusterImagePolicy). + Do(ctx). + Into(result) + return +} + +// Delete takes name of the clusterImagePolicy and deletes it. Returns an error if one occurs. +func (c *clusterImagePolicies) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { + return c.client.Delete(). + Resource("clusterimagepolicies"). + Name(name). + Body(&opts). + Do(ctx). + Error() +} + +// DeleteCollection deletes a collection of objects. +func (c *clusterImagePolicies) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { + var timeout time.Duration + if listOpts.TimeoutSeconds != nil { + timeout = time.Duration(*listOpts.TimeoutSeconds) * time.Second + } + return c.client.Delete(). + Resource("clusterimagepolicies"). + VersionedParams(&listOpts, scheme.ParameterCodec). + Timeout(timeout). + Body(&opts). + Do(ctx). + Error() +} + +// Patch applies the patch and returns the patched clusterImagePolicy. +func (c *clusterImagePolicies) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.ClusterImagePolicy, err error) { + result = &v1beta1.ClusterImagePolicy{} + err = c.client.Patch(pt). + Resource("clusterimagepolicies"). + Name(name). + SubResource(subresources...). + VersionedParams(&opts, scheme.ParameterCodec). + Body(data). + Do(ctx). + Into(result) + return +} diff --git a/pkg/client/clientset/versioned/typed/cosigned/v1beta1/cosigned_client.go b/pkg/client/clientset/versioned/typed/cosigned/v1beta1/cosigned_client.go new file mode 100644 index 00000000000..90bbd4d7097 --- /dev/null +++ b/pkg/client/clientset/versioned/typed/cosigned/v1beta1/cosigned_client.go @@ -0,0 +1,105 @@ +// Copyright 2022 The Sigstore Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Code generated by client-gen. DO NOT EDIT. + +package v1beta1 + +import ( + "net/http" + + v1beta1 "github.com/sigstore/cosign/pkg/apis/cosigned/v1beta1" + "github.com/sigstore/cosign/pkg/client/clientset/versioned/scheme" + rest "k8s.io/client-go/rest" +) + +type CosignedV1beta1Interface interface { + RESTClient() rest.Interface + ClusterImagePoliciesGetter +} + +// CosignedV1beta1Client is used to interact with features provided by the cosigned.sigstore.dev group. +type CosignedV1beta1Client struct { + restClient rest.Interface +} + +func (c *CosignedV1beta1Client) ClusterImagePolicies() ClusterImagePolicyInterface { + return newClusterImagePolicies(c) +} + +// NewForConfig creates a new CosignedV1beta1Client for the given config. +// NewForConfig is equivalent to NewForConfigAndClient(c, httpClient), +// where httpClient was generated with rest.HTTPClientFor(c). +func NewForConfig(c *rest.Config) (*CosignedV1beta1Client, error) { + config := *c + if err := setConfigDefaults(&config); err != nil { + return nil, err + } + httpClient, err := rest.HTTPClientFor(&config) + if err != nil { + return nil, err + } + return NewForConfigAndClient(&config, httpClient) +} + +// NewForConfigAndClient creates a new CosignedV1beta1Client for the given config and http client. +// Note the http client provided takes precedence over the configured transport values. +func NewForConfigAndClient(c *rest.Config, h *http.Client) (*CosignedV1beta1Client, error) { + config := *c + if err := setConfigDefaults(&config); err != nil { + return nil, err + } + client, err := rest.RESTClientForConfigAndClient(&config, h) + if err != nil { + return nil, err + } + return &CosignedV1beta1Client{client}, nil +} + +// NewForConfigOrDie creates a new CosignedV1beta1Client for the given config and +// panics if there is an error in the config. +func NewForConfigOrDie(c *rest.Config) *CosignedV1beta1Client { + client, err := NewForConfig(c) + if err != nil { + panic(err) + } + return client +} + +// New creates a new CosignedV1beta1Client for the given RESTClient. +func New(c rest.Interface) *CosignedV1beta1Client { + return &CosignedV1beta1Client{c} +} + +func setConfigDefaults(config *rest.Config) error { + gv := v1beta1.SchemeGroupVersion + config.GroupVersion = &gv + config.APIPath = "/apis" + config.NegotiatedSerializer = scheme.Codecs.WithoutConversion() + + if config.UserAgent == "" { + config.UserAgent = rest.DefaultKubernetesUserAgent() + } + + return nil +} + +// RESTClient returns a RESTClient that is used to communicate +// with API server by this client implementation. +func (c *CosignedV1beta1Client) RESTClient() rest.Interface { + if c == nil { + return nil + } + return c.restClient +} diff --git a/pkg/client/clientset/versioned/typed/cosigned/v1beta1/doc.go b/pkg/client/clientset/versioned/typed/cosigned/v1beta1/doc.go new file mode 100644 index 00000000000..9888ca9ee46 --- /dev/null +++ b/pkg/client/clientset/versioned/typed/cosigned/v1beta1/doc.go @@ -0,0 +1,18 @@ +// Copyright 2022 The Sigstore Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Code generated by client-gen. DO NOT EDIT. + +// This package has the automatically generated typed clients. +package v1beta1 diff --git a/pkg/client/clientset/versioned/typed/cosigned/v1beta1/fake/doc.go b/pkg/client/clientset/versioned/typed/cosigned/v1beta1/fake/doc.go new file mode 100644 index 00000000000..91f77e52434 --- /dev/null +++ b/pkg/client/clientset/versioned/typed/cosigned/v1beta1/fake/doc.go @@ -0,0 +1,18 @@ +// Copyright 2022 The Sigstore Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Code generated by client-gen. DO NOT EDIT. + +// Package fake has the automatically generated clients. +package fake diff --git a/pkg/client/clientset/versioned/typed/cosigned/v1beta1/fake/fake_clusterimagepolicy.go b/pkg/client/clientset/versioned/typed/cosigned/v1beta1/fake/fake_clusterimagepolicy.go new file mode 100644 index 00000000000..9120290357a --- /dev/null +++ b/pkg/client/clientset/versioned/typed/cosigned/v1beta1/fake/fake_clusterimagepolicy.go @@ -0,0 +1,120 @@ +// Copyright 2022 The Sigstore Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Code generated by client-gen. DO NOT EDIT. + +package fake + +import ( + "context" + + v1beta1 "github.com/sigstore/cosign/pkg/apis/cosigned/v1beta1" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + labels "k8s.io/apimachinery/pkg/labels" + schema "k8s.io/apimachinery/pkg/runtime/schema" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + testing "k8s.io/client-go/testing" +) + +// FakeClusterImagePolicies implements ClusterImagePolicyInterface +type FakeClusterImagePolicies struct { + Fake *FakeCosignedV1beta1 +} + +var clusterimagepoliciesResource = schema.GroupVersionResource{Group: "cosigned.sigstore.dev", Version: "v1beta1", Resource: "clusterimagepolicies"} + +var clusterimagepoliciesKind = schema.GroupVersionKind{Group: "cosigned.sigstore.dev", Version: "v1beta1", Kind: "ClusterImagePolicy"} + +// Get takes name of the clusterImagePolicy, and returns the corresponding clusterImagePolicy object, and an error if there is any. +func (c *FakeClusterImagePolicies) Get(ctx context.Context, name string, options v1.GetOptions) (result *v1beta1.ClusterImagePolicy, err error) { + obj, err := c.Fake. + Invokes(testing.NewRootGetAction(clusterimagepoliciesResource, name), &v1beta1.ClusterImagePolicy{}) + if obj == nil { + return nil, err + } + return obj.(*v1beta1.ClusterImagePolicy), err +} + +// List takes label and field selectors, and returns the list of ClusterImagePolicies that match those selectors. +func (c *FakeClusterImagePolicies) List(ctx context.Context, opts v1.ListOptions) (result *v1beta1.ClusterImagePolicyList, err error) { + obj, err := c.Fake. + Invokes(testing.NewRootListAction(clusterimagepoliciesResource, clusterimagepoliciesKind, opts), &v1beta1.ClusterImagePolicyList{}) + if obj == nil { + return nil, err + } + + label, _, _ := testing.ExtractFromListOptions(opts) + if label == nil { + label = labels.Everything() + } + list := &v1beta1.ClusterImagePolicyList{ListMeta: obj.(*v1beta1.ClusterImagePolicyList).ListMeta} + for _, item := range obj.(*v1beta1.ClusterImagePolicyList).Items { + if label.Matches(labels.Set(item.Labels)) { + list.Items = append(list.Items, item) + } + } + return list, err +} + +// Watch returns a watch.Interface that watches the requested clusterImagePolicies. +func (c *FakeClusterImagePolicies) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { + return c.Fake. + InvokesWatch(testing.NewRootWatchAction(clusterimagepoliciesResource, opts)) +} + +// Create takes the representation of a clusterImagePolicy and creates it. Returns the server's representation of the clusterImagePolicy, and an error, if there is any. +func (c *FakeClusterImagePolicies) Create(ctx context.Context, clusterImagePolicy *v1beta1.ClusterImagePolicy, opts v1.CreateOptions) (result *v1beta1.ClusterImagePolicy, err error) { + obj, err := c.Fake. + Invokes(testing.NewRootCreateAction(clusterimagepoliciesResource, clusterImagePolicy), &v1beta1.ClusterImagePolicy{}) + if obj == nil { + return nil, err + } + return obj.(*v1beta1.ClusterImagePolicy), err +} + +// Update takes the representation of a clusterImagePolicy and updates it. Returns the server's representation of the clusterImagePolicy, and an error, if there is any. +func (c *FakeClusterImagePolicies) Update(ctx context.Context, clusterImagePolicy *v1beta1.ClusterImagePolicy, opts v1.UpdateOptions) (result *v1beta1.ClusterImagePolicy, err error) { + obj, err := c.Fake. + Invokes(testing.NewRootUpdateAction(clusterimagepoliciesResource, clusterImagePolicy), &v1beta1.ClusterImagePolicy{}) + if obj == nil { + return nil, err + } + return obj.(*v1beta1.ClusterImagePolicy), err +} + +// Delete takes name of the clusterImagePolicy and deletes it. Returns an error if one occurs. +func (c *FakeClusterImagePolicies) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { + _, err := c.Fake. + Invokes(testing.NewRootDeleteActionWithOptions(clusterimagepoliciesResource, name, opts), &v1beta1.ClusterImagePolicy{}) + return err +} + +// DeleteCollection deletes a collection of objects. +func (c *FakeClusterImagePolicies) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { + action := testing.NewRootDeleteCollectionAction(clusterimagepoliciesResource, listOpts) + + _, err := c.Fake.Invokes(action, &v1beta1.ClusterImagePolicyList{}) + return err +} + +// Patch applies the patch and returns the patched clusterImagePolicy. +func (c *FakeClusterImagePolicies) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.ClusterImagePolicy, err error) { + obj, err := c.Fake. + Invokes(testing.NewRootPatchSubresourceAction(clusterimagepoliciesResource, name, pt, data, subresources...), &v1beta1.ClusterImagePolicy{}) + if obj == nil { + return nil, err + } + return obj.(*v1beta1.ClusterImagePolicy), err +} diff --git a/pkg/client/clientset/versioned/typed/cosigned/v1beta1/fake/fake_cosigned_client.go b/pkg/client/clientset/versioned/typed/cosigned/v1beta1/fake/fake_cosigned_client.go new file mode 100644 index 00000000000..eca513ac70e --- /dev/null +++ b/pkg/client/clientset/versioned/typed/cosigned/v1beta1/fake/fake_cosigned_client.go @@ -0,0 +1,38 @@ +// Copyright 2022 The Sigstore Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Code generated by client-gen. DO NOT EDIT. + +package fake + +import ( + v1beta1 "github.com/sigstore/cosign/pkg/client/clientset/versioned/typed/cosigned/v1beta1" + rest "k8s.io/client-go/rest" + testing "k8s.io/client-go/testing" +) + +type FakeCosignedV1beta1 struct { + *testing.Fake +} + +func (c *FakeCosignedV1beta1) ClusterImagePolicies() v1beta1.ClusterImagePolicyInterface { + return &FakeClusterImagePolicies{c} +} + +// RESTClient returns a RESTClient that is used to communicate +// with API server by this client implementation. +func (c *FakeCosignedV1beta1) RESTClient() rest.Interface { + var ret *rest.RESTClient + return ret +} diff --git a/pkg/client/clientset/versioned/typed/cosigned/v1beta1/generated_expansion.go b/pkg/client/clientset/versioned/typed/cosigned/v1beta1/generated_expansion.go new file mode 100644 index 00000000000..a7547fd7972 --- /dev/null +++ b/pkg/client/clientset/versioned/typed/cosigned/v1beta1/generated_expansion.go @@ -0,0 +1,19 @@ +// Copyright 2022 The Sigstore Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Code generated by client-gen. DO NOT EDIT. + +package v1beta1 + +type ClusterImagePolicyExpansion interface{} diff --git a/pkg/client/informers/externalversions/cosigned/interface.go b/pkg/client/informers/externalversions/cosigned/interface.go index bc896828b40..96625713d1f 100644 --- a/pkg/client/informers/externalversions/cosigned/interface.go +++ b/pkg/client/informers/externalversions/cosigned/interface.go @@ -18,6 +18,7 @@ package cosigned import ( v1alpha1 "github.com/sigstore/cosign/pkg/client/informers/externalversions/cosigned/v1alpha1" + v1beta1 "github.com/sigstore/cosign/pkg/client/informers/externalversions/cosigned/v1beta1" internalinterfaces "github.com/sigstore/cosign/pkg/client/informers/externalversions/internalinterfaces" ) @@ -25,6 +26,8 @@ import ( type Interface interface { // V1alpha1 provides access to shared informers for resources in V1alpha1. V1alpha1() v1alpha1.Interface + // V1beta1 provides access to shared informers for resources in V1beta1. + V1beta1() v1beta1.Interface } type group struct { @@ -42,3 +45,8 @@ func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakList func (g *group) V1alpha1() v1alpha1.Interface { return v1alpha1.New(g.factory, g.namespace, g.tweakListOptions) } + +// V1beta1 returns a new v1beta1.Interface. +func (g *group) V1beta1() v1beta1.Interface { + return v1beta1.New(g.factory, g.namespace, g.tweakListOptions) +} diff --git a/pkg/client/informers/externalversions/cosigned/v1beta1/clusterimagepolicy.go b/pkg/client/informers/externalversions/cosigned/v1beta1/clusterimagepolicy.go new file mode 100644 index 00000000000..e952111966d --- /dev/null +++ b/pkg/client/informers/externalversions/cosigned/v1beta1/clusterimagepolicy.go @@ -0,0 +1,87 @@ +// Copyright 2022 The Sigstore Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Code generated by informer-gen. DO NOT EDIT. + +package v1beta1 + +import ( + "context" + time "time" + + cosignedv1beta1 "github.com/sigstore/cosign/pkg/apis/cosigned/v1beta1" + versioned "github.com/sigstore/cosign/pkg/client/clientset/versioned" + internalinterfaces "github.com/sigstore/cosign/pkg/client/informers/externalversions/internalinterfaces" + v1beta1 "github.com/sigstore/cosign/pkg/client/listers/cosigned/v1beta1" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + runtime "k8s.io/apimachinery/pkg/runtime" + watch "k8s.io/apimachinery/pkg/watch" + cache "k8s.io/client-go/tools/cache" +) + +// ClusterImagePolicyInformer provides access to a shared informer and lister for +// ClusterImagePolicies. +type ClusterImagePolicyInformer interface { + Informer() cache.SharedIndexInformer + Lister() v1beta1.ClusterImagePolicyLister +} + +type clusterImagePolicyInformer struct { + factory internalinterfaces.SharedInformerFactory + tweakListOptions internalinterfaces.TweakListOptionsFunc +} + +// NewClusterImagePolicyInformer constructs a new informer for ClusterImagePolicy type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewClusterImagePolicyInformer(client versioned.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { + return NewFilteredClusterImagePolicyInformer(client, resyncPeriod, indexers, nil) +} + +// NewFilteredClusterImagePolicyInformer constructs a new informer for ClusterImagePolicy type. +// Always prefer using an informer factory to get a shared informer instead of getting an independent +// one. This reduces memory footprint and number of connections to the server. +func NewFilteredClusterImagePolicyInformer(client versioned.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { + return cache.NewSharedIndexInformer( + &cache.ListWatch{ + ListFunc: func(options v1.ListOptions) (runtime.Object, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.CosignedV1beta1().ClusterImagePolicies().List(context.TODO(), options) + }, + WatchFunc: func(options v1.ListOptions) (watch.Interface, error) { + if tweakListOptions != nil { + tweakListOptions(&options) + } + return client.CosignedV1beta1().ClusterImagePolicies().Watch(context.TODO(), options) + }, + }, + &cosignedv1beta1.ClusterImagePolicy{}, + resyncPeriod, + indexers, + ) +} + +func (f *clusterImagePolicyInformer) defaultInformer(client versioned.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { + return NewFilteredClusterImagePolicyInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) +} + +func (f *clusterImagePolicyInformer) Informer() cache.SharedIndexInformer { + return f.factory.InformerFor(&cosignedv1beta1.ClusterImagePolicy{}, f.defaultInformer) +} + +func (f *clusterImagePolicyInformer) Lister() v1beta1.ClusterImagePolicyLister { + return v1beta1.NewClusterImagePolicyLister(f.Informer().GetIndexer()) +} diff --git a/pkg/client/informers/externalversions/cosigned/v1beta1/interface.go b/pkg/client/informers/externalversions/cosigned/v1beta1/interface.go new file mode 100644 index 00000000000..8d1bab9367a --- /dev/null +++ b/pkg/client/informers/externalversions/cosigned/v1beta1/interface.go @@ -0,0 +1,43 @@ +// Copyright 2022 The Sigstore Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Code generated by informer-gen. DO NOT EDIT. + +package v1beta1 + +import ( + internalinterfaces "github.com/sigstore/cosign/pkg/client/informers/externalversions/internalinterfaces" +) + +// Interface provides access to all the informers in this group version. +type Interface interface { + // ClusterImagePolicies returns a ClusterImagePolicyInformer. + ClusterImagePolicies() ClusterImagePolicyInformer +} + +type version struct { + factory internalinterfaces.SharedInformerFactory + namespace string + tweakListOptions internalinterfaces.TweakListOptionsFunc +} + +// New returns a new Interface. +func New(f internalinterfaces.SharedInformerFactory, namespace string, tweakListOptions internalinterfaces.TweakListOptionsFunc) Interface { + return &version{factory: f, namespace: namespace, tweakListOptions: tweakListOptions} +} + +// ClusterImagePolicies returns a ClusterImagePolicyInformer. +func (v *version) ClusterImagePolicies() ClusterImagePolicyInformer { + return &clusterImagePolicyInformer{factory: v.factory, tweakListOptions: v.tweakListOptions} +} diff --git a/pkg/client/informers/externalversions/generic.go b/pkg/client/informers/externalversions/generic.go index 79bec18eb1a..3875bd4e9fc 100644 --- a/pkg/client/informers/externalversions/generic.go +++ b/pkg/client/informers/externalversions/generic.go @@ -20,6 +20,7 @@ import ( "fmt" v1alpha1 "github.com/sigstore/cosign/pkg/apis/cosigned/v1alpha1" + v1beta1 "github.com/sigstore/cosign/pkg/apis/cosigned/v1beta1" schema "k8s.io/apimachinery/pkg/runtime/schema" cache "k8s.io/client-go/tools/cache" ) @@ -54,6 +55,10 @@ func (f *sharedInformerFactory) ForResource(resource schema.GroupVersionResource case v1alpha1.SchemeGroupVersion.WithResource("clusterimagepolicies"): return &genericInformer{resource: resource.GroupResource(), informer: f.Cosigned().V1alpha1().ClusterImagePolicies().Informer()}, nil + // Group=cosigned.sigstore.dev, Version=v1beta1 + case v1beta1.SchemeGroupVersion.WithResource("clusterimagepolicies"): + return &genericInformer{resource: resource.GroupResource(), informer: f.Cosigned().V1beta1().ClusterImagePolicies().Informer()}, nil + } return nil, fmt.Errorf("no informer found for %v", resource) diff --git a/pkg/client/injection/client/client.go b/pkg/client/injection/client/client.go index 441ee3aa483..2a4e5914d85 100644 --- a/pkg/client/injection/client/client.go +++ b/pkg/client/injection/client/client.go @@ -23,8 +23,10 @@ import ( fmt "fmt" v1alpha1 "github.com/sigstore/cosign/pkg/apis/cosigned/v1alpha1" + v1beta1 "github.com/sigstore/cosign/pkg/apis/cosigned/v1beta1" versioned "github.com/sigstore/cosign/pkg/client/clientset/versioned" typedcosignedv1alpha1 "github.com/sigstore/cosign/pkg/client/clientset/versioned/typed/cosigned/v1alpha1" + typedcosignedv1beta1 "github.com/sigstore/cosign/pkg/client/clientset/versioned/typed/cosigned/v1beta1" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" unstructured "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" runtime "k8s.io/apimachinery/pkg/runtime" @@ -235,3 +237,145 @@ func (w *wrapCosignedV1alpha1ClusterImagePolicyImpl) UpdateStatus(ctx context.Co func (w *wrapCosignedV1alpha1ClusterImagePolicyImpl) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { return nil, errors.New("NYI: Watch") } + +// CosignedV1beta1 retrieves the CosignedV1beta1Client +func (w *wrapClient) CosignedV1beta1() typedcosignedv1beta1.CosignedV1beta1Interface { + return &wrapCosignedV1beta1{ + dyn: w.dyn, + } +} + +type wrapCosignedV1beta1 struct { + dyn dynamic.Interface +} + +func (w *wrapCosignedV1beta1) RESTClient() rest.Interface { + panic("RESTClient called on dynamic client!") +} + +func (w *wrapCosignedV1beta1) ClusterImagePolicies() typedcosignedv1beta1.ClusterImagePolicyInterface { + return &wrapCosignedV1beta1ClusterImagePolicyImpl{ + dyn: w.dyn.Resource(schema.GroupVersionResource{ + Group: "cosigned.sigstore.dev", + Version: "v1beta1", + Resource: "clusterimagepolicies", + }), + } +} + +type wrapCosignedV1beta1ClusterImagePolicyImpl struct { + dyn dynamic.NamespaceableResourceInterface +} + +var _ typedcosignedv1beta1.ClusterImagePolicyInterface = (*wrapCosignedV1beta1ClusterImagePolicyImpl)(nil) + +func (w *wrapCosignedV1beta1ClusterImagePolicyImpl) Create(ctx context.Context, in *v1beta1.ClusterImagePolicy, opts v1.CreateOptions) (*v1beta1.ClusterImagePolicy, error) { + in.SetGroupVersionKind(schema.GroupVersionKind{ + Group: "cosigned.sigstore.dev", + Version: "v1beta1", + Kind: "ClusterImagePolicy", + }) + uo := &unstructured.Unstructured{} + if err := convert(in, uo); err != nil { + return nil, err + } + uo, err := w.dyn.Create(ctx, uo, opts) + if err != nil { + return nil, err + } + out := &v1beta1.ClusterImagePolicy{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapCosignedV1beta1ClusterImagePolicyImpl) Delete(ctx context.Context, name string, opts v1.DeleteOptions) error { + return w.dyn.Delete(ctx, name, opts) +} + +func (w *wrapCosignedV1beta1ClusterImagePolicyImpl) DeleteCollection(ctx context.Context, opts v1.DeleteOptions, listOpts v1.ListOptions) error { + return w.dyn.DeleteCollection(ctx, opts, listOpts) +} + +func (w *wrapCosignedV1beta1ClusterImagePolicyImpl) Get(ctx context.Context, name string, opts v1.GetOptions) (*v1beta1.ClusterImagePolicy, error) { + uo, err := w.dyn.Get(ctx, name, opts) + if err != nil { + return nil, err + } + out := &v1beta1.ClusterImagePolicy{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapCosignedV1beta1ClusterImagePolicyImpl) List(ctx context.Context, opts v1.ListOptions) (*v1beta1.ClusterImagePolicyList, error) { + uo, err := w.dyn.List(ctx, opts) + if err != nil { + return nil, err + } + out := &v1beta1.ClusterImagePolicyList{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapCosignedV1beta1ClusterImagePolicyImpl) Patch(ctx context.Context, name string, pt types.PatchType, data []byte, opts v1.PatchOptions, subresources ...string) (result *v1beta1.ClusterImagePolicy, err error) { + uo, err := w.dyn.Patch(ctx, name, pt, data, opts) + if err != nil { + return nil, err + } + out := &v1beta1.ClusterImagePolicy{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapCosignedV1beta1ClusterImagePolicyImpl) Update(ctx context.Context, in *v1beta1.ClusterImagePolicy, opts v1.UpdateOptions) (*v1beta1.ClusterImagePolicy, error) { + in.SetGroupVersionKind(schema.GroupVersionKind{ + Group: "cosigned.sigstore.dev", + Version: "v1beta1", + Kind: "ClusterImagePolicy", + }) + uo := &unstructured.Unstructured{} + if err := convert(in, uo); err != nil { + return nil, err + } + uo, err := w.dyn.Update(ctx, uo, opts) + if err != nil { + return nil, err + } + out := &v1beta1.ClusterImagePolicy{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapCosignedV1beta1ClusterImagePolicyImpl) UpdateStatus(ctx context.Context, in *v1beta1.ClusterImagePolicy, opts v1.UpdateOptions) (*v1beta1.ClusterImagePolicy, error) { + in.SetGroupVersionKind(schema.GroupVersionKind{ + Group: "cosigned.sigstore.dev", + Version: "v1beta1", + Kind: "ClusterImagePolicy", + }) + uo := &unstructured.Unstructured{} + if err := convert(in, uo); err != nil { + return nil, err + } + uo, err := w.dyn.UpdateStatus(ctx, uo, opts) + if err != nil { + return nil, err + } + out := &v1beta1.ClusterImagePolicy{} + if err := convert(uo, out); err != nil { + return nil, err + } + return out, nil +} + +func (w *wrapCosignedV1beta1ClusterImagePolicyImpl) Watch(ctx context.Context, opts v1.ListOptions) (watch.Interface, error) { + return nil, errors.New("NYI: Watch") +} diff --git a/pkg/client/injection/informers/cosigned/v1beta1/clusterimagepolicy/clusterimagepolicy.go b/pkg/client/injection/informers/cosigned/v1beta1/clusterimagepolicy/clusterimagepolicy.go new file mode 100644 index 00000000000..93ad5da2422 --- /dev/null +++ b/pkg/client/injection/informers/cosigned/v1beta1/clusterimagepolicy/clusterimagepolicy.go @@ -0,0 +1,108 @@ +// Copyright 2022 The Sigstore Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Code generated by injection-gen. DO NOT EDIT. + +package clusterimagepolicy + +import ( + context "context" + + apiscosignedv1beta1 "github.com/sigstore/cosign/pkg/apis/cosigned/v1beta1" + versioned "github.com/sigstore/cosign/pkg/client/clientset/versioned" + v1beta1 "github.com/sigstore/cosign/pkg/client/informers/externalversions/cosigned/v1beta1" + client "github.com/sigstore/cosign/pkg/client/injection/client" + factory "github.com/sigstore/cosign/pkg/client/injection/informers/factory" + cosignedv1beta1 "github.com/sigstore/cosign/pkg/client/listers/cosigned/v1beta1" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + labels "k8s.io/apimachinery/pkg/labels" + cache "k8s.io/client-go/tools/cache" + controller "knative.dev/pkg/controller" + injection "knative.dev/pkg/injection" + logging "knative.dev/pkg/logging" +) + +func init() { + injection.Default.RegisterInformer(withInformer) + injection.Dynamic.RegisterDynamicInformer(withDynamicInformer) +} + +// Key is used for associating the Informer inside the context.Context. +type Key struct{} + +func withInformer(ctx context.Context) (context.Context, controller.Informer) { + f := factory.Get(ctx) + inf := f.Cosigned().V1beta1().ClusterImagePolicies() + return context.WithValue(ctx, Key{}, inf), inf.Informer() +} + +func withDynamicInformer(ctx context.Context) context.Context { + inf := &wrapper{client: client.Get(ctx), resourceVersion: injection.GetResourceVersion(ctx)} + return context.WithValue(ctx, Key{}, inf) +} + +// Get extracts the typed informer from the context. +func Get(ctx context.Context) v1beta1.ClusterImagePolicyInformer { + untyped := ctx.Value(Key{}) + if untyped == nil { + logging.FromContext(ctx).Panic( + "Unable to fetch github.com/sigstore/cosign/pkg/client/informers/externalversions/cosigned/v1beta1.ClusterImagePolicyInformer from context.") + } + return untyped.(v1beta1.ClusterImagePolicyInformer) +} + +type wrapper struct { + client versioned.Interface + + resourceVersion string +} + +var _ v1beta1.ClusterImagePolicyInformer = (*wrapper)(nil) +var _ cosignedv1beta1.ClusterImagePolicyLister = (*wrapper)(nil) + +func (w *wrapper) Informer() cache.SharedIndexInformer { + return cache.NewSharedIndexInformer(nil, &apiscosignedv1beta1.ClusterImagePolicy{}, 0, nil) +} + +func (w *wrapper) Lister() cosignedv1beta1.ClusterImagePolicyLister { + return w +} + +// SetResourceVersion allows consumers to adjust the minimum resourceVersion +// used by the underlying client. It is not accessible via the standard +// lister interface, but can be accessed through a user-defined interface and +// an implementation check e.g. rvs, ok := foo.(ResourceVersionSetter) +func (w *wrapper) SetResourceVersion(resourceVersion string) { + w.resourceVersion = resourceVersion +} + +func (w *wrapper) List(selector labels.Selector) (ret []*apiscosignedv1beta1.ClusterImagePolicy, err error) { + lo, err := w.client.CosignedV1beta1().ClusterImagePolicies().List(context.TODO(), v1.ListOptions{ + LabelSelector: selector.String(), + ResourceVersion: w.resourceVersion, + }) + if err != nil { + return nil, err + } + for idx := range lo.Items { + ret = append(ret, &lo.Items[idx]) + } + return ret, nil +} + +func (w *wrapper) Get(name string) (*apiscosignedv1beta1.ClusterImagePolicy, error) { + return w.client.CosignedV1beta1().ClusterImagePolicies().Get(context.TODO(), name, v1.GetOptions{ + ResourceVersion: w.resourceVersion, + }) +} diff --git a/pkg/client/injection/informers/cosigned/v1beta1/clusterimagepolicy/fake/fake.go b/pkg/client/injection/informers/cosigned/v1beta1/clusterimagepolicy/fake/fake.go new file mode 100644 index 00000000000..195133defd0 --- /dev/null +++ b/pkg/client/injection/informers/cosigned/v1beta1/clusterimagepolicy/fake/fake.go @@ -0,0 +1,38 @@ +// Copyright 2022 The Sigstore Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Code generated by injection-gen. DO NOT EDIT. + +package fake + +import ( + context "context" + + clusterimagepolicy "github.com/sigstore/cosign/pkg/client/injection/informers/cosigned/v1beta1/clusterimagepolicy" + fake "github.com/sigstore/cosign/pkg/client/injection/informers/factory/fake" + controller "knative.dev/pkg/controller" + injection "knative.dev/pkg/injection" +) + +var Get = clusterimagepolicy.Get + +func init() { + injection.Fake.RegisterInformer(withInformer) +} + +func withInformer(ctx context.Context) (context.Context, controller.Informer) { + f := fake.Get(ctx) + inf := f.Cosigned().V1beta1().ClusterImagePolicies() + return context.WithValue(ctx, clusterimagepolicy.Key{}, inf), inf.Informer() +} diff --git a/pkg/client/injection/informers/cosigned/v1beta1/clusterimagepolicy/filtered/clusterimagepolicy.go b/pkg/client/injection/informers/cosigned/v1beta1/clusterimagepolicy/filtered/clusterimagepolicy.go new file mode 100644 index 00000000000..642dc133dc5 --- /dev/null +++ b/pkg/client/injection/informers/cosigned/v1beta1/clusterimagepolicy/filtered/clusterimagepolicy.go @@ -0,0 +1,128 @@ +// Copyright 2022 The Sigstore Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Code generated by injection-gen. DO NOT EDIT. + +package filtered + +import ( + context "context" + + apiscosignedv1beta1 "github.com/sigstore/cosign/pkg/apis/cosigned/v1beta1" + versioned "github.com/sigstore/cosign/pkg/client/clientset/versioned" + v1beta1 "github.com/sigstore/cosign/pkg/client/informers/externalversions/cosigned/v1beta1" + client "github.com/sigstore/cosign/pkg/client/injection/client" + filtered "github.com/sigstore/cosign/pkg/client/injection/informers/factory/filtered" + cosignedv1beta1 "github.com/sigstore/cosign/pkg/client/listers/cosigned/v1beta1" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + labels "k8s.io/apimachinery/pkg/labels" + cache "k8s.io/client-go/tools/cache" + controller "knative.dev/pkg/controller" + injection "knative.dev/pkg/injection" + logging "knative.dev/pkg/logging" +) + +func init() { + injection.Default.RegisterFilteredInformers(withInformer) + injection.Dynamic.RegisterDynamicInformer(withDynamicInformer) +} + +// Key is used for associating the Informer inside the context.Context. +type Key struct { + Selector string +} + +func withInformer(ctx context.Context) (context.Context, []controller.Informer) { + untyped := ctx.Value(filtered.LabelKey{}) + if untyped == nil { + logging.FromContext(ctx).Panic( + "Unable to fetch labelkey from context.") + } + labelSelectors := untyped.([]string) + infs := []controller.Informer{} + for _, selector := range labelSelectors { + f := filtered.Get(ctx, selector) + inf := f.Cosigned().V1beta1().ClusterImagePolicies() + ctx = context.WithValue(ctx, Key{Selector: selector}, inf) + infs = append(infs, inf.Informer()) + } + return ctx, infs +} + +func withDynamicInformer(ctx context.Context) context.Context { + untyped := ctx.Value(filtered.LabelKey{}) + if untyped == nil { + logging.FromContext(ctx).Panic( + "Unable to fetch labelkey from context.") + } + labelSelectors := untyped.([]string) + for _, selector := range labelSelectors { + inf := &wrapper{client: client.Get(ctx), selector: selector} + ctx = context.WithValue(ctx, Key{Selector: selector}, inf) + } + return ctx +} + +// Get extracts the typed informer from the context. +func Get(ctx context.Context, selector string) v1beta1.ClusterImagePolicyInformer { + untyped := ctx.Value(Key{Selector: selector}) + if untyped == nil { + logging.FromContext(ctx).Panicf( + "Unable to fetch github.com/sigstore/cosign/pkg/client/informers/externalversions/cosigned/v1beta1.ClusterImagePolicyInformer with selector %s from context.", selector) + } + return untyped.(v1beta1.ClusterImagePolicyInformer) +} + +type wrapper struct { + client versioned.Interface + + selector string +} + +var _ v1beta1.ClusterImagePolicyInformer = (*wrapper)(nil) +var _ cosignedv1beta1.ClusterImagePolicyLister = (*wrapper)(nil) + +func (w *wrapper) Informer() cache.SharedIndexInformer { + return cache.NewSharedIndexInformer(nil, &apiscosignedv1beta1.ClusterImagePolicy{}, 0, nil) +} + +func (w *wrapper) Lister() cosignedv1beta1.ClusterImagePolicyLister { + return w +} + +func (w *wrapper) List(selector labels.Selector) (ret []*apiscosignedv1beta1.ClusterImagePolicy, err error) { + reqs, err := labels.ParseToRequirements(w.selector) + if err != nil { + return nil, err + } + selector = selector.Add(reqs...) + lo, err := w.client.CosignedV1beta1().ClusterImagePolicies().List(context.TODO(), v1.ListOptions{ + LabelSelector: selector.String(), + // TODO(mattmoor): Incorporate resourceVersion bounds based on staleness criteria. + }) + if err != nil { + return nil, err + } + for idx := range lo.Items { + ret = append(ret, &lo.Items[idx]) + } + return ret, nil +} + +func (w *wrapper) Get(name string) (*apiscosignedv1beta1.ClusterImagePolicy, error) { + // TODO(mattmoor): Check that the fetched object matches the selector. + return w.client.CosignedV1beta1().ClusterImagePolicies().Get(context.TODO(), name, v1.GetOptions{ + // TODO(mattmoor): Incorporate resourceVersion bounds based on staleness criteria. + }) +} diff --git a/pkg/client/injection/informers/cosigned/v1beta1/clusterimagepolicy/filtered/fake/fake.go b/pkg/client/injection/informers/cosigned/v1beta1/clusterimagepolicy/filtered/fake/fake.go new file mode 100644 index 00000000000..9ae1b0a8f2b --- /dev/null +++ b/pkg/client/injection/informers/cosigned/v1beta1/clusterimagepolicy/filtered/fake/fake.go @@ -0,0 +1,50 @@ +// Copyright 2022 The Sigstore Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Code generated by injection-gen. DO NOT EDIT. + +package fake + +import ( + context "context" + + filtered "github.com/sigstore/cosign/pkg/client/injection/informers/cosigned/v1beta1/clusterimagepolicy/filtered" + factoryfiltered "github.com/sigstore/cosign/pkg/client/injection/informers/factory/filtered" + controller "knative.dev/pkg/controller" + injection "knative.dev/pkg/injection" + logging "knative.dev/pkg/logging" +) + +var Get = filtered.Get + +func init() { + injection.Fake.RegisterFilteredInformers(withInformer) +} + +func withInformer(ctx context.Context) (context.Context, []controller.Informer) { + untyped := ctx.Value(factoryfiltered.LabelKey{}) + if untyped == nil { + logging.FromContext(ctx).Panic( + "Unable to fetch labelkey from context.") + } + labelSelectors := untyped.([]string) + infs := []controller.Informer{} + for _, selector := range labelSelectors { + f := factoryfiltered.Get(ctx, selector) + inf := f.Cosigned().V1beta1().ClusterImagePolicies() + ctx = context.WithValue(ctx, filtered.Key{Selector: selector}, inf) + infs = append(infs, inf.Informer()) + } + return ctx, infs +} diff --git a/pkg/client/injection/reconciler/cosigned/v1beta1/clusterimagepolicy/controller.go b/pkg/client/injection/reconciler/cosigned/v1beta1/clusterimagepolicy/controller.go new file mode 100644 index 00000000000..1dd6081ee4f --- /dev/null +++ b/pkg/client/injection/reconciler/cosigned/v1beta1/clusterimagepolicy/controller.go @@ -0,0 +1,157 @@ +// Copyright 2022 The Sigstore Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Code generated by injection-gen. DO NOT EDIT. + +package clusterimagepolicy + +import ( + context "context" + fmt "fmt" + reflect "reflect" + strings "strings" + + versionedscheme "github.com/sigstore/cosign/pkg/client/clientset/versioned/scheme" + client "github.com/sigstore/cosign/pkg/client/injection/client" + clusterimagepolicy "github.com/sigstore/cosign/pkg/client/injection/informers/cosigned/v1beta1/clusterimagepolicy" + zap "go.uber.org/zap" + corev1 "k8s.io/api/core/v1" + labels "k8s.io/apimachinery/pkg/labels" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + scheme "k8s.io/client-go/kubernetes/scheme" + v1 "k8s.io/client-go/kubernetes/typed/core/v1" + record "k8s.io/client-go/tools/record" + kubeclient "knative.dev/pkg/client/injection/kube/client" + controller "knative.dev/pkg/controller" + logging "knative.dev/pkg/logging" + logkey "knative.dev/pkg/logging/logkey" + reconciler "knative.dev/pkg/reconciler" +) + +const ( + defaultControllerAgentName = "clusterimagepolicy-controller" + defaultFinalizerName = "clusterimagepolicies.cosigned.sigstore.dev" +) + +// NewImpl returns a controller.Impl that handles queuing and feeding work from +// the queue through an implementation of controller.Reconciler, delegating to +// the provided Interface and optional Finalizer methods. OptionsFn is used to return +// controller.ControllerOptions to be used by the internal reconciler. +func NewImpl(ctx context.Context, r Interface, optionsFns ...controller.OptionsFn) *controller.Impl { + logger := logging.FromContext(ctx) + + // Check the options function input. It should be 0 or 1. + if len(optionsFns) > 1 { + logger.Fatal("Up to one options function is supported, found: ", len(optionsFns)) + } + + clusterimagepolicyInformer := clusterimagepolicy.Get(ctx) + + lister := clusterimagepolicyInformer.Lister() + + var promoteFilterFunc func(obj interface{}) bool + + rec := &reconcilerImpl{ + LeaderAwareFuncs: reconciler.LeaderAwareFuncs{ + PromoteFunc: func(bkt reconciler.Bucket, enq func(reconciler.Bucket, types.NamespacedName)) error { + all, err := lister.List(labels.Everything()) + if err != nil { + return err + } + for _, elt := range all { + if promoteFilterFunc != nil { + if ok := promoteFilterFunc(elt); !ok { + continue + } + } + enq(bkt, types.NamespacedName{ + Namespace: elt.GetNamespace(), + Name: elt.GetName(), + }) + } + return nil + }, + }, + Client: client.Get(ctx), + Lister: lister, + reconciler: r, + finalizerName: defaultFinalizerName, + } + + ctrType := reflect.TypeOf(r).Elem() + ctrTypeName := fmt.Sprintf("%s.%s", ctrType.PkgPath(), ctrType.Name()) + ctrTypeName = strings.ReplaceAll(ctrTypeName, "/", ".") + + logger = logger.With( + zap.String(logkey.ControllerType, ctrTypeName), + zap.String(logkey.Kind, "cosigned.sigstore.dev.ClusterImagePolicy"), + ) + + impl := controller.NewContext(ctx, rec, controller.ControllerOptions{WorkQueueName: ctrTypeName, Logger: logger}) + agentName := defaultControllerAgentName + + // Pass impl to the options. Save any optional results. + for _, fn := range optionsFns { + opts := fn(impl) + if opts.ConfigStore != nil { + rec.configStore = opts.ConfigStore + } + if opts.FinalizerName != "" { + rec.finalizerName = opts.FinalizerName + } + if opts.AgentName != "" { + agentName = opts.AgentName + } + if opts.DemoteFunc != nil { + rec.DemoteFunc = opts.DemoteFunc + } + if opts.PromoteFilterFunc != nil { + promoteFilterFunc = opts.PromoteFilterFunc + } + } + + rec.Recorder = createRecorder(ctx, agentName) + + return impl +} + +func createRecorder(ctx context.Context, agentName string) record.EventRecorder { + logger := logging.FromContext(ctx) + + recorder := controller.GetEventRecorder(ctx) + if recorder == nil { + // Create event broadcaster + logger.Debug("Creating event broadcaster") + eventBroadcaster := record.NewBroadcaster() + watches := []watch.Interface{ + eventBroadcaster.StartLogging(logger.Named("event-broadcaster").Infof), + eventBroadcaster.StartRecordingToSink( + &v1.EventSinkImpl{Interface: kubeclient.Get(ctx).CoreV1().Events("")}), + } + recorder = eventBroadcaster.NewRecorder(scheme.Scheme, corev1.EventSource{Component: agentName}) + go func() { + <-ctx.Done() + for _, w := range watches { + w.Stop() + } + }() + } + + return recorder +} + +func init() { + versionedscheme.AddToScheme(scheme.Scheme) +} diff --git a/pkg/client/injection/reconciler/cosigned/v1beta1/clusterimagepolicy/reconciler.go b/pkg/client/injection/reconciler/cosigned/v1beta1/clusterimagepolicy/reconciler.go new file mode 100644 index 00000000000..88fa7a3fe26 --- /dev/null +++ b/pkg/client/injection/reconciler/cosigned/v1beta1/clusterimagepolicy/reconciler.go @@ -0,0 +1,376 @@ +// Copyright 2022 The Sigstore Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Code generated by injection-gen. DO NOT EDIT. + +package clusterimagepolicy + +import ( + context "context" + json "encoding/json" + fmt "fmt" + + v1beta1 "github.com/sigstore/cosign/pkg/apis/cosigned/v1beta1" + versioned "github.com/sigstore/cosign/pkg/client/clientset/versioned" + cosignedv1beta1 "github.com/sigstore/cosign/pkg/client/listers/cosigned/v1beta1" + zap "go.uber.org/zap" + v1 "k8s.io/api/core/v1" + errors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + labels "k8s.io/apimachinery/pkg/labels" + types "k8s.io/apimachinery/pkg/types" + sets "k8s.io/apimachinery/pkg/util/sets" + record "k8s.io/client-go/tools/record" + controller "knative.dev/pkg/controller" + logging "knative.dev/pkg/logging" + reconciler "knative.dev/pkg/reconciler" +) + +// Interface defines the strongly typed interfaces to be implemented by a +// controller reconciling v1beta1.ClusterImagePolicy. +type Interface interface { + // ReconcileKind implements custom logic to reconcile v1beta1.ClusterImagePolicy. Any changes + // to the objects .Status or .Finalizers will be propagated to the stored + // object. It is recommended that implementors do not call any update calls + // for the Kind inside of ReconcileKind, it is the responsibility of the calling + // controller to propagate those properties. The resource passed to ReconcileKind + // will always have an empty deletion timestamp. + ReconcileKind(ctx context.Context, o *v1beta1.ClusterImagePolicy) reconciler.Event +} + +// Finalizer defines the strongly typed interfaces to be implemented by a +// controller finalizing v1beta1.ClusterImagePolicy. +type Finalizer interface { + // FinalizeKind implements custom logic to finalize v1beta1.ClusterImagePolicy. Any changes + // to the objects .Status or .Finalizers will be ignored. Returning a nil or + // Normal type reconciler.Event will allow the finalizer to be deleted on + // the resource. The resource passed to FinalizeKind will always have a set + // deletion timestamp. + FinalizeKind(ctx context.Context, o *v1beta1.ClusterImagePolicy) reconciler.Event +} + +// ReadOnlyInterface defines the strongly typed interfaces to be implemented by a +// controller reconciling v1beta1.ClusterImagePolicy if they want to process resources for which +// they are not the leader. +type ReadOnlyInterface interface { + // ObserveKind implements logic to observe v1beta1.ClusterImagePolicy. + // This method should not write to the API. + ObserveKind(ctx context.Context, o *v1beta1.ClusterImagePolicy) reconciler.Event +} + +type doReconcile func(ctx context.Context, o *v1beta1.ClusterImagePolicy) reconciler.Event + +// reconcilerImpl implements controller.Reconciler for v1beta1.ClusterImagePolicy resources. +type reconcilerImpl struct { + // LeaderAwareFuncs is inlined to help us implement reconciler.LeaderAware. + reconciler.LeaderAwareFuncs + + // Client is used to write back status updates. + Client versioned.Interface + + // Listers index properties about resources. + Lister cosignedv1beta1.ClusterImagePolicyLister + + // Recorder is an event recorder for recording Event resources to the + // Kubernetes API. + Recorder record.EventRecorder + + // configStore allows for decorating a context with config maps. + // +optional + configStore reconciler.ConfigStore + + // reconciler is the implementation of the business logic of the resource. + reconciler Interface + + // finalizerName is the name of the finalizer to reconcile. + finalizerName string +} + +// Check that our Reconciler implements controller.Reconciler. +var _ controller.Reconciler = (*reconcilerImpl)(nil) + +// Check that our generated Reconciler is always LeaderAware. +var _ reconciler.LeaderAware = (*reconcilerImpl)(nil) + +func NewReconciler(ctx context.Context, logger *zap.SugaredLogger, client versioned.Interface, lister cosignedv1beta1.ClusterImagePolicyLister, recorder record.EventRecorder, r Interface, options ...controller.Options) controller.Reconciler { + // Check the options function input. It should be 0 or 1. + if len(options) > 1 { + logger.Fatal("Up to one options struct is supported, found: ", len(options)) + } + + // Fail fast when users inadvertently implement the other LeaderAware interface. + // For the typed reconcilers, Promote shouldn't take any arguments. + if _, ok := r.(reconciler.LeaderAware); ok { + logger.Fatalf("%T implements the incorrect LeaderAware interface. Promote() should not take an argument as genreconciler handles the enqueuing automatically.", r) + } + + rec := &reconcilerImpl{ + LeaderAwareFuncs: reconciler.LeaderAwareFuncs{ + PromoteFunc: func(bkt reconciler.Bucket, enq func(reconciler.Bucket, types.NamespacedName)) error { + all, err := lister.List(labels.Everything()) + if err != nil { + return err + } + for _, elt := range all { + // TODO: Consider letting users specify a filter in options. + enq(bkt, types.NamespacedName{ + Namespace: elt.GetNamespace(), + Name: elt.GetName(), + }) + } + return nil + }, + }, + Client: client, + Lister: lister, + Recorder: recorder, + reconciler: r, + finalizerName: defaultFinalizerName, + } + + for _, opts := range options { + if opts.ConfigStore != nil { + rec.configStore = opts.ConfigStore + } + if opts.FinalizerName != "" { + rec.finalizerName = opts.FinalizerName + } + if opts.DemoteFunc != nil { + rec.DemoteFunc = opts.DemoteFunc + } + } + + return rec +} + +// Reconcile implements controller.Reconciler +func (r *reconcilerImpl) Reconcile(ctx context.Context, key string) error { + logger := logging.FromContext(ctx) + + // Initialize the reconciler state. This will convert the namespace/name + // string into a distinct namespace and name, determine if this instance of + // the reconciler is the leader, and any additional interfaces implemented + // by the reconciler. Returns an error is the resource key is invalid. + s, err := newState(key, r) + if err != nil { + logger.Error("Invalid resource key: ", key) + return nil + } + + // If we are not the leader, and we don't implement either ReadOnly + // observer interfaces, then take a fast-path out. + if s.isNotLeaderNorObserver() { + return controller.NewSkipKey(key) + } + + // If configStore is set, attach the frozen configuration to the context. + if r.configStore != nil { + ctx = r.configStore.ToContext(ctx) + } + + // Add the recorder to context. + ctx = controller.WithEventRecorder(ctx, r.Recorder) + + // Get the resource with this namespace/name. + + getter := r.Lister + + original, err := getter.Get(s.name) + + if errors.IsNotFound(err) { + // The resource may no longer exist, in which case we stop processing and call + // the ObserveDeletion handler if appropriate. + logger.Debugf("Resource %q no longer exists", key) + if del, ok := r.reconciler.(reconciler.OnDeletionInterface); ok { + return del.ObserveDeletion(ctx, types.NamespacedName{ + Namespace: s.namespace, + Name: s.name, + }) + } + return nil + } else if err != nil { + return err + } + + // Don't modify the informers copy. + resource := original.DeepCopy() + + var reconcileEvent reconciler.Event + + name, do := s.reconcileMethodFor(resource) + // Append the target method to the logger. + logger = logger.With(zap.String("targetMethod", name)) + switch name { + case reconciler.DoReconcileKind: + // Set and update the finalizer on resource if r.reconciler + // implements Finalizer. + if resource, err = r.setFinalizerIfFinalizer(ctx, resource); err != nil { + return fmt.Errorf("failed to set finalizers: %w", err) + } + + // Reconcile this copy of the resource and then write back any status + // updates regardless of whether the reconciliation errored out. + reconcileEvent = do(ctx, resource) + + case reconciler.DoFinalizeKind: + // For finalizing reconcilers, if this resource being marked for deletion + // and reconciled cleanly (nil or normal event), remove the finalizer. + reconcileEvent = do(ctx, resource) + + if resource, err = r.clearFinalizer(ctx, resource, reconcileEvent); err != nil { + return fmt.Errorf("failed to clear finalizers: %w", err) + } + + case reconciler.DoObserveKind: + // Observe any changes to this resource, since we are not the leader. + reconcileEvent = do(ctx, resource) + + } + + // Report the reconciler event, if any. + if reconcileEvent != nil { + var event *reconciler.ReconcilerEvent + if reconciler.EventAs(reconcileEvent, &event) { + logger.Infow("Returned an event", zap.Any("event", reconcileEvent)) + r.Recorder.Event(resource, event.EventType, event.Reason, event.Error()) + + // the event was wrapped inside an error, consider the reconciliation as failed + if _, isEvent := reconcileEvent.(*reconciler.ReconcilerEvent); !isEvent { + return reconcileEvent + } + return nil + } + + if controller.IsSkipKey(reconcileEvent) { + // This is a wrapped error, don't emit an event. + } else if ok, _ := controller.IsRequeueKey(reconcileEvent); ok { + // This is a wrapped error, don't emit an event. + } else { + logger.Errorw("Returned an error", zap.Error(reconcileEvent)) + r.Recorder.Event(resource, v1.EventTypeWarning, "InternalError", reconcileEvent.Error()) + } + return reconcileEvent + } + + return nil +} + +// updateFinalizersFiltered will update the Finalizers of the resource. +// TODO: this method could be generic and sync all finalizers. For now it only +// updates defaultFinalizerName or its override. +func (r *reconcilerImpl) updateFinalizersFiltered(ctx context.Context, resource *v1beta1.ClusterImagePolicy) (*v1beta1.ClusterImagePolicy, error) { + + getter := r.Lister + + actual, err := getter.Get(resource.Name) + if err != nil { + return resource, err + } + + // Don't modify the informers copy. + existing := actual.DeepCopy() + + var finalizers []string + + // If there's nothing to update, just return. + existingFinalizers := sets.NewString(existing.Finalizers...) + desiredFinalizers := sets.NewString(resource.Finalizers...) + + if desiredFinalizers.Has(r.finalizerName) { + if existingFinalizers.Has(r.finalizerName) { + // Nothing to do. + return resource, nil + } + // Add the finalizer. + finalizers = append(existing.Finalizers, r.finalizerName) + } else { + if !existingFinalizers.Has(r.finalizerName) { + // Nothing to do. + return resource, nil + } + // Remove the finalizer. + existingFinalizers.Delete(r.finalizerName) + finalizers = existingFinalizers.List() + } + + mergePatch := map[string]interface{}{ + "metadata": map[string]interface{}{ + "finalizers": finalizers, + "resourceVersion": existing.ResourceVersion, + }, + } + + patch, err := json.Marshal(mergePatch) + if err != nil { + return resource, err + } + + patcher := r.Client.CosignedV1beta1().ClusterImagePolicies() + + resourceName := resource.Name + updated, err := patcher.Patch(ctx, resourceName, types.MergePatchType, patch, metav1.PatchOptions{}) + if err != nil { + r.Recorder.Eventf(existing, v1.EventTypeWarning, "FinalizerUpdateFailed", + "Failed to update finalizers for %q: %v", resourceName, err) + } else { + r.Recorder.Eventf(updated, v1.EventTypeNormal, "FinalizerUpdate", + "Updated %q finalizers", resource.GetName()) + } + return updated, err +} + +func (r *reconcilerImpl) setFinalizerIfFinalizer(ctx context.Context, resource *v1beta1.ClusterImagePolicy) (*v1beta1.ClusterImagePolicy, error) { + if _, ok := r.reconciler.(Finalizer); !ok { + return resource, nil + } + + finalizers := sets.NewString(resource.Finalizers...) + + // If this resource is not being deleted, mark the finalizer. + if resource.GetDeletionTimestamp().IsZero() { + finalizers.Insert(r.finalizerName) + } + + resource.Finalizers = finalizers.List() + + // Synchronize the finalizers filtered by r.finalizerName. + return r.updateFinalizersFiltered(ctx, resource) +} + +func (r *reconcilerImpl) clearFinalizer(ctx context.Context, resource *v1beta1.ClusterImagePolicy, reconcileEvent reconciler.Event) (*v1beta1.ClusterImagePolicy, error) { + if _, ok := r.reconciler.(Finalizer); !ok { + return resource, nil + } + if resource.GetDeletionTimestamp().IsZero() { + return resource, nil + } + + finalizers := sets.NewString(resource.Finalizers...) + + if reconcileEvent != nil { + var event *reconciler.ReconcilerEvent + if reconciler.EventAs(reconcileEvent, &event) { + if event.EventType == v1.EventTypeNormal { + finalizers.Delete(r.finalizerName) + } + } + } else { + finalizers.Delete(r.finalizerName) + } + + resource.Finalizers = finalizers.List() + + // Synchronize the finalizers filtered by r.finalizerName. + return r.updateFinalizersFiltered(ctx, resource) +} diff --git a/pkg/client/injection/reconciler/cosigned/v1beta1/clusterimagepolicy/state.go b/pkg/client/injection/reconciler/cosigned/v1beta1/clusterimagepolicy/state.go new file mode 100644 index 00000000000..7bb1188e615 --- /dev/null +++ b/pkg/client/injection/reconciler/cosigned/v1beta1/clusterimagepolicy/state.go @@ -0,0 +1,95 @@ +// Copyright 2022 The Sigstore Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Code generated by injection-gen. DO NOT EDIT. + +package clusterimagepolicy + +import ( + fmt "fmt" + + v1beta1 "github.com/sigstore/cosign/pkg/apis/cosigned/v1beta1" + types "k8s.io/apimachinery/pkg/types" + cache "k8s.io/client-go/tools/cache" + reconciler "knative.dev/pkg/reconciler" +) + +// state is used to track the state of a reconciler in a single run. +type state struct { + // key is the original reconciliation key from the queue. + key string + // namespace is the namespace split from the reconciliation key. + namespace string + // name is the name split from the reconciliation key. + name string + // reconciler is the reconciler. + reconciler Interface + // roi is the read only interface cast of the reconciler. + roi ReadOnlyInterface + // isROI (Read Only Interface) the reconciler only observes reconciliation. + isROI bool + // isLeader the instance of the reconciler is the elected leader. + isLeader bool +} + +func newState(key string, r *reconcilerImpl) (*state, error) { + // Convert the namespace/name string into a distinct namespace and name. + namespace, name, err := cache.SplitMetaNamespaceKey(key) + if err != nil { + return nil, fmt.Errorf("invalid resource key: %s", key) + } + + roi, isROI := r.reconciler.(ReadOnlyInterface) + + isLeader := r.IsLeaderFor(types.NamespacedName{ + Namespace: namespace, + Name: name, + }) + + return &state{ + key: key, + namespace: namespace, + name: name, + reconciler: r.reconciler, + roi: roi, + isROI: isROI, + isLeader: isLeader, + }, nil +} + +// isNotLeaderNorObserver checks to see if this reconciler with the current +// state is enabled to do any work or not. +// isNotLeaderNorObserver returns true when there is no work possible for the +// reconciler. +func (s *state) isNotLeaderNorObserver() bool { + if !s.isLeader && !s.isROI { + // If we are not the leader, and we don't implement the ReadOnly + // interface, then take a fast-path out. + return true + } + return false +} + +func (s *state) reconcileMethodFor(o *v1beta1.ClusterImagePolicy) (string, doReconcile) { + if o.GetDeletionTimestamp().IsZero() { + if s.isLeader { + return reconciler.DoReconcileKind, s.reconciler.ReconcileKind + } else if s.isROI { + return reconciler.DoObserveKind, s.roi.ObserveKind + } + } else if fin, ok := s.reconciler.(Finalizer); s.isLeader && ok { + return reconciler.DoFinalizeKind, fin.FinalizeKind + } + return "unknown", nil +} diff --git a/pkg/client/listers/cosigned/v1beta1/clusterimagepolicy.go b/pkg/client/listers/cosigned/v1beta1/clusterimagepolicy.go new file mode 100644 index 00000000000..81332814b0f --- /dev/null +++ b/pkg/client/listers/cosigned/v1beta1/clusterimagepolicy.go @@ -0,0 +1,66 @@ +// Copyright 2022 The Sigstore Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Code generated by lister-gen. DO NOT EDIT. + +package v1beta1 + +import ( + v1beta1 "github.com/sigstore/cosign/pkg/apis/cosigned/v1beta1" + "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/labels" + "k8s.io/client-go/tools/cache" +) + +// ClusterImagePolicyLister helps list ClusterImagePolicies. +// All objects returned here must be treated as read-only. +type ClusterImagePolicyLister interface { + // List lists all ClusterImagePolicies in the indexer. + // Objects returned here must be treated as read-only. + List(selector labels.Selector) (ret []*v1beta1.ClusterImagePolicy, err error) + // Get retrieves the ClusterImagePolicy from the index for a given name. + // Objects returned here must be treated as read-only. + Get(name string) (*v1beta1.ClusterImagePolicy, error) + ClusterImagePolicyListerExpansion +} + +// clusterImagePolicyLister implements the ClusterImagePolicyLister interface. +type clusterImagePolicyLister struct { + indexer cache.Indexer +} + +// NewClusterImagePolicyLister returns a new ClusterImagePolicyLister. +func NewClusterImagePolicyLister(indexer cache.Indexer) ClusterImagePolicyLister { + return &clusterImagePolicyLister{indexer: indexer} +} + +// List lists all ClusterImagePolicies in the indexer. +func (s *clusterImagePolicyLister) List(selector labels.Selector) (ret []*v1beta1.ClusterImagePolicy, err error) { + err = cache.ListAll(s.indexer, selector, func(m interface{}) { + ret = append(ret, m.(*v1beta1.ClusterImagePolicy)) + }) + return ret, err +} + +// Get retrieves the ClusterImagePolicy from the index for a given name. +func (s *clusterImagePolicyLister) Get(name string) (*v1beta1.ClusterImagePolicy, error) { + obj, exists, err := s.indexer.GetByKey(name) + if err != nil { + return nil, err + } + if !exists { + return nil, errors.NewNotFound(v1beta1.Resource("clusterimagepolicy"), name) + } + return obj.(*v1beta1.ClusterImagePolicy), nil +} diff --git a/pkg/client/listers/cosigned/v1beta1/expansion_generated.go b/pkg/client/listers/cosigned/v1beta1/expansion_generated.go new file mode 100644 index 00000000000..43d2cf43e00 --- /dev/null +++ b/pkg/client/listers/cosigned/v1beta1/expansion_generated.go @@ -0,0 +1,21 @@ +// Copyright 2022 The Sigstore Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Code generated by lister-gen. DO NOT EDIT. + +package v1beta1 + +// ClusterImagePolicyListerExpansion allows custom methods to be added to +// ClusterImagePolicyLister. +type ClusterImagePolicyListerExpansion interface{} diff --git a/third_party/VENDOR-LICENSE/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/LICENSE b/third_party/VENDOR-LICENSE/k8s.io/apiextensions-apiserver/pkg/LICENSE similarity index 100% rename from third_party/VENDOR-LICENSE/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/LICENSE rename to third_party/VENDOR-LICENSE/k8s.io/apiextensions-apiserver/pkg/LICENSE